diff light.py @ 2:c6fd04e07db0

refactor light.py
author drewp@bigasterisk.com
date Sun, 28 Jan 2024 15:44:10 -0800
parents
children e8e4fd6d5619
line wrap: on
line diff
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/light.py	Sun Jan 28 15:44:10 2024 -0800
@@ -0,0 +1,53 @@
+
+import asyncio
+import logging
+from dataclasses import dataclass
+
+log = logging.getLogger('light')
+
+class Color(str):
+
+    def to_js(self):
+        return self
+
+
+@dataclass
+class Light:
+    name: str
+    address: str
+    online: bool
+    colorRequest: Color
+    colorMessage: dict
+    colorCurrent: Color
+    latencyMs: float
+
+    def to_js(self):
+        return {
+            'light': {
+                'name': self.name,
+                'address': self.address,
+                'online': self.online,
+                'colorRequest': self.colorRequest.to_js(),
+                'colorMessage': self.colorMessage,
+                'colorCurrent': self.colorCurrent.to_js(),
+                'latencyMs': self.latencyMs,
+            }
+        }
+
+
+class Lights:
+    _d: dict[str, Light] = {}
+
+    def add(self, d: Light):
+        self._d[d.name] = d
+
+    def byName(self, name: str) -> Light:
+        return self._d[name]
+
+    async def changes(self):  # yields None on any data change
+        while True:
+            yield None
+            await asyncio.sleep(1)
+
+    def to_js(self):
+        return {'lights': [d.to_js() for d in sorted(self._d.values(), key=lambda r: r.name)]}