diff sensor_bridge.py @ 0:62cca1da7955

start
author drewp@bigasterisk.com
date Sat, 14 Dec 2024 17:46:42 -0800
parents
children 087b57dd3587
line wrap: on
line diff
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/sensor_bridge.py	Sat Dec 14 17:46:42 2024 -0800
@@ -0,0 +1,67 @@
+import logging
+import os
+from typing import cast
+
+import aiomqtt
+import httpx
+from rdferry import StarletteServer
+
+logging.basicConfig(level=logging.INFO)
+log = logging.getLogger()
+
+DIMCURVE_SERVICE_HOST = os.environ['DIMCURVE_SERVICE_HOST']
+
+httpClient = httpx.AsyncClient()
+
+
+def faderValueUrl(faderName: str):
+    return f'http://{DIMCURVE_SERVICE_HOST}/dimcurve/api/faders/{faderName}/value'
+
+
+async def sendValue(faderName: str, value: float):
+    await httpClient.put(faderValueUrl(faderName), content=str(value).encode('ascii'))
+
+
+async def onMessage(message):
+    log.info(f'{message.topic}: {message.payload}')
+    payloadMap = {
+        b'1_single': 1,
+        b'2_single': 0.50,
+        b'3_single': 0.25,
+        b'4_single': 0,
+    }
+    value = payloadMap.get(cast(bytes, message.payload))
+    if value is None:
+        raise ValueError(str(message.payload))
+    await sendValue('tr', value)
+
+
+async def watchMqtt():
+    client = aiomqtt.Client('mqtt2.bigasterisk.com')
+    async with client:
+        await client.subscribe('zigbee/tr-4button-1/action')
+        await client.subscribe('zigbee/tr-4button-2/action')
+        async for message in client.messages:
+            try:
+                await onMessage(message)
+            except Exception:
+                log.warning("onMessage failed", exc_info=True)
+
+
+async def watchMqttReconnect():
+    while True:
+        try:
+            await watchMqtt()
+        except Exception:
+            log.warning("watchMqtt restarting", exc_info=True)
+
+
+def main():
+
+    server = StarletteServer()
+    server.serve(startup_tasks=[watchMqttReconnect()])
+
+    return app
+
+
+app = main()