aboutsummaryrefslogtreecommitdiff
path: root/app.py
blob: 836dabf286f59f08b5daf32a7fd79feb5b4a105c (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
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
import logging
from colorsys import hsv_to_rgb, rgb_to_hsv
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.enums import RequestEncodingType
from litestar.logging import LoggingConfig
from litestar.params import Body
from litestar.response import Template
from litestar.template import TemplateConfig

DEFAULT_COLOR = "#FF0000"
TEMPLATE_STR = """<!DOCTYPE html>
<html lang="zxx">
<head>
<title>lux</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
  body { margin: 0; display: flex; flex-direction: column; align-items: center; justify-content: center; min-height: 100dvh; }
  h1 { font-family: monospace; font-size: 2rem; }
  input[type=color] {
    width: 60vmin; height: 60vmin; border: none; border-radius: 50%; cursor: pointer; padding: 0;
    background: radial-gradient(circle, white 0%, transparent 70%),
      conic-gradient(hsl(0,100%,50%), hsl(60,100%,50%), hsl(120,100%,50%),
        hsl(180,100%,50%), hsl(240,100%,50%), hsl(300,100%,50%), hsl(360,100%,50%));
  }
  input[type=color]::-webkit-color-swatch-wrapper { padding: 0; }
  input[type=color]::-webkit-color-swatch { border: none; border-radius: 50%; opacity: 0; }
  input[type=color]::-moz-color-swatch { border: none; border-radius: 50%; opacity: 0; }
</style>
</head>
<body style="background-color: {{ background_color }};">
<h1 style="color: {{ color }};">{{ message }}</h1>
<form method="post">
<input type="color" name="color" value="{{ current_color }}" onchange="this.form.submit()">
</form>
<script data-goatcounter="https://test.bunkergate.org/count" async src="https://test.bunkergate.org/count.js"></script>
</body>
</html>
"""

lux: Light | None = None

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


@dataclass
class RGBColor:
    red: int
    green: int
    blue: int

    @classmethod
    def from_hex(cls, hex_str: str) -> "RGBColor":
        hex_str = hex_str.lstrip("#")
        return cls(
            red=int(hex_str[0:2], 16),
            green=int(hex_str[2:4], 16),
            blue=int(hex_str[4:6], 16),
        )

    @property
    def hex(self) -> str:
        return "#%02X%02X%02X" % (self.red, self.green, self.blue)

    @property
    def hsbk(self) -> "HSBKColor":
        h, s, v = rgb_to_hsv(self.red / 255, self.green / 255, self.blue / 255)
        return HSBKColor(
            hue=int(h * 65535),
            saturation=int(s * 65535),
            brightness=int(v * 65535),
            kelvin=3500,
        )

    @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 _set_light_color(lux: Light, hsbk: HSBKColor) -> Template:
    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={
                "background_color": DEFAULT_COLOR,
                "color": "white",
                "message": f"error: {str(e)}",
                "current_color": DEFAULT_COLOR,
            },
        )

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


def random_color(lux: Light) -> Template:
    return _set_light_color(lux, get_random_hsbk_color())


def chosen_color(lux: Light, hex_color: str) -> Template:
    rgb = RGBColor.from_hex(hex_color)
    return _set_light_color(lux, rgb.hsbk)


@get("/")
async def get_index(lux: Light = Provide(get_lux)) -> Template:
    """Return index"""
    return random_color(lux)


@dataclass
class ColorForm:
    color: str


@post("/")
async def post_index(
    data: ColorForm = Body(media_type=RequestEncodingType.URL_ENCODED),
    lux: Light = Provide(get_lux),
) -> Template:
    """Set light to chosen color"""
    return chosen_color(lux, data.color)


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",
    ),
)