Debian Codegraph @

asusrouter/modules/state.py

raw
1 """State module."""
2
3 from __future__ import annotations
4
5 from collections.abc import Awaitable, Callable
6 from enum import Enum
7 import importlib
8 import logging
9 from types import ModuleType
10 from typing import Any
11
12 from asusrouter.modules.aura import AsusAura
13 from asusrouter.modules.connection import ConnectionState
14 from asusrouter.modules.data import AsusData, AsusDataState
15 from asusrouter.modules.ddns import AsusDDNS
16 from asusrouter.modules.parental_control import (
17 AsusBlockAll,
18 AsusParentalControl,
19 ParentalControlRule,
20 )
21 from asusrouter.modules.port_forwarding import AsusPortForwarding
22 from asusrouter.modules.system import AsusSystem
23 from asusrouter.modules.vpnc import AsusVPNC
24 from asusrouter.modules.wireguard import (
25 AsusWireGuardClient,
26 AsusWireGuardServer,
27 )
28 from asusrouter.modules.wlan import AsusWLAN
29 from asusrouter.tools.converters import get_enum_key_by_value
30
31 from .led import AsusLED
32 from .openvpn import AsusOVPNClient, AsusOVPNServer
33
34 _LOGGER = logging.getLogger(__name__)
35
36
37 class AsusStateNone(int, Enum):
38 """Asus state none."""
39
40 NONE = 0
41
42
43 # AsusState = Union[AsusLED, AsusOVPNClient, AsusOVPNServer, AsusStateNone]
44
45
46 class AsusState(Enum):
47 """Asus state."""
48
49 NONE = AsusStateNone
50 AURA = AsusAura
51 BLOCK_ALL = AsusBlockAll
52 CONNECTION = ConnectionState
53 DDNS = AsusDDNS
54 LED = AsusLED
55 OPENVPN_CLIENT = AsusOVPNClient
56 OPENVPN_SERVER = AsusOVPNServer
57 PARENTAL_CONTROL = AsusParentalControl
58 PC_RULE = ParentalControlRule
59 PORT_FORWARDING = AsusPortForwarding
60 SYSTEM = AsusSystem
61 VPNC = AsusVPNC
62 WIREGUARD_CLIENT = AsusWireGuardClient
63 WIREGUARD_SERVER = AsusWireGuardServer
64 WLAN = AsusWLAN
65
66
67 AsusStateMap: dict[AsusState, AsusData | None] = {
68 AsusState.NONE: None,
69 AsusState.AURA: AsusData.AURA,
70 AsusState.BLOCK_ALL: AsusData.PARENTAL_CONTROL,
71 AsusState.CONNECTION: None,
72 AsusState.DDNS: None,
73 AsusState.LED: AsusData.LED,
74 AsusState.OPENVPN_CLIENT: AsusData.OPENVPN_CLIENT,
75 AsusState.OPENVPN_SERVER: AsusData.OPENVPN_SERVER,
76 AsusState.PARENTAL_CONTROL: AsusData.PARENTAL_CONTROL,
77 AsusState.PC_RULE: AsusData.PARENTAL_CONTROL,
78 AsusState.PORT_FORWARDING: AsusData.PORT_FORWARDING,
79 AsusState.SYSTEM: AsusData.SYSTEM,
80 AsusState.VPNC: AsusData.VPNC,
81 AsusState.WIREGUARD_CLIENT: AsusData.WIREGUARD_CLIENT,
82 AsusState.WIREGUARD_SERVER: AsusData.WIREGUARD_SERVER,
83 AsusState.WLAN: AsusData.WLAN,
84 }
85
86
87 def add_conditional_state(state: AsusState, data: AsusData) -> None:
88 """Add or change AsusStateMap."""
89
90 if not isinstance(state, AsusState) or not isinstance(data, AsusData):
91 _LOGGER.debug("Invalid state or data type: %s -> %s", state, data)
92 return
93
94 AsusStateMap[state] = data
95 _LOGGER.debug("Added conditional state rule: %s -> %s", state, data)
96
97
98 def get_datatype(state: Any | None) -> AsusData | None:
99 """Get the datatype."""
100
101 asus_state = get_enum_key_by_value(
102 AsusState, type(state), default=AsusState.NONE
103 )
104
105 return AsusStateMap.get(asus_state)
106
107
108 def _get_module_name(state: AsusState) -> str | None:
109 """Get the module name."""
110
111 module_class = get_datatype(state)
112 if module_class:
113 return module_class.value
114
115 return None
116
117
118 def _get_module(state: AsusState) -> ModuleType | None:
119 """Get the module."""
120
121 # Module name
122 module_name = _get_module_name(state)
123 if not module_name:
124 return None
125
126 if module_name.endswith(("_client", "_server")):
127 module_name = module_name[:-7]
128
129 # Module path
130 module_path = f"asusrouter.modules.{module_name}"
131
132 try:
133 # Import and return the module
134 return importlib.import_module(module_path)
135 except ModuleNotFoundError:
136 _LOGGER.debug("No module found for state %s", state)
137 return None
138
139
140 def _has_method(module: ModuleType, method: str) -> bool:
141 """Check if the module has the method."""
142
143 return hasattr(module, method) and callable(getattr(module, method))
144
145
146 async def set_state(
147 callback: Callable[..., Awaitable[bool]],
148 state: AsusState,
149 **kwargs: Any,
150 ) -> bool:
151 """Set the state."""
152
153 # Get the module
154 submodule = _get_module(state)
155
156 # Process the data if module found
157 if submodule and _has_method(submodule, "set_state"):
158 # Determine the extra parameter
159 if getattr(submodule, "REQUIRE_STATE", False):
160 kwargs["extra_param"] = kwargs.get("router_state")
161 if getattr(submodule, "REQUIRE_IDENTITY", False):
162 kwargs["extra_param"] = kwargs.get("identity")
163
164 # Call the function with the determined parameters
165 return await submodule.set_state(
166 callback=callback,
167 state=state,
168 **kwargs,
169 )
170
171 if submodule is None:
172 # Log the enum class and member name if possible
173 if isinstance(state, Enum):
174 _LOGGER.debug(
175 "No module found for state %s.%s",
176 type(state).__name__,
177 state.name,
178 )
179 else:
180 _LOGGER.debug("No module found for state %r", state)
181
182 return False
183
184
185 def save_state(
186 state: AsusState,
187 library: dict[AsusData, AsusDataState],
188 needed_time: int | None = None,
189 last_id: int | None = None,
190 ) -> None:
191 """Save the state."""
192
193 # Get the correct data key
194 datatype = get_datatype(state)
195 if datatype is None or datatype not in library:
196 return
197
198 # Save the state
199 library[datatype].update_state(state, last_id)
200 library[datatype].offset_time(needed_time)
201
202
203 async def keep_state(
204 callback: Callable[..., Awaitable[Any]],
205 states: AsusState | list[AsusState] | None,
206 **kwargs: Any,
207 ) -> None:
208 """Keep the state."""
209
210 if states is None:
211 return
212
213 # Make sure the state is a list
214 states = [states] if not isinstance(states, list) else states
215
216 # Process each state
217 awaitables = [
218 submodule.keep_state(callback, state, **kwargs)
219 for state in states
220 if (submodule := _get_module(state))
221 and _has_method(submodule, "keep_state")
222 ]
223
224 # Execute all awaitables
225 for awaitable in awaitables:
226 await awaitable