import logging
from colorsys import hsv_to_rgb
from dataclasses import dataclass
from random import randint
from jinja2 import Environment
from lifxlan import LifxLAN, Light
from litestar import Litestar, get, post
from litestar.contrib.jinja import JinjaTemplateEngine
from litestar.di import Provide
from litestar.logging import LoggingConfig
from litestar.response import Template
from litestar.template import TemplateConfig
DEFAULT_COLOR = "#FF0000"
TEMPLATE_STR = """
lux
{{ message }}
"""
lux: Light | None = None
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)
@property
def yit(self) -> int:
yit = ((self.red * 299) + (self.green * 587) + (self.blue * 114)) // 1000
log.info(f"yit: {yit}")
return yit
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_lux() -> Light:
global lux
if lux:
return lux
for light in LifxLAN().get_lights():
if light.get_label() == "lux":
log.info(f"Found lux light: {light.get_label()} {light.get_mac_addr()}")
lux = light
return lux
log.error("Could not find lux light")
raise RuntimeError("Could not find lux light")
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_color(lux: Light) -> Template:
hsbk = get_random_hsbk_color()
log.info(f"Setting color to {hsbk} {hsbk.rgb}")
try:
lux.set_color(
[hsbk.hue, hsbk.saturation, hsbk.brightness, hsbk.kelvin], rapid=True
)
except Exception as e:
log.exception("Error setting color")
return Template(
template_str=TEMPLATE_STR,
context={"color": DEFAULT_COLOR, "message": f"error: {str(e)}"},
)
rgb = hsbk.rgb
rgb_hex = rgb.hex
text_color = "black" if rgb.yit >= 128 else "white"
return Template(
template_str=TEMPLATE_STR,
context={
"background_color": rgb_hex,
"color": text_color,
"message": rgb_hex,
},
)
@get("/")
async def get_index(lux: Light = Provide(get_lux)) -> Template:
"""Return index"""
return random_color(lux)
@post("/")
async def post_index(lux: Light = Provide(get_lux)) -> Template:
"""Update index"""
return random_color(lux)
app = Litestar(
[
get_index,
post_index,
],
dependencies={"lux": Provide(get_lux)},
template_config=TemplateConfig(
instance=JinjaTemplateEngine.from_environment(Environment())
),
logging_config=LoggingConfig(
root={"level": "INFO", "handlers": ["queue_listener"]},
formatters={
"standard": {
"format": "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
}
},
log_exceptions="always",
),
)