Add retain on config, so that when broker restarts it can still publish

This commit is contained in:
2024-07-22 16:06:51 +02:00
parent 9a8136c8c4
commit dcd4e366e0

10
poo.py
View File

@@ -4,7 +4,7 @@ from fastapi_mqtt import FastMQTT, MQTTConfig
class PooRecorder: class PooRecorder:
mqtt_config = MQTTConfig(username="mqtt", password="mqtt") # noqa: S106 mqtt_config = MQTTConfig(username="mqtt", password="mqtt", reconnect_retries=-1) # noqa: S106
mqtt = FastMQTT(config=mqtt_config) mqtt = FastMQTT(config=mqtt_config)
CONFIG_TOPIC = "homeassistant/text/poo_recorder/config" CONFIG_TOPIC = "homeassistant/text/poo_recorder/config"
AVAILABILITY_TOPIC = "studiotj/poo_recorder/status" AVAILABILITY_TOPIC = "studiotj/poo_recorder/status"
@@ -35,18 +35,18 @@ class PooRecorder:
def on_connect(client, flags, rc, properties) -> None: # noqa: ANN001, ARG004 def on_connect(client, flags, rc, properties) -> None: # noqa: ANN001, ARG004
print("Connected") print("Connected")
config = PooRecorder.compose_config() config = PooRecorder.compose_config()
PooRecorder.mqtt.publish(PooRecorder.CONFIG_TOPIC, config) PooRecorder.mqtt.publish(PooRecorder.CONFIG_TOPIC, config, retain=True)
PooRecorder.mqtt.publish(PooRecorder.AVAILABILITY_TOPIC, PooRecorder.ONLINE) PooRecorder.mqtt.publish(PooRecorder.AVAILABILITY_TOPIC, PooRecorder.ONLINE, retain=True)
@staticmethod @staticmethod
def publish_text(new_text: str) -> None: def publish_text(new_text: str) -> None:
PooRecorder.mqtt.publish(PooRecorder.AVAILABILITY_TOPIC, PooRecorder.ONLINE) PooRecorder.mqtt.publish(PooRecorder.AVAILABILITY_TOPIC, PooRecorder.ONLINE, retain=True)
PooRecorder.mqtt.publish(PooRecorder.STATE_TOPIC, new_text, retain=True) PooRecorder.mqtt.publish(PooRecorder.STATE_TOPIC, new_text, retain=True)
@staticmethod @staticmethod
def publish_time(time: datetime) -> None: def publish_time(time: datetime) -> None:
formatted_time = time.strftime("%a | %Y-%m-%d | %H:%M") formatted_time = time.strftime("%a | %Y-%m-%d | %H:%M")
PooRecorder.mqtt.publish(PooRecorder.AVAILABILITY_TOPIC, PooRecorder.ONLINE) PooRecorder.mqtt.publish(PooRecorder.AVAILABILITY_TOPIC, PooRecorder.ONLINE, retain=True)
json_string = {"last_poo": formatted_time} json_string = {"last_poo": formatted_time}
PooRecorder.mqtt.publish(PooRecorder.JSON_TOPIC, json_string, retain=True) PooRecorder.mqtt.publish(PooRecorder.JSON_TOPIC, json_string, retain=True)