| 1 |
"""Converters module. |
| 2 |
|
| 3 |
This module has methods to convert data between different formats |
| 4 |
without complicated logic. In case data cannot be converted, |
| 5 |
`None` is returned and no exception is raised. |
| 6 |
|
| 7 |
If data conversion requires complicated logic, |
| 8 |
it should be in the Readers module |
| 9 |
""" |
| 10 |
|
| 11 |
from __future__ import annotations |
| 12 |
|
| 13 |
from collections.abc import Callable, Iterable |
| 14 |
from datetime import UTC, datetime, timedelta |
| 15 |
from enum import Enum |
| 16 |
from typing import Any, TypeVar, cast |
| 17 |
|
| 18 |
from asusrouter.tools.cleaners import clean_content |
| 19 |
|
| 20 |
true_values = {"true", "allow", "1", "on", "enabled"} |
| 21 |
false_values = {"false", "block", "0", "off", "disabled"} |
| 22 |
|
| 23 |
|
| 24 |
_T = TypeVar("_T") |
| 25 |
_E = TypeVar("_E", bound=Enum) |
| 26 |
|
| 27 |
|
| 28 |
def clean_input(func: Callable[..., Any]) -> Callable[..., Any]: |
| 29 |
"""Clean input data.""" |
| 30 |
|
| 31 |
def wrapper(content: Any, *args: Any, **kwargs: Any) -> Any: |
| 32 |
"""Return a clean input data before passing it to the function.""" |
| 33 |
|
| 34 |
if isinstance(content, str): |
| 35 |
return func(clean_string(content), *args, **kwargs) |
| 36 |
return func(content, *args, **kwargs) |
| 37 |
|
| 38 |
return wrapper |
| 39 |
|
| 40 |
|
| 41 |
def clean_jitter(value: _T, jitter: int = 1) -> int | _T: |
| 42 |
"""Clean jitter from an integer value. |
| 43 |
|
| 44 |
If input is int-compatible, remove unwanted jitter |
| 45 |
`jitter` by lowering value resolution. If any other |
| 46 |
non-compatible value is given, return it unchanged. |
| 47 |
""" |
| 48 |
|
| 49 |
vint = safe_int(value) |
| 50 |
jint = safe_int(jitter, default=1) |
| 51 |
if isinstance(vint, int) and jint > 0: |
| 52 |
block_size = 2 * jint + 1 |
| 53 |
return int(vint - (vint % block_size) + jint) |
| 54 |
|
| 55 |
return value |
| 56 |
|
| 57 |
|
| 58 |
def clean_string(content: str | None) -> str | None: |
| 59 |
"""Get a clean string or return None if it is empty.""" |
| 60 |
|
| 61 |
# Not a string |
| 62 |
if not content or not isinstance(content, str): |
| 63 |
return None |
| 64 |
|
| 65 |
content = clean_content(content.strip()) |
| 66 |
# Empty string |
| 67 |
if not content: |
| 68 |
return None |
| 69 |
|
| 70 |
return content |
| 71 |
|
| 72 |
|
| 73 |
def flatten_dict( |
| 74 |
d: dict[Any, Any] | None, |
| 75 |
parent_key: str = "", |
| 76 |
sep: str = "_", |
| 77 |
exclude: str | Iterable[str] | None = None, |
| 78 |
) -> dict[str, Any] | None: |
| 79 |
"""Flatten a nested dictionary.""" |
| 80 |
|
| 81 |
if d is None: |
| 82 |
return None |
| 83 |
|
| 84 |
if not isinstance(d, dict): |
| 85 |
return {} |
| 86 |
|
| 87 |
items = [] |
| 88 |
exclude = (exclude,) if isinstance(exclude, str) else tuple(exclude or []) |
| 89 |
for k, v in d.items(): |
| 90 |
new_key = ( |
| 91 |
f"{parent_key}{sep}{k}" if parent_key not in ("", None) else k |
| 92 |
) |
| 93 |
# We have a dict - check it |
| 94 |
if isinstance(v, dict): |
| 95 |
# This key should be skipped |
| 96 |
if isinstance(new_key, str) and new_key.endswith(exclude): |
| 97 |
items.append((new_key, v)) |
| 98 |
continue |
| 99 |
# Go recursive |
| 100 |
flattened = flatten_dict(v, new_key, sep, exclude) |
| 101 |
if flattened is not None: |
| 102 |
items.extend(flattened.items()) |
| 103 |
continue |
| 104 |
# Not a dict - add it |
| 105 |
items.append((new_key, v)) |
| 106 |
return dict(items) |
| 107 |
|
| 108 |
|
| 109 |
def get_arguments( |
| 110 |
args: str | tuple[str, ...], **kwargs: Any |
| 111 |
) -> Any | tuple[Any | None, ...]: |
| 112 |
"""Get the arguments from kwargs.""" |
| 113 |
|
| 114 |
# Make sure args is a tuple |
| 115 |
if not isinstance(args, tuple): |
| 116 |
args = (args,) |
| 117 |
|
| 118 |
arguments = kwargs.get("arguments", {}) |
| 119 |
|
| 120 |
found_args: list[Any | None] = [] |
| 121 |
|
| 122 |
for arg in args: |
| 123 |
# Skip if not a string |
| 124 |
if not isinstance(arg, str): |
| 125 |
continue |
| 126 |
# Get the arg and save to found_args |
| 127 |
arg_value = arguments.get(arg) if arguments else kwargs.get(arg) |
| 128 |
found_args.append(arg_value) |
| 129 |
|
| 130 |
if len(found_args) == 1: |
| 131 |
return found_args[0] |
| 132 |
|
| 133 |
return tuple(found_args) if found_args else None |
| 134 |
|
| 135 |
|
| 136 |
def get_enum_key_by_value( |
| 137 |
enum: type[_E], value: Any, default: _E | None = None |
| 138 |
) -> _E: |
| 139 |
"""Get the enum key by value.""" |
| 140 |
|
| 141 |
if issubclass(enum, Enum): |
| 142 |
for enum_value in enum: |
| 143 |
if enum_value.value == value: |
| 144 |
return enum_value |
| 145 |
|
| 146 |
if default is not None: |
| 147 |
return default |
| 148 |
|
| 149 |
raise ValueError(f"Invalid value: {value}") |
| 150 |
|
| 151 |
|
| 152 |
def handle_none_content(content: _T | None, default: _T | None) -> _T | None: |
| 153 |
"""Return the default value if content is None, else return the content.""" |
| 154 |
|
| 155 |
if content is None: |
| 156 |
return default |
| 157 |
return content |
| 158 |
|
| 159 |
|
| 160 |
def int_as_bits(value: int) -> list[bool]: |
| 161 |
"""Convert an integer to a list of bits.""" |
| 162 |
|
| 163 |
if not isinstance(value, int): |
| 164 |
return [] |
| 165 |
|
| 166 |
# Negative values are not supported |
| 167 |
if value < 0: |
| 168 |
return [] |
| 169 |
|
| 170 |
# Zero is a special case |
| 171 |
if value == 0: |
| 172 |
return [False] |
| 173 |
|
| 174 |
return [bool(value & (1 << i)) for i in range(value.bit_length())] |
| 175 |
|
| 176 |
|
| 177 |
def int_as_capabilities( |
| 178 |
value: int, capabilities: type[Enum] |
| 179 |
) -> dict[Enum, bool]: |
| 180 |
"""Convert an integer to a dict of capabilities.""" |
| 181 |
|
| 182 |
# Check if the capabilities is an enum |
| 183 |
if not is_enum(capabilities) or not isinstance(value, int): |
| 184 |
return {} |
| 185 |
|
| 186 |
# Convert the value to a list of bits |
| 187 |
bits = int_as_bits(value) |
| 188 |
|
| 189 |
result = {} |
| 190 |
|
| 191 |
# For each capability in the capabilities |
| 192 |
# Considering key as a capability name and value as a capability bit |
| 193 |
for capability in capabilities: |
| 194 |
# Check that the capability is an integer |
| 195 |
if not isinstance(capability.value, int): |
| 196 |
continue |
| 197 |
|
| 198 |
# Check if the bit is set |
| 199 |
result[capability] = ( |
| 200 |
bits[capability.value] if capability.value < len(bits) else False |
| 201 |
) |
| 202 |
|
| 203 |
return result |
| 204 |
|
| 205 |
|
| 206 |
def is_enum(v: Any) -> bool: |
| 207 |
"""Check if the value is an enum.""" |
| 208 |
|
| 209 |
return isinstance(v, type) and issubclass(v, Enum) |
| 210 |
|
| 211 |
|
| 212 |
def list_from_dict(raw: dict[Any, Any] | list[Any] | None) -> list[str]: |
| 213 |
"""Return dictionary keys as list.""" |
| 214 |
|
| 215 |
if isinstance(raw, list): |
| 216 |
return raw |
| 217 |
|
| 218 |
if not isinstance(raw, dict): |
| 219 |
return [] |
| 220 |
|
| 221 |
return list(raw.keys()) |
| 222 |
|
| 223 |
|
| 224 |
def nvram_get( |
| 225 |
content: list[str] | str | None, |
| 226 |
) -> list[tuple[str, ...]] | None: |
| 227 |
"""Convert values to NVRAM request.""" |
| 228 |
|
| 229 |
if not content: |
| 230 |
return None |
| 231 |
|
| 232 |
if not isinstance(content, list | str): |
| 233 |
content = str(content) |
| 234 |
|
| 235 |
if isinstance(content, str): |
| 236 |
content = [content] |
| 237 |
|
| 238 |
return [("nvram_get", value) for value in content] |
| 239 |
|
| 240 |
|
| 241 |
def run_method( |
| 242 |
value: Any, method: Callable[..., Any] | list[Callable[..., Any]] | None |
| 243 |
) -> Any: |
| 244 |
"""Run a method or a list of methods on a value and return the result.""" |
| 245 |
|
| 246 |
if not method: |
| 247 |
return value |
| 248 |
|
| 249 |
if not isinstance(method, list): |
| 250 |
method = [method] |
| 251 |
|
| 252 |
for func in method: |
| 253 |
if is_enum(func): |
| 254 |
try: |
| 255 |
value = func(value) |
| 256 |
except ValueError: |
| 257 |
value = func.UNKNOWN if hasattr(func, "UNKNOWN") else None |
| 258 |
else: |
| 259 |
value = func(value) |
| 260 |
|
| 261 |
return value |
| 262 |
|
| 263 |
|
| 264 |
@clean_input |
| 265 |
def safe_bool(content: str | float | bool | None) -> bool | None: |
| 266 |
"""Read the content as boolean or return None.""" |
| 267 |
|
| 268 |
if content is None: |
| 269 |
return None |
| 270 |
|
| 271 |
if isinstance(content, bool): |
| 272 |
return content |
| 273 |
if isinstance(content, int | float): |
| 274 |
return content != 0 |
| 275 |
if isinstance(content, str): |
| 276 |
content = content.lower() |
| 277 |
if content in true_values: |
| 278 |
return True |
| 279 |
if content in false_values: |
| 280 |
return False |
| 281 |
|
| 282 |
return None |
| 283 |
|
| 284 |
|
| 285 |
def safe_bool_nn(content: Any) -> bool: |
| 286 |
"""Read the content as boolean or return False.""" |
| 287 |
|
| 288 |
result = safe_bool(content) |
| 289 |
return result if isinstance(result, bool) else False |
| 290 |
|
| 291 |
|
| 292 |
def safe_convert( |
| 293 |
convert_func: Callable[[str | int | float], _T], |
| 294 |
content: str | float | None, |
| 295 |
default: _T | None = None, |
| 296 |
fallback_func: Callable[[Any], _T] | None = None, |
| 297 |
) -> _T | None: |
| 298 |
"""Try to convert the content using the conversion function. |
| 299 |
|
| 300 |
Return the default value if it fails. |
| 301 |
""" |
| 302 |
|
| 303 |
if content is None: |
| 304 |
return default |
| 305 |
try: |
| 306 |
return convert_func(content) |
| 307 |
except (ValueError, TypeError): |
| 308 |
if fallback_func is not None and isinstance(content, str): |
| 309 |
try: |
| 310 |
return fallback_func(content) |
| 311 |
except (ValueError, TypeError): |
| 312 |
pass |
| 313 |
return default |
| 314 |
|
| 315 |
|
| 316 |
@clean_input |
| 317 |
def safe_datetime(content: str | None) -> datetime | None: |
| 318 |
"""Read the content as datetime or return None.""" |
| 319 |
|
| 320 |
if not content: |
| 321 |
return None |
| 322 |
|
| 323 |
try: |
| 324 |
return datetime.fromisoformat(content) |
| 325 |
except (ValueError, TypeError): |
| 326 |
try: |
| 327 |
return datetime.strptime(content, "%a, %d %b %Y %H:%M:%S %z") |
| 328 |
except (ValueError, TypeError): |
| 329 |
return None |
| 330 |
|
| 331 |
|
| 332 |
def safe_enum( |
| 333 |
enum: type[_E], |
| 334 |
value: Any, |
| 335 |
default_value: Any | None = None, |
| 336 |
default: _E | None = None, |
| 337 |
) -> _E | None: |
| 338 |
"""Get the enum key by value.""" |
| 339 |
|
| 340 |
# Fast return |
| 341 |
# Return the default enum member |
| 342 |
if not default_value and not value and default is not None: |
| 343 |
return default |
| 344 |
|
| 345 |
if issubclass(enum, Enum): |
| 346 |
_def_enum_value = None |
| 347 |
# Go through the enum values |
| 348 |
for enum_value in enum: |
| 349 |
# Check for the value |
| 350 |
if enum_value.value == value: |
| 351 |
# Fast return |
| 352 |
return enum_value |
| 353 |
# Check for the default value |
| 354 |
if enum_value.value == default_value: |
| 355 |
_def_enum_value = enum_value |
| 356 |
# Return the default value |
| 357 |
if _def_enum_value is not None: |
| 358 |
return _def_enum_value |
| 359 |
|
| 360 |
return None |
| 361 |
|
| 362 |
|
| 363 |
@clean_input |
| 364 |
def safe_exists(content: str | None) -> bool: |
| 365 |
"""Read the content as boolean or return None.""" |
| 366 |
|
| 367 |
return content is not None |
| 368 |
|
| 369 |
|
| 370 |
@clean_input |
| 371 |
def safe_float( |
| 372 |
content: str | float | None, default: float | None = None |
| 373 |
) -> float | None: |
| 374 |
"""Read the content as float or return None.""" |
| 375 |
|
| 376 |
content = cast( |
| 377 |
str | int | float | None, handle_none_content(content, default) |
| 378 |
) |
| 379 |
return safe_convert(float, content, default) |
| 380 |
|
| 381 |
|
| 382 |
def safe_float_nn(content: Any) -> float: |
| 383 |
"""Read the content as a float or return 0.0.""" |
| 384 |
|
| 385 |
result = safe_float(content) |
| 386 |
return result if isinstance(result, float) else 0.0 |
| 387 |
|
| 388 |
|
| 389 |
@clean_input |
| 390 |
def safe_int( |
| 391 |
content: str | float | None, |
| 392 |
default: int | None = None, |
| 393 |
base: int = 10, |
| 394 |
) -> int | None: |
| 395 |
"""Read the content as int or return the default value. |
| 396 |
|
| 397 |
(None if not specified). |
| 398 |
""" |
| 399 |
|
| 400 |
content = cast( |
| 401 |
str | int | float | None, handle_none_content(content, default) |
| 402 |
) |
| 403 |
if isinstance(content, str): |
| 404 |
return safe_convert( |
| 405 |
lambda x: int(x, base=base), |
| 406 |
content, |
| 407 |
default, |
| 408 |
lambda x: int(float(x)), |
| 409 |
) |
| 410 |
return safe_convert( |
| 411 |
int, content, default if isinstance(default, int) else None |
| 412 |
) |
| 413 |
|
| 414 |
|
| 415 |
def safe_list(content: Any) -> list[Any]: |
| 416 |
"""Read any content as a list.""" |
| 417 |
|
| 418 |
if isinstance(content, list): |
| 419 |
return content |
| 420 |
|
| 421 |
if content is None: |
| 422 |
return [] |
| 423 |
|
| 424 |
return [content] |
| 425 |
|
| 426 |
|
| 427 |
def safe_list_csv(content: str | None) -> list[str]: |
| 428 |
"""Read the list as comma separated values.""" |
| 429 |
|
| 430 |
return safe_list_from_string(content, ",") |
| 431 |
|
| 432 |
|
| 433 |
@clean_input |
| 434 |
def safe_list_from_string( |
| 435 |
content: str | None, delimiter: str = " " |
| 436 |
) -> list[str]: |
| 437 |
"""Read the content as list or return empty list.""" |
| 438 |
|
| 439 |
if not isinstance(content, str): |
| 440 |
return [] |
| 441 |
|
| 442 |
return content.split(delimiter) |
| 443 |
|
| 444 |
|
| 445 |
@clean_input |
| 446 |
def safe_return(content: Any) -> Any: |
| 447 |
"""Return the content.""" |
| 448 |
|
| 449 |
return content |
| 450 |
|
| 451 |
|
| 452 |
def safe_speed( |
| 453 |
current: (float), |
| 454 |
previous: (float), |
| 455 |
time_delta: float | None = None, |
| 456 |
) -> float: |
| 457 |
"""Calculate speed. |
| 458 |
|
| 459 |
Allows calculation only of positive speed, otherwise returns 0.0. |
| 460 |
""" |
| 461 |
|
| 462 |
if time_delta is None or time_delta == 0.0: |
| 463 |
return 0.0 |
| 464 |
|
| 465 |
diff = current - previous if current > previous else 0.0 |
| 466 |
|
| 467 |
return diff / time_delta |
| 468 |
|
| 469 |
|
| 470 |
def safe_time_from_delta(content: str) -> datetime: |
| 471 |
"""Transform time delta to the date in the past.""" |
| 472 |
|
| 473 |
return datetime.now(UTC).replace( |
| 474 |
microsecond=0, tzinfo=UTC |
| 475 |
) - safe_timedelta_long(content) |
| 476 |
|
| 477 |
|
| 478 |
@clean_input |
| 479 |
def safe_timedelta_long(content: str | None) -> timedelta: |
| 480 |
"""Transform connection timedelta. |
| 481 |
|
| 482 |
Transform timedelta of the device to a proper datetime object |
| 483 |
when the device was connected. |
| 484 |
""" |
| 485 |
|
| 486 |
if not content: |
| 487 |
return timedelta() |
| 488 |
|
| 489 |
part = content.split(":") |
| 490 |
try: |
| 491 |
return timedelta( |
| 492 |
hours=int(part[-3]), minutes=int(part[-2]), seconds=int(part[-1]) |
| 493 |
) |
| 494 |
except (ValueError, IndexError): |
| 495 |
return timedelta() |
| 496 |
|
| 497 |
|
| 498 |
def safe_unpack_key( |
| 499 |
content: tuple[str, Callable[..., Any] | None | list[Callable[..., Any]]] |
| 500 |
| str |
| 501 |
| tuple[str], |
| 502 |
) -> tuple[str, Callable[..., Any] | list[Callable[..., Any]] | None]: |
| 503 |
""" |
| 504 |
Unpacks a tuple containing a key and a method. |
| 505 |
|
| 506 |
The input can be a tuple of a string and a method, a single string, |
| 507 |
or a single-item tuple with a string. |
| 508 |
If the input is a string or a single-item tuple, the returned method |
| 509 |
is None. |
| 510 |
If the input is a tuple of a string and a method, both are returned as is. |
| 511 |
|
| 512 |
Args: |
| 513 |
content: A tuple of a string and a method, a single string, |
| 514 |
or a single-item tuple with a string. |
| 515 |
|
| 516 |
Returns: |
| 517 |
A tuple containing a string and a method. |
| 518 |
If no method was provided in the input, None is returned as the method. |
| 519 |
""" |
| 520 |
|
| 521 |
if isinstance(content, tuple): |
| 522 |
key = content[0] |
| 523 |
if len(content) > 1: |
| 524 |
content = cast( |
| 525 |
tuple[ |
| 526 |
str, |
| 527 |
Callable[..., Any] | None | list[Callable[..., Any]], |
| 528 |
], |
| 529 |
content, |
| 530 |
) |
| 531 |
methods = content[1] |
| 532 |
if methods is not None and not ( |
| 533 |
callable(methods) or isinstance(methods, Iterable) |
| 534 |
): |
| 535 |
methods = None |
| 536 |
else: |
| 537 |
methods = None |
| 538 |
return key, methods |
| 539 |
|
| 540 |
# No method selected |
| 541 |
return content, None |
| 542 |
|
| 543 |
|
| 544 |
def safe_unpack_keys( |
| 545 |
content: tuple[ |
| 546 |
str, str, Callable[..., Any] | None | list[Callable[..., Any]] |
| 547 |
] |
| 548 |
| tuple[str, str] |
| 549 |
| str, |
| 550 |
) -> tuple[Any, ...]: |
| 551 |
"""Unpack key/key_to_use/method tuple even if some values are missing.""" |
| 552 |
|
| 553 |
if isinstance(content, tuple): |
| 554 |
# All 3 values are present |
| 555 |
if len(content) == 3: # noqa: PLR2004 |
| 556 |
return content |
| 557 |
|
| 558 |
# No method selected |
| 559 |
if len(content) == 2: # noqa: PLR2004 |
| 560 |
return content + (None,) |
| 561 |
|
| 562 |
# No method and key_to_use selected |
| 563 |
# We need to replace key_to_use with key |
| 564 |
new_content = (content, content) |
| 565 |
return new_content + (None,) |
| 566 |
|
| 567 |
|
| 568 |
def safe_usage(used: float, total: float) -> float: |
| 569 |
"""Calculate usage in percents. |
| 570 |
|
| 571 |
Allows calculation only of positive usage, otherwise returns 0.0. |
| 572 |
""" |
| 573 |
|
| 574 |
if total == 0: |
| 575 |
return 0.0 |
| 576 |
|
| 577 |
usage = round(used / total * 100, 2) |
| 578 |
|
| 579 |
# Don't allow negative usage |
| 580 |
if usage < 0: |
| 581 |
return 0.0 |
| 582 |
|
| 583 |
return usage |
| 584 |
|
| 585 |
|
| 586 |
def safe_usage_historic( |
| 587 |
used: float, |
| 588 |
total: float, |
| 589 |
prev_used: float, |
| 590 |
prev_total: float, |
| 591 |
) -> float: |
| 592 |
"""Calculate usage in percents for difference between values. |
| 593 |
|
| 594 |
This method is just an interface to calculate usage using `usage` method |
| 595 |
""" |
| 596 |
|
| 597 |
used_diff = used - prev_used |
| 598 |
total_diff = total - prev_total |
| 599 |
|
| 600 |
# Don't allow negative differences |
| 601 |
if used_diff < 0 or total_diff < 0: |
| 602 |
return 0.0 |
| 603 |
|
| 604 |
return safe_usage(used_diff, total_diff) |
| 605 |
|
| 606 |
|
| 607 |
def safe_timestamp_to_utc(value: int | None) -> datetime | None: |
| 608 |
"""Convert timestamp to UTC datetime.""" |
| 609 |
|
| 610 |
if value is None: |
| 611 |
return None |
| 612 |
|
| 613 |
try: |
| 614 |
return datetime.fromtimestamp(value, UTC) |
| 615 |
except (ValueError, TypeError, OSError): |
| 616 |
try: |
| 617 |
return datetime.fromtimestamp(value / 1000, UTC) |
| 618 |
except (ValueError, TypeError, OSError): |
| 619 |
return None |
| 620 |
|
| 621 |
|
| 622 |
def safe_utc_to_timestamp(value: datetime | None) -> float | None: |
| 623 |
"""Convert UTC datetime to timestamp.""" |
| 624 |
|
| 625 |
if value is None or not isinstance(value, datetime): |
| 626 |
return None |
| 627 |
|
| 628 |
return value.timestamp() |
| 629 |
|
| 630 |
|
| 631 |
def safe_utc_to_timestamp_milli(value: datetime | None) -> int | None: |
| 632 |
"""Convert UTC datetime to timestamp in milliseconds.""" |
| 633 |
|
| 634 |
_timestamp = safe_utc_to_timestamp(value) |
| 635 |
|
| 636 |
if _timestamp is None: |
| 637 |
return None |
| 638 |
|
| 639 |
return int(_timestamp * 1000) |
| 640 |
|
| 641 |
|
| 642 |
def scale_value_int( |
| 643 |
value: int, |
| 644 |
scale: int, |
| 645 |
scale_from: int | None = None, |
| 646 |
) -> int: |
| 647 |
"""Scale the value from the custom scale.""" |
| 648 |
|
| 649 |
if scale_from is None or scale_from == scale: |
| 650 |
return value |
| 651 |
|
| 652 |
return ( |
| 653 |
min(round(value * scale / scale_from), scale) if scale_from != 0 else 0 |
| 654 |
) |