Mercurial > code > home > repos > sensor-bridge
comparison sensor_bridge.py @ 0:62cca1da7955
start
author | drewp@bigasterisk.com |
---|---|
date | Sat, 14 Dec 2024 17:46:42 -0800 |
parents | |
children | 087b57dd3587 |
comparison
equal
deleted
inserted
replaced
-1:000000000000 | 0:62cca1da7955 |
---|---|
1 import logging | |
2 import os | |
3 from typing import cast | |
4 | |
5 import aiomqtt | |
6 import httpx | |
7 from rdferry import StarletteServer | |
8 | |
9 logging.basicConfig(level=logging.INFO) | |
10 log = logging.getLogger() | |
11 | |
12 DIMCURVE_SERVICE_HOST = os.environ['DIMCURVE_SERVICE_HOST'] | |
13 | |
14 httpClient = httpx.AsyncClient() | |
15 | |
16 | |
17 def faderValueUrl(faderName: str): | |
18 return f'http://{DIMCURVE_SERVICE_HOST}/dimcurve/api/faders/{faderName}/value' | |
19 | |
20 | |
21 async def sendValue(faderName: str, value: float): | |
22 await httpClient.put(faderValueUrl(faderName), content=str(value).encode('ascii')) | |
23 | |
24 | |
25 async def onMessage(message): | |
26 log.info(f'{message.topic}: {message.payload}') | |
27 payloadMap = { | |
28 b'1_single': 1, | |
29 b'2_single': 0.50, | |
30 b'3_single': 0.25, | |
31 b'4_single': 0, | |
32 } | |
33 value = payloadMap.get(cast(bytes, message.payload)) | |
34 if value is None: | |
35 raise ValueError(str(message.payload)) | |
36 await sendValue('tr', value) | |
37 | |
38 | |
39 async def watchMqtt(): | |
40 client = aiomqtt.Client('mqtt2.bigasterisk.com') | |
41 async with client: | |
42 await client.subscribe('zigbee/tr-4button-1/action') | |
43 await client.subscribe('zigbee/tr-4button-2/action') | |
44 async for message in client.messages: | |
45 try: | |
46 await onMessage(message) | |
47 except Exception: | |
48 log.warning("onMessage failed", exc_info=True) | |
49 | |
50 | |
51 async def watchMqttReconnect(): | |
52 while True: | |
53 try: | |
54 await watchMqtt() | |
55 except Exception: | |
56 log.warning("watchMqtt restarting", exc_info=True) | |
57 | |
58 | |
59 def main(): | |
60 | |
61 server = StarletteServer() | |
62 server.serve(startup_tasks=[watchMqttReconnect()]) | |
63 | |
64 return app | |
65 | |
66 | |
67 app = main() |