Debian Codegraph @

asusrouter/modules/client.py

raw
1 """Client module for AsusRouter."""
2
3 from __future__ import annotations
4
5 from dataclasses import dataclass
6 from datetime import datetime
7 from typing import Any
8
9 from asusrouter.modules.connection import (
10 ConnectionState,
11 ConnectionType,
12 InternetMode,
13 get_connection_type,
14 get_internet_mode,
15 )
16 from asusrouter.modules.const import MapValueType
17 from asusrouter.modules.ip_address import IPAddressType, read_ip_address_type
18 from asusrouter.modules.vendor import replace_vendor
19 from asusrouter.tools.converters import (
20 safe_bool,
21 safe_float,
22 safe_int,
23 safe_time_from_delta,
24 safe_unpack_key,
25 )
26
27
28 @dataclass
29 class AsusClient:
30 """Client class."""
31
32 state: ConnectionState = ConnectionState.UNKNOWN
33
34 description: AsusClientDescription | None = None
35
36 connection: AsusClientConnection | None = None
37
38
39 @dataclass
40 class AsusClientConnection:
41 """Connection class."""
42
43 type: ConnectionType = ConnectionType.DISCONNECTED
44 ip_address: str | None = None
45 ip_method: str | None = None
46 internet_state: bool | None = None
47 internet_mode: InternetMode = InternetMode.UNKNOWN
48 node: str | None = None
49 online: bool = False
50
51 # Is an AiMesh node
52 aimesh: bool | None = None
53
54
55 @dataclass
56 class AsusClientConnectionWlan(AsusClientConnection):
57 """WLAN connection class."""
58
59 guest: bool | None = None
60 guest_id: int | None = None
61 rssi: int | None = None
62 since: datetime | None = None
63 rx_speed: float | None = None
64 tx_speed: float | None = None
65
66
67 @dataclass
68 class AsusClientDescription:
69 """Client description class."""
70
71 name: str | None = None
72 mac: str | None = None
73
74 vendor: str | None = None
75
76
77 CLIENT_MAP: dict[str, list[MapValueType]] = {
78 "connected_since": [
79 ("wlConnectTime", safe_time_from_delta),
80 ],
81 "connection_type": [
82 ("connection_type"),
83 ("isWL", safe_int),
84 ],
85 "guest": [
86 ("guest"),
87 ("isGN", safe_int),
88 ],
89 "internet_mode": [
90 ("internetMode", get_internet_mode),
91 ],
92 "internet_state": [
93 ("internetState", safe_bool),
94 ],
95 "ip": [
96 ("ip"),
97 ],
98 "ip_method": [
99 ("ipMethod"),
100 ],
101 "mac": [
102 ("mac"),
103 ],
104 "name": [
105 ("nickName"),
106 ("name"),
107 ("mac"),
108 ],
109 "node": [
110 ("node"),
111 ],
112 "online": [
113 ("online"),
114 ("isOnline", safe_bool),
115 ],
116 "rssi": [
117 ("rssi", safe_int),
118 ],
119 "rx_speed": [
120 ("curRx", safe_float),
121 ],
122 "tx_speed": [
123 ("curTx", safe_float),
124 ],
125 }
126
127 CLIENT_MAP_DESCRIPTION: dict[str, list[MapValueType]] = {
128 "name": [
129 ("nickName"),
130 ("name"),
131 ("mac"),
132 ],
133 "mac": [
134 ("mac"),
135 ],
136 "vendor": [
137 ("vendor", replace_vendor),
138 ],
139 }
140
141 CLIENT_MAP_CONNECTION: dict[str, list[MapValueType]] = {
142 "type": [
143 ("connection_type", get_connection_type),
144 ("isWL", get_connection_type),
145 ],
146 "ip_address": [
147 ("ip"),
148 ],
149 "ip_method": [
150 ("ipMethod", read_ip_address_type),
151 ],
152 "internet_state": [
153 ("internetState", safe_bool),
154 ],
155 "internet_mode": [
156 ("internetMode", get_internet_mode),
157 ],
158 "node": [
159 ("node"),
160 ],
161 "online": [
162 ("online", safe_bool),
163 ("isOnline", safe_bool),
164 ],
165 "aimesh": [
166 ("amesh_isRe", safe_bool),
167 ],
168 }
169
170 CLIENT_MAP_CONNECTION_WLAN: dict[str, list[MapValueType]] = {
171 "guest_id": [
172 ("guest"),
173 ("isGN", safe_int),
174 ],
175 "rssi": [
176 ("rssi", safe_int),
177 ],
178 "since": [
179 ("wlConnectTime", safe_time_from_delta),
180 ],
181 "rx_speed": [
182 ("curRx", safe_float),
183 ],
184 "tx_speed": [
185 ("curTx", safe_float),
186 ],
187 }
188
189
190 def process_client(
191 data: dict[str, Any], history: AsusClient | None = None, **kwargs: Any
192 ) -> AsusClient:
193 """
194 Process client data.
195
196 Parameters:
197 data (dict[str, Any]): The client data to process.
198 history (Optional[AsusClient]): The previous state of the client, if any.
199
200 Returns:
201 AsusClient: The processed client data.
202 """
203
204 description: AsusClientDescription = process_client_description(data)
205 connection: AsusClientConnection | AsusClientConnectionWlan = (
206 process_client_connection(data)
207 )
208
209 state: ConnectionState = process_client_state(connection, **kwargs)
210
211 # Clean disconnected client
212 if state != ConnectionState.CONNECTED:
213 connection = process_disconnected(connection)
214
215 # Check history for the oscillating values
216 if history is not None and history.connection is not None:
217 connection = process_history(connection, history.connection)
218
219 return AsusClient(
220 state=state, description=description, connection=connection
221 )
222
223
224 def process_data(
225 data: dict[str, Any], mapping: dict[str, Any], obj: Any
226 ) -> Any:
227 """Process data based on a mapping and set attributes on an object."""
228
229 # Go through all keys in mapping
230 for key, value in mapping.items():
231 for pair in value:
232 # Get the search key and converter(s)
233 key_to_find, converters = safe_unpack_key(pair)
234 # Get the value from the data
235 item = data.get(key_to_find)
236
237 # Process the value if it's an actual value
238 if item is not None and item != "":
239 # Apply converters one by one if there are multiple
240 if isinstance(converters, list):
241 for converter in converters:
242 item = converter(item)
243 # Apply single converter
244 elif converters:
245 item = converters(item)
246
247 # Set the attribute on the object
248 setattr(obj, key, item)
249
250 # We found the value, no need to continue searching
251 break
252
253 return obj
254
255
256 def process_client_description(data: dict[str, Any]) -> AsusClientDescription:
257 """Process client description data."""
258
259 return process_data(data, CLIENT_MAP_DESCRIPTION, AsusClientDescription())
260
261
262 def process_client_connection(data: dict[str, Any]) -> AsusClientConnection:
263 """Process client connection data."""
264
265 connection = process_data(
266 data, CLIENT_MAP_CONNECTION, AsusClientConnection()
267 )
268
269 if connection.type not in (
270 ConnectionType.WIRED,
271 ConnectionType.DISCONNECTED,
272 ):
273 connection = process_client_connection_wlan(data, connection)
274
275 return connection
276
277
278 def process_client_connection_wlan(
279 data: dict[str, Any], base_connection: AsusClientConnection
280 ) -> AsusClientConnectionWlan:
281 """Process WLAN client connection data."""
282
283 wlan_connection = AsusClientConnectionWlan(**base_connection.__dict__)
284 wlan_connection = process_data(
285 data, CLIENT_MAP_CONNECTION_WLAN, wlan_connection
286 )
287
288 # Mark `guest` attribute if `guest_id` is non-zero
289 wlan_connection.guest = (
290 wlan_connection.guest_id != 0 and wlan_connection.guest_id is not None
291 )
292
293 return wlan_connection
294
295
296 def process_client_state(
297 connection: AsusClientConnection,
298 **kwargs: Any,
299 ) -> ConnectionState:
300 """Process client state."""
301
302 # If no IP address or type is disconnected, it's disconnected
303 if (
304 connection.ip_address is None
305 or connection.type == ConnectionType.DISCONNECTED
306 ):
307 return ConnectionState.DISCONNECTED
308
309 # If client is an AiMesh node, it's not a client
310 if connection.aimesh is True:
311 return ConnectionState.DISCONNECTED
312
313 # If we have support for AiMesh but no node, client is disconnected
314 aimesh = kwargs.get("aimesh", False)
315 if aimesh is True and connection.node is None:
316 return ConnectionState.DISCONNECTED
317
318 # This one is a weak check, should always be the last one
319 if connection.online is True:
320 return ConnectionState.CONNECTED
321
322 return ConnectionState.DISCONNECTED
323
324
325 def process_disconnected(
326 connection: AsusClientConnection,
327 ) -> AsusClientConnection:
328 """Process disconnected client."""
329
330 # We keep values set by the user:
331 # - internet mode
332 # - ip method
333 # - ip address if ip method is static
334 return AsusClientConnection(
335 type=ConnectionType.DISCONNECTED,
336 ip_address=connection.ip_address
337 if connection.ip_method == IPAddressType.STATIC
338 else None,
339 ip_method=connection.ip_method,
340 internet_mode=connection.internet_mode,
341 )
342
343
344 def process_history(
345 connection: AsusClientConnection, history: AsusClientConnection
346 ) -> AsusClientConnection:
347 """Process values from history to avoid oscillating values."""
348
349 # Wireless connection
350 if (
351 isinstance(connection, AsusClientConnectionWlan)
352 and isinstance(history, AsusClientConnectionWlan)
353 and connection.since is not None
354 and history.since is not None
355 ):
356 # Fix the oscillating connection time: ignore any value less
357 # than 10 seconds. This comes from the device itself and cannot
358 # be fixed from AsusRouter side.
359 diff = abs((history.since - connection.since).total_seconds())
360 if diff < 10: # noqa: PLR2004
361 connection.since = history.since
362
363 return connection