| 1 |
"""Traffic module.""" |
| 2 |
|
| 3 |
from __future__ import annotations |
| 4 |
|
| 5 |
from enum import StrEnum |
| 6 |
import logging |
| 7 |
from typing import Any, Final |
| 8 |
|
| 9 |
from asusrouter.const import ( |
| 10 |
AR_CALL_GET_STATE, |
| 11 |
AR_CALL_TRANSLATE_STATE, |
| 12 |
HTTPStatus, |
| 13 |
) |
| 14 |
from asusrouter.modules.endpoint import ( |
| 15 |
EndpointTools, |
| 16 |
EndpointType, |
| 17 |
get_request_type, |
| 18 |
) |
| 19 |
from asusrouter.modules.source import ARDataSource |
| 20 |
from asusrouter.registry import ARCallableRegistry as ARCallReg |
| 21 |
from asusrouter.tools.converters import flatten_dict, safe_bool_nn |
| 22 |
from asusrouter.tools.enum import FromStrMixin |
| 23 |
from asusrouter.tools.identifiers import MacAddress |
| 24 |
from asusrouter.tools.readers import read_units_data_rate |
| 25 |
from asusrouter.tools.types import ARCallableType, ARCallbackType |
| 26 |
from asusrouter.tools.units import UnitOfDataRate |
| 27 |
from asusrouter.tools.writers import dict_to_request |
| 28 |
|
| 29 |
_LOGGER = logging.getLogger(__name__) |
| 30 |
|
| 31 |
# Initialize data rate readers once |
| 32 |
_read_kibps = read_units_data_rate(UnitOfDataRate.KIBIBIT_PER_SECOND) |
| 33 |
_read_Mibps = read_units_data_rate(UnitOfDataRate.MEBIBIT_PER_SECOND) # noqa: N816 |
| 34 |
|
| 35 |
_TRANSLATION_TABLE: dict[str, tuple[str, ARCallableType]] = { |
| 36 |
# Data rate / speed (current) |
| 37 |
"data_rx": ("rx_speed", _read_kibps), |
| 38 |
"data_tx": ("tx_speed", _read_kibps), |
| 39 |
# Data rate / speed (average) |
| 40 |
"data_avg_rx": ("rx_speed_avg", _read_kibps), |
| 41 |
"data_avg_tx": ("tx_speed_avg", _read_kibps), |
| 42 |
# Physical layer rate / speed |
| 43 |
"phy_rx": ("phy_rx", _read_Mibps), |
| 44 |
"phy_tx": ("phy_tx", _read_Mibps), |
| 45 |
# Status code |
| 46 |
"error_status": ("status", HTTPStatus.from_value), |
| 47 |
} |
| 48 |
|
| 49 |
|
| 50 |
class ARTrafficType(FromStrMixin, StrEnum): |
| 51 |
"""Traffic type.""" |
| 52 |
|
| 53 |
UNKNOWN = "unknown" |
| 54 |
|
| 55 |
BACKHAUL = "backhaul" |
| 56 |
ETHERNET = "ethernet" |
| 57 |
WIFI = "wifi" |
| 58 |
|
| 59 |
|
| 60 |
AR_TRAFFIC_SOURCE: Final[dict[ARTrafficType, EndpointType]] = { |
| 61 |
ARTrafficType.BACKHAUL: EndpointTools.TRAFFIC_BACKHAUL, |
| 62 |
ARTrafficType.ETHERNET: EndpointTools.TRAFFIC_ETHERNET, |
| 63 |
ARTrafficType.WIFI: EndpointTools.TRAFFIC_WIFI, |
| 64 |
} |
| 65 |
|
| 66 |
|
| 67 |
class ARTrafficSource(ARDataSource): |
| 68 |
"""Traffic data source.""" |
| 69 |
|
| 70 |
def __init__(self, target: Any, type: Any = None) -> None: |
| 71 |
"""Initialize the traffic source.""" |
| 72 |
|
| 73 |
super().__init__() |
| 74 |
|
| 75 |
self._target: MacAddress | None = None |
| 76 |
self._type: ARTrafficType = ARTrafficType.UNKNOWN |
| 77 |
|
| 78 |
# Try to set the target and type from input |
| 79 |
self.target = target |
| 80 |
self.type = type |
| 81 |
|
| 82 |
def __repr__(self) -> str: |
| 83 |
"""Representation of the traffic source.""" |
| 84 |
|
| 85 |
return f"<ARTrafficSource type=`{self.type}`>" |
| 86 |
|
| 87 |
@property |
| 88 |
def target(self) -> MacAddress | None: |
| 89 |
"""Get the target.""" |
| 90 |
|
| 91 |
return self._target |
| 92 |
|
| 93 |
@target.setter |
| 94 |
def target(self, value: Any) -> None: |
| 95 |
"""Set the target.""" |
| 96 |
|
| 97 |
try: |
| 98 |
self._target = MacAddress(value) |
| 99 |
except ValueError: |
| 100 |
self._target = None |
| 101 |
|
| 102 |
@property |
| 103 |
def type(self) -> ARTrafficType: |
| 104 |
"""Get the traffic type.""" |
| 105 |
|
| 106 |
return self._type |
| 107 |
|
| 108 |
@type.setter |
| 109 |
def type(self, type: ARTrafficType) -> None: |
| 110 |
"""Set the traffic type.""" |
| 111 |
|
| 112 |
self._type = ARTrafficType.from_value(type) |
| 113 |
|
| 114 |
|
| 115 |
class ARTrafficSourceEthernet(ARTrafficSource): |
| 116 |
"""Ethernet traffic source. |
| 117 |
|
| 118 |
This source provides data for: |
| 119 |
|
| 120 |
- LAN if `bh_flag` is `False` |
| 121 |
- Wired backhaul to the parent (if `bh_flag` is `True`) |
| 122 |
""" |
| 123 |
|
| 124 |
def __init__( |
| 125 |
self, target: Any, type: Any = None, bh_flag: Any = None |
| 126 |
) -> None: |
| 127 |
"""Initialize the Ethernet traffic source.""" |
| 128 |
|
| 129 |
super().__init__(target, type) |
| 130 |
self.type = ARTrafficType.ETHERNET |
| 131 |
|
| 132 |
self._bh_flag: bool |
| 133 |
self.bh_flag = bh_flag |
| 134 |
|
| 135 |
@property |
| 136 |
def bh_flag(self) -> bool: |
| 137 |
"""Get the backhaul flag.""" |
| 138 |
|
| 139 |
return self._bh_flag |
| 140 |
|
| 141 |
@bh_flag.setter |
| 142 |
def bh_flag(self, value: Any) -> None: |
| 143 |
"""Set the backhaul flag.""" |
| 144 |
|
| 145 |
self._bh_flag = safe_bool_nn(value) |
| 146 |
|
| 147 |
|
| 148 |
class ARTrafficSourceBetween(ARTrafficSource): |
| 149 |
"""Traffic source between two points.""" |
| 150 |
|
| 151 |
def __init__( |
| 152 |
self, target: Any, type: Any = None, towards: Any = None |
| 153 |
) -> None: |
| 154 |
"""Initialize the traffic source between two points.""" |
| 155 |
|
| 156 |
super().__init__(target, type) |
| 157 |
|
| 158 |
self._towards: MacAddress | None |
| 159 |
self.towards = towards |
| 160 |
|
| 161 |
@property |
| 162 |
def towards(self) -> MacAddress | None: |
| 163 |
"""Get the target MAC address.""" |
| 164 |
|
| 165 |
return self._towards |
| 166 |
|
| 167 |
@towards.setter |
| 168 |
def towards(self, value: Any) -> None: |
| 169 |
"""Set the target MAC address.""" |
| 170 |
|
| 171 |
try: |
| 172 |
self._towards = MacAddress(value) |
| 173 |
except ValueError: |
| 174 |
self._towards = None |
| 175 |
|
| 176 |
|
| 177 |
class ARTrafficSourceWiFi(ARTrafficSourceBetween): |
| 178 |
"""WiFi traffic source. |
| 179 |
|
| 180 |
Traffic of the router / node (`target`) on the specific |
| 181 |
wireless band (`towards`) defined by its MAC address. |
| 182 |
""" |
| 183 |
|
| 184 |
def __init__(self, target: Any, towards: Any) -> None: |
| 185 |
"""Initialize the WiFi traffic source.""" |
| 186 |
|
| 187 |
super().__init__(target, type=ARTrafficType.WIFI, towards=towards) |
| 188 |
self.type = ARTrafficType.WIFI |
| 189 |
|
| 190 |
|
| 191 |
class ARTrafficSourceBackhaul(ARTrafficSourceBetween): |
| 192 |
"""Backhaul traffic source. |
| 193 |
|
| 194 |
Traffic from the router / node (`target`) to the specific |
| 195 |
node (`towards`) defined by its MAC address. |
| 196 |
""" |
| 197 |
|
| 198 |
def __init__(self, target: Any, towards: Any) -> None: |
| 199 |
"""Initialize the backhaul traffic source.""" |
| 200 |
|
| 201 |
super().__init__(target, type=ARTrafficType.BACKHAUL, towards=towards) |
| 202 |
self.type = ARTrafficType.BACKHAUL |
| 203 |
|
| 204 |
|
| 205 |
def _check_state(source: Any) -> None: |
| 206 |
"""Check the state of the traffic source. |
| 207 |
|
| 208 |
This helper allows checking that all the required arguments |
| 209 |
are present and valid. |
| 210 |
""" |
| 211 |
|
| 212 |
# Is a traffic source |
| 213 |
if not isinstance(source, ARTrafficSource): |
| 214 |
raise TypeError(f"Expected `ARTrafficSource`, got `{type(source)}`") |
| 215 |
|
| 216 |
# Has target and type set |
| 217 |
if source.target is None: |
| 218 |
raise ValueError("Traffic source must have a `target` property set") |
| 219 |
if source.type == ARTrafficType.UNKNOWN: |
| 220 |
raise ValueError("Traffic source must have a `type` property set") |
| 221 |
|
| 222 |
# Has a `toward` property if required |
| 223 |
if isinstance(source, ARTrafficSourceBetween) and source.towards is None: |
| 224 |
raise ValueError( |
| 225 |
f"Traffic source of type `{source.type}` requires " |
| 226 |
"a `towards` property set" |
| 227 |
) |
| 228 |
|
| 229 |
|
| 230 |
async def get_state( |
| 231 |
callback: ARCallbackType, |
| 232 |
source: ARTrafficSource, |
| 233 |
**kwargs: Any, |
| 234 |
) -> Any: |
| 235 |
"""Get the state of the traffic source.""" |
| 236 |
|
| 237 |
# Check the input source |
| 238 |
_check_state(source) |
| 239 |
|
| 240 |
# Get the correct traffic endpoint |
| 241 |
endpoint: EndpointType | None = AR_TRAFFIC_SOURCE.get(source.type, None) |
| 242 |
if endpoint is None: |
| 243 |
raise ValueError( |
| 244 |
f"Cannot find endpoint for traffic type `{source.type}`" |
| 245 |
) |
| 246 |
|
| 247 |
_LOGGER.debug("Getting state for traffic source: %s", source) |
| 248 |
|
| 249 |
arguments: dict[str, Any] = { |
| 250 |
"node_mac": source.target, |
| 251 |
} |
| 252 |
|
| 253 |
# Add backhaul flag if required |
| 254 |
if isinstance(source, ARTrafficSourceEthernet): |
| 255 |
arguments["is_bh"] = source.bh_flag |
| 256 |
|
| 257 |
# Add towards channel if required |
| 258 |
if isinstance(source, ARTrafficSourceBackhaul): |
| 259 |
arguments["sta_mac"] = source.towards |
| 260 |
if isinstance(source, ARTrafficSourceWiFi): |
| 261 |
arguments["band_mac"] = source.towards |
| 262 |
|
| 263 |
# Call the callback to get the state |
| 264 |
request = dict_to_request( |
| 265 |
arguments, request_type=get_request_type(endpoint) |
| 266 |
) |
| 267 |
return await callback(endpoint=endpoint, request=request) |
| 268 |
|
| 269 |
|
| 270 |
def translate_state( |
| 271 |
data: dict[str, Any], |
| 272 |
**kwargs: Any, |
| 273 |
) -> dict[str, Any]: |
| 274 |
"""Translate the traffic data to a simple format.""" |
| 275 |
|
| 276 |
result: dict[str, Any] = {} |
| 277 |
|
| 278 |
simplified_data = flatten_dict(data) |
| 279 |
if not simplified_data: |
| 280 |
return {} |
| 281 |
|
| 282 |
for key, value in simplified_data.items(): |
| 283 |
if key in _TRANSLATION_TABLE: |
| 284 |
new_key, transform = _TRANSLATION_TABLE[key] |
| 285 |
result[new_key] = transform(value) |
| 286 |
continue |
| 287 |
result[key] = value |
| 288 |
|
| 289 |
return result |
| 290 |
|
| 291 |
|
| 292 |
# Register callables for traffic sources |
| 293 |
calls: dict[str, ARCallableType] = { |
| 294 |
AR_CALL_GET_STATE: get_state, |
| 295 |
AR_CALL_TRANSLATE_STATE: translate_state, |
| 296 |
} |
| 297 |
ARCallReg.register(ARTrafficSourceEthernet, **calls) |
| 298 |
ARCallReg.register(ARTrafficSourceWiFi, **calls) |
| 299 |
ARCallReg.register(ARTrafficSourceBackhaul, **calls) |