aboutsummaryrefslogtreecommitdiff
path: root/app.py
blob: e36d5712cfcd9ab90863d02c9fb2835c5e3e0cb1 (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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
import logging
from colorsys import hsv_to_rgb
from dataclasses import dataclass
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

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

DEFAULT_COLOR = "#FF0000"
TEMPLATE_STR = """<!DOCTYPE html>
<html>
<head>
<title>lux</title>
</head>
<body style="background-color: {{ background_color }};">
<h1 style="color: {{ color }}; font-family: monospace">{{ message }}</h1>
<script data-goatcounter="https://test.bunkergate.org/count" async src="https://test.bunkergate.org/count.js"></script>
</body>
</html>
"""


@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_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:
    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(
            [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() -> Template:
    """Return index"""
    return random_light()


@post("/")
async def post_index() -> Template:
    """Update index"""
    return random_light()


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