Debian Codegraph @

airos/data.py

raw
1 """Provide mashumaro data object for AirOSData."""
2
3 from dataclasses import dataclass
4 from enum import Enum
5 import ipaddress
6 import logging
7 import re
8 from typing import Any
9
10 from mashumaro import DataClassDictMixin
11 from mashumaro.config import BaseConfig
12
13 logger = logging.getLogger(__name__)
14
15 # Regex for a standard MAC address format (e.g., 01:23:45:67:89:AB)
16 # This handles both colon and hyphen separators.
17 MAC_ADDRESS_REGEX = re.compile(r"^([0-9a-fA-F]{2}[:-]){5}([0-9a-fA-F]{2})$")
18
19 # Regex for a MAC address mask (e.g., the redacted format 00:00:00:00:89:AB)
20 MAC_ADDRESS_MASK_REGEX = re.compile(r"^(00:){4}[0-9a-fA-F]{2}[:-][0-9a-fA-F]{2}$")
21
22
23 # Helper functions
24 def is_mac_address(value: str) -> bool:
25 """Check if a string is a valid MAC address."""
26 return bool(MAC_ADDRESS_REGEX.match(value))
27
28
29 def is_mac_address_mask(value: str) -> bool:
30 """Check if a string is a valid MAC address mask (e.g., the redacted format)."""
31 return bool(MAC_ADDRESS_MASK_REGEX.match(value))
32
33
34 def is_ip_address(value: str) -> bool:
35 """Check if a string is a valid IPv4 or IPv6 address."""
36 try:
37 ipaddress.ip_address(value)
38 except ValueError:
39 return False
40 return True # pragma: no cover
41
42
43 def redact_data_smart(data: dict[str, Any]) -> dict[str, Any]:
44 """Recursively redacts sensitive keys in a dictionary."""
45 sensitive_keys = {
46 "hostname",
47 "essid",
48 "mac",
49 "apmac",
50 "hwaddr",
51 "lastip",
52 "ipaddr",
53 "ip6addr",
54 "device_id",
55 "sys_id",
56 "station_id",
57 "platform",
58 }
59
60 def _redact(d: dict[str, Any]) -> dict[str, Any]:
61 redacted_d = {}
62 for k, v in d.items():
63 if k in sensitive_keys:
64 if isinstance(v, str) and (is_mac_address(v) or is_mac_address_mask(v)):
65 # Redact only the last part of a MAC address to a dummy value
66 redacted_d[k] = "00:11:22:33:" + v.replace("-", ":").upper()[-5:]
67 elif isinstance(v, str) and is_ip_address(v): # pragma: no cover
68 # Redact to a dummy local IP address
69 redacted_d[k] = "127.0.0.3"
70 elif isinstance(v, list) and all(
71 isinstance(i, str) and is_ip_address(i) for i in v
72 ): # pragma: no cover
73 # Redact list of IPs to a dummy list
74 redacted_d[k] = ["127.0.0.3"] # type: ignore[assignment]
75 elif isinstance(v, list) and all(
76 isinstance(i, dict) and "addr" in i and is_ip_address(i["addr"])
77 for i in v
78 ): # pragma: no cover
79 # Redact list of dictionaries with IP addresses to a dummy list
80 redacted_list = []
81 for item in v:
82 redacted_item = item.copy()
83 redacted_item["addr"] = (
84 "127.0.0.3"
85 if ipaddress.ip_address(redacted_item["addr"]).version == 4
86 else "::1"
87 )
88 redacted_list.append(redacted_item)
89 redacted_d[k] = redacted_list # type: ignore[assignment]
90 else:
91 redacted_d[k] = "REDACTED"
92 elif isinstance(v, dict):
93 redacted_d[k] = _redact(v) # type: ignore[assignment]
94 elif isinstance(v, list):
95 redacted_d[k] = [
96 _redact(item) if isinstance(item, dict) else item for item in v
97 ] # type: ignore[assignment]
98 else:
99 redacted_d[k] = v
100 return redacted_d
101
102 return _redact(data)
103
104
105 class AirOSDataClass(DataClassDictMixin):
106 """A base class for all mashumaro dataclasses."""
107
108
109 @dataclass
110 class AirOSDataBaseClass(AirOSDataClass):
111 """Base class for all AirOS data models."""
112
113 class Config(BaseConfig):
114 """Create base class for multiple version support."""
115
116 alias_generator = str.upper
117
118
119 def _check_and_log_unknown_enum_value(
120 data_dict: dict[str, Any],
121 key: str,
122 enum_class: type[Enum],
123 dataclass_name: str,
124 field_name: str,
125 ) -> None:
126 """Clean unsupported parameters with logging."""
127 value = data_dict.get(key)
128 if value is not None and isinstance(value, str):
129 if value not in [e.value for e in enum_class]:
130 logger.warning(
131 "Unknown value '%s' for %s.%s. Please report at "
132 "https://github.com/CoMPaTech/python-airos/issues so we can add support.",
133 value,
134 dataclass_name,
135 field_name,
136 )
137 del data_dict[key]
138
139
140 class IeeeMode(Enum):
141 """Enum definition."""
142
143 AUTO = "AUTO"
144 _11ACVHT80 = "11ACVHT80" # On a NanoStation
145 _11ACVHT60 = "11ACVHT60"
146 _11ACVHT50 = "11ACVHT50"
147 _11ACVHT40 = "11ACVHT40"
148 _11ACVHT20 = "11ACVHT20" # On a LiteBeam
149 _11NAHT40MINUS = "11NAHT40MINUS" # On a v6 XM
150 _11NAHT40PLUS = "11NAHT40PLUS" # On a v6 XW
151 _11NGHT20 = "11NGHT20" # On a v6 XM 900 MHz device (NanoStation loco M900)
152 # More to be added when known
153
154
155 class DerivedWirelessRole(Enum):
156 """Enum definition."""
157
158 STATION = "station"
159 ACCESS_POINT = "access_point"
160
161
162 class DerivedWirelessMode(Enum):
163 """Enum definition."""
164
165 PTP = "point_to_point"
166 PTMP = "point_to_multipoint"
167
168
169 class WirelessMode(Enum):
170 """Enum definition."""
171
172 PTMP_ACCESSPOINT = "ap-ptmp"
173 PTMP_STATION = "sta-ptmp"
174 PTP_ACCESSPOINT = "ap-ptp"
175 PTP_STATION = "sta-ptp"
176 UNKNOWN = "unknown" # Reported on v8.7.18 NanoBeam 5AC for remote.mode
177 # More to be added when known
178
179
180 class Wireless6Mode(Enum):
181 """Enum definition."""
182
183 STATION = "sta"
184 ACCESSPOINT = "ap"
185 # More to be added when known
186
187
188 class Security(Enum):
189 """Enum definition."""
190
191 NONE = "none"
192 WPA2 = "WPA2"
193 # More to be added when known
194
195
196 class NetRole(Enum):
197 """Enum definition."""
198
199 BRIDGE = "bridge"
200 ROUTER = "router"
201 # More to be added when known
202
203
204 @dataclass
205 class ChainName(AirOSDataClass):
206 """Leaf definition."""
207
208 number: int
209 name: str
210
211
212 @dataclass
213 class Host(AirOSDataClass):
214 """Leaf definition."""
215
216 hostname: str
217 uptime: int
218 power_time: int
219 time: str
220 timestamp: int
221 fwversion: str
222 devmodel: str
223 netrole: NetRole
224 loadavg: float | int | None
225 totalram: int
226 freeram: int
227 temperature: int
228 cpuload: float | int | None
229 device_id: str
230 height: int | None # Reported none on LiteBeam 5AC
231
232 @classmethod
233 def __pre_deserialize__(cls, d: dict[str, Any]) -> dict[str, Any]:
234 """Pre-deserialize hook for Host."""
235 _check_and_log_unknown_enum_value(d, "netrole", NetRole, "Host", "netrole")
236 return d
237
238
239 @dataclass
240 class Host6(AirOSDataClass):
241 """Leaf definition."""
242
243 hostname: str
244 uptime: int
245 fwversion: str
246 fwprefix: str
247 devmodel: str
248 netrole: NetRole
249 totalram: int
250 freeram: int
251 cpuload: float | int | None
252 cputotal: float | int | None # Reported on XM firmware
253 cpubusy: float | int | None # Reported on XM firmware
254
255 @classmethod
256 def __pre_deserialize__(cls, d: dict[str, Any]) -> dict[str, Any]:
257 """Pre-deserialize hook for Host."""
258 _check_and_log_unknown_enum_value(d, "netrole", NetRole, "Host", "netrole")
259
260 # Calculate cpufloat from actuals instead on relying on near 100% value
261 if (
262 all(isinstance(d.get(k), (int, float)) for k in ("cpubusy", "cputotal"))
263 and d["cputotal"] > 0
264 ):
265 d["cpuload"] = round((d["cpubusy"] / d["cputotal"]) * 100, 2)
266 return d
267
268
269 @dataclass
270 class Services(AirOSDataClass):
271 """Leaf definition."""
272
273 dhcpc: bool
274 dhcpd: bool
275 dhcp6d_stateful: bool
276 pppoe: bool
277 airview: int
278
279
280 @dataclass
281 class Services6(AirOSDataClass):
282 """Leaf definition."""
283
284 dhcpc: bool
285 dhcpd: bool
286 pppoe: bool
287
288
289 @dataclass
290 class Airview6(AirOSDataClass):
291 """Leaf definition."""
292
293 enabled: int
294
295
296 @dataclass
297 class Firewall(AirOSDataClass):
298 """Leaf definition."""
299
300 iptables: bool
301 ebtables: bool
302 ip6tables: bool
303 eb6tables: bool
304
305
306 @dataclass
307 class Throughput(AirOSDataClass):
308 """Leaf definition."""
309
310 tx: int
311 rx: int
312
313
314 @dataclass
315 class ServiceTime(AirOSDataClass):
316 """Leaf definition."""
317
318 time: int
319 link: int
320
321
322 @dataclass
323 class Polling(AirOSDataClass):
324 """Leaf definition."""
325
326 cb_capacity: int
327 dl_capacity: int
328 ul_capacity: int
329 use: int
330 tx_use: int
331 rx_use: int
332 atpc_status: int
333 fixed_frame: bool
334 gps_sync: bool
335 ff_cap_rep: bool
336 flex_mode: int | None = None # Not present in all devices
337
338
339 @dataclass
340 class Polling6(AirOSDataClass):
341 """Leaf definition."""
342
343 dl_capacity: int | None = None # New
344 ul_capacity: int | None = None # New
345
346
347 @dataclass
348 class Stats(AirOSDataClass):
349 """Leaf definition."""
350
351 rx_bytes: int
352 rx_packets: int
353 rx_pps: int
354 tx_bytes: int
355 tx_packets: int
356 tx_pps: int
357
358
359 @dataclass
360 class EvmData(AirOSDataClass):
361 """Leaf definition."""
362
363 usage: int
364 cinr: int
365 evm: list[list[int]]
366
367
368 @dataclass
369 class Airmax(AirOSDataClass):
370 """Leaf definition."""
371
372 actual_priority: int
373 beam: int
374 desired_priority: int
375 cb_capacity: int
376 dl_capacity: int
377 ul_capacity: int
378 atpc_status: int
379 rx: EvmData
380 tx: EvmData
381
382
383 @dataclass
384 class EthList(AirOSDataClass):
385 """Leaf definition."""
386
387 ifname: str
388 enabled: bool
389 plugged: bool
390 duplex: bool
391 speed: int
392 snr: list[int]
393 cable_len: int
394
395
396 @dataclass
397 class GPSData(AirOSDataClass):
398 """Leaf definition."""
399
400 lat: float | int | None = None
401 lon: float | int | None = None
402 fix: int | None = None
403 sats: int | None = None # LiteAP GPS
404 dim: int | None = None # LiteAP GPS
405 dop: float | int | None = None # LiteAP GPS
406 alt: float | int | None = None # LiteAP GPS
407 time_synced: int | None = None # LiteAP GPS
408
409
410 @dataclass
411 class UnmsStatus(AirOSDataClass):
412 """Leaf definition."""
413
414 status: int
415 timestamp: str | None = None
416
417
418 @dataclass
419 class Remote(AirOSDataClass):
420 """Leaf definition."""
421
422 device_id: str
423 hostname: str
424 platform: str
425 version: str
426 time: str
427 cpuload: float | int | None
428 temperature: int
429 totalram: int
430 freeram: int
431 netrole: str
432 sys_id: str
433 tx_throughput: int
434 rx_throughput: int
435 uptime: int
436 power_time: int
437 compat_11n: int
438 signal: int
439 rssi: int
440 noisefloor: int
441 tx_power: int
442 distance: int # In meters
443 rx_chainmask: int
444 chainrssi: list[int]
445 tx_ratedata: list[int]
446 tx_bytes: int
447 rx_bytes: int
448 cable_loss: int
449 ethlist: list[EthList]
450 ipaddr: list[str]
451 oob: bool
452 unms: UnmsStatus
453 airview: int
454 service: ServiceTime
455 mode: WirelessMode | None = None # Investigate why remotes can have no mode set
456 ip6addr: list[str] | None = None # For v4 only devices
457 height: int | None = None
458 age: int | None = None # At least not present on 8.7.11
459 gps: GPSData | None = (
460 None # Reported NanoStation 5AC 8.7.18 without GPS Core 150491
461 )
462 antenna_gain: int | None = None # Reported on Prism 6.3.5? and LiteBeam 8.7.8
463
464 @classmethod
465 def __pre_deserialize__(cls, d: dict[str, Any]) -> dict[str, Any]:
466 """Pre-deserialize hook for Wireless."""
467 _check_and_log_unknown_enum_value(d, "mode", WirelessMode, "Remote", "mode")
468 return d
469
470
471 @dataclass
472 class Disconnected(AirOSDataClass):
473 """Leaf definition for disconnected devices."""
474
475 mac: str
476 lastip: str
477 hostname: str
478 platform: str
479 reason_code: int
480 disconnect_duration: int
481 airos_connected: bool = False # Mock add to determine Disconnected vs Station
482 signal: int | None = None # Litebeam 5AC can have no signal
483
484
485 @dataclass
486 class Station(AirOSDataClass):
487 """Leaf definition for connected/active devices."""
488
489 mac: str
490 lastip: str
491 signal: int
492 rssi: int
493 noisefloor: int
494 chainrssi: list[int]
495 tx_idx: int
496 rx_idx: int
497 tx_nss: int
498 rx_nss: int
499 tx_latency: int
500 distance: int # In meters
501 tx_packets: int
502 tx_lretries: int
503 tx_sretries: int
504 uptime: int
505 dl_signal_expect: int
506 ul_signal_expect: int
507 cb_capacity_expect: int
508 dl_capacity_expect: int
509 ul_capacity_expect: int
510 dl_rate_expect: int
511 ul_rate_expect: int
512 dl_linkscore: int
513 ul_linkscore: int
514 dl_avg_linkscore: int
515 ul_avg_linkscore: int
516 tx_ratedata: list[int]
517 stats: Stats
518 airmax: Airmax
519 last_disc: int
520 remote: Remote
521 airos_connected: bool = True # Mock add to determine Disconnected vs Station
522
523
524 @dataclass
525 class Wireless(AirOSDataClass):
526 """Leaf definition."""
527
528 essid: str
529 band: int
530 compat_11n: int
531 hide_essid: int
532 apmac: str
533 frequency: int
534 center1_freq: int
535 dfs: int
536 distance: int # In meters
537 security: Security
538 noisef: int
539 txpower: int
540 aprepeater: bool
541 rstatus: int
542 chanbw: int
543 rx_chainmask: int
544 tx_chainmask: int
545 cac_state: int
546 cac_timeout: int
547 rx_idx: int
548 rx_nss: int
549 tx_idx: int
550 tx_nss: int
551 throughput: Throughput
552 service: ServiceTime
553 polling: Polling
554 count: int
555 sta: list[Station]
556 sta_disconnected: list[Disconnected]
557 ieeemode: IeeeMode
558 mode: WirelessMode | None = None # Investigate further (see WirelessMode in Remote)
559 nol_state: int | None = None # Reported on Prism 6.3.5? and LiteBeam 8.7.8
560 nol_timeout: int | None = None # Reported on Prism 6.3.5? and LiteBeam 8.7.8
561 antenna_gain: int | None = None # Reported on Prism 6.3.5? and LiteBeam 8.7.8
562
563 @classmethod
564 def __pre_deserialize__(cls, d: dict[str, Any]) -> dict[str, Any]:
565 """Pre-deserialize hook for Wireless."""
566
567 _check_and_log_unknown_enum_value(d, "mode", WirelessMode, "Wireless", "mode")
568
569 _check_and_log_unknown_enum_value(
570 d, "security", Security, "Wireless", "security"
571 )
572
573 # Ensure ieeemode/opmode are in uppercase and map opmode back into ieeemode
574 d["ieeemode"] = d["ieeemode"].upper() or None
575 _check_and_log_unknown_enum_value(
576 d, "ieeemode", IeeeMode, "Wireless", "ieeemode"
577 )
578
579 return d
580
581
582 @dataclass
583 class Wireless6(AirOSDataClass):
584 """Leaf definition."""
585
586 essid: str
587 hide_essid: int
588 apmac: str
589 countrycode: int
590 channel: int
591 frequency: int
592 dfs: int
593 opmode: str
594 antenna: str
595 chains: str
596 signal: int
597 rssi: int
598 noisef: int
599 txpower: int
600 ack: int
601 distance: int # In meters
602 ccq: int
603 txrate: str
604 rxrate: str
605 security: Security
606 qos: str
607 rstatus: int
608 cac_nol: int
609 nol_chans: int
610 wds: int
611 aprepeater: int # Not bool as v8
612 chanbw: int
613 polling: Polling6
614 ieeemode: IeeeMode # Virtual to match base/v8
615 mode: Wireless6Mode | None = None
616 antenna_gain: int | None = None # Virtual to match base/v8
617
618 @classmethod
619 def __pre_deserialize__(cls, d: dict[str, Any]) -> dict[str, Any]:
620 """Pre-deserialize hook for Wireless6."""
621 _check_and_log_unknown_enum_value(d, "mode", Wireless6Mode, "Wireless6", "mode")
622 _check_and_log_unknown_enum_value(
623 d, "security", Security, "Wireless", "security"
624 )
625
626 freq = d.get("frequency")
627 if isinstance(freq, str) and "MHz" in freq:
628 d["frequency"] = int(freq.split()[0])
629
630 rxrate = d.get("rxrate")
631 txrate = d.get("txrate")
632 d["polling"] = { # Map to Polling6 as MBPS strings to int kbps
633 "dl_capacity": int(float(rxrate) * 1000) if rxrate else 0,
634 "ul_capacity": int(float(txrate) * 1000) if txrate else 0,
635 }
636
637 d["ieeemode"] = d["opmode"].upper() or None
638 _check_and_log_unknown_enum_value(
639 d, "ieeemode", IeeeMode, "Wireless", "ieeemode"
640 )
641 match = re.search(r"(\d+)\s*dBi", d["antenna"])
642 d["antenna_gain"] = int(match.group(1)) if match else None
643
644 return d
645
646
647 @dataclass
648 class InterfaceStatus(AirOSDataClass):
649 """Leaf definition."""
650
651 plugged: bool
652 tx_bytes: int
653 rx_bytes: int
654 tx_packets: int
655 rx_packets: int
656 tx_errors: int
657 rx_errors: int
658 tx_dropped: int
659 rx_dropped: int
660 ipaddr: str
661 speed: int
662 duplex: bool
663 snr: list[int] | None = None
664 cable_len: int | None = None
665 ip6addr: list[dict[str, Any]] | None = None
666
667
668 @dataclass
669 class Interface6Status(AirOSDataClass):
670 """Leaf definition."""
671
672 duplex: bool
673 plugged: bool
674 speed: int
675 snr: list[int] | None = None
676 cable_len: int | None = None
677 ip6addr: list[dict[str, Any]] | None = None
678
679
680 @dataclass
681 class Interface(AirOSDataClass):
682 """Leaf definition."""
683
684 ifname: str
685 hwaddr: str
686 enabled: bool
687 status: InterfaceStatus
688 mtu: int
689
690
691 @dataclass
692 class Interface6(AirOSDataClass):
693 """Leaf definition."""
694
695 ifname: str
696 hwaddr: str
697 enabled: bool
698 status: Interface6Status
699 mtu: int | None = None # Reported unpresent on v6
700
701
702 @dataclass
703 class ProvisioningMode(AirOSDataClass):
704 """Leaf definition."""
705
706
707 @dataclass
708 class NtpClient(AirOSDataClass):
709 """Leaf definition."""
710
711
712 @dataclass
713 class GPSMain(AirOSDataClass):
714 """Leaf definition."""
715
716 lat: float | int | None
717 lon: float | int | None
718 fix: int
719
720
721 @dataclass
722 class Derived(AirOSDataClass):
723 """Contain custom data generated by this module."""
724
725 mac: str # Base device MAC address (i.e. eth0)
726 mac_interface: str # Interface derived from
727
728 # Split for WirelessMode
729 station: bool
730 access_point: bool
731
732 # Split for WirelessMode
733 ptp: bool
734 ptmp: bool
735
736 role: DerivedWirelessRole
737 mode: DerivedWirelessMode
738
739 # Lookup of model_id (presumed via SKU)
740 sku: str
741
742 # Firmware major version
743 fw_major: int | None = None
744
745
746 @dataclass
747 class AirOS8Data(AirOSDataBaseClass):
748 """Dataclass for AirOS v8 devices."""
749
750 chain_names: list[ChainName]
751 host: Host
752 genuine: str
753 services: Services
754 firewall: Firewall
755 portfw: bool
756 wireless: Wireless
757 interfaces: list[Interface]
758 provmode: Any
759 ntpclient: Any
760 unms: UnmsStatus
761 derived: Derived
762 gps: GPSData | None = (
763 None # Reported NanoStation 5AC 8.7.18 without GPS Core 150491
764 )
765
766
767 @dataclass
768 class AirOS6Data(AirOSDataBaseClass):
769 """Dataclass for AirOS v6 devices."""
770
771 airview: Airview6
772 host: Host6
773 genuine: str
774 services: Services6
775 firewall: Firewall
776 wireless: Wireless6
777 interfaces: list[Interface6]
778 unms: UnmsStatus
779 derived: Derived