Debian Codegraph @

asusrouter/modules/identity.py

raw
1 """Identity module.
2
3 This module contains all the classes and method to handle
4 the identity of an Asus device.
5 """
6
7 from __future__ import annotations
8
9 from collections.abc import Awaitable, Callable
10 from dataclasses import dataclass
11 from itertools import chain
12 import logging
13 from typing import Any
14
15 from asusrouter.error import AsusRouterIdentityError
16 from asusrouter.modules.aimesh import AiMeshDevice
17 from asusrouter.modules.color import color_zone
18 from asusrouter.modules.data import AsusData
19 from asusrouter.modules.endpoint import (
20 Endpoint,
21 EndpointNoCheck,
22 EndpointTools,
23 EndpointType,
24 check_available,
25 )
26 from asusrouter.modules.endpoint.onboarding import (
27 process as process_onboarding,
28 read as read_onboarding,
29 )
30 from asusrouter.modules.firmware import Firmware
31 from asusrouter.modules.wlan import WLAN_TYPE, Wlan
32 from asusrouter.tools import writers
33 from asusrouter.tools.cleaners import clean_dict
34 from asusrouter.tools.converters import (
35 safe_exists,
36 safe_list_from_string,
37 safe_unpack_keys,
38 )
39
40 _LOGGER = logging.getLogger(__name__)
41
42 MAP_IDENTITY: tuple = (
43 ("serial_no", "serial"),
44 ("label_mac", "mac"),
45 ("lan_hwaddr", "lan_mac"),
46 ("wan_hwaddr", "wan_mac"),
47 ("productid", "product_id"),
48 ("productid", "model"),
49 ("firmver", "fw_major"),
50 ("buildno", "fw_minor"),
51 ("extendno", "fw_build"),
52 ("rc_support", "services", safe_list_from_string),
53 ("ss_support", "services", safe_list_from_string),
54 ("led_val", "led", safe_exists),
55 ("ledg_rgb1", "aura", safe_exists),
56 ("ledg_rgb2", "aura_zone", color_zone),
57 )
58
59
60 @dataclass
61 class AsusDevice: # pylint: disable=too-many-instance-attributes
62 """Asus device class.
63
64 This class contains information about an Asus device
65 and can represent a router, AiMesh nore or range extender.
66 """
67
68 # Device-defining values
69 serial: str | None = None
70 mac: str | None = None
71 product_id: str | None = None
72 model: str | None = None
73 brand: str = "ASUSTek"
74
75 # Supported features
76 aimesh: bool = False
77
78 # Device information
79 firmware: Firmware | None = None
80 merlin: bool = False
81 wlan: list[Wlan] | None = None
82 endpoints: dict[EndpointType, bool] | None = None
83 services: list[str] | None = None
84
85 # Flags for device features
86 aura: bool = False
87 aura_zone: int = 0
88 dsl: bool = False
89 led: bool = False
90 ookla: bool = False
91 vpn_status: bool = False
92
93
94 async def collect_identity(
95 api_hook: Callable[..., Awaitable[dict[str, Any]]],
96 api_query: Callable[..., Awaitable[Any]],
97 ) -> AsusDevice:
98 """Collect device identity."""
99
100 _LOGGER.debug("Collecting device identity")
101
102 # Prepare a request
103 request_values = []
104 for map_item in MAP_IDENTITY:
105 key, _, _ = safe_unpack_keys(map_item)
106 request_values.append(key)
107 request = writers.nvram(request_values)
108
109 # Get the identity data
110 try:
111 identity_map = await api_hook(request)
112 except Exception as ex: # pylint: disable=broad-except
113 raise AsusRouterIdentityError(
114 "Failed to collect identity data from the router"
115 ) from ex
116 _LOGGER.debug("Identity collected")
117
118 # Read the identity
119 identity = _read_nvram(identity_map)
120 _LOGGER.debug("Identity read")
121
122 # Process services
123 identity["aimesh"] = "amas" in identity["services"]
124
125 # Check endpoints
126 endpoints, onboarding = await _check_endpoints(api_query)
127 identity["endpoints"] = endpoints
128 _LOGGER.debug("Endpoints checked")
129 # Manually assign Aura endpoint value
130 identity["endpoints"][EndpointTools.AURA] = identity.get("aura", False)
131
132 # Check onboarding to get nice model name
133 this_device = onboarding.get(identity["mac"])
134 if isinstance(this_device, AiMeshDevice):
135 identity["model"] = this_device.model
136
137 # Check if DSL
138 if endpoints[Endpoint.DSL] is True:
139 identity["dsl"] = True
140 _LOGGER.debug("DSL-compatible device detected")
141
142 # Check if Merlin
143 if endpoints[Endpoint.SYSINFO] is True:
144 identity["merlin"] = True
145 _LOGGER.debug("Merlin FW detected")
146
147 # Return the identity convered from a dict
148 return AsusDevice(**identity)
149
150
151 # UPDATE THIS METHOD
152 def _read_nvram(data: dict[str, Any]) -> dict[str, Any]: # noqa: C901, PLR0912
153 """Read the NVRAM identity data."""
154
155 # Check the input data
156 if not data:
157 raise AsusRouterIdentityError("No nvram data received")
158
159 # Create the identity dictionary
160 identity: dict[str, Any] = {}
161
162 # Loop through the identity map
163 for map_item in MAP_IDENTITY:
164 key, key_to_use, method = safe_unpack_keys(map_item)
165 try:
166 value = method(data[key]) if method else data[key]
167 if key_to_use in identity:
168 if isinstance(identity[key_to_use], list):
169 identity[key_to_use].extend(value)
170 else:
171 identity[key_to_use] = value
172 else:
173 identity[key_to_use] = value
174 except Exception as ex:
175 raise ex
176
177 # Clean up the identity dictionary
178 identity = clean_dict(identity)
179
180 # MAC (for some Merlin firmwares missing label_mac)
181 if not identity.get("mac"):
182 if identity.get("lan_mac"):
183 identity["mac"] = identity["lan_mac"]
184 elif identity.get("wan_mac"):
185 identity["mac"] = identity["wan_mac"]
186 # Remove extra MACs
187 identity.pop("lan_mac")
188 identity.pop("wan_mac")
189
190 # Firmware
191 # TODO: Optimize this
192 firmware = Firmware(
193 f"{identity['fw_major']}.{identity['fw_minor']}.{identity['fw_build']}"
194 )
195 identity["firmware"] = firmware
196 identity.pop("fw_major")
197 identity.pop("fw_minor")
198 identity.pop("fw_build")
199
200 # WLAN list
201 identity["wlan"] = []
202 for value in identity["services"]:
203 if value in WLAN_TYPE:
204 identity["wlan"].append(WLAN_TYPE[value])
205
206 # OOKLA Speedtest
207 if "ookla" in identity["services"]:
208 identity["ookla"] = True
209
210 return identity
211
212
213 async def _check_endpoints(
214 api_hook: Callable[..., Awaitable[Any]],
215 ) -> tuple[dict[EndpointType, bool], dict[str, Any]]:
216 """Check which endpoints are available."""
217
218 endpoints: dict[EndpointType, bool] = {}
219 contents: dict[EndpointType, Any] = {}
220
221 for endpoint in chain(Endpoint, EndpointTools):
222 if endpoint.name in EndpointNoCheck.__members__:
223 continue
224 result, content = await check_available(endpoint, api_hook)
225 endpoints[endpoint] = result
226 contents[endpoint] = content
227
228 onboarding = {}
229 if endpoints[Endpoint.ONBOARDING] is True:
230 onboarding = process_onboarding(
231 read_onboarding(contents[Endpoint.ONBOARDING])
232 ).get(AsusData.AIMESH, {})
233
234 return (endpoints, onboarding)