Debian Codegraph @

asusrouter/modules/color.py

raw
1 """Color module."""
2
3 from __future__ import annotations
4
5 import logging
6 from typing import Any
7
8 from asusrouter.tools.converters import clean_input, safe_int, scale_value_int
9
10 _LOGGER = logging.getLogger(__name__)
11
12 DEFAULT_COLOR = (0, 0, 0)
13 DEFAULT_COLOR_SCALE = 255
14 DEFAULT_COLOR_SCALE_ASUS = 128
15 DEFAULT_COLOR_DELIMITER = ","
16
17
18 def average_color(
19 colors: ColorRGB | list[ColorRGB],
20 ) -> ColorRGB:
21 """Get the average color."""
22
23 if isinstance(colors, ColorRGB):
24 return colors
25
26 if not colors:
27 return ColorRGB()
28
29 # Get the scale as the maximum scale from the colors
30 scale = max(color.scale for color in colors)
31
32 # Calculate the average color components
33 num_colors = len(colors)
34 red = sum(color.r for color in colors) // num_colors
35 green = sum(color.g for color in colors) // num_colors
36 blue = sum(color.b for color in colors) // num_colors
37
38 return ColorRGB(red, green, blue, scale=scale)
39
40
41 @clean_input
42 def color_zone(
43 color_str: str | None,
44 delimiter: str = ",",
45 ) -> int:
46 """Return the number of color zones."""
47
48 if not color_str:
49 return 0
50
51 return (len(color_str.split(delimiter))) // 3
52
53
54 @clean_input
55 def parse_colors(
56 color_str: str | None,
57 delimiter: str = ",",
58 scale: int = DEFAULT_COLOR_SCALE_ASUS,
59 ) -> list[ColorRGBB] | None:
60 """Parse the colors from the string."""
61
62 if not color_str:
63 return None
64
65 # Split the string to separate groups of 3 digits
66 channels = color_str.split(delimiter)
67 if len(channels) % 3 != 0:
68 _LOGGER.warning(
69 "Invalid color string: %s, but will parse what is possible",
70 color_str,
71 )
72
73 colors = []
74 for i in range(0, len(channels), 3):
75 color = ColorRGBB()
76 if i + 2 >= len(channels):
77 break
78 color.from_rgbwb(
79 rgb=(
80 safe_int(channels[i]),
81 safe_int(channels[i + 1]),
82 safe_int(channels[i + 2]),
83 ),
84 scale=scale,
85 )
86 colors.append(color)
87
88 return colors if len(colors) > 0 else None
89
90
91 class ColorRGB:
92 """RGB color class."""
93
94 def __init__(
95 self,
96 r: int | tuple[int, int, int] | Any = DEFAULT_COLOR,
97 g: int | None = None,
98 b: int | None = None,
99 scale: int = DEFAULT_COLOR_SCALE_ASUS,
100 ) -> None:
101 """Initialize the color."""
102
103 self._r: int
104 self._g: int
105 self._b: int
106 self._scale = scale
107
108 # Single value(s)
109 if isinstance(r, int):
110 g = g if g is not None else r
111 b = b if b is not None else r
112 self.from_rgb((r, g, b))
113 return
114
115 # Any other than tuple
116 if not isinstance(r, tuple):
117 r = DEFAULT_COLOR
118
119 self.from_rgb(r)
120 return
121
122 def _normalize_input_rgb(
123 self,
124 rgb: tuple[int, ...] | str | None,
125 delimiter: str = DEFAULT_COLOR_DELIMITER,
126 ) -> tuple[int, int, int]:
127 """Normalize the RGB input."""
128
129 if rgb is None:
130 return DEFAULT_COLOR
131
132 if isinstance(rgb, str):
133 rgb = tuple(safe_int(value) for value in rgb.split(delimiter))
134 elif isinstance(rgb, ColorRGB):
135 rgb = rgb.as_tuple()
136 else:
137 rgb = tuple(safe_int(value) for value in rgb)
138
139 # Add extra values if needed or remove them
140 rgb = (rgb + (0,) * 3)[:3]
141
142 return rgb[0], rgb[1], rgb[2]
143
144 def _normalize_scale(
145 self,
146 values: tuple[int, ...],
147 scale: int,
148 ) -> tuple[int, ...]:
149 """Normalize the input values to the scale."""
150
151 _brightness = max(values)
152 if _brightness > scale:
153 values = tuple(
154 scale_value_int(value, scale, _brightness) for value in values
155 )
156
157 return values
158
159 def from_rgb(
160 self,
161 rgb: tuple[int, ...] | str,
162 delimiter: str = DEFAULT_COLOR_DELIMITER,
163 ) -> None:
164 """Load a color from RGB values."""
165
166 # Prepare and normalize the input
167 rgb = self._normalize_scale(
168 self._normalize_input_rgb(rgb, delimiter),
169 self._scale,
170 )
171
172 # Set the RGB values
173 self._r, self._g, self._b = rgb
174
175 def from_rgbs(
176 self,
177 rgb: tuple[int, int, int] | str,
178 delimiter: str = DEFAULT_COLOR_DELIMITER,
179 scale: int | None = None,
180 ) -> None:
181 """Load a color from RGB + Scale values."""
182
183 self._scale = scale or self._scale
184 self.from_rgb(rgb, delimiter)
185
186 def as_tuple(self) -> tuple[int, int, int]:
187 """Return the color as tuple."""
188
189 return self._r, self._g, self._b
190
191 def __repr__(self) -> str:
192 """Return the color as string."""
193
194 return f"{self._r},{self._g},{self._b}"
195
196 def __str__(self) -> str:
197 """Return the color as string."""
198
199 return f"{self._r},{self._g},{self._b}"
200
201 def __eq__(self, other: object) -> bool:
202 """Check if the colors are equal."""
203
204 if not isinstance(other, ColorRGB):
205 return False
206 return (
207 self._r == other._r
208 and self._g == other._g
209 and self._b == other._b
210 and self._scale == other._scale
211 )
212
213 def __hash__(self) -> int:
214 """Return the hash of the object."""
215
216 return hash((self._r, self._g, self._b, self._scale))
217
218 @property
219 def r(self) -> int:
220 """Return the red component of the color."""
221
222 return self._r
223
224 @property
225 def g(self) -> int:
226 """Return the green component of the color."""
227
228 return self._g
229
230 @property
231 def b(self) -> int:
232 """Return the blue component of the color."""
233
234 return self._b
235
236 @property
237 def scale(self) -> int:
238 """Return the scale of the color."""
239
240 return self._scale
241
242 @property
243 def color_brightness(self) -> int:
244 """Return the brightness of the color."""
245
246 return max(self._r, self._g, self._b)
247
248
249 class ColorRGBB(ColorRGB):
250 """RGB + Brightness color class."""
251
252 def __init__(
253 self,
254 rgb: tuple[int, int, int] | ColorRGB = DEFAULT_COLOR,
255 br: int | None = None,
256 scale: int = DEFAULT_COLOR_SCALE_ASUS,
257 ) -> None:
258 """Initialize the color."""
259
260 self._scale = scale
261 self.from_rgbwb(rgb)
262 self._br = min(br, self._scale) if br is not None else self._scale
263
264 def set_brightness(self, br: int) -> None:
265 """Set the brightness."""
266
267 self._br = max(0, min(br, self._scale))
268
269 def _from_rgb(
270 self,
271 rgb: tuple[int, ...] | str,
272 delimiter: str = DEFAULT_COLOR_DELIMITER,
273 scale: int | None = None,
274 ) -> tuple[int, int, int]:
275 """Read the RGB values."""
276
277 # Prepare and normalize the input
278 rgb = self._normalize_scale(
279 self._normalize_input_rgb(rgb, delimiter),
280 scale or self._scale,
281 )
282
283 return rgb[0], rgb[1], rgb[2]
284
285 def from_rgb(
286 self,
287 rgb: tuple[int, ...] | str | ColorRGB,
288 delimiter: str = DEFAULT_COLOR_DELIMITER,
289 scale: int | None = None,
290 ) -> None:
291 """Load a color from RGB values."""
292
293 if isinstance(rgb, ColorRGB):
294 rgb = (rgb.r, rgb.g, rgb.b)
295
296 self._scale = scale or self._scale
297 rgb = self._from_rgb(rgb, delimiter, self._scale)
298
299 self._r, self._g, self._b = rgb
300
301 def from_rgbwb(
302 self,
303 rgb: tuple[int, ...] | ColorRGB,
304 delimiter: str = DEFAULT_COLOR_DELIMITER,
305 scale: int | None = None,
306 ) -> None:
307 """Load a color from RGB/wb (RGB with B embedded) values."""
308
309 if isinstance(rgb, ColorRGB):
310 rgb = (rgb.r, rgb.g, rgb.b)
311
312 self._scale = scale or self._scale
313 rgb = self._from_rgb(rgb, delimiter, self._scale)
314
315 # Get color brightness
316 self._br = max(rgb)
317
318 # Rescale RGB to the full scale
319 rgb = tuple(
320 scale_value_int(value, self._scale, self._br) for value in rgb
321 )
322 self._r, self._g, self._b = rgb
323
324 def _to_rgb(
325 self,
326 rgbb: tuple[int, ...] | None = None,
327 ) -> tuple[int, int, int]:
328 """Return RGBB color as RGB."""
329
330 if rgbb is not None and len(rgbb) >= 4: # noqa: PLR2004
331 return (
332 scale_value_int(rgbb[0], rgbb[3], self._scale),
333 scale_value_int(rgbb[1], rgbb[3], self._scale),
334 scale_value_int(rgbb[2], rgbb[3], self._scale),
335 )
336
337 return (
338 scale_value_int(self._r, self._br, self._scale),
339 scale_value_int(self._g, self._br, self._scale),
340 scale_value_int(self._b, self._br, self._scale),
341 )
342
343 def to_rgb(
344 self,
345 scale: int | None = None,
346 ) -> ColorRGB:
347 """Return RGBB color as RGB."""
348
349 rgb = self._to_rgb()
350
351 if scale is not None:
352 return ColorRGB(self._to_rgb((rgb[0], rgb[1], rgb[2], scale)))
353
354 return ColorRGB(rgb, scale=self._scale)
355
356 def __repr__(self) -> str:
357 """Return the color as string."""
358
359 return f"{self._r},{self._g},{self._b},{self._br},{self._scale}"
360
361 def __str__(self) -> str:
362 """Return the color as string."""
363
364 return f"{self._r},{self._g},{self._b},{self._br},{self._scale}"
365
366 @property
367 def brightness(self) -> int:
368 """Return the brightness of the color."""
369
370 return self._br