Skip to content

Commit

Permalink
Merge pull request #122 from Meatballs1/flush_print
Browse files Browse the repository at this point in the history
Ensure all log messages are flushed straight away in hc2mqtt
  • Loading branch information
Meatballs1 authored Jan 30, 2025
2 parents 5f68fc9 + d1195e9 commit 7ccc321
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 25 deletions.
45 changes: 21 additions & 24 deletions hc2mqtt.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,10 @@
from HCSocket import HCSocket, now


def hcprint(*args):
print(now(), *args, flush=True)


@click.command()
@click.option("-d", "--devices_file", default="config/devices.json")
@click.option("-h", "--mqtt_host", default="localhost")
Expand Down Expand Up @@ -51,15 +55,15 @@ def hc2mqtt(

def on_connect(client, userdata, flags, rc):
if rc == 5:
print(now(), f"ERROR MQTT connection failed: unauthorized - {rc}")
hcprint(f"ERROR MQTT connection failed: unauthorized - {rc}")
elif rc == 0:
print(now(), f"MQTT connection established: {rc}")
hcprint(f"MQTT connection established: {rc}")
client.publish(f"{mqtt_prefix}LWT", payload="online", qos=0, retain=True)
# Re-subscribe to all device topics on reconnection
for device in devices:
mqtt_topic = f"{mqtt_prefix}{device['name']}"
mqtt_set_topic = f"{mqtt_prefix}{device['name']}/set"
print(now(), device["name"], f"set topic: {mqtt_set_topic}")
hcprint(device["name"], f"set topic: {mqtt_set_topic}")
client.subscribe(mqtt_set_topic)
for value in device["features"]:
# If the device has the ActiveProgram feature it allows programs to be started
Expand All @@ -69,36 +73,30 @@ def on_connect(client, userdata, flags, rc):
mqtt_active_program_topic = (
f"{mqtt_prefix}{device['name']}/activeProgram"
)
print(
now(),
device["name"],
f"program topic: {mqtt_active_program_topic}",
)
hcprint(device["name"], f"program topic: {mqtt_active_program_topic}")
client.subscribe(mqtt_active_program_topic)
# If the device has the SelectedProgram feature it allows programs to be
# selected via /ro/selectedProgram
if "BSH.Common.Root.SelectedProgram" == device["features"][value]["name"]:
mqtt_selected_program_topic = (
f"{mqtt_prefix}{device['name']}/selectedProgram"
)
print(
now(),
device["name"],
f"program topic: {mqtt_selected_program_topic}",
hcprint(
device["name"], f"program topic: {mqtt_selected_program_topic}"
)
client.subscribe(mqtt_selected_program_topic)
if ha_discovery:
publish_ha_discovery(device, client, mqtt_topic)
else:
print(now(), f"ERROR MQTT connection failed: {rc}")
hcprint(f"ERROR MQTT connection failed: {rc}")

def on_disconnect(client, userdata, rc):
print(now(), f"ERROR MQTT client disconnected: {rc}")
hcprint(f"ERROR MQTT client disconnected: {rc}")

def on_message(client, userdata, msg):
mqtt_state = msg.payload.decode()
mqtt_topic = msg.topic.split("/")
print(now(), f"{msg.topic} received mqtt message {mqtt_state}")
hcprint(f"{msg.topic} received mqtt message {mqtt_state}")

try:
if len(mqtt_topic) >= 2:
Expand All @@ -124,9 +122,9 @@ def on_message(client, userdata, msg):
if dev[device_name].connected:
dev[device_name].get(resource, 1, "POST", msg)
else:
print(now(), device_name, "ERROR cant send message as websocket is not connected")
hcprint(device_name, "ERROR cant send message as websocket is not connected")
except Exception as e:
print(now(), device_name, "ERROR", e, file=sys.stderr)
hcprint(device_name, "ERROR", e, file=sys.stderr)

click.echo(
f"Hello {devices_file=} {mqtt_host=} {mqtt_prefix=} "
Expand Down Expand Up @@ -184,7 +182,7 @@ def client_connect(client, device, mqtt_topic, domain_suffix, debug):
def on_message(msg):
if msg is not None:
if len(msg) > 0:
print(now(), name, msg)
hcprint(name, msg)

update = False
for key in msg.keys():
Expand All @@ -206,11 +204,10 @@ def on_message(msg):

if client.is_connected():
msg = json.dumps(state)
print(now(), name, f"publish to {mqtt_topic} with {msg}")
hcprint(name, f"publish to {mqtt_topic} with {msg}")
client.publish(f"{mqtt_topic}/state", msg, retain=True)
else:
print(
now(),
hcprint(
name,
"ERROR Unable to publish update as mqtt is not connected.",
)
Expand All @@ -220,17 +217,17 @@ def on_open(ws):

def on_close(ws, code, message):
client.publish(f"{mqtt_topic}/LWT", "offline", retain=True)
print(now(), device["name"], "websocket closed, reconnecting...")
hcprint(device["name"], "websocket closed, reconnecting...")

while True:
time.sleep(3)
try:
print(now(), name, f"connecting to {host}")
hcprint(name, f"connecting to {host}")
ws = HCSocket(host, device["key"], device.get("iv", None), domain_suffix)
dev[name] = HCDevice(ws, device, debug)
dev[name].run_forever(on_message=on_message, on_open=on_open, on_close=on_close)
except Exception as e:
print(now(), device["name"], "ERROR", e, file=sys.stderr)
print(now(), device["name"], "ERROR", e, file=sys.stderr, flush=True)
client.publish(f"{mqtt_topic}/LWT", "offline", retain=True)

time.sleep(57)
Expand Down
2 changes: 1 addition & 1 deletion home-assistant-addon/config.yaml
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
---
name: "HomeConnect2MQTT"
description: "Run HCPY as addon"
version: "v0.1.6"
version: "v0.1.7"
slug: "hcpy"
image: ghcr.io/hcpy2-0/hcpy
init: false
Expand Down

0 comments on commit 7ccc321

Please sign in to comment.