Debian Codegraph @

asusrouter/config.py

raw
1 """Configuration module for AsusRouter."""
2
3 from __future__ import annotations
4
5 from collections.abc import Callable
6 from enum import StrEnum
7 import threading
8 from typing import Any
9
10 from asusrouter.tools.converters import safe_bool, safe_int
11 from asusrouter.tools.security import ARSecurityLevel
12
13
14 class ARConfigKeyBase(StrEnum):
15 """Base configuration key class."""
16
17
18 class ARConfigKey(ARConfigKeyBase):
19 """Configuration keys for AsusRouter."""
20
21 # Debug payload
22 DEBUG_PAYLOAD = "debug_payload"
23 # Optimistic data
24 OPTIMISTIC_DATA = "optimistic_data"
25 # Optimistic temperature
26 OPTIMISTIC_TEMPERATURE = "optimistic_temperature"
27 NOTIFIED_OPTIMISTIC_TEMPERATURE = "notified_optimistic_temperature"
28 # Robust boottime
29 ROBUST_BOOTTIME = "robust_boottime"
30
31
32 CONFIG_DEFAULT_BOOL: bool = False
33 CONFIG_DEFAULT_INT: int = 0
34 CONFIG_DEFAULT_ALREADY_NOTIFIED: bool = False
35
36
37 def safe_bool_config(value: Any) -> bool:
38 """Convert a value to a boolean, defaulting to CONFIG_DEFAULT_BOOL."""
39
40 config_value: bool | None = safe_bool(value)
41
42 if config_value is None:
43 return CONFIG_DEFAULT_BOOL
44
45 return config_value
46
47
48 def safe_int_config(value: Any) -> int:
49 """Convert a value to an integer, defaulting to CONFIG_DEFAULT_INT."""
50
51 config_value: int | None = safe_int(value)
52
53 if config_value is None:
54 return CONFIG_DEFAULT_INT
55
56 return config_value
57
58
59 CONFIG_DEFAULT: dict[ARConfigKey, Any] = {
60 # If set, payload sent to the router will be available
61 # in the debug logs
62 ARConfigKey.DEBUG_PAYLOAD: ARSecurityLevel.DEFAULT,
63 ARConfigKey.OPTIMISTIC_DATA: CONFIG_DEFAULT_BOOL,
64 # If set, the temperature will be automatically adjusted
65 # to fit the expected range
66 ARConfigKey.OPTIMISTIC_TEMPERATURE: CONFIG_DEFAULT_BOOL,
67 ARConfigKey.NOTIFIED_OPTIMISTIC_TEMPERATURE: CONFIG_DEFAULT_ALREADY_NOTIFIED, # noqa: E501
68 # If set, the boottime will be processed with 2 seconds
69 # precision to avoid +- 1 second uncertainty in the raw data.
70 ARConfigKey.ROBUST_BOOTTIME: CONFIG_DEFAULT_BOOL,
71 }
72
73 TYPES_DEFAULT: dict[ARConfigKey, Callable[[Any], Any]] = {
74 # Debug payload
75 ARConfigKey.DEBUG_PAYLOAD: ARSecurityLevel.from_value,
76 # Optimistic data
77 ARConfigKey.OPTIMISTIC_DATA: safe_bool_config,
78 # Optimistic temperature
79 ARConfigKey.OPTIMISTIC_TEMPERATURE: safe_bool_config,
80 ARConfigKey.NOTIFIED_OPTIMISTIC_TEMPERATURE: safe_bool_config,
81 # Robust boottime
82 ARConfigKey.ROBUST_BOOTTIME: safe_bool_config,
83 }
84
85
86 class ARConfigBase:
87 """Base class for configuration options."""
88
89 def __init__(self) -> None:
90 """Initialize the base configuration."""
91
92 self._lock = threading.Lock()
93 self._options: dict[ARConfigKeyBase, Any] = {}
94 self._types: dict[ARConfigKeyBase, Callable[[Any], Any]] = {}
95
96 def set(self, key: ARConfigKeyBase, value: Any) -> None:
97 """Set the configuration option."""
98
99 with self._lock:
100 if isinstance(key, ARConfigKeyBase) and key in self._options:
101 converter: Callable[[Any], Any] = self._types.get(
102 key, safe_bool_config
103 )
104 self._options[key] = converter(value)
105 else:
106 raise KeyError(
107 f"Unknown configuration option: {key}. "
108 "Register it before setting."
109 )
110
111 def get(self, key: ARConfigKeyBase) -> Any:
112 """Get the configuration option."""
113
114 with self._lock:
115 if isinstance(key, ARConfigKeyBase) and key in self._options:
116 return self._options[key]
117 raise KeyError(f"Unknown configuration option: {key}")
118
119 def keys(self) -> list[ARConfigKeyBase]:
120 """Get the list of configuration keys."""
121
122 with self._lock:
123 return list(self._options.keys())
124
125 def list(self) -> list[tuple[ARConfigKeyBase, Any]]:
126 """List all configuration options."""
127
128 with self._lock:
129 return list(self._options.items())
130
131 def reset(self) -> None:
132 """Reset all configuration options to their default values."""
133
134 with self._lock:
135 self._options = {}
136 self._types = {}
137
138 def register(
139 self,
140 key: ARConfigKeyBase,
141 converter: Callable[[Any], Any] | None = None,
142 ) -> None:
143 """Register a custom converter for a config key."""
144
145 if not isinstance(key, ARConfigKeyBase):
146 raise KeyError(f"Unknown configuration key: {key}")
147
148 if not converter:
149 converter = safe_bool_config
150
151 with self._lock:
152 self._types[key] = converter
153 self._options[key] = converter(None)
154
155 def __contains__(self, key: ARConfigKeyBase) -> bool:
156 """Check if a configuration key exists."""
157
158 with self._lock:
159 return key in self._options
160
161 @property
162 def types(self) -> dict[ARConfigKeyBase, Callable[[Any], Any]]:
163 """Get the dictionary of configuration types."""
164
165 with self._lock:
166 return self._types.copy()
167
168
169 class ARGlobalConfig(ARConfigBase):
170 """Configuration class for AsusRouter."""
171
172 def __init__(
173 self,
174 defaults: dict[ARConfigKey, Any] | None = None,
175 ) -> None:
176 """Initialize the configuration."""
177
178 super().__init__()
179 self.reset(defaults)
180
181 def reset(
182 self,
183 defaults: dict[ARConfigKey, Any] | None = None,
184 ) -> None:
185 """Reset all configuration options."""
186
187 super().reset()
188
189 with self._lock:
190 defaults = defaults or CONFIG_DEFAULT
191 for key in ARConfigKey:
192 self._options[key] = defaults.get(key)
193 self._types[key] = TYPES_DEFAULT.get(key, safe_bool_config)
194
195
196 ARConfig: ARGlobalConfig = ARGlobalConfig()
197
198
199 class ARInstanceConfig(ARConfigBase):
200 """Configuration class for AsusRouter instances.
201
202 These configurations are used to overwrite the global configuration.
203 If the search key is present in the instance configuration, AR will
204 use it when needed.
205 """
206
207 def __init__(self, defaults: dict[ARConfigKey, Any] | None = None) -> None:
208 """Initialize the instance configuration."""
209
210 super().__init__()
211 self.reset(defaults)
212
213 def reset(self, defaults: dict[ARConfigKey, Any] | None = None) -> None:
214 """Reset all configuration options using the provided defaults.
215
216 This method removes all the existing configuration options
217 and converters. The new defaults will be checked to have a valid
218 type converter. If a converter is found, the value will be written
219 after the conversion.
220
221 Any key with an unknown default converter will be considered a boolean.
222 For any custom converter, it must be registered separately using
223 the `register_type` method after initialization of the key.
224 """
225
226 super().reset()
227
228 with self._lock:
229 defaults = defaults or {}
230 for key, value in defaults.items():
231 # Make sure, this is a valid key
232 if key in ARConfigKey:
233 # Check if a default converter is available
234 converter: Callable[[Any], Any] = TYPES_DEFAULT.get(
235 key, safe_bool_config
236 )
237
238 # Save the converter
239 self._types[key] = converter
240
241 # Safe apply the value
242 self._options[key] = converter(value)
243
244 def get(self, key: ARConfigKeyBase) -> Any:
245 """Get configuration option of the instance.
246
247 This method falls back to global ARConfig if not present.
248 """
249
250 # Prefer instance option, otherwise consult global config
251 with self._lock:
252 if key in self._options:
253 return self._options[key]
254
255 # Defer to global configuration
256 return ARConfig.get(key)
257
258 def remove(self, key: ARConfigKeyBase) -> None:
259 """Remove configuration option of the instance."""
260
261 with self._lock:
262 if key in self._options:
263 self._options.pop(key, None)
264 self._types.pop(key, None)