Debian Codegraph @

asusrouter/modules/aura.py

raw
1 """Aura module."""
2
3 from __future__ import annotations
4
5 from collections.abc import Awaitable, Callable
6 from enum import Enum, IntEnum
7 import logging
8 import re
9 from typing import Any
10
11 from asusrouter.modules.color import (
12 ColorRGB,
13 ColorRGBB,
14 average_color,
15 parse_colors,
16 )
17 from asusrouter.modules.data import AsusData, AsusDataState
18 from asusrouter.modules.endpoint import EndpointTools
19 from asusrouter.modules.identity import AsusDevice
20 from asusrouter.tools.converters import (
21 get_arguments,
22 safe_bool,
23 safe_enum,
24 safe_int,
25 )
26
27 _LOGGER = logging.getLogger(__name__)
28
29
30 class AsusAura(IntEnum):
31 """Asus Aura state."""
32
33 UNKNOWN = -999
34 ON = -1
35 OFF = 0
36 GRADIENT = 1
37 STATIC = 2
38 BREATHING = 3
39 EVOLUTION = 4
40 RAINBOW = 5
41 WAVE = 6
42 MARQUEE = 7
43
44
45 class AsusAuraColor(IntEnum):
46 """Asus Aura with color support."""
47
48 GRADIENT = 1
49 STATIC = 2
50 BREATHING = 3
51 MARQUEE = 7
52
53
54 class DefaultAuraColor(Enum):
55 """Default Aura colors."""
56
57 COLOR1 = ColorRGBB((20, 0, 128))
58 COLOR2 = ColorRGBB((110, 0, 100))
59 COLOR3 = ColorRGBB((128, 0, 80))
60
61
62 DEFAULT_COLOR_PATTERN = (
63 DefaultAuraColor.COLOR1,
64 DefaultAuraColor.COLOR2,
65 DefaultAuraColor.COLOR3,
66 DefaultAuraColor.COLOR2,
67 )
68
69 DEFAULT_AURA_SCHEME = AsusAura.STATIC
70
71
72 def get_default_aura_color(zones: int) -> tuple[ColorRGBB, ...]:
73 """Get the default Aura color for the zones."""
74
75 _pattern_length = len(DEFAULT_COLOR_PATTERN)
76 # Repeat the pattern enough times to cover the required length
77 repeated_pattern = DEFAULT_COLOR_PATTERN * (
78 (zones + _pattern_length - 1) // _pattern_length
79 )
80
81 # Return the required length
82 return tuple(color.value for color in repeated_pattern[:zones])
83
84
85 def get_scheme_from_state(aura_state: dict) -> AsusAura:
86 """Get the scheme from the state."""
87
88 def is_valid_scheme(scheme: Any) -> bool:
89 """Check if the scheme is valid."""
90
91 # Keep compatible with Python 3.11,
92 valid_schemes = [
93 e.value
94 for e in AsusAura
95 if e not in (AsusAura.UNKNOWN, AsusAura.ON, AsusAura.OFF)
96 ]
97 return scheme in valid_schemes
98
99 current_scheme = safe_int(aura_state.get("scheme"))
100 if current_scheme is not None and is_valid_scheme(current_scheme):
101 return AsusAura(current_scheme)
102
103 prev_scheme = safe_int(aura_state.get("scheme_prev"))
104 if prev_scheme is not None and is_valid_scheme(prev_scheme):
105 return AsusAura(prev_scheme)
106
107 return DEFAULT_AURA_SCHEME
108
109
110 def set_color(
111 colors: list[ColorRGBB],
112 color_to_set: ColorRGB | list[ColorRGB] | None,
113 zone: int | None = None,
114 zones: int | None = None,
115 ) -> None:
116 """Set new color(s) to the existing color list."""
117
118 # Fallback in case zones have wrong data written
119 zones = zones or len(colors)
120
121 # Make sure, we have enough colors in the list (fix wrong data)
122 if len(colors) < zones:
123 colors.extend(colors[: zones - len(colors)])
124
125 # No new color defined
126 if not color_to_set:
127 _LOGGER.debug("No new color defined. Skipping")
128 return
129
130 if isinstance(color_to_set, ColorRGB):
131 _LOGGER.debug("Single color defined: %s", color_to_set)
132 # Single zone defined
133 if zone is not None and zone < zones:
134 _LOGGER.debug("Applying the color to the zone %s", zone)
135 colors[zone].from_rgb(color_to_set)
136 # No zone defined - set the color to all zones
137 else:
138 _LOGGER.debug("Applying the color to all zones")
139 for i in range(zones):
140 colors[i].from_rgb(color_to_set)
141 return
142
143 if isinstance(color_to_set, list):
144 # We have a list of colors to set
145 _LOGGER.debug("List of colors defined")
146 for i in range(zones):
147 color = color_to_set[i % len(color_to_set)]
148 if isinstance(color, ColorRGB):
149 colors[i].from_rgb(color)
150
151 return
152
153
154 def set_brightness(
155 colors: list[ColorRGBB],
156 brightness: int | None,
157 zone: int | None = None,
158 ) -> None:
159 """Set the brightness for the zones."""
160
161 # Prepare the brightness
162 brightness = safe_int(brightness)
163
164 # No brightness defined
165 if brightness is None:
166 return
167
168 # Change the brightness for the selected zone
169 if isinstance(zone, int) and 0 <= zone < len(colors):
170 colors[zone].set_brightness(brightness)
171 return
172
173 # Change the brightness for all zones
174 for color in colors:
175 color.set_brightness(brightness)
176
177 return
178
179
180 async def set_state(
181 callback: Callable[..., Awaitable[bool]],
182 state: AsusAura,
183 **kwargs: Any,
184 ) -> bool:
185 """Set the Aura state."""
186
187 # Get the identity
188 identity: AsusDevice = kwargs.get("identity", AsusDevice())
189 # Get the number of zones
190 zones = identity.aura_zone
191 if zones < 1:
192 _LOGGER.debug("No Aura zones found. Skipping the Aura service.")
193 return False
194
195 # Get the current router state
196 aura_state = (
197 kwargs.get("router_state", {}).get(AsusData.AURA, AsusDataState).data
198 )
199
200 # Get the arguments
201 color_to_set, brightness, zone = get_arguments(
202 ("color", "brightness", "zone"), **kwargs
203 )
204
205 if state == AsusAura.ON:
206 _LOGGER.debug("Aura effect not specified. Checking the previous state")
207 # Get the previous state
208 state = get_scheme_from_state(aura_state)
209
210 # Check if the state has color support
211 if state.name not in AsusAuraColor.__members__:
212 # No color selection for the state
213 _LOGGER.debug(
214 "Setting the Aura state to `%s`. No color / brightness support"
215 "for this state",
216 state.name,
217 )
218 return await callback(
219 endpoint=EndpointTools.AURA,
220 commands={"ledg_scheme": state.value},
221 )
222
223 # Get the state number
224 state_number = AsusAuraColor[state.name].value
225
226 # Get the previous colors / fallback to the default color
227 colors = aura_state.get("effect", {}).get(
228 state_number, get_default_aura_color(zones)
229 )
230 # Convert to ColorRGBB if needed
231 colors = [
232 ColorRGBB(color) if isinstance(color, ColorRGB) else color
233 for color in colors
234 ]
235
236 # Set new color(s) and brightness
237 set_color(colors, color_to_set, zone, zones)
238 set_brightness(colors, brightness, zone)
239
240 # Convert color_set to the string
241 color_to_use = ",".join(
242 [color_zone.to_rgb().__str__() for color_zone in colors]
243 )
244 _LOGGER.debug("Setting the Aura color to `%s`", color_to_use)
245
246 # Prepare the arguments
247 arguments = {
248 "ledg_scheme": state.value,
249 "ledg_rgb": color_to_use,
250 }
251
252 # Run the service
253 return await callback(
254 endpoint=EndpointTools.AURA,
255 commands=arguments,
256 )
257
258
259 def process_aura(data: dict[str, Any]) -> dict[str, Any]:
260 """Process Aura data."""
261
262 def get_scheme(key: str) -> AsusAura:
263 """Get the scheme from the data."""
264
265 scheme_value = data.get(key)
266 _scheme_value = safe_int(scheme_value)
267 _scheme_enum = safe_enum(AsusAura, _scheme_value, default_value=-999)
268 scheme: AsusAura = (
269 _scheme_enum if _scheme_enum is not None else AsusAura.UNKNOWN
270 )
271
272 if scheme == AsusAura.UNKNOWN and _scheme_value is not None:
273 _LOGGER.warning("Unknown Aura scheme: `%s`", scheme_value)
274 return scheme
275
276 # Get the effects data
277 rgb_key_pattern = re.compile(r"ledg_rgb(\d+)")
278 effect = {
279 safe_int(match.group(1)): parse_colors(data[key])
280 for key in data
281 if (match := rgb_key_pattern.match(key))
282 }
283
284 aura = {
285 "state": safe_bool(data.get("AllLED")),
286 "night_mode": safe_bool(data.get("ledg_night_mode")),
287 "scheme": get_scheme("ledg_scheme"),
288 "scheme_prev": get_scheme("ledg_scheme_old"),
289 "effect": effect,
290 "active": {},
291 }
292
293 if aura["scheme"] == AsusAura.OFF:
294 aura["state"] = False
295
296 # Active effect
297 active_effect = aura["effect"].get(aura["scheme"].value)
298 if active_effect:
299 _active_brightness = 0
300 for i, color in enumerate(active_effect):
301 _brightness = color.brightness
302 aura["active"][i] = {"color": color, "brightness": _brightness}
303 _active_brightness = max(_active_brightness, _brightness)
304
305 # Active color and brightness
306 active_color = ColorRGBB(average_color(active_effect))
307 active_color.set_brightness(_active_brightness)
308 aura["active"]["color"] = active_color
309 aura["active"]["brightness"] = _active_brightness
310
311 # Get number of zones from the Static effect length
312 _effect_static = aura["effect"].get(AsusAuraColor.STATIC)
313 aura["zones"] = len(_effect_static) if _effect_static else 0
314
315 return aura