| 1 |
"""AsusRouter module. |
| 2 |
|
| 3 |
This module contains the main class for interacting with an Asus device. |
| 4 |
""" |
| 5 |
|
| 6 |
from __future__ import annotations |
| 7 |
|
| 8 |
import asyncio |
| 9 |
from collections.abc import Awaitable, Callable |
| 10 |
from datetime import UTC, datetime, timedelta |
| 11 |
import json |
| 12 |
import logging |
| 13 |
from typing import Any |
| 14 |
|
| 15 |
import aiohttp |
| 16 |
|
| 17 |
from asusrouter.config import ARConfigKey as ARConfKey, ARInstanceConfig |
| 18 |
from asusrouter.connection import Connection |
| 19 |
from asusrouter.connection_config import ARConnectionConfigKey as ARCCKey |
| 20 |
from asusrouter.const import ( |
| 21 |
AR_CALL_GET_STATE, |
| 22 |
AR_CALL_TRANSLATE_STATE, |
| 23 |
DEFAULT_CACHE_TIME, |
| 24 |
DEFAULT_PORT_HTTP, |
| 25 |
DEFAULT_PORT_HTTPS, |
| 26 |
DEFAULT_RESULT_SUCCESS, |
| 27 |
DEFAULT_TIMEOUT, |
| 28 |
RequestType, |
| 29 |
) |
| 30 |
from asusrouter.error import ( |
| 31 |
AsusRouter404Error, |
| 32 |
AsusRouterAccessError, |
| 33 |
AsusRouterConnectionError, |
| 34 |
AsusRouterDataError, |
| 35 |
) |
| 36 |
from asusrouter.modules.attributes import AsusRouterAttribute |
| 37 |
from asusrouter.modules.data import AsusData, AsusDataState |
| 38 |
from asusrouter.modules.data_finder import ( |
| 39 |
ASUSDATA_ENDPOINT_APPEND, |
| 40 |
ASUSDATA_MAP, |
| 41 |
ASUSDATA_NVRAM, |
| 42 |
AsusDataFinder, |
| 43 |
AsusDataMerge, |
| 44 |
add_conditional_data_alias, |
| 45 |
add_conditional_data_rule, |
| 46 |
remove_data_rule, |
| 47 |
) |
| 48 |
from asusrouter.modules.data_transform import ( |
| 49 |
transform_clients, |
| 50 |
transform_cpu, |
| 51 |
transform_ethernet_ports, |
| 52 |
transform_network, |
| 53 |
transform_wan, |
| 54 |
) |
| 55 |
from asusrouter.modules.endpoint import ( |
| 56 |
ENDPOINT_FORCE_REQUEST, |
| 57 |
Endpoint, |
| 58 |
EndpointControl, |
| 59 |
EndpointType, |
| 60 |
process, |
| 61 |
read, |
| 62 |
) |
| 63 |
from asusrouter.modules.endpoint.error import AccessError |
| 64 |
from asusrouter.modules.firmware import Firmware |
| 65 |
from asusrouter.modules.flags import Flag |
| 66 |
from asusrouter.modules.identity import AsusDevice, collect_identity |
| 67 |
from asusrouter.modules.port_forwarding import PortForwardingRule |
| 68 |
from asusrouter.modules.service import async_call_service |
| 69 |
from asusrouter.modules.source import ( |
| 70 |
ARDataSource, |
| 71 |
ARDataState, |
| 72 |
ARDataStateDynamic, |
| 73 |
ARDataStateStatic, |
| 74 |
ARDataType, |
| 75 |
) |
| 76 |
from asusrouter.modules.state import ( |
| 77 |
AsusState, |
| 78 |
add_conditional_state, |
| 79 |
get_datatype, |
| 80 |
keep_state, |
| 81 |
save_state, |
| 82 |
set_state, |
| 83 |
) |
| 84 |
from asusrouter.registry import ARCallableRegistry as ARCallReg |
| 85 |
from asusrouter.tools import legacy |
| 86 |
from asusrouter.tools.converters import get_enum_key_by_value, safe_list |
| 87 |
from asusrouter.tools.readers import merge_dicts |
| 88 |
from asusrouter.tools.types import ARCallbackType |
| 89 |
|
| 90 |
_LOGGER = logging.getLogger(__name__) |
| 91 |
|
| 92 |
|
| 93 |
class AsusRouter: |
| 94 |
"""The interface class.""" |
| 95 |
|
| 96 |
def __init__( # noqa: PLR0913 |
| 97 |
self, |
| 98 |
hostname: str, |
| 99 |
username: str, |
| 100 |
password: str, |
| 101 |
port: int | None = None, |
| 102 |
use_ssl: bool = False, |
| 103 |
cache_time: float | None = None, |
| 104 |
session: aiohttp.ClientSession | None = None, |
| 105 |
dumpback: Callable[..., Awaitable[None]] | None = None, |
| 106 |
config: dict[ARConfKey, Any] | None = None, |
| 107 |
connection_config: dict[ARCCKey, Any] | None = None, |
| 108 |
): |
| 109 |
"""Initialize the interface.""" |
| 110 |
|
| 111 |
_LOGGER.debug("Initializing a new interface to `%s`", hostname) |
| 112 |
|
| 113 |
# Initialize configs |
| 114 |
_LOGGER.debug("Setting up AR instance config: %s", config) |
| 115 |
self._config = ARInstanceConfig(defaults=config) |
| 116 |
|
| 117 |
# Set the cache time |
| 118 |
self._cache_time = cache_time or DEFAULT_CACHE_TIME |
| 119 |
self._cache_threshold = timedelta(seconds=self._cache_time) |
| 120 |
|
| 121 |
# Set the host |
| 122 |
self._hostname: str = hostname |
| 123 |
|
| 124 |
# Set the device identity |
| 125 |
self._identity: AsusDevice | None = None |
| 126 |
self._state: dict[AsusData, AsusDataState] = {} |
| 127 |
self._data_states: dict[ARDataSource | ARDataType, ARDataState] = {} |
| 128 |
|
| 129 |
# Set the flags |
| 130 |
self._flags: Flag = Flag() |
| 131 |
# Time for change to take effect before available to fetch |
| 132 |
self._needed_time: int | None = None |
| 133 |
# ID from the last called service |
| 134 |
self._last_id: int | None = None |
| 135 |
|
| 136 |
# Create an empty connection and save the credentials |
| 137 |
self._connection: Connection | None = None |
| 138 |
self._username = username |
| 139 |
self._password = password |
| 140 |
self._port = port |
| 141 |
self._use_ssl = use_ssl |
| 142 |
self._session = session |
| 143 |
self._dumpback = dumpback |
| 144 |
self._connection_config = connection_config |
| 145 |
|
| 146 |
# --------------------------- |
| 147 |
# Connection-related methods --> |
| 148 |
# --------------------------- |
| 149 |
|
| 150 |
async def async_init_connection(self) -> None: |
| 151 |
"""Initialize the connection.""" |
| 152 |
|
| 153 |
_LOGGER.debug("Triggered method async_init_connection") |
| 154 |
|
| 155 |
self._connection = await Connection.create( |
| 156 |
hostname=self._hostname, |
| 157 |
username=self._username, |
| 158 |
password=self._password, |
| 159 |
port=self._port, |
| 160 |
use_ssl=self._use_ssl, |
| 161 |
session=self._session, |
| 162 |
timeout=DEFAULT_TIMEOUT, |
| 163 |
dumpback=self._dumpback, |
| 164 |
config=self._connection_config, |
| 165 |
) |
| 166 |
|
| 167 |
async def async_del_connection(self) -> None: |
| 168 |
"""Delete the connection.""" |
| 169 |
|
| 170 |
_LOGGER.debug("Triggered method async_del_connection") |
| 171 |
|
| 172 |
# Disconnect from the device if connected |
| 173 |
await self.async_disconnect() |
| 174 |
|
| 175 |
# Close the connection |
| 176 |
if self._connection: |
| 177 |
await self._connection.async_close() |
| 178 |
self._connection = None |
| 179 |
|
| 180 |
async def async_connect(self) -> bool: |
| 181 |
"""Connect to the device and get its identity.""" |
| 182 |
|
| 183 |
_LOGGER.debug("Triggered method async_connect") |
| 184 |
|
| 185 |
# Connect to the device |
| 186 |
try: |
| 187 |
# Make sure the connection is initialized |
| 188 |
if self._connection is None: |
| 189 |
await self.async_init_connection() |
| 190 |
|
| 191 |
# Connect to the device |
| 192 |
result = ( |
| 193 |
await self._connection.async_connect() |
| 194 |
if self._connection |
| 195 |
else False |
| 196 |
) |
| 197 |
if result is False: |
| 198 |
return False |
| 199 |
except Exception as ex: # pylint: disable=broad-except |
| 200 |
raise ex |
| 201 |
|
| 202 |
# Get the device identity |
| 203 |
return await self.async_get_identity() is not None |
| 204 |
|
| 205 |
async def async_disconnect(self) -> bool: |
| 206 |
"""Disconnect from the device.""" |
| 207 |
|
| 208 |
_LOGGER.debug("Triggered method async_disconnect") |
| 209 |
|
| 210 |
# Disconnect from the device |
| 211 |
try: |
| 212 |
if self._connection: |
| 213 |
await self._connection.async_disconnect() |
| 214 |
except Exception as ex: # noqa: BLE001 |
| 215 |
await self._async_handle_exception(ex) |
| 216 |
|
| 217 |
return True |
| 218 |
|
| 219 |
async def _async_drop_connection(self) -> None: |
| 220 |
"""Drop the connection. |
| 221 |
|
| 222 |
In case we know it cannot reply due to our last actions. |
| 223 |
""" |
| 224 |
|
| 225 |
_LOGGER.debug("Triggered method _async_drop_connection") |
| 226 |
|
| 227 |
if self._connection: |
| 228 |
self._connection.reset_connection() |
| 229 |
|
| 230 |
async def _async_handle_exception(self, ex: Exception) -> None: |
| 231 |
"""Handle exceptions.""" |
| 232 |
|
| 233 |
_LOGGER.debug("Triggered method _async_handle_exception") |
| 234 |
|
| 235 |
raise ex |
| 236 |
|
| 237 |
async def _async_handle_reboot(self) -> None: |
| 238 |
"""Handle reboot.""" |
| 239 |
|
| 240 |
_LOGGER.debug("Triggered method _async_handle_reboot") |
| 241 |
|
| 242 |
led_state = self._state.get(AsusData.LED) |
| 243 |
if led_state and led_state.data: |
| 244 |
_LOGGER.debug("Restoring LED state") |
| 245 |
await keep_state( |
| 246 |
callback=self.async_run_service, |
| 247 |
states=led_state.data["state"], |
| 248 |
identity=self._identity, |
| 249 |
) |
| 250 |
|
| 251 |
# Reset the reboot flag |
| 252 |
self._reset_flag("reboot") |
| 253 |
|
| 254 |
def _reset_flag(self, flag: str) -> None: |
| 255 |
"""Reset a flag.""" |
| 256 |
|
| 257 |
_LOGGER.debug("Triggered method _reset_flag") |
| 258 |
|
| 259 |
# Check that AsusData.FLAGS is available |
| 260 |
if AsusData.FLAGS not in self._state: |
| 261 |
return |
| 262 |
|
| 263 |
# Get the data from the state |
| 264 |
data = self._state[AsusData.FLAGS].data |
| 265 |
|
| 266 |
# Check that data is a dict |
| 267 |
if not isinstance(data, dict): |
| 268 |
return |
| 269 |
|
| 270 |
# Reset the flag |
| 271 |
data.pop(flag, None) |
| 272 |
|
| 273 |
_LOGGER.debug("Flag `%s` reset", flag) |
| 274 |
|
| 275 |
# --------------------------- |
| 276 |
# <-- Connection-related methods |
| 277 |
# --------------------------- |
| 278 |
|
| 279 |
# --------------------------- |
| 280 |
# Identity-related methods --> |
| 281 |
# --------------------------- |
| 282 |
|
| 283 |
async def async_get_identity(self, force: bool = False) -> AsusDevice: |
| 284 |
"""Get the device identity.""" |
| 285 |
|
| 286 |
_LOGGER.debug("Triggered method async_get_identity") |
| 287 |
|
| 288 |
# Check whether we already have the identity and not forcing a refresh |
| 289 |
if self._identity and not force: |
| 290 |
return self._identity |
| 291 |
|
| 292 |
# Collect the identity |
| 293 |
self._identity = await collect_identity( |
| 294 |
api_hook=self.async_api_hook, |
| 295 |
api_query=self.async_api_query, |
| 296 |
) |
| 297 |
|
| 298 |
# Add conditional data rules |
| 299 |
if self._identity: |
| 300 |
firmware = self._identity.firmware |
| 301 |
merlin = self._identity.merlin |
| 302 |
fw_388 = Firmware(major="3.0.0.4", minor=388, build=0) |
| 303 |
# Stock |
| 304 |
if not merlin: |
| 305 |
_LOGGER.debug("Adding conditional rules for stock firmware") |
| 306 |
if fw_388 < firmware: |
| 307 |
add_conditional_state( |
| 308 |
AsusState.OPENVPN_CLIENT, AsusData.VPNC |
| 309 |
) |
| 310 |
add_conditional_state( |
| 311 |
AsusState.WIREGUARD_CLIENT, AsusData.VPNC |
| 312 |
) |
| 313 |
add_conditional_data_alias( |
| 314 |
AsusData.OPENVPN_CLIENT, AsusData.VPNC |
| 315 |
) |
| 316 |
add_conditional_data_alias( |
| 317 |
AsusData.WIREGUARD_CLIENT, AsusData.VPNC |
| 318 |
) |
| 319 |
add_conditional_data_rule( |
| 320 |
AsusData.OPENVPN_SERVER, |
| 321 |
AsusDataFinder( |
| 322 |
Endpoint.HOOK, |
| 323 |
nvram=ASUSDATA_NVRAM["openvpn_server_388"], |
| 324 |
), |
| 325 |
) |
| 326 |
# Merlin |
| 327 |
else: |
| 328 |
_LOGGER.debug("Adding conditional rules for Merlin firmware") |
| 329 |
if fw_388 < firmware: |
| 330 |
add_conditional_data_rule( |
| 331 |
AsusData.VPNC, |
| 332 |
AsusDataFinder( |
| 333 |
Endpoint.HOOK, |
| 334 |
nvram=ASUSDATA_NVRAM["vpnc"], |
| 335 |
), |
| 336 |
) |
| 337 |
# Before 388 |
| 338 |
if firmware < fw_388: |
| 339 |
# Remove VPNC rules |
| 340 |
remove_data_rule(AsusData.VPNC) |
| 341 |
remove_data_rule(AsusData.VPNC_CLIENTLIST) |
| 342 |
# Remove WireGuard rules |
| 343 |
remove_data_rule(AsusData.WIREGUARD) |
| 344 |
remove_data_rule(AsusData.WIREGUARD_CLIENT) |
| 345 |
remove_data_rule(AsusData.WIREGUARD_SERVER) |
| 346 |
|
| 347 |
# DSL connection |
| 348 |
if self._identity.dsl is False: |
| 349 |
remove_data_rule(AsusData.DSL) |
| 350 |
|
| 351 |
# Ookla Speedtest |
| 352 |
if self._identity.ookla is False: |
| 353 |
remove_data_rule(AsusData.SPEEDTEST) |
| 354 |
# remove_data_rule(AsusData.SPEEDTEST_HISTORY) |
| 355 |
remove_data_rule(AsusData.SPEEDTEST_RESULT) |
| 356 |
# remove_data_rule(AsusData.SPEEDTEST_SERVERS) |
| 357 |
|
| 358 |
# Return new identity |
| 359 |
return self._identity |
| 360 |
|
| 361 |
# --------------------------- |
| 362 |
# <-- Identity-related methods |
| 363 |
# --------------------------- |
| 364 |
|
| 365 |
# --------------------------- |
| 366 |
# Request-related methods --> |
| 367 |
# --------------------------- |
| 368 |
|
| 369 |
def _get_attribute( |
| 370 |
self, attribute: AsusRouterAttribute | None |
| 371 |
) -> Any | None: |
| 372 |
"""Get an attribute value.""" |
| 373 |
|
| 374 |
if not attribute: |
| 375 |
return None |
| 376 |
|
| 377 |
match attribute: |
| 378 |
case AsusRouterAttribute.MAC: |
| 379 |
if self._identity: |
| 380 |
return self._identity.mac |
| 381 |
case AsusRouterAttribute.WLAN_LIST: |
| 382 |
if self._identity: |
| 383 |
return self._identity.wlan |
| 384 |
|
| 385 |
return None |
| 386 |
|
| 387 |
async def _check_flags(self) -> None: |
| 388 |
"""Check flags.""" |
| 389 |
|
| 390 |
_LOGGER.debug("Triggered method _check_flags") |
| 391 |
|
| 392 |
flags: dict[str, bool] = {} |
| 393 |
|
| 394 |
state_flags = self._state.get(AsusData.FLAGS) |
| 395 |
if isinstance(state_flags, AsusDataState) and isinstance( |
| 396 |
state_flags.data, dict |
| 397 |
): |
| 398 |
flags = state_flags.data |
| 399 |
|
| 400 |
if flags.get("reboot", False) is True: |
| 401 |
_LOGGER.debug("Reboot flag is set") |
| 402 |
await self._async_handle_reboot() |
| 403 |
|
| 404 |
async def async_api_query( |
| 405 |
self, endpoint: EndpointType, payload: str | None = None |
| 406 |
) -> tuple[int, dict[str, str], str]: |
| 407 |
"""Query the API endpoint.""" |
| 408 |
|
| 409 |
if endpoint in ASUSDATA_ENDPOINT_APPEND: |
| 410 |
payload = payload or "" |
| 411 |
for key, attribute in ASUSDATA_ENDPOINT_APPEND[endpoint].items(): |
| 412 |
if isinstance(attribute, AsusRouterAttribute): |
| 413 |
value = self._get_attribute(attribute) |
| 414 |
else: |
| 415 |
value = attribute |
| 416 |
if value: |
| 417 |
payload += f"{key}={value};" |
| 418 |
# Remove trailing semicolon |
| 419 |
payload = payload[:-1] |
| 420 |
|
| 421 |
_LOGGER.debug( |
| 422 |
"Triggered method async_api_query: %s | %s", endpoint, payload |
| 423 |
) |
| 424 |
|
| 425 |
request_type = ENDPOINT_FORCE_REQUEST.get(endpoint, RequestType.POST) |
| 426 |
|
| 427 |
return await self._connection.async_query( |
| 428 |
endpoint, payload, request_type=request_type |
| 429 |
) |
| 430 |
|
| 431 |
async def async_api_load( |
| 432 |
self, |
| 433 |
endpoint: EndpointType, |
| 434 |
request: str = "", |
| 435 |
retry: int = 0, |
| 436 |
) -> dict[str, Any]: |
| 437 |
"""Load API endpoint with optional request.""" |
| 438 |
|
| 439 |
_LOGGER.debug("Triggered method async_api_load: %s", endpoint) |
| 440 |
|
| 441 |
# Load the endpoint |
| 442 |
try: |
| 443 |
status, _, content = await self.async_api_query(endpoint, request) |
| 444 |
except AsusRouter404Error: |
| 445 |
_LOGGER.debug("Endpoint %s not found", endpoint) |
| 446 |
return {} |
| 447 |
except AsusRouterAccessError as ex: |
| 448 |
# Check whether we are not connected |
| 449 |
args = ex.args |
| 450 |
if args[1] == AccessError.AUTHORIZATION: |
| 451 |
# Mark the connection as dropped |
| 452 |
await self._async_drop_connection() |
| 453 |
# Wait before repeating the request |
| 454 |
await asyncio.sleep(1 + retry * 3) |
| 455 |
# Repeat request once more and see what happens |
| 456 |
return await self.async_api_load(endpoint, request, True) |
| 457 |
# Otherwise just raise the exception |
| 458 |
raise ex |
| 459 |
|
| 460 |
# Log status |
| 461 |
_LOGGER.debug("Response %s received from %s", status, endpoint) |
| 462 |
|
| 463 |
# Try to read the content |
| 464 |
try: |
| 465 |
result = read(endpoint, content, config=self.config) |
| 466 |
except json.JSONDecodeError as ex: |
| 467 |
# Not like this is supposed to happen, but just in case |
| 468 |
_LOGGER.debug("Failed to read content from %s", endpoint) |
| 469 |
_LOGGER.debug("Content: %s", content) |
| 470 |
# Just repeat request once more and see what happens |
| 471 |
# Only if we haven't tried already |
| 472 |
if not retry: |
| 473 |
return await self.async_api_load(endpoint, request, True) |
| 474 |
raise AsusRouterDataError( |
| 475 |
"Something went wrong while reading the content" |
| 476 |
) from ex |
| 477 |
|
| 478 |
# Check if we need to drop the connection |
| 479 |
run_service = result.get("run_service", None) |
| 480 |
if run_service in ("restart_httpd", "reboot"): |
| 481 |
await self._async_drop_connection() |
| 482 |
|
| 483 |
return result |
| 484 |
|
| 485 |
async def async_api_hook(self, request: str) -> dict[str, Any]: |
| 486 |
"""Perform a hook to the device API. |
| 487 |
|
| 488 |
Hooks are used to fetch data from the device. |
| 489 |
""" |
| 490 |
|
| 491 |
_LOGGER.debug("Triggered method async_api_hook: %s", request) |
| 492 |
|
| 493 |
return await self.async_api_load( |
| 494 |
endpoint=Endpoint.HOOK, |
| 495 |
request=f"hook={request}", |
| 496 |
) |
| 497 |
|
| 498 |
async def async_api_command( |
| 499 |
self, |
| 500 |
commands: dict[str, str] | None, |
| 501 |
endpoint: EndpointType = EndpointControl.COMMAND, |
| 502 |
) -> dict[str, Any]: |
| 503 |
"""Send a command to the device.""" |
| 504 |
|
| 505 |
_LOGGER.debug( |
| 506 |
"Triggered method async_api_command: %s | %s", endpoint, commands |
| 507 |
) |
| 508 |
|
| 509 |
return await self.async_api_load( |
| 510 |
endpoint=endpoint, |
| 511 |
request=str(commands), |
| 512 |
) |
| 513 |
|
| 514 |
# --------------------------- |
| 515 |
# <-- Request-related methods |
| 516 |
# --------------------------- |
| 517 |
|
| 518 |
def _where_to_get_data(self, datatype: AsusData) -> AsusDataFinder | None: |
| 519 |
"""Get the list of endpoints to get data from.""" |
| 520 |
|
| 521 |
_LOGGER.debug("Triggered method _where_to_get_data") |
| 522 |
|
| 523 |
# Check that device identity is available |
| 524 |
if not self._identity: |
| 525 |
_LOGGER.debug("No device identity available") |
| 526 |
return None |
| 527 |
|
| 528 |
# Get the map |
| 529 |
data_map = ASUSDATA_MAP.get(datatype) |
| 530 |
# Consider aliases |
| 531 |
while isinstance(data_map, AsusData): |
| 532 |
data_map = ASUSDATA_MAP.get(data_map) |
| 533 |
# Check if we have a map |
| 534 |
if not isinstance(data_map, AsusDataFinder): |
| 535 |
_LOGGER.debug("No map found for %s", datatype) |
| 536 |
return None |
| 537 |
|
| 538 |
# Check if endpoints are available |
| 539 |
for endpoint in data_map.endpoint: |
| 540 |
# Check endpoint availability in identity |
| 541 |
if self._identity.endpoints and self._identity.endpoints.get( |
| 542 |
endpoint |
| 543 |
) in ( |
| 544 |
False, |
| 545 |
None, |
| 546 |
): |
| 547 |
# Remove the endpoint from the map |
| 548 |
data_map.endpoint.remove(endpoint) |
| 549 |
|
| 550 |
_LOGGER.debug("Endpoints to check: %s", data_map.endpoint) |
| 551 |
|
| 552 |
return data_map |
| 553 |
|
| 554 |
def _transform_data( |
| 555 |
self, datatype: AsusData, data: Any, **kwargs: Any |
| 556 |
) -> Any: |
| 557 |
"""Transform data if needed.""" |
| 558 |
|
| 559 |
_LOGGER.debug("Triggered method _transform_data for `%s`", datatype) |
| 560 |
|
| 561 |
if datatype == AsusData.CLIENTS: |
| 562 |
_LOGGER.debug("Transforming clients data") |
| 563 |
return transform_clients( |
| 564 |
data, |
| 565 |
self._state.get(AsusData.CLIENTS), |
| 566 |
aimesh=self._identity.aimesh if self._identity else False, |
| 567 |
) |
| 568 |
|
| 569 |
if datatype == AsusData.CPU: |
| 570 |
_LOGGER.debug("Transforming CPU data") |
| 571 |
return transform_cpu(data) |
| 572 |
|
| 573 |
if datatype == AsusData.NETWORK: |
| 574 |
_LOGGER.debug("Transforming network data") |
| 575 |
return transform_network( |
| 576 |
data, |
| 577 |
self._identity.services if self._identity else [], |
| 578 |
self._state.get(AsusData.NETWORK), |
| 579 |
model=self._identity.model if self._identity else None, |
| 580 |
) |
| 581 |
|
| 582 |
if datatype == AsusData.PORTS: |
| 583 |
_LOGGER.debug("Transforming port data") |
| 584 |
return transform_ethernet_ports( |
| 585 |
data, |
| 586 |
self._identity.mac if self._identity else None, |
| 587 |
) |
| 588 |
|
| 589 |
if datatype == AsusData.WAN: |
| 590 |
_LOGGER.debug("Transforming WAN data") |
| 591 |
return transform_wan( |
| 592 |
data, |
| 593 |
self._identity.services if self._identity else [], |
| 594 |
) |
| 595 |
|
| 596 |
return data |
| 597 |
|
| 598 |
def _drop_data(self, datatype: AsusData, endpoint: EndpointType) -> bool: |
| 599 |
"""Check whether data should be dropped. |
| 600 |
|
| 601 |
This is required for some data obtained from multiple endpoints. |
| 602 |
""" |
| 603 |
|
| 604 |
if not self._identity: |
| 605 |
return False |
| 606 |
|
| 607 |
if ( |
| 608 |
datatype == AsusData.OPENVPN_CLIENT |
| 609 |
and self._identity.merlin is True |
| 610 |
): |
| 611 |
return endpoint == Endpoint.HOOK |
| 612 |
|
| 613 |
return False |
| 614 |
|
| 615 |
async def _check_prerequisites(self, datatype: AsusData) -> None: |
| 616 |
"""Check prerequisites before fetching data.""" |
| 617 |
|
| 618 |
_LOGGER.debug( |
| 619 |
"Triggered method _check_prerequisites for datatype `%s`", datatype |
| 620 |
) |
| 621 |
|
| 622 |
# A placeholder for future checks |
| 623 |
|
| 624 |
async def _check_postrequisites(self, datatype: AsusData) -> None: |
| 625 |
"""Check postrequisites after fetching data. |
| 626 |
|
| 627 |
This method is also used to fetch additional data. |
| 628 |
""" |
| 629 |
|
| 630 |
_LOGGER.debug( |
| 631 |
"Triggered method _check_postrequisites for datatype `%s`", |
| 632 |
datatype, |
| 633 |
) |
| 634 |
|
| 635 |
# Firmware |
| 636 |
if datatype == AsusData.FIRMWARE: |
| 637 |
# Check if update is available |
| 638 |
firmware = self._state[AsusData.FIRMWARE].data |
| 639 |
if firmware and firmware["state"] is True: |
| 640 |
# Get release notes |
| 641 |
release_note = await self.async_get_data( |
| 642 |
AsusData.FIRMWARE_NOTE, force=True |
| 643 |
) |
| 644 |
if release_note: |
| 645 |
firmware.update(release_note) |
| 646 |
|
| 647 |
def _check_state(self, datatype: AsusData | None) -> None: |
| 648 |
"""Make sure the state object is available.""" |
| 649 |
|
| 650 |
_LOGGER.debug("Triggered method _check_state") |
| 651 |
|
| 652 |
if not datatype: |
| 653 |
return |
| 654 |
|
| 655 |
# Add state object but make sure it's marked expired |
| 656 |
if datatype not in self._state: |
| 657 |
self._state[datatype] = AsusDataState( |
| 658 |
timestamp=( |
| 659 |
datetime.now(UTC) - timedelta(seconds=2 * self._cache_time) |
| 660 |
) |
| 661 |
) |
| 662 |
|
| 663 |
def _return_state(self, datatype: AsusData, **kwargs: Any) -> Any: |
| 664 |
"""Return a proper state.""" |
| 665 |
|
| 666 |
_LOGGER.debug("Triggered method _return_state") |
| 667 |
|
| 668 |
# Get the state |
| 669 |
state = self._state[datatype].data |
| 670 |
|
| 671 |
if datatype == AsusData.PORTS: |
| 672 |
own_mac = self._identity.mac if self._identity else None |
| 673 |
|
| 674 |
# Get the device selected |
| 675 |
device = kwargs.get("device") |
| 676 |
|
| 677 |
match device: |
| 678 |
case None: |
| 679 |
if isinstance(state, dict): |
| 680 |
return state.get(own_mac, {}) |
| 681 |
return state |
| 682 |
case "all": |
| 683 |
return state |
| 684 |
# Case when substate is a MAC address |
| 685 |
case a if isinstance(a, str): |
| 686 |
if isinstance(state, dict) and a in state: |
| 687 |
return state[a] |
| 688 |
return {} |
| 689 |
|
| 690 |
return state |
| 691 |
|
| 692 |
def _get_callback_for_state( |
| 693 |
self, source: ARDataSource | ARDataType |
| 694 |
) -> ARCallbackType | None: |
| 695 |
"""Get a callback function for the specified state.""" |
| 696 |
|
| 697 |
return self.async_api_load |
| 698 |
|
| 699 |
def _create_data_state(self, source: ARDataSource | ARDataType) -> bool: |
| 700 |
"""Create a new data state if does not exist.""" |
| 701 |
|
| 702 |
# State already exists |
| 703 |
if source in self._data_states: |
| 704 |
return True |
| 705 |
|
| 706 |
# Try to create a correct state |
| 707 |
state: ARDataState | None = None |
| 708 |
if isinstance(source, ARDataSource): |
| 709 |
state = ARDataStateDynamic(source) |
| 710 |
elif isinstance(source, ARDataType): |
| 711 |
state = ARDataStateStatic(source) |
| 712 |
|
| 713 |
# Did not manage to create a state |
| 714 |
if state is None: |
| 715 |
return False |
| 716 |
|
| 717 |
# Find and assign callback for this state |
| 718 |
state.callback = self._get_callback_for_state(source) |
| 719 |
|
| 720 |
self._data_states[source] = state |
| 721 |
return True |
| 722 |
|
| 723 |
async def _async_refresh_data_state( |
| 724 |
self, |
| 725 |
source: ARDataSource | ARDataType, |
| 726 |
force: bool = False, |
| 727 |
**kwargs: Any, |
| 728 |
) -> None: |
| 729 |
"""Refresh the data state for the specified source.""" |
| 730 |
|
| 731 |
# Get the state to work with |
| 732 |
state: ARDataState | None = self._data_states.get(source) |
| 733 |
if not state: |
| 734 |
return |
| 735 |
|
| 736 |
# Get the correct getter from the registry |
| 737 |
data_caller = ARCallReg.get_callable(source, name=AR_CALL_GET_STATE) |
| 738 |
if not data_caller: |
| 739 |
return |
| 740 |
|
| 741 |
# Get the callback |
| 742 |
callback = state.callback |
| 743 |
|
| 744 |
# Fetch the data |
| 745 |
data = await data_caller(callback, source, force=force, **kwargs) |
| 746 |
if not data: |
| 747 |
return |
| 748 |
|
| 749 |
# Translate the data if a translator is available |
| 750 |
translator = ARCallReg.get_callable( |
| 751 |
source, name=AR_CALL_TRANSLATE_STATE |
| 752 |
) |
| 753 |
if translator: |
| 754 |
data = translator(data) |
| 755 |
|
| 756 |
# Update the state with the new data |
| 757 |
state.update(data) |
| 758 |
self._data_states[source] = state |
| 759 |
|
| 760 |
async def async_get_data_state( |
| 761 |
self, |
| 762 |
source: ARDataSource | ARDataType, |
| 763 |
force: bool = False, |
| 764 |
**kwargs: Any, |
| 765 |
) -> ARDataState: |
| 766 |
"""Get the full data state for the specified source.""" |
| 767 |
|
| 768 |
# Create a state for the source if it doesn't exist |
| 769 |
self._create_data_state(source) |
| 770 |
|
| 771 |
# Update the state |
| 772 |
await self._async_refresh_data_state(source, force=force, **kwargs) |
| 773 |
|
| 774 |
# Return the state |
| 775 |
return self._data_states[source] |
| 776 |
|
| 777 |
async def async_get_data_v2( |
| 778 |
self, |
| 779 |
source: ARDataSource | ARDataType, |
| 780 |
force: bool = False, |
| 781 |
**kwargs: Any, |
| 782 |
) -> Any: |
| 783 |
"""Get data from the specified source.""" |
| 784 |
|
| 785 |
_LOGGER.debug("Querying data V2") |
| 786 |
|
| 787 |
# Get the new data state |
| 788 |
data_state: ARDataState | None = await self.async_get_data_state( |
| 789 |
source, force=force, **kwargs |
| 790 |
) |
| 791 |
if not data_state: |
| 792 |
return None |
| 793 |
|
| 794 |
# Check if the data is fresh |
| 795 |
if not data_state.is_fresh(self._cache_threshold): |
| 796 |
_LOGGER.debug("Data for %s is older than cache threshold", source) |
| 797 |
return None |
| 798 |
|
| 799 |
# Return the data |
| 800 |
return data_state.content |
| 801 |
|
| 802 |
async def async_get_data( # noqa: C901, PLR0912, PLR0915 |
| 803 |
self, datatype: AsusData, force: bool = False, **kwargs: Any |
| 804 |
) -> Any: |
| 805 |
"""Get data from the device.""" |
| 806 |
|
| 807 |
# --- V2 COMPATIBILITY --- |
| 808 |
# This small switcher will allow gradual switching from v1 to v2 logic |
| 809 |
if isinstance(datatype, ARDataSource | ARDataType): |
| 810 |
return await self.async_get_data_v2( |
| 811 |
source=datatype, force=force, **kwargs |
| 812 |
) |
| 813 |
|
| 814 |
# Check if we have a state object for this data |
| 815 |
self._check_state(datatype) |
| 816 |
|
| 817 |
# If state object is active, wait for it to finish and return the data |
| 818 |
if self._state[datatype].active: |
| 819 |
try: |
| 820 |
_LOGGER.debug( |
| 821 |
"Already in progress. Waiting for data to be fetched" |
| 822 |
) |
| 823 |
await asyncio.wait_for( |
| 824 |
self._state[datatype].inactive_event.wait(), |
| 825 |
DEFAULT_TIMEOUT, |
| 826 |
) |
| 827 |
except TimeoutError: |
| 828 |
_LOGGER.debug( |
| 829 |
"Timeout while waiting for data. Will try fetching again" |
| 830 |
) |
| 831 |
|
| 832 |
# Check if we have the data already and not forcing a refresh |
| 833 |
if self._state[datatype].data and not force: |
| 834 |
# Check if the data is younger than the cache time |
| 835 |
if datetime.now(UTC) - self._state[datatype].timestamp < timedelta( |
| 836 |
seconds=self._cache_time |
| 837 |
): |
| 838 |
_LOGGER.debug( |
| 839 |
"Using cached data for `%s`: %s", |
| 840 |
datatype, |
| 841 |
self._state[datatype].data, |
| 842 |
) |
| 843 |
# Return the cached data |
| 844 |
return self._state[datatype].data |
| 845 |
_LOGGER.debug("Data for %s is too old. Fetching", datatype) |
| 846 |
|
| 847 |
# Mark the data as active |
| 848 |
self._state[datatype].start() |
| 849 |
|
| 850 |
# Check prerequisites |
| 851 |
await self._check_prerequisites(datatype) |
| 852 |
|
| 853 |
# Get the data finder |
| 854 |
data_finder = self._where_to_get_data(datatype) |
| 855 |
|
| 856 |
# Check if we have a data finder |
| 857 |
if not data_finder: |
| 858 |
_LOGGER.debug("No data finder for %s", datatype) |
| 859 |
return {} |
| 860 |
|
| 861 |
# The data we are looking for |
| 862 |
data = {} |
| 863 |
result: dict[AsusData, Any] = {} |
| 864 |
|
| 865 |
try: |
| 866 |
for endpoint in data_finder.endpoint: |
| 867 |
# Get the data from the endpoint |
| 868 |
request = "hook=" if endpoint == Endpoint.HOOK else "" |
| 869 |
for item in data_finder.request: |
| 870 |
key, value = item |
| 871 |
request += f"{key}({value});" |
| 872 |
if data_finder.method: |
| 873 |
argument = self._get_attribute(data_finder.arguments) |
| 874 |
request += ( |
| 875 |
data_finder.method(argument) |
| 876 |
if argument |
| 877 |
else data_finder.method() |
| 878 |
) |
| 879 |
# Check that we are not fetching this data already |
| 880 |
|
| 881 |
# Add the request from kwargs |
| 882 |
kw_request = kwargs.get("request", {}) |
| 883 |
if isinstance(kw_request, dict): |
| 884 |
for key, value in kw_request.items(): |
| 885 |
request += f"{key}={value};" |
| 886 |
# Remove trailing symbol |
| 887 |
request = request[:-1] |
| 888 |
|
| 889 |
# Fetch the data |
| 890 |
data = await self.async_api_load(endpoint, request) |
| 891 |
|
| 892 |
# Make sure, identity is available |
| 893 |
if not self._identity: |
| 894 |
self._identity = await self.async_get_identity() |
| 895 |
|
| 896 |
processed = process( |
| 897 |
endpoint, |
| 898 |
data, |
| 899 |
self._state, |
| 900 |
self._identity.firmware, |
| 901 |
self._identity.wlan, |
| 902 |
) |
| 903 |
|
| 904 |
# Check whether data should be dropped |
| 905 |
to_drop = [] |
| 906 |
for key, value in processed.items(): |
| 907 |
if self._drop_data(key, endpoint): |
| 908 |
to_drop.append(key) |
| 909 |
for key in to_drop: |
| 910 |
processed.pop(key, None) |
| 911 |
|
| 912 |
result = merge_dicts(result, processed) |
| 913 |
|
| 914 |
# Check if we have data and data finder merge is ANY |
| 915 |
if result and data_finder.merge == AsusDataMerge.ANY: |
| 916 |
break |
| 917 |
|
| 918 |
# Save the data state |
| 919 |
for key, value in result.items(): |
| 920 |
# Transform data if needed |
| 921 |
transformed_value = self._transform_data(key, value) |
| 922 |
# Save the data |
| 923 |
result[key] = transformed_value |
| 924 |
# Update the state |
| 925 |
if key not in self._state: |
| 926 |
self._state[key] = AsusDataState() |
| 927 |
self._state[key].update(transformed_value) |
| 928 |
except (AsusRouterConnectionError, AsusRouterDataError): |
| 929 |
return self._return_state(datatype, **kwargs) |
| 930 |
|
| 931 |
# Check flags |
| 932 |
await self._check_flags() |
| 933 |
|
| 934 |
# Check postrequisites |
| 935 |
await self._check_postrequisites(datatype) |
| 936 |
|
| 937 |
# Return the data we were looking for |
| 938 |
_LOGGER.debug( |
| 939 |
"Returning data for `%s` with object type `%s`", |
| 940 |
datatype, |
| 941 |
type(self._state[datatype].data), |
| 942 |
) |
| 943 |
return self._return_state(datatype, **kwargs) |
| 944 |
|
| 945 |
# --------------------------- |
| 946 |
# Service-related methods --> |
| 947 |
# --------------------------- |
| 948 |
|
| 949 |
async def async_run_service( |
| 950 |
self, |
| 951 |
service: str | None, |
| 952 |
arguments: dict[str, Any] | None = None, |
| 953 |
apply: bool = False, |
| 954 |
expect_modify: bool = True, |
| 955 |
drop_connection: bool = False, |
| 956 |
) -> bool: |
| 957 |
"""Run a service.""" |
| 958 |
|
| 959 |
_LOGGER.debug("Triggered method async_run_service") |
| 960 |
|
| 961 |
# Run the service |
| 962 |
result, self._needed_time, self._last_id = await async_call_service( |
| 963 |
self.async_api_command, |
| 964 |
service, |
| 965 |
arguments, |
| 966 |
apply, |
| 967 |
expect_modify, |
| 968 |
) |
| 969 |
|
| 970 |
if drop_connection: |
| 971 |
await self._async_drop_connection() |
| 972 |
|
| 973 |
return result |
| 974 |
|
| 975 |
async def _async_check_state_dependency(self, state: AsusState) -> None: |
| 976 |
"""Check and queue state dependencies. Required for some states.""" |
| 977 |
|
| 978 |
_LOGGER.debug("Triggered method _async_check_state_dependency") |
| 979 |
|
| 980 |
dependency = get_datatype(state) |
| 981 |
|
| 982 |
if dependency == AsusData.VPNC: |
| 983 |
# VPNC state change requires the correct previous state |
| 984 |
await self.async_get_data(AsusData.VPNC, force=True) |
| 985 |
|
| 986 |
if dependency == AsusData.AURA: |
| 987 |
# Aura state change requires the correct previous state |
| 988 |
await self.async_get_data(AsusData.AURA, force=True) |
| 989 |
|
| 990 |
async def _async_get_state_callback( |
| 991 |
self, state: AsusState |
| 992 |
) -> Callable[..., Awaitable]: |
| 993 |
"""Get the state callback.""" |
| 994 |
|
| 995 |
_LOGGER.debug("Triggered method _async_get_state_callback") |
| 996 |
|
| 997 |
datatype = get_datatype(state) |
| 998 |
# If state is one of AsusState.AURA enum |
| 999 |
if datatype == AsusData.AURA: |
| 1000 |
return self.async_api_command |
| 1001 |
|
| 1002 |
return self.async_run_service |
| 1003 |
|
| 1004 |
async def async_set_state( |
| 1005 |
self, |
| 1006 |
state: AsusState, |
| 1007 |
expect_modify: bool = False, |
| 1008 |
**kwargs: Any, |
| 1009 |
) -> bool: |
| 1010 |
"""Set the state.""" |
| 1011 |
|
| 1012 |
_LOGGER.debug("Triggered method async_set_state") |
| 1013 |
|
| 1014 |
_LOGGER.debug( |
| 1015 |
"Setting state `%s` with arguments `%s`. Expecting modify: `%s`", |
| 1016 |
state, |
| 1017 |
kwargs, |
| 1018 |
expect_modify, |
| 1019 |
) |
| 1020 |
|
| 1021 |
# Check dependencies |
| 1022 |
await self._async_check_state_dependency(state) |
| 1023 |
|
| 1024 |
# Get the state callback |
| 1025 |
callback = await self._async_get_state_callback(state) |
| 1026 |
|
| 1027 |
result = await set_state( |
| 1028 |
callback=callback, |
| 1029 |
state=state, |
| 1030 |
expect_modify=expect_modify, |
| 1031 |
router_state=self._state, |
| 1032 |
identity=self._identity, |
| 1033 |
**kwargs, |
| 1034 |
) |
| 1035 |
|
| 1036 |
# Rewrite the result if it is the default one |
| 1037 |
if result == DEFAULT_RESULT_SUCCESS: |
| 1038 |
result = True |
| 1039 |
|
| 1040 |
if result is True: |
| 1041 |
_datatype = get_datatype(state) |
| 1042 |
|
| 1043 |
if _datatype in (AsusData.VPNC, AsusData.AURA): |
| 1044 |
# The only way to make it work with VPN Fusion |
| 1045 |
await asyncio.sleep(1) |
| 1046 |
await self._async_check_state_dependency(state) |
| 1047 |
elif ( |
| 1048 |
get_enum_key_by_value( |
| 1049 |
AsusState, type(state), default=AsusState.NONE |
| 1050 |
) |
| 1051 |
== AsusState.PC_RULE |
| 1052 |
): |
| 1053 |
# We should not save this state, since it is saved differently |
| 1054 |
pass |
| 1055 |
else: |
| 1056 |
# Check if we have a state object for this data |
| 1057 |
self._check_state(_datatype) |
| 1058 |
# Save the state |
| 1059 |
_LOGGER.debug( |
| 1060 |
"Saving state `%s` for `%s` s with id=`%s`", |
| 1061 |
state, |
| 1062 |
self._needed_time, |
| 1063 |
self._last_id, |
| 1064 |
) |
| 1065 |
save_state( |
| 1066 |
state, self._state, self._needed_time, self._last_id |
| 1067 |
) |
| 1068 |
# Reset the needed time and last id |
| 1069 |
self._needed_time = None |
| 1070 |
self._last_id = None |
| 1071 |
|
| 1072 |
return result |
| 1073 |
|
| 1074 |
# --------------------------- |
| 1075 |
# <-- Service-related methods |
| 1076 |
# --------------------------- |
| 1077 |
|
| 1078 |
# --------------------------- |
| 1079 |
# Legacy methods --> |
| 1080 |
# --------------------------- |
| 1081 |
# Not tested, not used, not documented |
| 1082 |
# This part can be changed / removed in the future |
| 1083 |
# It might also not be working properly |
| 1084 |
|
| 1085 |
# If any of port forwarding methods gets removed, |
| 1086 |
# notify in https://github.com/Vaskivskyi/asusrouter/issues/611 |
| 1087 |
# so that users of these methods will know of a breaking change |
| 1088 |
|
| 1089 |
async def async_apply_port_forwarding_rules( |
| 1090 |
self, |
| 1091 |
rules: list[PortForwardingRule], |
| 1092 |
) -> bool: |
| 1093 |
"""Apply port forwarding rules.""" |
| 1094 |
|
| 1095 |
request = legacy.compile_port_forwarding(rules) |
| 1096 |
|
| 1097 |
if request: |
| 1098 |
return await self.async_run_service( |
| 1099 |
service="restart_firewall", |
| 1100 |
arguments=request, |
| 1101 |
apply=True, |
| 1102 |
) |
| 1103 |
|
| 1104 |
return False |
| 1105 |
|
| 1106 |
async def async_remove_port_forwarding_rules( |
| 1107 |
self, |
| 1108 |
ips: str | list[str] | None = None, |
| 1109 |
rules: PortForwardingRule | list[PortForwardingRule] | None = None, |
| 1110 |
apply: bool = True, |
| 1111 |
) -> list[PortForwardingRule]: |
| 1112 |
"""Remove port forwarding rules.""" |
| 1113 |
|
| 1114 |
ips = set() if ips is None else set(safe_list(ips)) |
| 1115 |
rules = [] if rules is None else safe_list(rules) |
| 1116 |
|
| 1117 |
# Get current rules |
| 1118 |
current_rules: list[PortForwardingRule] = ( |
| 1119 |
await self.async_get_data(AsusData.PORT_FORWARDING) |
| 1120 |
)["rules"] |
| 1121 |
|
| 1122 |
# Remove all rules for these IPs |
| 1123 |
current_rules = [ |
| 1124 |
rule for rule in current_rules if rule.ip_address not in ips |
| 1125 |
] |
| 1126 |
# Remove exact rules |
| 1127 |
for rule_to_find in rules: |
| 1128 |
current_rules = [ |
| 1129 |
rule |
| 1130 |
for rule in current_rules |
| 1131 |
if not ( |
| 1132 |
rule.ip_address == rule_to_find.ip_address |
| 1133 |
and rule.port_external == rule_to_find.port_external |
| 1134 |
and rule.protocol == rule_to_find.protocol |
| 1135 |
and ( |
| 1136 |
rule_to_find.ip_external is None |
| 1137 |
or rule.ip_external == rule_to_find.ip_external |
| 1138 |
) |
| 1139 |
and ( |
| 1140 |
rule_to_find.port is None |
| 1141 |
or rule.port == rule_to_find.port |
| 1142 |
) |
| 1143 |
) |
| 1144 |
] |
| 1145 |
|
| 1146 |
# Apply new rules |
| 1147 |
if apply: |
| 1148 |
await self.async_apply_port_forwarding_rules(current_rules) |
| 1149 |
|
| 1150 |
# Return the new rules |
| 1151 |
return current_rules |
| 1152 |
|
| 1153 |
async def async_set_port_forwarding_rules( |
| 1154 |
self, |
| 1155 |
rules: PortForwardingRule | list[PortForwardingRule], |
| 1156 |
) -> bool: |
| 1157 |
"""Set port forwarding rules.""" |
| 1158 |
|
| 1159 |
rules = safe_list(rules) |
| 1160 |
|
| 1161 |
# Get current rules |
| 1162 |
current_rules: list[PortForwardingRule] = ( |
| 1163 |
await self.async_get_data(AsusData.PORT_FORWARDING) |
| 1164 |
)["rules"] |
| 1165 |
|
| 1166 |
# Make a copy to avoid modifying the original list |
| 1167 |
current_rules = list(current_rules) |
| 1168 |
|
| 1169 |
# Add new rules |
| 1170 |
current_rules.extend(rules) |
| 1171 |
|
| 1172 |
# Apply new rules |
| 1173 |
return await self.async_apply_port_forwarding_rules(current_rules) |
| 1174 |
|
| 1175 |
# --------------------------- |
| 1176 |
# <-- Legacy methods |
| 1177 |
# --------------------------- |
| 1178 |
|
| 1179 |
# --------------------------- |
| 1180 |
# Properties --> |
| 1181 |
# --------------------------- |
| 1182 |
|
| 1183 |
@property |
| 1184 |
def connected(self) -> bool: |
| 1185 |
"""Return connection status.""" |
| 1186 |
|
| 1187 |
return self._connection.connected if self._connection else False |
| 1188 |
|
| 1189 |
@property |
| 1190 |
def config(self) -> ARInstanceConfig: |
| 1191 |
"""Return connection config.""" |
| 1192 |
|
| 1193 |
return self._config |
| 1194 |
|
| 1195 |
@property |
| 1196 |
def webpanel(self) -> str: |
| 1197 |
"""Return the web panel URL.""" |
| 1198 |
|
| 1199 |
if self._connection: |
| 1200 |
return self._connection.webpanel |
| 1201 |
|
| 1202 |
return ( |
| 1203 |
f"https://{self._hostname}:{self._port or DEFAULT_PORT_HTTPS}" |
| 1204 |
if self._use_ssl |
| 1205 |
else f"http://{self._hostname}:{self._port or DEFAULT_PORT_HTTP}" |
| 1206 |
) |
| 1207 |
|
| 1208 |
# --------------------------- |
| 1209 |
# <-- Properties |
| 1210 |
# --------------------------- |
| 1211 |
|
| 1212 |
# --------------------------- |
| 1213 |
# Additional settings --> |
| 1214 |
# --------------------------- |
| 1215 |
|
| 1216 |
# --------------------------- |
| 1217 |
# <-- Additional settings |
| 1218 |
# --------------------------- |
| 1219 |
|
| 1220 |
# --------------------------- |
| 1221 |
# General management --> |
| 1222 |
# --------------------------- |
| 1223 |
|
| 1224 |
async def async_cleanup(self) -> None: |
| 1225 |
"""Cleanup the connection.""" |
| 1226 |
|
| 1227 |
if self._connection: |
| 1228 |
self._connection.reset_connection() |
| 1229 |
# await self._connection._async_close_session() |
| 1230 |
|
| 1231 |
# --------------------------- |
| 1232 |
# <-- General management |
| 1233 |
# --------------------------- |