Mercurial > code > home > repos > light-bridge
comparison light.py @ 2:c6fd04e07db0
refactor light.py
author | drewp@bigasterisk.com |
---|---|
date | Sun, 28 Jan 2024 15:44:10 -0800 |
parents | |
children | e8e4fd6d5619 |
comparison
equal
deleted
inserted
replaced
1:42a494b8ee1a | 2:c6fd04e07db0 |
---|---|
1 | |
2 import asyncio | |
3 import logging | |
4 from dataclasses import dataclass | |
5 | |
6 log = logging.getLogger('light') | |
7 | |
8 class Color(str): | |
9 | |
10 def to_js(self): | |
11 return self | |
12 | |
13 | |
14 @dataclass | |
15 class Light: | |
16 name: str | |
17 address: str | |
18 online: bool | |
19 colorRequest: Color | |
20 colorMessage: dict | |
21 colorCurrent: Color | |
22 latencyMs: float | |
23 | |
24 def to_js(self): | |
25 return { | |
26 'light': { | |
27 'name': self.name, | |
28 'address': self.address, | |
29 'online': self.online, | |
30 'colorRequest': self.colorRequest.to_js(), | |
31 'colorMessage': self.colorMessage, | |
32 'colorCurrent': self.colorCurrent.to_js(), | |
33 'latencyMs': self.latencyMs, | |
34 } | |
35 } | |
36 | |
37 | |
38 class Lights: | |
39 _d: dict[str, Light] = {} | |
40 | |
41 def add(self, d: Light): | |
42 self._d[d.name] = d | |
43 | |
44 def byName(self, name: str) -> Light: | |
45 return self._d[name] | |
46 | |
47 async def changes(self): # yields None on any data change | |
48 while True: | |
49 yield None | |
50 await asyncio.sleep(1) | |
51 | |
52 def to_js(self): | |
53 return {'lights': [d.to_js() for d in sorted(self._d.values(), key=lambda r: r.name)]} |