import logging from colorsys import hsv_to_rgb from random import randint from textwrap import dedent from jinja2 import Environment from lifxlan import LifxLAN from litestar import Litestar, get, post from litestar.contrib.jinja import JinjaTemplateEngine from litestar.response import Template from litestar.template import TemplateConfig lifxlan = LifxLAN() DEFAULT_COLOR = "#FF0000" logging.basicConfig(level=logging.DEBUG) log = logging.getLogger() @get("/") async def get_index() -> Template: template_string = dedent( """

{{ message }}

""" ).strip() 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}") try: # colors = lifxlan.get_color_all_lights() lifxlan.set_color_all_lights( [hue, saturation, brightness, kelvin], rapid=True, ) except Exception as e: log.exception("Error setting color") return Template( template_str=template_string, context={"color": DEFAULT_COLOR, "message": str(e)}, ) rgb_color = 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_color = "#%02x%02x%02x" % (int(r * 255), int(g * 255), int(b * 255)) log.info("hex RGB: %s", rgb_color) except Exception as e: log.exception("Error converting color") return Template( template_str=template_string, context={"color": DEFAULT_COLOR, "message": str(e)}, ) return Template( template_str=template_string, context={"color": rgb_color, "message": ""} ) @post("/") async def post_index( hue: int, saturation: int, brightness: int, kelvin: int ) -> dict[str, str]: try: lifxlan.set_color_all_lights( [hue, saturation, brightness, kelvin], rapid=True, ) except Exception as e: return {"status": "error", "message": str(e)} return {"status": "ok"} app = Litestar( [ get_index, post_index, ], template_config=TemplateConfig( instance=JinjaTemplateEngine.from_environment(Environment()) ), )