| 1 |
"""async_upnp_client.profiles.igd module.""" |
| 2 |
|
| 3 |
|
| 4 |
import asyncio |
| 5 |
import logging |
| 6 |
from datetime import datetime, timedelta |
| 7 |
from enum import Enum |
| 8 |
from ipaddress import IPv4Address, IPv6Address |
| 9 |
from typing import NamedTuple, Sequence, cast |
| 10 |
|
| 11 |
from async_upnp_client.client import UpnpAction, UpnpDevice, UpnpStateVariable |
| 12 |
from async_upnp_client.event_handler import UpnpEventHandler |
| 13 |
from async_upnp_client.profiles.profile import UpnpProfileDevice |
| 14 |
|
| 15 |
TIMESTAMP = "timestamp" |
| 16 |
BYTES_RECEIVED = "bytes_received" |
| 17 |
BYTES_SENT = "bytes_sent" |
| 18 |
PACKETS_RECEIVED = "packets_received" |
| 19 |
PACKETS_SENT = "packets_sent" |
| 20 |
KIBIBYTES_PER_SEC_RECEIVED = "kibytes_sec_received" |
| 21 |
KIBIBYTES_PER_SEC_SENT = "kibytes_sec_sent" |
| 22 |
PACKETS_SEC_RECEIVED = "packets_sec_received" |
| 23 |
PACKETS_SEC_SENT = "packets_sec_sent" |
| 24 |
KIBIBYTES_PER_SEC_RECEIVED_NO_ROLLOVER = "kibytes_sec_received_no_rollover" |
| 25 |
KIBIBYTES_PER_SEC_SENT_NO_ROLLOVER = "kibytes_sec_sent_no_rollover" |
| 26 |
PACKETS_SEC_RECEIVED_NO_ROLLOVER = "packets_sec_received_no_rollover" |
| 27 |
PACKETS_SEC_SENT_NO_ROLLOVER = "packets_sec_sent_no_rollover" |
| 28 |
STATUS_INFO = "status_info" |
| 29 |
EXTERNAL_IP_ADDRESS = "external_ip_address" |
| 30 |
|
| 31 |
_LOGGER = logging.getLogger(__name__) |
| 32 |
|
| 33 |
|
| 34 |
class CommonLinkProperties(NamedTuple): |
| 35 |
"""Common link properties.""" |
| 36 |
|
| 37 |
wan_access_type: str |
| 38 |
layer1_upstream_max_bit_rate: int |
| 39 |
layer1_downstream_max_bit_rate: int |
| 40 |
physical_link_status: str |
| 41 |
|
| 42 |
|
| 43 |
class ConnectionTypeInfo(NamedTuple): |
| 44 |
"""Connection type info.""" |
| 45 |
|
| 46 |
connection_type: str |
| 47 |
possible_connection_types: str |
| 48 |
|
| 49 |
|
| 50 |
class StatusInfo(NamedTuple): |
| 51 |
"""Status info.""" |
| 52 |
|
| 53 |
connection_status: str |
| 54 |
last_connection_error: str |
| 55 |
uptime: int |
| 56 |
|
| 57 |
|
| 58 |
class NatRsipStatusInfo(NamedTuple): |
| 59 |
"""NAT RSIP status info.""" |
| 60 |
|
| 61 |
nat_enabled: bool |
| 62 |
rsip_available: bool |
| 63 |
|
| 64 |
|
| 65 |
class PortMappingEntry(NamedTuple): |
| 66 |
"""Port mapping entry.""" |
| 67 |
|
| 68 |
remote_host: IPv4Address | None |
| 69 |
external_port: int |
| 70 |
protocol: str |
| 71 |
internal_port: int |
| 72 |
internal_client: IPv4Address |
| 73 |
enabled: bool |
| 74 |
description: str |
| 75 |
lease_duration: timedelta | None |
| 76 |
|
| 77 |
|
| 78 |
class FirewallStatus(NamedTuple): |
| 79 |
"""IPv6 Firewall status.""" |
| 80 |
|
| 81 |
firewall_enabled: bool |
| 82 |
inbound_pinhole_allowed: bool |
| 83 |
|
| 84 |
|
| 85 |
class Pinhole(NamedTuple): |
| 86 |
"""IPv6 Pinhole.""" |
| 87 |
|
| 88 |
remote_host: str |
| 89 |
remote_port: int |
| 90 |
internal_client: str |
| 91 |
internal_port: int |
| 92 |
protocol: int |
| 93 |
lease_time: int |
| 94 |
|
| 95 |
|
| 96 |
class TrafficCounterState(NamedTuple): |
| 97 |
"""Traffic state.""" |
| 98 |
|
| 99 |
timestamp: datetime |
| 100 |
bytes_received: None | BaseException | int |
| 101 |
bytes_sent: None | BaseException | int |
| 102 |
packets_received: None | BaseException | int |
| 103 |
packets_sent: None | BaseException | int |
| 104 |
bytes_received_original: None | BaseException | int |
| 105 |
bytes_sent_original: None | BaseException | int |
| 106 |
packets_received_original: None | BaseException | int |
| 107 |
packets_sent_original: None | BaseException | int |
| 108 |
|
| 109 |
|
| 110 |
class IgdState(NamedTuple): |
| 111 |
"""IGD state.""" |
| 112 |
|
| 113 |
timestamp: datetime |
| 114 |
bytes_received: None | BaseException | int |
| 115 |
bytes_sent: None | BaseException | int |
| 116 |
packets_received: None | BaseException | int |
| 117 |
packets_sent: None | BaseException | int |
| 118 |
connection_status: None | BaseException | str |
| 119 |
last_connection_error: None | BaseException | str |
| 120 |
uptime: None | BaseException | int |
| 121 |
external_ip_address: None | BaseException | str |
| 122 |
port_mapping_number_of_entries: None | BaseException | int |
| 123 |
|
| 124 |
|
| 125 |
kibibytes_per_sec_received: None | float |
| 126 |
kibibytes_per_sec_sent: None | float |
| 127 |
packets_per_sec_received: None | float |
| 128 |
packets_per_sec_sent: None | float |
| 129 |
kibibytes_per_sec_received_no_rollover: None | float |
| 130 |
kibibytes_per_sec_sent_no_rollover: None | float |
| 131 |
packets_per_sec_received_no_rollover: None | float |
| 132 |
packets_per_sec_sent_no_rollover: None | float |
| 133 |
|
| 134 |
|
| 135 |
class IgdStateItem(Enum): |
| 136 |
""" |
| 137 |
IGD state item. |
| 138 |
|
| 139 |
Used to specify what to request from the device. |
| 140 |
""" |
| 141 |
|
| 142 |
BYTES_RECEIVED = 1 |
| 143 |
BYTES_SENT = 2 |
| 144 |
PACKETS_RECEIVED = 3 |
| 145 |
PACKETS_SENT = 4 |
| 146 |
CONNECTION_STATUS = 5 |
| 147 |
LAST_CONNECTION_ERROR = 6 |
| 148 |
UPTIME = 7 |
| 149 |
EXTERNAL_IP_ADDRESS = 8 |
| 150 |
PORT_MAPPING_NUMBER_OF_ENTRIES = 9 |
| 151 |
|
| 152 |
KIBIBYTES_PER_SEC_RECEIVED = 11 |
| 153 |
KIBIBYTES_PER_SEC_SENT = 12 |
| 154 |
PACKETS_PER_SEC_RECEIVED = 13 |
| 155 |
PACKETS_PER_SEC_SENT = 14 |
| 156 |
KIBIBYTES_PER_SEC_RECEIVED_NO_ROLLOVER = 15 |
| 157 |
KIBIBYTES_PER_SEC_SENT_NO_ROLLOVER = 16 |
| 158 |
PACKETS_PER_SEC_RECEIVED_NO_ROLLOVER = 17 |
| 159 |
PACKETS_PER_SEC_SENT_NO_ROLLOVER = 18 |
| 160 |
|
| 161 |
|
| 162 |
async def _nop() -> None: |
| 163 |
"""No-op coroutine used as a placeholder in asyncio.gather calls.""" |
| 164 |
|
| 165 |
|
| 166 |
def _derive_value_per_second( |
| 167 |
|
| 168 |
value_name: str, |
| 169 |
current_timestamp: datetime, |
| 170 |
current_value: None | BaseException | StatusInfo | int | str, |
| 171 |
last_timestamp: None | BaseException | datetime, |
| 172 |
last_value: None | BaseException | StatusInfo | int | str, |
| 173 |
handle_uint32_overflow: bool = True, |
| 174 |
) -> None | float: |
| 175 |
"""Calculate average based on current and last value.""" |
| 176 |
if ( |
| 177 |
not isinstance(current_value, int) |
| 178 |
or not isinstance(last_timestamp, datetime) |
| 179 |
or not isinstance(last_value, int) |
| 180 |
): |
| 181 |
return None |
| 182 |
|
| 183 |
if last_value > current_value: |
| 184 |
if not handle_uint32_overflow: |
| 185 |
|
| 186 |
return None |
| 187 |
|
| 188 |
current_value += 2**32 |
| 189 |
|
| 190 |
delta_time = current_timestamp - last_timestamp |
| 191 |
delta_value: int | float = current_value - last_value |
| 192 |
if value_name in (BYTES_RECEIVED, BYTES_SENT): |
| 193 |
delta_value = delta_value / 1024 |
| 194 |
return delta_value / delta_time.total_seconds() |
| 195 |
|
| 196 |
|
| 197 |
class IgdDevice(UpnpProfileDevice): |
| 198 |
"""Representation of a IGD device.""" |
| 199 |
|
| 200 |
|
| 201 |
|
| 202 |
DEVICE_TYPES = [ |
| 203 |
"urn:schemas-upnp-org:device:InternetGatewayDevice:1", |
| 204 |
"urn:schemas-upnp-org:device:InternetGatewayDevice:2", |
| 205 |
] |
| 206 |
|
| 207 |
_SERVICE_TYPES = { |
| 208 |
"WANIP6FC": { |
| 209 |
"urn:schemas-upnp-org:service:WANIPv6FirewallControl:1", |
| 210 |
}, |
| 211 |
"WANPPPC": { |
| 212 |
"urn:schemas-upnp-org:service:WANPPPConnection:1", |
| 213 |
}, |
| 214 |
"WANIPC": { |
| 215 |
"urn:schemas-upnp-org:service:WANIPConnection:1", |
| 216 |
"urn:schemas-upnp-org:service:WANIPConnection:2", |
| 217 |
}, |
| 218 |
"WANCIC": { |
| 219 |
"urn:schemas-upnp-org:service:WANCommonInterfaceConfig:1", |
| 220 |
}, |
| 221 |
"L3FWD": { |
| 222 |
"urn:schemas-upnp-org:service:Layer3Forwarding:1", |
| 223 |
}, |
| 224 |
} |
| 225 |
|
| 226 |
def __init__(self, device: UpnpDevice, event_handler: UpnpEventHandler | None) -> None: |
| 227 |
"""Initialize.""" |
| 228 |
super().__init__(device, event_handler) |
| 229 |
|
| 230 |
self._last_traffic_state = TrafficCounterState( |
| 231 |
timestamp=datetime.now(), |
| 232 |
bytes_received=None, |
| 233 |
bytes_sent=None, |
| 234 |
packets_received=None, |
| 235 |
packets_sent=None, |
| 236 |
bytes_received_original=None, |
| 237 |
bytes_sent_original=None, |
| 238 |
packets_received_original=None, |
| 239 |
packets_sent_original=None, |
| 240 |
) |
| 241 |
self._offset_bytes_received = 0 |
| 242 |
self._offset_bytes_sent = 0 |
| 243 |
self._offset_packets_received = 0 |
| 244 |
self._offset_packets_sent = 0 |
| 245 |
|
| 246 |
def _any_action(self, service_names: Sequence[str], action_name: str) -> UpnpAction | None: |
| 247 |
for service_name in service_names: |
| 248 |
action = self._action(service_name, action_name) |
| 249 |
if action is not None: |
| 250 |
return action |
| 251 |
|
| 252 |
_LOGGER.debug("Could not find action %s/%s", service_names, action_name) |
| 253 |
return None |
| 254 |
|
| 255 |
def _any_state_variable(self, service_names: Sequence[str], variable_name: str) -> UpnpStateVariable | None: |
| 256 |
for service_name in service_names: |
| 257 |
state_var = self._state_variable(service_name, variable_name) |
| 258 |
if state_var is not None: |
| 259 |
return state_var |
| 260 |
|
| 261 |
_LOGGER.debug("Could not find state variable %s/%s", service_names, variable_name) |
| 262 |
return None |
| 263 |
|
| 264 |
@property |
| 265 |
def external_ip_address(self) -> str | None: |
| 266 |
""" |
| 267 |
Get the external IP address, from the state variable ExternalIPAddress. |
| 268 |
|
| 269 |
This requires a subscription to the WANIPC/WANPPPC service. |
| 270 |
""" |
| 271 |
services = ["WANIPC", "WANPPPC"] |
| 272 |
state_var = self._any_state_variable(services, "ExternalIPAddress") |
| 273 |
if not state_var: |
| 274 |
return None |
| 275 |
|
| 276 |
external_ip_address: str | None = state_var.value |
| 277 |
return external_ip_address |
| 278 |
|
| 279 |
@property |
| 280 |
def connection_status(self) -> str | None: |
| 281 |
""" |
| 282 |
Get the connection status, from the state variable ConnectionStatus. |
| 283 |
|
| 284 |
This requires a subscription to the WANIPC/WANPPPC service. |
| 285 |
""" |
| 286 |
services = ["WANIPC", "WANPPPC"] |
| 287 |
state_var = self._any_state_variable(services, "ConnectionStatus") |
| 288 |
if not state_var: |
| 289 |
return None |
| 290 |
|
| 291 |
connection_status: str | None = state_var.value |
| 292 |
return connection_status |
| 293 |
|
| 294 |
@property |
| 295 |
def port_mapping_number_of_entries(self) -> int | None: |
| 296 |
""" |
| 297 |
Get number of port mapping entries, from the state variable `PortMappingNumberOfEntries`. |
| 298 |
|
| 299 |
This requires a subscription to the WANIPC/WANPPPC service. |
| 300 |
""" |
| 301 |
services = ["WANIPC", "WANPPPC"] |
| 302 |
state_var = self._any_state_variable(services, "PortMappingNumberOfEntries") |
| 303 |
if not state_var: |
| 304 |
return None |
| 305 |
|
| 306 |
number_of_entries: int | None = state_var.value |
| 307 |
return number_of_entries |
| 308 |
|
| 309 |
async def async_get_total_bytes_received(self) -> int | None: |
| 310 |
"""Get total bytes received.""" |
| 311 |
action = self._action("WANCIC", "GetTotalBytesReceived") |
| 312 |
if not action: |
| 313 |
return None |
| 314 |
|
| 315 |
result = await action.async_call() |
| 316 |
total_bytes_received: int | None = result.get("NewTotalBytesReceived") |
| 317 |
|
| 318 |
if total_bytes_received is None: |
| 319 |
return None |
| 320 |
|
| 321 |
if total_bytes_received < 0: |
| 322 |
self._offset_bytes_received = 2**31 |
| 323 |
|
| 324 |
return total_bytes_received + self._offset_bytes_received |
| 325 |
|
| 326 |
async def async_get_total_bytes_sent(self) -> int | None: |
| 327 |
"""Get total bytes sent.""" |
| 328 |
action = self._action("WANCIC", "GetTotalBytesSent") |
| 329 |
if not action: |
| 330 |
return None |
| 331 |
|
| 332 |
result = await action.async_call() |
| 333 |
total_bytes_sent: int | None = result.get("NewTotalBytesSent") |
| 334 |
|
| 335 |
if total_bytes_sent is None: |
| 336 |
return None |
| 337 |
|
| 338 |
if total_bytes_sent < 0: |
| 339 |
self._offset_bytes_sent = 2**31 |
| 340 |
|
| 341 |
return total_bytes_sent + self._offset_bytes_sent |
| 342 |
|
| 343 |
async def async_get_total_packets_received(self) -> int | None: |
| 344 |
"""Get total packets received.""" |
| 345 |
action = self._action("WANCIC", "GetTotalPacketsReceived") |
| 346 |
if not action: |
| 347 |
return None |
| 348 |
|
| 349 |
result = await action.async_call() |
| 350 |
total_packets_received: int | None = result.get("NewTotalPacketsReceived") |
| 351 |
|
| 352 |
if total_packets_received is None: |
| 353 |
return None |
| 354 |
|
| 355 |
if total_packets_received < 0: |
| 356 |
self._offset_packets_received = 2**31 |
| 357 |
|
| 358 |
return total_packets_received + self._offset_packets_received |
| 359 |
|
| 360 |
async def async_get_total_packets_sent(self) -> int | None: |
| 361 |
"""Get total packets sent.""" |
| 362 |
action = self._action("WANCIC", "GetTotalPacketsSent") |
| 363 |
if not action: |
| 364 |
return None |
| 365 |
|
| 366 |
result = await action.async_call() |
| 367 |
total_packets_sent: int | None = result.get("NewTotalPacketsSent") |
| 368 |
|
| 369 |
if total_packets_sent is None: |
| 370 |
return None |
| 371 |
|
| 372 |
if total_packets_sent < 0: |
| 373 |
self._offset_packets_sent = 2**31 |
| 374 |
|
| 375 |
return total_packets_sent + self._offset_packets_sent |
| 376 |
|
| 377 |
async def async_get_enabled_for_internet(self) -> bool | None: |
| 378 |
"""Get internet access enabled state.""" |
| 379 |
action = self._action("WANCIC", "GetEnabledForInternet") |
| 380 |
if not action: |
| 381 |
return None |
| 382 |
|
| 383 |
result = await action.async_call() |
| 384 |
enabled_for_internet: bool | None = result.get("NewEnabledForInternet") |
| 385 |
return enabled_for_internet |
| 386 |
|
| 387 |
async def async_set_enabled_for_internet(self, enabled: bool) -> None: |
| 388 |
""" |
| 389 |
Set internet access enabled state. |
| 390 |
|
| 391 |
:param enabled whether access should be enabled |
| 392 |
""" |
| 393 |
action = self._action("WANCIC", "SetEnabledForInternet") |
| 394 |
if not action: |
| 395 |
return |
| 396 |
|
| 397 |
await action.async_call(NewEnabledForInternet=enabled) |
| 398 |
|
| 399 |
async def async_get_common_link_properties(self) -> CommonLinkProperties | None: |
| 400 |
"""Get common link properties.""" |
| 401 |
action = self._action("WANCIC", "GetCommonLinkProperties") |
| 402 |
if not action: |
| 403 |
return None |
| 404 |
|
| 405 |
result = await action.async_call() |
| 406 |
return CommonLinkProperties( |
| 407 |
result["NewWANAccessType"], |
| 408 |
int(result["NewLayer1UpstreamMaxBitRate"]), |
| 409 |
int(result["NewLayer1DownstreamMaxBitRate"]), |
| 410 |
result["NewPhysicalLinkStatus"], |
| 411 |
) |
| 412 |
|
| 413 |
async def async_get_external_ip_address(self, services: Sequence[str] | None = None) -> str | None: |
| 414 |
""" |
| 415 |
Get the external IP address. |
| 416 |
|
| 417 |
:param services List of service names to try to get action from, |
| 418 |
defaults to [WANIPC,WANPPPC] |
| 419 |
""" |
| 420 |
services = services or ["WANIPC", "WANPPPC"] |
| 421 |
action = self._any_action(services, "GetExternalIPAddress") |
| 422 |
if not action: |
| 423 |
return None |
| 424 |
|
| 425 |
result = await action.async_call() |
| 426 |
external_ip_address: str | None = result.get("NewExternalIPAddress") |
| 427 |
return external_ip_address |
| 428 |
|
| 429 |
async def async_get_generic_port_mapping_entry( |
| 430 |
self, port_mapping_index: int, services: list[str] | None = None |
| 431 |
) -> PortMappingEntry | None: |
| 432 |
""" |
| 433 |
Get generic port mapping entry. |
| 434 |
|
| 435 |
:param port_mapping_index Index of port mapping entry |
| 436 |
:param services List of service names to try to get action from, |
| 437 |
defaults to [WANIPC,WANPPPC] |
| 438 |
""" |
| 439 |
services = services or ["WANIPC", "WANPPPC"] |
| 440 |
action = self._any_action(services, "GetGenericPortMappingEntry") |
| 441 |
if not action: |
| 442 |
return None |
| 443 |
|
| 444 |
result = await action.async_call(NewPortMappingIndex=port_mapping_index) |
| 445 |
return PortMappingEntry( |
| 446 |
(IPv4Address(result["NewRemoteHost"]) if result.get("NewRemoteHost") else None), |
| 447 |
result["NewExternalPort"], |
| 448 |
result["NewProtocol"], |
| 449 |
result["NewInternalPort"], |
| 450 |
IPv4Address(result["NewInternalClient"]), |
| 451 |
result["NewEnabled"], |
| 452 |
result["NewPortMappingDescription"], |
| 453 |
(timedelta(seconds=result["NewLeaseDuration"]) if result.get("NewLeaseDuration") else None), |
| 454 |
) |
| 455 |
|
| 456 |
async def async_get_specific_port_mapping_entry( |
| 457 |
self, |
| 458 |
remote_host: IPv4Address | None, |
| 459 |
external_port: int, |
| 460 |
protocol: str, |
| 461 |
services: list[str] | None = None, |
| 462 |
) -> PortMappingEntry | None: |
| 463 |
""" |
| 464 |
Get specific port mapping entry. |
| 465 |
|
| 466 |
:param remote_host Address of remote host or None |
| 467 |
:param external_port External port |
| 468 |
:param protocol Protocol, 'TCP' or 'UDP' |
| 469 |
:param services List of service names to try to get action from, |
| 470 |
defaults to [WANIPC,WANPPPC] |
| 471 |
""" |
| 472 |
services = services or ["WANIPC", "WANPPPC"] |
| 473 |
action = self._any_action(services, "GetSpecificPortMappingEntry") |
| 474 |
if not action: |
| 475 |
return None |
| 476 |
|
| 477 |
result = await action.async_call( |
| 478 |
NewRemoteHost=remote_host.exploded if remote_host else "", |
| 479 |
NewExternalPort=external_port, |
| 480 |
NewProtocol=protocol, |
| 481 |
) |
| 482 |
return PortMappingEntry( |
| 483 |
remote_host, |
| 484 |
external_port, |
| 485 |
protocol, |
| 486 |
result["NewInternalPort"], |
| 487 |
IPv4Address(result["NewInternalClient"]), |
| 488 |
result["NewEnabled"], |
| 489 |
result["NewPortMappingDescription"], |
| 490 |
(timedelta(seconds=result["NewLeaseDuration"]) if result.get("NewLeaseDuration") else None), |
| 491 |
) |
| 492 |
|
| 493 |
async def async_add_port_mapping( |
| 494 |
self, |
| 495 |
remote_host: IPv4Address, |
| 496 |
external_port: int, |
| 497 |
protocol: str, |
| 498 |
internal_port: int, |
| 499 |
internal_client: IPv4Address, |
| 500 |
enabled: bool, |
| 501 |
description: str, |
| 502 |
lease_duration: timedelta, |
| 503 |
services: list[str] | None = None, |
| 504 |
) -> None: |
| 505 |
""" |
| 506 |
Add a port mapping. |
| 507 |
|
| 508 |
:param remote_host Address of remote host or None |
| 509 |
:param external_port External port |
| 510 |
:param protocol Protocol, 'TCP' or 'UDP' |
| 511 |
:param internal_port Internal port |
| 512 |
:param internal_client Address of internal host |
| 513 |
:param enabled Port mapping enabled |
| 514 |
:param description Description for port mapping |
| 515 |
:param lease_duration Lease duration |
| 516 |
:param services List of service names to try to get action from, |
| 517 |
defaults to [WANIPC,WANPPPC] |
| 518 |
""" |
| 519 |
|
| 520 |
services = services or ["WANIPC", "WANPPPC"] |
| 521 |
action = self._any_action(services, "AddPortMapping") |
| 522 |
if not action: |
| 523 |
return |
| 524 |
|
| 525 |
await action.async_call( |
| 526 |
NewRemoteHost=remote_host.exploded, |
| 527 |
NewExternalPort=external_port, |
| 528 |
NewProtocol=protocol, |
| 529 |
NewInternalPort=internal_port, |
| 530 |
NewInternalClient=internal_client.exploded, |
| 531 |
NewEnabled=enabled, |
| 532 |
NewPortMappingDescription=description, |
| 533 |
NewLeaseDuration=int(lease_duration.seconds), |
| 534 |
) |
| 535 |
|
| 536 |
async def async_delete_port_mapping( |
| 537 |
self, |
| 538 |
remote_host: IPv4Address, |
| 539 |
external_port: int, |
| 540 |
protocol: str, |
| 541 |
services: list[str] | None = None, |
| 542 |
) -> None: |
| 543 |
""" |
| 544 |
Delete an existing port mapping. |
| 545 |
|
| 546 |
:param remote_host Address of remote host or None |
| 547 |
:param external_port External port |
| 548 |
:param protocol Protocol, 'TCP' or 'UDP' |
| 549 |
:param services List of service names to try to get action from, |
| 550 |
defaults to [WANIPC,WANPPPC] |
| 551 |
""" |
| 552 |
services = services or ["WANIPC", "WANPPPC"] |
| 553 |
action = self._any_action(services, "DeletePortMapping") |
| 554 |
if not action: |
| 555 |
return |
| 556 |
|
| 557 |
await action.async_call( |
| 558 |
NewRemoteHost=remote_host.exploded, |
| 559 |
NewExternalPort=external_port, |
| 560 |
NewProtocol=protocol, |
| 561 |
) |
| 562 |
|
| 563 |
async def async_get_firewall_status(self) -> FirewallStatus | None: |
| 564 |
"""Get (IPv6) firewall status.""" |
| 565 |
action = self._action("WANIP6FC", "GetFirewallStatus") |
| 566 |
if not action: |
| 567 |
return None |
| 568 |
|
| 569 |
result = await action.async_call() |
| 570 |
return FirewallStatus( |
| 571 |
result["FirewallEnabled"], |
| 572 |
result["InboundPinholeAllowed"], |
| 573 |
) |
| 574 |
|
| 575 |
async def async_add_pinhole( |
| 576 |
self, |
| 577 |
remote_host: IPv6Address, |
| 578 |
remote_port: int, |
| 579 |
internal_client: IPv6Address, |
| 580 |
internal_port: int, |
| 581 |
protocol: int, |
| 582 |
lease_time: timedelta, |
| 583 |
) -> int | None: |
| 584 |
"""Add a pinhole.""" |
| 585 |
|
| 586 |
action = self._action("WANIP6FC", "AddPinhole") |
| 587 |
if not action: |
| 588 |
return None |
| 589 |
|
| 590 |
result = await action.async_call( |
| 591 |
RemoteHost=str(remote_host), |
| 592 |
RemotePort=remote_port, |
| 593 |
InternalClient=str(internal_client), |
| 594 |
InternalPort=internal_port, |
| 595 |
Protocol=protocol, |
| 596 |
LeaseTime=int(lease_time.total_seconds()), |
| 597 |
) |
| 598 |
return cast(int, result["UniqueID"]) |
| 599 |
|
| 600 |
async def async_update_pinhole(self, pinhole_id: int, new_lease_time: int) -> None: |
| 601 |
"""Update pinhole.""" |
| 602 |
action = self._action("WANIP6FC", "UpdatePinhole") |
| 603 |
if not action: |
| 604 |
return |
| 605 |
|
| 606 |
await action.async_call( |
| 607 |
UniqueID=pinhole_id, |
| 608 |
NewLeaseTime=new_lease_time, |
| 609 |
) |
| 610 |
|
| 611 |
async def async_delete_pinhole(self, pinhole_id: int) -> None: |
| 612 |
"""Delete an existing pinhole.""" |
| 613 |
action = self._action("WANIP6FC", "DeletePinhole") |
| 614 |
if not action: |
| 615 |
return |
| 616 |
|
| 617 |
await action.async_call( |
| 618 |
UniqueID=pinhole_id, |
| 619 |
) |
| 620 |
|
| 621 |
async def async_get_pinhole_packets(self, pinhole_id: int) -> int | None: |
| 622 |
"""Get pinhole packet count.""" |
| 623 |
action = self._action("WANIP6FC", "GetPinholePackets") |
| 624 |
if not action: |
| 625 |
return None |
| 626 |
|
| 627 |
result = await action.async_call( |
| 628 |
UniqueID=pinhole_id, |
| 629 |
) |
| 630 |
return cast(int, result["PinholePackets"]) |
| 631 |
|
| 632 |
async def async_get_connection_type_info(self, services: Sequence[str] | None = None) -> ConnectionTypeInfo | None: |
| 633 |
""" |
| 634 |
Get connection type info. |
| 635 |
|
| 636 |
:param services List of service names to try to get action from, |
| 637 |
defaults to [WANIPC,WANPPPC] |
| 638 |
""" |
| 639 |
services = services or ["WANIPC", "WANPPPC"] |
| 640 |
action = self._any_action(services, "GetConnectionTypeInfo") |
| 641 |
if not action: |
| 642 |
return None |
| 643 |
|
| 644 |
result = await action.async_call() |
| 645 |
return ConnectionTypeInfo(result["NewConnectionType"], result["NewPossibleConnectionTypes"]) |
| 646 |
|
| 647 |
async def async_set_connection_type(self, connection_type: str, services: list[str] | None = None) -> None: |
| 648 |
""" |
| 649 |
Set connection type. |
| 650 |
|
| 651 |
:param connection_type connection type |
| 652 |
:param services List of service names to try to get action from, |
| 653 |
defaults to [WANIPC,WANPPPC] |
| 654 |
""" |
| 655 |
services = services or ["WANIPC", "WANPPPC"] |
| 656 |
action = self._any_action(services, "SetConnectionType") |
| 657 |
if not action: |
| 658 |
return |
| 659 |
|
| 660 |
await action.async_call(NewConnectionType=connection_type) |
| 661 |
|
| 662 |
async def async_request_connection(self, services: Sequence[str] | None = None) -> None: |
| 663 |
""" |
| 664 |
Request connection. |
| 665 |
|
| 666 |
:param services List of service names to try to get action from, |
| 667 |
defaults to [WANIPC,WANPPPC] |
| 668 |
""" |
| 669 |
services = services or ["WANIPC", "WANPPPC"] |
| 670 |
action = self._any_action(services, "RequestConnection") |
| 671 |
if not action: |
| 672 |
return |
| 673 |
|
| 674 |
await action.async_call() |
| 675 |
|
| 676 |
async def async_request_termination(self, services: Sequence[str] | None = None) -> None: |
| 677 |
""" |
| 678 |
Request connection termination. |
| 679 |
|
| 680 |
:param services List of service names to try to get action from, |
| 681 |
defaults to [WANIPC,WANPPPC] |
| 682 |
""" |
| 683 |
services = services or ["WANIPC", "WANPPPC"] |
| 684 |
action = self._any_action(services, "RequestTermination") |
| 685 |
if not action: |
| 686 |
return |
| 687 |
|
| 688 |
await action.async_call() |
| 689 |
|
| 690 |
async def async_force_termination(self, services: Sequence[str] | None = None) -> None: |
| 691 |
""" |
| 692 |
Force connection termination. |
| 693 |
|
| 694 |
:param services List of service names to try to get action from, |
| 695 |
defaults to [WANIPC,WANPPPC] |
| 696 |
""" |
| 697 |
services = services or ["WANIPC", "WANPPPC"] |
| 698 |
action = self._any_action(services, "ForceTermination") |
| 699 |
if not action: |
| 700 |
return |
| 701 |
|
| 702 |
await action.async_call() |
| 703 |
|
| 704 |
async def async_get_status_info(self, services: Sequence[str] | None = None) -> StatusInfo | None: |
| 705 |
""" |
| 706 |
Get status info. |
| 707 |
|
| 708 |
:param services List of service names to try to get action from, |
| 709 |
defaults to [WANIPC,WANPPPC] |
| 710 |
""" |
| 711 |
services = services or ["WANIPC", "WANPPPC"] |
| 712 |
action = self._any_action(services, "GetStatusInfo") |
| 713 |
if not action: |
| 714 |
return None |
| 715 |
|
| 716 |
try: |
| 717 |
result = await action.async_call() |
| 718 |
except ValueError: |
| 719 |
_LOGGER.debug("Caught ValueError parsing results") |
| 720 |
return None |
| 721 |
|
| 722 |
return StatusInfo( |
| 723 |
result["NewConnectionStatus"], |
| 724 |
result["NewLastConnectionError"], |
| 725 |
result["NewUptime"], |
| 726 |
) |
| 727 |
|
| 728 |
async def async_get_port_mapping_number_of_entries(self, services: Sequence[str] | None = None) -> int | None: |
| 729 |
""" |
| 730 |
Get number of port mapping entries. |
| 731 |
|
| 732 |
Note that this action is not officially supported by the IGD specification. |
| 733 |
|
| 734 |
:param services List of service names to try to get action from, |
| 735 |
defaults to [WANIPC,WANPPPC] |
| 736 |
""" |
| 737 |
services = services or ["WANIPC", "WANPPPC"] |
| 738 |
action = self._any_action(services, "GetPortMappingNumberOfEntries") |
| 739 |
if not action: |
| 740 |
return None |
| 741 |
|
| 742 |
result = await action.async_call() |
| 743 |
number_of_entries: str | None = result.get("NewPortMappingNumberOfEntries") |
| 744 |
if number_of_entries is None: |
| 745 |
return None |
| 746 |
return int(number_of_entries) |
| 747 |
|
| 748 |
async def async_get_nat_rsip_status(self, services: Sequence[str] | None = None) -> NatRsipStatusInfo | None: |
| 749 |
""" |
| 750 |
Get NAT enabled and RSIP availability statuses. |
| 751 |
|
| 752 |
:param services List of service names to try to get action from, |
| 753 |
defaults to [WANIPC,WANPPPC] |
| 754 |
""" |
| 755 |
services = services or ["WANIPC", "WANPPPC"] |
| 756 |
action = self._any_action(services, "GetNATRSIPStatus") |
| 757 |
if not action: |
| 758 |
return None |
| 759 |
|
| 760 |
result = await action.async_call() |
| 761 |
return NatRsipStatusInfo(result["NewNATEnabled"], result["NewRSIPAvailable"]) |
| 762 |
|
| 763 |
async def async_get_default_connection_service(self) -> str | None: |
| 764 |
"""Get default connection service.""" |
| 765 |
action = self._action("L3FWD", "GetDefaultConnectionService") |
| 766 |
if not action: |
| 767 |
return None |
| 768 |
|
| 769 |
result = await action.async_call() |
| 770 |
default_connection_service: str | None = result.get("NewDefaultConnectionService") |
| 771 |
return default_connection_service |
| 772 |
|
| 773 |
async def async_set_default_connection_service(self, service: str) -> None: |
| 774 |
""" |
| 775 |
Set default connection service. |
| 776 |
|
| 777 |
:param service default connection service |
| 778 |
""" |
| 779 |
action = self._action("L3FWD", "SetDefaultConnectionService") |
| 780 |
if not action: |
| 781 |
return |
| 782 |
|
| 783 |
await action.async_call(NewDefaultConnectionService=service) |
| 784 |
|
| 785 |
async def async_poll_traffic_data( |
| 786 |
self, |
| 787 |
items: set[IgdStateItem], |
| 788 |
) -> TrafficCounterState: |
| 789 |
"""Poll current traffic counter data from the device.""" |
| 790 |
timestamp = datetime.now() |
| 791 |
values = await asyncio.gather( |
| 792 |
( |
| 793 |
self.async_get_total_bytes_received() |
| 794 |
if IgdStateItem.BYTES_RECEIVED in items |
| 795 |
or IgdStateItem.KIBIBYTES_PER_SEC_RECEIVED in items |
| 796 |
or IgdStateItem.KIBIBYTES_PER_SEC_RECEIVED_NO_ROLLOVER in items |
| 797 |
else _nop() |
| 798 |
), |
| 799 |
( |
| 800 |
self.async_get_total_bytes_sent() |
| 801 |
if IgdStateItem.BYTES_SENT in items |
| 802 |
or IgdStateItem.KIBIBYTES_PER_SEC_SENT in items |
| 803 |
or IgdStateItem.KIBIBYTES_PER_SEC_SENT_NO_ROLLOVER in items |
| 804 |
else _nop() |
| 805 |
), |
| 806 |
( |
| 807 |
self.async_get_total_packets_received() |
| 808 |
if IgdStateItem.PACKETS_RECEIVED in items |
| 809 |
or IgdStateItem.PACKETS_PER_SEC_RECEIVED in items |
| 810 |
or IgdStateItem.PACKETS_PER_SEC_RECEIVED_NO_ROLLOVER in items |
| 811 |
else _nop() |
| 812 |
), |
| 813 |
( |
| 814 |
self.async_get_total_packets_sent() |
| 815 |
if IgdStateItem.PACKETS_SENT in items |
| 816 |
or IgdStateItem.PACKETS_PER_SEC_SENT in items |
| 817 |
or IgdStateItem.PACKETS_PER_SEC_SENT_NO_ROLLOVER in items |
| 818 |
else _nop() |
| 819 |
), |
| 820 |
return_exceptions=True, |
| 821 |
) |
| 822 |
|
| 823 |
return TrafficCounterState( |
| 824 |
timestamp=timestamp, |
| 825 |
bytes_received=values[0], |
| 826 |
bytes_sent=values[1], |
| 827 |
packets_received=values[2], |
| 828 |
packets_sent=values[3], |
| 829 |
bytes_received_original=values[0], |
| 830 |
bytes_sent_original=values[1], |
| 831 |
packets_received_original=values[2], |
| 832 |
packets_sent_original=values[3], |
| 833 |
) |
| 834 |
|
| 835 |
def _build_igd_state( |
| 836 |
|
| 837 |
self, |
| 838 |
current_traffic: TrafficCounterState, |
| 839 |
last_traffic: TrafficCounterState, |
| 840 |
status_info: StatusInfo | BaseException | None = None, |
| 841 |
external_ip_address: str | BaseException | None = None, |
| 842 |
port_mapping_number_of_entries: int | BaseException | None = None, |
| 843 |
connection_status: str | None = None, |
| 844 |
) -> IgdState: |
| 845 |
"""Build IgdState with derived rates from two traffic counter states.""" |
| 846 |
kibibytes_per_sec_received = _derive_value_per_second( |
| 847 |
BYTES_RECEIVED, |
| 848 |
current_traffic.timestamp, |
| 849 |
current_traffic.bytes_received, |
| 850 |
last_traffic.timestamp, |
| 851 |
last_traffic.bytes_received, |
| 852 |
) |
| 853 |
kibibytes_per_sec_sent = _derive_value_per_second( |
| 854 |
BYTES_SENT, |
| 855 |
current_traffic.timestamp, |
| 856 |
current_traffic.bytes_sent, |
| 857 |
last_traffic.timestamp, |
| 858 |
last_traffic.bytes_sent, |
| 859 |
) |
| 860 |
packets_per_sec_received = _derive_value_per_second( |
| 861 |
PACKETS_RECEIVED, |
| 862 |
current_traffic.timestamp, |
| 863 |
current_traffic.packets_received, |
| 864 |
last_traffic.timestamp, |
| 865 |
last_traffic.packets_received, |
| 866 |
) |
| 867 |
packets_per_sec_sent = _derive_value_per_second( |
| 868 |
PACKETS_SENT, |
| 869 |
current_traffic.timestamp, |
| 870 |
current_traffic.packets_sent, |
| 871 |
last_traffic.timestamp, |
| 872 |
last_traffic.packets_sent, |
| 873 |
) |
| 874 |
kibibytes_per_sec_received_no_rollover = _derive_value_per_second( |
| 875 |
BYTES_RECEIVED, |
| 876 |
current_traffic.timestamp, |
| 877 |
current_traffic.bytes_received, |
| 878 |
last_traffic.timestamp, |
| 879 |
last_traffic.bytes_received, |
| 880 |
handle_uint32_overflow=False, |
| 881 |
) |
| 882 |
kibibytes_per_sec_sent_no_rollover = _derive_value_per_second( |
| 883 |
BYTES_SENT, |
| 884 |
current_traffic.timestamp, |
| 885 |
current_traffic.bytes_sent, |
| 886 |
last_traffic.timestamp, |
| 887 |
last_traffic.bytes_sent, |
| 888 |
handle_uint32_overflow=False, |
| 889 |
) |
| 890 |
packets_per_sec_received_no_rollover = _derive_value_per_second( |
| 891 |
PACKETS_RECEIVED, |
| 892 |
current_traffic.timestamp, |
| 893 |
current_traffic.packets_received, |
| 894 |
last_traffic.timestamp, |
| 895 |
last_traffic.packets_received, |
| 896 |
handle_uint32_overflow=False, |
| 897 |
) |
| 898 |
packets_per_sec_sent_no_rollover = _derive_value_per_second( |
| 899 |
PACKETS_SENT, |
| 900 |
current_traffic.timestamp, |
| 901 |
current_traffic.packets_sent, |
| 902 |
last_traffic.timestamp, |
| 903 |
last_traffic.packets_sent, |
| 904 |
handle_uint32_overflow=False, |
| 905 |
) |
| 906 |
|
| 907 |
return IgdState( |
| 908 |
timestamp=current_traffic.timestamp, |
| 909 |
bytes_received=current_traffic.bytes_received, |
| 910 |
bytes_sent=current_traffic.bytes_sent, |
| 911 |
packets_received=current_traffic.packets_received, |
| 912 |
packets_sent=current_traffic.packets_sent, |
| 913 |
kibibytes_per_sec_received=kibibytes_per_sec_received, |
| 914 |
kibibytes_per_sec_sent=kibibytes_per_sec_sent, |
| 915 |
packets_per_sec_received=packets_per_sec_received, |
| 916 |
packets_per_sec_sent=packets_per_sec_sent, |
| 917 |
kibibytes_per_sec_received_no_rollover=kibibytes_per_sec_received_no_rollover, |
| 918 |
kibibytes_per_sec_sent_no_rollover=kibibytes_per_sec_sent_no_rollover, |
| 919 |
packets_per_sec_received_no_rollover=packets_per_sec_received_no_rollover, |
| 920 |
packets_per_sec_sent_no_rollover=packets_per_sec_sent_no_rollover, |
| 921 |
connection_status=( |
| 922 |
status_info.connection_status if isinstance(status_info, StatusInfo) else connection_status |
| 923 |
), |
| 924 |
last_connection_error=(status_info.last_connection_error if isinstance(status_info, StatusInfo) else None), |
| 925 |
uptime=status_info.uptime if isinstance(status_info, StatusInfo) else None, |
| 926 |
external_ip_address=external_ip_address, |
| 927 |
port_mapping_number_of_entries=port_mapping_number_of_entries, |
| 928 |
) |
| 929 |
|
| 930 |
async def async_get_traffic_and_status_data( |
| 931 |
self, |
| 932 |
items: set[IgdStateItem] | None = None, |
| 933 |
force_poll: bool = False, |
| 934 |
) -> IgdState: |
| 935 |
""" |
| 936 |
Get all traffic data at once, including derived data. |
| 937 |
|
| 938 |
Data: |
| 939 |
* total bytes received |
| 940 |
* total bytes sent |
| 941 |
* total packets received |
| 942 |
* total packets sent |
| 943 |
* bytes per second received (derived from last update) |
| 944 |
* bytes per second sent (derived from last update) |
| 945 |
* packets per second received (derived from last update) |
| 946 |
* packets per second sent (derived from last update) |
| 947 |
* bytes per second received, with uint32 overflow handling (derived from last update) |
| 948 |
* bytes per second sent, with uint32 overflow handling (derived from last update) |
| 949 |
* packets per second received, with uint32 overflow handling (derived from last update) |
| 950 |
* packets per second sent, with uint32 overflow handling (derived from last update) |
| 951 |
* connection status (status info) |
| 952 |
* last connection error (status info) |
| 953 |
* uptime (status info) |
| 954 |
* external IP address |
| 955 |
* number of port mapping entries |
| 956 |
""" |
| 957 |
|
| 958 |
items = items or set(IgdStateItem) |
| 959 |
|
| 960 |
external_ip_address: str | None = None |
| 961 |
connection_status: str | None = None |
| 962 |
port_mapping_number_of_entries: int | None = None |
| 963 |
if not force_poll: |
| 964 |
if ( |
| 965 |
IgdStateItem.EXTERNAL_IP_ADDRESS in items |
| 966 |
and (external_ip_address := self.external_ip_address) is not None |
| 967 |
): |
| 968 |
items.remove(IgdStateItem.EXTERNAL_IP_ADDRESS) |
| 969 |
|
| 970 |
if IgdStateItem.CONNECTION_STATUS in items and (connection_status := self.connection_status) is not None: |
| 971 |
items.remove(IgdStateItem.CONNECTION_STATUS) |
| 972 |
|
| 973 |
if ( |
| 974 |
IgdStateItem.PORT_MAPPING_NUMBER_OF_ENTRIES in items |
| 975 |
and (port_mapping_number_of_entries := self.port_mapping_number_of_entries) is not None |
| 976 |
): |
| 977 |
items.remove(IgdStateItem.PORT_MAPPING_NUMBER_OF_ENTRIES) |
| 978 |
|
| 979 |
current_traffic_state = await self.async_poll_traffic_data(items) |
| 980 |
|
| 981 |
status_values = await asyncio.gather( |
| 982 |
( |
| 983 |
self.async_get_status_info() |
| 984 |
if IgdStateItem.CONNECTION_STATUS in items |
| 985 |
or IgdStateItem.LAST_CONNECTION_ERROR in items |
| 986 |
or IgdStateItem.UPTIME in items |
| 987 |
else _nop() |
| 988 |
), |
| 989 |
(self.async_get_external_ip_address() if IgdStateItem.EXTERNAL_IP_ADDRESS in items else _nop()), |
| 990 |
( |
| 991 |
self.async_get_port_mapping_number_of_entries() |
| 992 |
if IgdStateItem.PORT_MAPPING_NUMBER_OF_ENTRIES in items |
| 993 |
else _nop() |
| 994 |
), |
| 995 |
return_exceptions=True, |
| 996 |
) |
| 997 |
|
| 998 |
last_traffic_state = self._last_traffic_state |
| 999 |
self._last_traffic_state = current_traffic_state |
| 1000 |
|
| 1001 |
|
| 1002 |
all_values: list[object] = [ |
| 1003 |
current_traffic_state.bytes_received, |
| 1004 |
current_traffic_state.bytes_sent, |
| 1005 |
current_traffic_state.packets_received, |
| 1006 |
current_traffic_state.packets_sent, |
| 1007 |
*status_values, |
| 1008 |
] |
| 1009 |
non_exceptions = [value for value in all_values if not isinstance(value, BaseException)] |
| 1010 |
if not non_exceptions: |
| 1011 |
|
| 1012 |
exc = cast(BaseException, current_traffic_state.bytes_received) |
| 1013 |
raise exc |
| 1014 |
|
| 1015 |
return self._build_igd_state( |
| 1016 |
current_traffic=current_traffic_state, |
| 1017 |
last_traffic=last_traffic_state, |
| 1018 |
status_info=status_values[0], |
| 1019 |
external_ip_address=status_values[1] or external_ip_address, |
| 1020 |
port_mapping_number_of_entries=status_values[2] or port_mapping_number_of_entries, |
| 1021 |
connection_status=connection_status, |
| 1022 |
) |