van-router-mqtt: subscribe and publish discovery in on_connect
Clean sessions lose subscriptions on reconnect and a refused first connect loses the retained discovery, so both now happen on every successful connect. Adds reason codes 132-136 and behavioural tests. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01KqhjP7nud5gdBg25zCiRk9
This commit is contained in:
@@ -561,7 +561,8 @@ def on_message(mqc, userdata, msg):
|
||||
REFUSAL_REASONS = {
|
||||
1: "unacceptable protocol version", 2: "client identifier rejected",
|
||||
3: "server unavailable", 4: "bad username or password", 5: "not authorised",
|
||||
134: "bad username or password", 135: "not authorised",
|
||||
132: "unsupported protocol version", 133: "client identifier rejected",
|
||||
134: "bad username or password", 135: "not authorised", 136: "server unavailable",
|
||||
}
|
||||
_mqtt_state = None # None | "connected" | "refused" | "down": log changes only
|
||||
|
||||
@@ -597,6 +598,16 @@ def note_disconnect(rc):
|
||||
|
||||
def on_connect(mqc, userdata, flags, reason_code, properties=None):
|
||||
note_connect(reason_code)
|
||||
if getattr(reason_code, "value", reason_code) != 0:
|
||||
return
|
||||
# (Re)subscribe and republish discovery on EVERY successful connect: a clean
|
||||
# session drops subscriptions on reconnect and a refused first connect loses them.
|
||||
try:
|
||||
for topic in COMMANDS:
|
||||
mqc.subscribe(topic)
|
||||
publish_discovery(mqc)
|
||||
except Exception as e:
|
||||
log(f"MQTT on_connect setup failed: {type(e).__name__}: {e}")
|
||||
|
||||
|
||||
def on_disconnect(mqc, userdata, disconnect_flags, reason_code, properties=None):
|
||||
@@ -611,10 +622,7 @@ def main():
|
||||
mqc.on_connect = on_connect
|
||||
mqc.on_disconnect = on_disconnect
|
||||
mqc.connect(broker, mqtt_port, keepalive=60)
|
||||
for topic in COMMANDS:
|
||||
mqc.subscribe(topic)
|
||||
mqc.loop_start()
|
||||
publish_discovery(mqc)
|
||||
log(f"van-router-mqtt started: broker={broker}:{mqtt_port} poll={poll_interval_s}s")
|
||||
while True:
|
||||
publish_state(mqc)
|
||||
|
||||
Reference in New Issue
Block a user