Debian Codegraph @

asusrouter/modules/endpoint/devicemap.py

raw
1 """Devicemap endpoint module."""
2
3 from __future__ import annotations
4
5 from datetime import datetime, timedelta
6 import logging
7 import re
8 from typing import Any
9
10 import xmltodict
11
12 from asusrouter.config import ARConfig, ARConfigKey as ARConfKey
13 from asusrouter.modules.data import AsusData, AsusDataState
14 from asusrouter.modules.endpoint import data_get
15 from asusrouter.modules.openvpn import AsusOVPNClient, AsusOVPNServer
16 from asusrouter.tools.cleaners import clean_dict, clean_dict_key_prefix
17 from asusrouter.tools.converters import safe_datetime, safe_int
18 from asusrouter.tools.readers import merge_dicts
19
20 from .devicemap_const import (
21 DEVICEMAP_BY_INDEX,
22 DEVICEMAP_BY_KEY,
23 DEVICEMAP_CLEAR,
24 )
25
26 _LOGGER = logging.getLogger(__name__)
27
28 REQUIRE_HISTORY = True
29
30
31 def read(content: str, **kwargs: Any) -> dict[str, Any]:
32 """Read devicemap data."""
33
34 # Create a dict to store the data
35 devicemap: dict[str, Any] = {}
36
37 # Parse the XML data
38 try:
39 xml_content: dict[str, Any] = xmltodict.parse(content).get(
40 "devicemap", {}
41 )
42 if not xml_content:
43 _LOGGER.debug("Received empty devicemap XML")
44 return devicemap
45 except xmltodict.expat.ExpatError as ex: # pyright: ignore[reportAttributeAccessIssue]
46 _LOGGER.debug("Received invalid devicemap XML: %s", ex)
47 return devicemap
48
49 # Go through the data and fill the dict
50
51 # Get values by index using read_devicemap_index method
52 devicemap = merge_dicts(devicemap, read_index(xml_content))
53
54 # Get values by key using read_devicemap_key method
55 devicemap = merge_dicts(devicemap, read_key(xml_content))
56
57 # Clear values from useless symbols
58 for output_group, clear_map in DEVICEMAP_CLEAR.items():
59 if output_group not in devicemap:
60 continue
61 for key, clear_value in clear_map.items():
62 # If the key is not in the devicemap, continue
63 if key not in devicemap[output_group]:
64 continue
65 devicemap[output_group][key] = devicemap[output_group][
66 key
67 ].replace(clear_value, "")
68
69 # Clean the devicemap values
70 devicemap = clean_dict(devicemap)
71
72 # Clean the devicemap values_dict from output_group prefix
73 for output_group, values_dict in devicemap.items():
74 devicemap[output_group] = clean_dict_key_prefix(
75 values_dict, output_group
76 )
77
78 # Return the devicemap
79 return devicemap
80
81
82 def read_index(xml_content: dict[str, Any]) -> dict[str, Any]:
83 """Read devicemap by index.
84
85 This method performs reading of the devicemap by index
86 to simplify the original read_devicemap method.
87 """
88
89 # Create a dict to store the data
90 devicemap: dict[str, Any] = {}
91
92 # Get values for which we only know their order (index)
93 for output_group, input_group, input_values in DEVICEMAP_BY_INDEX:
94 # Create an empty dictionary for the output group
95 devicemap[output_group] = {}
96
97 # Check that the input group is in the xml content
98 if input_group not in xml_content:
99 continue
100
101 # Use dict comprehension to build output_group_data
102 output_group_data = {
103 input_value: xml_content[input_group][index]
104 for index, input_value in enumerate(input_values)
105 if index < len(xml_content[input_group])
106 }
107
108 # Add the output group data to the devicemap
109 devicemap[output_group] = output_group_data
110
111 # Return the devicemap
112 return devicemap
113
114
115 def read_key(xml_content: dict[str, Any]) -> dict[str, Any]:
116 """Read devicemap by key.
117
118 This method performs reading of the devicemap by key
119 to simplify the original read_devicemap method.
120 """
121
122 # Create a dict to store the data
123 devicemap: dict[str, Any] = {}
124
125 # Get values for which we know their key
126 for output_group, input_group, input_values in DEVICEMAP_BY_KEY:
127 # Create a dict to store the data
128 output_group_data: dict[str, Any] = {}
129
130 # Go through the input values and fill the dict
131 for input_value in input_values:
132 # Get the input group data
133 xml_input_group = xml_content.get(input_group)
134
135 # If the input group data is None, skip this iteration
136 if xml_input_group is None:
137 continue
138
139 # If the input group data is a string, convert it to a list
140 if isinstance(xml_input_group, str):
141 xml_input_group = [xml_input_group]
142
143 # Go through the input group data and check
144 # if the input value is in it
145 for value in xml_input_group:
146 if input_value in value:
147 # Add the input value to the output group data
148 output_group_data[input_value] = value.replace(
149 f"{input_value}=", ""
150 )
151 break
152
153 # Add the output group data to the devicemap
154 devicemap[output_group] = output_group_data
155
156 # Return the devicemap
157 return devicemap
158
159
160 # This method performs reading of the devicemap special values
161 # pylint: disable-next=unused-argument
162 def read_special(xml_content: dict[str, Any]) -> dict[str, Any]:
163 """Read devicemap special values."""
164
165 # This method is not implemented yet
166
167 return {}
168
169
170 def read_uptime_string(
171 content: str,
172 ) -> tuple[datetime | None, int | None]:
173 """Read uptime string and return proper datetime object."""
174
175 # Split the content into the date/time part and the seconds part
176 uptime_parts = content.split("(")
177 if len(uptime_parts) < 2: # noqa: PLR2004
178 return (None, None)
179
180 # Extract the number of seconds from the seconds part
181 seconds_match = re.search("([0-9]+)", uptime_parts[1])
182 if not seconds_match:
183 return (None, None)
184 seconds: int | None = safe_int(seconds_match.group())
185
186 when = safe_datetime(uptime_parts[0])
187 if when is None or seconds is None:
188 return (None, seconds)
189
190 uptime = when - timedelta(seconds=seconds)
191
192 # If robust_boottime is enabled, floor the uptime to even seconds
193 # This will introduce a systematic error with up to 1 second delay
194 # but will avoid raw data uncertainty and the resulting jitter
195 if ARConfig.get(ARConfKey.ROBUST_BOOTTIME) is True:
196 even_seconds = uptime.second - (uptime.second % 2)
197 uptime = uptime.replace(second=even_seconds, microsecond=0)
198
199 return (uptime, seconds)
200
201
202 def process(data: dict[str, Any]) -> dict[AsusData, Any]:
203 """Process data from devicemap endpoint."""
204
205 # Get the passed arguments
206 history: dict[AsusData, AsusDataState] = data_get(data, "history") or {}
207
208 # Devicemap - just the data itself
209 devicemap = data
210
211 # Boot time
212 prev_boottime_object: AsusDataState | None = history.get(AsusData.BOOTTIME)
213 prev_boottime = prev_boottime_object.data if prev_boottime_object else None
214 boottime, reboot = process_boottime(devicemap, prev_boottime)
215
216 # Mark reboot
217 flags = {}
218 if reboot:
219 flags["reboot"] = True
220
221 # OpenVPN
222 openvpn = process_ovpn(devicemap)
223
224 # Return the processed data
225 return {
226 AsusData.DEVICEMAP: devicemap,
227 AsusData.BOOTTIME: boottime,
228 AsusData.OPENVPN: openvpn,
229 AsusData.FLAGS: flags,
230 }
231
232
233 def process_boottime(
234 devicemap: dict[str, Any], prev_boottime: dict[str, Any] | None
235 ) -> tuple[dict[str, Any], bool]:
236 """Process boottime data."""
237
238 # Reboot flag
239 reboot = False
240
241 boottime: dict[str, Any] = {}
242
243 # Since precision is 1 second, could be that old and new
244 # are 1 sec different. In this case, we should not change
245 # the boot time, but keep the previous value to avoid regular changes
246 sys = devicemap.get("sys")
247 if sys:
248 uptime_str = sys.get("uptimeStr")
249 _LOGGER.debug("Uptime string: %s", uptime_str)
250 if uptime_str:
251 time, seconds = read_uptime_string(uptime_str)
252 if time:
253 boottime["datetime"] = time
254 if prev_boottime and "datetime" in prev_boottime:
255 delta = time - prev_boottime["datetime"]
256
257 # Check for reboot
258 if abs(delta.seconds) >= 2 and delta.seconds >= 0: # noqa: PLR2004
259 reboot = True
260 else:
261 boottime = prev_boottime
262
263 boottime["uptime"] = seconds
264
265 return boottime, reboot
266
267
268 def process_ovpn(devicemap: dict[str, Any]) -> dict[str, Any]:
269 """Process OpenVPN data."""
270
271 vpn: dict[str, Any] = {
272 "client": {},
273 "server": {},
274 }
275 vpnmap = devicemap.get("vpn")
276
277 if vpnmap:
278 # There are only 5 clients actually in the current firmware
279 # but we in case it will be ever changed in the future
280 for num in range(1, 10):
281 # Check if this client exists
282 if f"client{num}_state" not in vpnmap:
283 break
284
285 # Get client data
286 # We define default state as 0, since it's not always present
287 client_state = AsusOVPNClient(
288 safe_int(vpnmap.get(f"client{num}_state"), default=0)
289 )
290 client_errno = safe_int(vpnmap.get(f"client{num}_errno"))
291
292 # Assign client data
293 vpn["client"][num] = {
294 "state": client_state,
295 "errno": client_errno,
296 }
297
298 # Server data. Usually only 2 servers
299 # but we in case it will be ever changed in the future
300 for num in range(1, 5):
301 # Check if this server exists
302 if f"server{num}_state" not in vpnmap:
303 break
304
305 # Get server data
306 # We define default state as 0, since it's not always present
307 server_state = AsusOVPNServer(
308 safe_int(vpnmap.get(f"server{num}_state"), default=0)
309 )
310
311 # Assign server data
312 vpn["server"][num] = {
313 "state": server_state,
314 }
315
316 return vpn