aboutsummaryrefslogtreecommitdiff
path: root/app.py
blob: 27f7a9e1912e9e4305f125cae765e694ae36fdac (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
import logging
from colorsys import hsv_to_rgb
from random import randint

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

# FIXME: discovery happens here, but things can change.
#  Try power cycling the light and see what happens.
lifxlan = LifxLAN()

DEFAULT_COLOR = "#FF0000"
TEMPLATE_STR = """<!DOCTYPE html>
<html>
<body style="background-color: {{ color }}">
<h1>{{ message }}</h1>
</body>
</html>
"""

logging.basicConfig(level=logging.DEBUG)
log = logging.getLogger()


@get("/")
async def get_index() -> 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}")

    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_STR,
            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": ""}
    )


@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())
    ),
)