diff options
Diffstat (limited to 'app.py')
-rw-r--r-- | app.py | 70 |
1 files changed, 48 insertions, 22 deletions
@@ -1,5 +1,6 @@ import logging from colorsys import hsv_to_rgb +from dataclasses import dataclass from random import randint from jinja2 import Environment @@ -9,6 +10,9 @@ from litestar.contrib.jinja import JinjaTemplateEngine from litestar.response import Template from litestar.template import TemplateConfig +logging.basicConfig(level=logging.DEBUG) +log = logging.getLogger() + # FIXME: discovery happens here, but things can change. # Try power cycling the light and see what happens. lifxlan = LifxLAN() @@ -26,21 +30,56 @@ TEMPLATE_STR = """<!DOCTYPE html> </html> """ -logging.basicConfig(level=logging.DEBUG) -log = logging.getLogger() + +@dataclass +class RGBColor: + red: int + green: int + blue: int + + @property + def hex(self) -> str: + return "#%02x%02x%02x" % (self.red, self.green, self.blue) + + def __str__(self) -> str: + return f"RGBColor(red={self.red}, green={self.green}, blue={self.blue})" + + +@dataclass +class HSBKColor: + hue: int + saturation: int + brightness: int + kelvin: int + + @property + def rgb(self) -> RGBColor: + r, g, b = hsv_to_rgb( + self.hue / 65535, self.saturation / 65535, self.brightness / 65535 + ) + return RGBColor(red=int(r * 255), green=int(g * 255), blue=int(b * 255)) + + def __str__(self) -> str: + return f"HSBKColor(hue={self.hue}, saturation={self.saturation}, brightness={self.brightness}, kelvin={self.kelvin})" + + +def get_random_hsbk_color() -> HSBKColor: + return HSBKColor( + hue=randint(0, 65535), + saturation=randint(0, 65535), + brightness=randint(0, 65535), + kelvin=randint(0, 9000), + ) def random_light() -> Template: - hue = randint(0, 65535) - saturation = randint(0, 65535) - brightness = randint(0, 65535) - kelvin = randint(0, 9000) - log.info(f"Setting color to {hue}, {saturation}, {brightness}, {kelvin}") + hsbk = get_random_hsbk_color() + log.info(f"Setting color to {hsbk} {hsbk.rgb}") try: # colors = lifxlan.get_color_all_lights() lifxlan.set_color_all_lights( - [hue, saturation, brightness, kelvin], + [hsbk.hue, hsbk.saturation, hsbk.brightness, hsbk.kelvin], rapid=True, ) except Exception as e: @@ -50,21 +89,8 @@ def random_light() -> Template: context={"color": DEFAULT_COLOR, "message": f"error: {str(e)}"}, ) - rgb_hex = DEFAULT_COLOR - try: - r, g, b = hsv_to_rgb(hue / 65535, saturation / 65535, brightness / 65535) - log.info("RGB: %s, %s, %s", r, g, b) - rgb_hex = "#%02x%02x%02x" % (int(r * 255), int(g * 255), int(b * 255)) - log.info("hex RGB: %s", rgb_hex) - except Exception as e: - log.exception("Error converting color") - return Template( - template_str=TEMPLATE_STR, - context={"color": DEFAULT_COLOR, "message": f"error: {str(e)}"}, - ) - return Template( - template_str=TEMPLATE_STR, context={"color": rgb_hex, "message": " "} + template_str=TEMPLATE_STR, context={"color": hsbk.rgb.hex, "message": " "} ) |