Mercurial > code > home > repos > sensor-bridge
annotate sensor_bridge.py @ 1:087b57dd3587 default tip
if dimcurve request times out, abort so we get its new address
author | drewp@bigasterisk.com |
---|---|
date | Sat, 14 Dec 2024 21:39:44 -0800 |
parents | 62cca1da7955 |
children |
rev | line source |
---|---|
0 | 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): | |
1
087b57dd3587
if dimcurve request times out, abort so we get its new address
drewp@bigasterisk.com
parents:
0
diff
changeset
|
22 try: |
087b57dd3587
if dimcurve request times out, abort so we get its new address
drewp@bigasterisk.com
parents:
0
diff
changeset
|
23 await httpClient.put(faderValueUrl(faderName), content=str(value).encode('ascii'), timeout=2) |
087b57dd3587
if dimcurve request times out, abort so we get its new address
drewp@bigasterisk.com
parents:
0
diff
changeset
|
24 except Exception: |
087b57dd3587
if dimcurve request times out, abort so we get its new address
drewp@bigasterisk.com
parents:
0
diff
changeset
|
25 log.warning("put failed - restarting service", exc_info=True) |
087b57dd3587
if dimcurve request times out, abort so we get its new address
drewp@bigasterisk.com
parents:
0
diff
changeset
|
26 os.abort() |
0 | 27 |
28 | |
29 async def onMessage(message): | |
30 log.info(f'{message.topic}: {message.payload}') | |
31 payloadMap = { | |
32 b'1_single': 1, | |
33 b'2_single': 0.50, | |
34 b'3_single': 0.25, | |
35 b'4_single': 0, | |
36 } | |
37 value = payloadMap.get(cast(bytes, message.payload)) | |
38 if value is None: | |
39 raise ValueError(str(message.payload)) | |
40 await sendValue('tr', value) | |
41 | |
42 | |
43 async def watchMqtt(): | |
44 client = aiomqtt.Client('mqtt2.bigasterisk.com') | |
45 async with client: | |
46 await client.subscribe('zigbee/tr-4button-1/action') | |
47 await client.subscribe('zigbee/tr-4button-2/action') | |
48 async for message in client.messages: | |
49 try: | |
50 await onMessage(message) | |
51 except Exception: | |
52 log.warning("onMessage failed", exc_info=True) | |
53 | |
54 | |
55 async def watchMqttReconnect(): | |
56 while True: | |
57 try: | |
58 await watchMqtt() | |
59 except Exception: | |
60 log.warning("watchMqtt restarting", exc_info=True) | |
61 | |
62 | |
63 def main(): | |
64 | |
65 server = StarletteServer() | |
66 server.serve(startup_tasks=[watchMqttReconnect()]) | |
67 | |
68 return app | |
69 | |
70 | |
71 app = main() |