| 1 |
"""WireGuard module.""" |
| 2 |
|
| 3 |
from __future__ import annotations |
| 4 |
|
| 5 |
from collections.abc import Awaitable, Callable |
| 6 |
from enum import IntEnum |
| 7 |
import logging |
| 8 |
from typing import Any |
| 9 |
|
| 10 |
_LOGGER = logging.getLogger(__name__) |
| 11 |
|
| 12 |
|
| 13 |
class AsusWireGuardClient(IntEnum): |
| 14 |
"""Asus WireGuard client state.""" |
| 15 |
|
| 16 |
UNKNOWN = -999 |
| 17 |
OFF = 0 |
| 18 |
ON = 1 |
| 19 |
|
| 20 |
|
| 21 |
class AsusWireGuardServer(IntEnum): |
| 22 |
"""Asus WireGuard server state.""" |
| 23 |
|
| 24 |
UNKNOWN = -999 |
| 25 |
OFF = 0 |
| 26 |
ON = 1 |
| 27 |
|
| 28 |
|
| 29 |
def _get_arguments(**kwargs: Any) -> int | None: |
| 30 |
"""Get the arguments from kwargs.""" |
| 31 |
|
| 32 |
arguments = kwargs.get("arguments", {}) |
| 33 |
|
| 34 |
# Get the id from arguments |
| 35 |
wlan_id = arguments.get("id") if arguments else kwargs.get("id") |
| 36 |
if wlan_id is None: |
| 37 |
wlan_id = 1 |
| 38 |
_LOGGER.debug("Using default id 1") |
| 39 |
|
| 40 |
return wlan_id |
| 41 |
|
| 42 |
|
| 43 |
async def set_state( |
| 44 |
callback: Callable[..., Awaitable[bool]], |
| 45 |
state: AsusWireGuardClient | AsusWireGuardServer, |
| 46 |
**kwargs: Any, |
| 47 |
) -> bool: |
| 48 |
"""Set the WireGuard state.""" |
| 49 |
|
| 50 |
# Get the arguments |
| 51 |
wlan_id = _get_arguments(**kwargs) |
| 52 |
|
| 53 |
# WireGuard unit type (server or client) |
| 54 |
wg_unit = "wgs" if isinstance(state, AsusWireGuardServer) else "wgc" |
| 55 |
|
| 56 |
# Callback arguments |
| 57 |
callback_arguments = { |
| 58 |
"id": wlan_id, |
| 59 |
f"{wg_unit}_enable": 1 |
| 60 |
if state in (AsusWireGuardClient.ON, AsusWireGuardServer.ON) |
| 61 |
else 0, |
| 62 |
f"{wg_unit}_unit": wlan_id, |
| 63 |
} |
| 64 |
|
| 65 |
# Get the expect_modify argument |
| 66 |
expect_modify = kwargs.get("expect_modify", False) |
| 67 |
|
| 68 |
# Get the correct service call |
| 69 |
service_map: dict[Any, str] = { |
| 70 |
(AsusWireGuardClient, AsusWireGuardClient.ON): f"start_wgc {wlan_id}", |
| 71 |
(AsusWireGuardClient, AsusWireGuardClient.OFF): f"stop_wgc {wlan_id}", |
| 72 |
( |
| 73 |
AsusWireGuardServer, |
| 74 |
AsusWireGuardServer.ON, |
| 75 |
): "restart_wgs;restart_dnsmasq", |
| 76 |
( |
| 77 |
AsusWireGuardServer, |
| 78 |
AsusWireGuardServer.OFF, |
| 79 |
): "restart_wgs;restart_dnsmasq", |
| 80 |
} |
| 81 |
|
| 82 |
service = service_map.get((type(state), state)) |
| 83 |
|
| 84 |
if not service: |
| 85 |
_LOGGER.debug("Unknown state %s", state) |
| 86 |
return False |
| 87 |
|
| 88 |
# Call the service |
| 89 |
return await callback( |
| 90 |
service=service, |
| 91 |
arguments=callback_arguments, |
| 92 |
apply=True, |
| 93 |
expect_modify=expect_modify, |
| 94 |
) |