Merge pull request #41 from Meatballs1/per_device_lwt

Per device lwt
This commit is contained in:
pmagyar
2024-04-11 11:11:12 +02:00
committed by GitHub
3 changed files with 16 additions and 10 deletions

View File

@@ -204,8 +204,7 @@ class HCDevice:
if buf is None:
return None
except Exception as e:
print(self.name, "receive error", e, traceback.format_exc())
return None
raise e
try:
return self.handle_message(buf)

View File

@@ -131,6 +131,10 @@ class HCSocket:
def reconnect(self):
self.reset()
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPIDLE, 30)
sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPINTVL, 3)
sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPCNT, 5)
sock.connect((self.host, self.port))
if not self.http:
@@ -143,11 +147,7 @@ class HCSocket:
print(now(), "CON:", self.uri)
self.ws = websocket.WebSocket()
self.ws.connect(
self.uri,
socket=sock,
origin="",
)
self.ws.connect(self.uri, socket=sock, origin="")
def send(self, msg):
buf = json.dumps(msg, separators=(",", ":"))

View File

@@ -64,7 +64,7 @@ def hc2mqtt(
print(now(), f"ERROR MQTT connection failed: {rc}")
def on_disconnect(client, userdata, rc):
print(now(), "ERROR MQTT client disconnected")
print(now(), f"ERROR MQTT client disconnected: {rc}")
def on_message(client, userdata, msg):
mqtt_state = msg.payload.decode()
@@ -157,8 +157,14 @@ def client_connect(client, device, mqtt_topic):
# ws.debug = True
dev[device["name"]].reconnect()
while True:
if client.is_connected():
client.publish(f"{mqtt_topic}/LWT", "", retain=True)
break
while True:
msg = dev[device["name"]].recv()
client.publish(f"{mqtt_topic}/LWT", "online")
if msg is None:
break
if len(msg) > 0:
@@ -185,7 +191,7 @@ def client_connect(client, device, mqtt_topic):
if client.is_connected():
msg = json.dumps(state)
print(now(), device["name"], f"publish to {mqtt_topic} with {msg}")
client.publish(f"{mqtt_topic}/state", msg)
client.publish(f"{mqtt_topic}/state", msg, retain=True)
else:
print(
now(),
@@ -194,7 +200,8 @@ def client_connect(client, device, mqtt_topic):
)
except Exception as e:
print(device["name"], "ERROR", e, file=sys.stderr)
print(now(), device["name"], "ERROR", e, file=sys.stderr)
client.publish(f"{mqtt_topic}/LWT", "offline", retain=True)
time.sleep(57)