hc2mqtt: create a thread per device

This commit is contained in:
Trammell Hudson
2022-02-06 14:27:56 +01:00
parent c6407d2a28
commit 87914adffa

86
hc2mqtt
View File

@@ -1,11 +1,12 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
# Contact a Bosh-Siemens Home Connect device # Contact Bosh-Siemens Home Connect devices
# and connect it to the mqtt server # and connect their messages to the mqtt server
import sys import sys
import json import json
import re import re
import time import time
import io import io
from threading import Thread
from HCSocket import HCSocket, now from HCSocket import HCSocket, now
from HCDevice import HCDevice from HCDevice import HCDevice
import paho.mqtt.client as mqtt import paho.mqtt.client as mqtt
@@ -14,11 +15,6 @@ mqtt_prefix = "homeconnect/"
client = mqtt.Client() client = mqtt.Client()
client.connect("dashboard", 1883, 70) client.connect("dashboard", 1883, 70)
device_name = 'dishwasher'
if len(sys.argv) > 1:
device_name = sys.argv[1]
devices = { devices = {
'clothes': { 'clothes': {
"host": '10.1.0.145', "host": '10.1.0.145',
@@ -32,14 +28,7 @@ devices = {
}, },
} }
device = devices.get(device_name, None) # Map their value names to easier state names
if not device:
print(device_name, " not known", file=sys.stderr)
exit(1)
mqtt_topic = mqtt_prefix + device_name
topics = { topics = {
"OperationState": "state", "OperationState": "state",
"DoorState": "door", "DoorState": "door",
@@ -51,40 +40,51 @@ topics = {
"FatalErrorOccured": "error", "FatalErrorOccured": "error",
} }
state = {}
for topic in topics:
state[topics[topic]] = None
while True:
try:
ws = HCSocket(device["host"], device["psk64"], device["iv64"])
dev = HCDevice(ws)
#ws.debug = True def client_connect(device_name, device):
ws.reconnect() mqtt_topic = mqtt_prefix + device_name
host = device["host"]
while True: state = {}
msg = dev.recv() for topic in topics:
if msg is None: state[topics[topic]] = None
break
if len(msg) > 0:
print(now(), msg)
update = False while True:
for topic in topics: try:
value = msg.get(topic, None) ws = HCSocket(host, device["psk64"], device["iv64"])
if value is None: dev = HCDevice(ws)
#ws.debug = True
ws.reconnect()
while True:
msg = dev.recv()
if msg is None:
break
if len(msg) > 0:
print(now(), msg)
update = False
for topic in topics:
value = msg.get(topic, None)
if value is None:
continue
state[topics[topic]] = value
update = True
if not update:
continue continue
state[topics[topic]] = value
update = True
if not update: msg = json.dumps(state)
continue client.publish(mqtt_topic + "/state", msg)
msg = json.dumps(state) except Exception as e:
client.publish(mqtt_topic + "/state", msg) print("ERROR", host, e, file=sys.stderr)
except Exception as e: time.sleep(5)
print("ERROR", device["host"], e, file=sys.stderr)
for device in devices:
thread = Thread(target=client_connect, args=(device, devices[device]))
thread.start()
time.sleep(5)