diff --git a/backend/mqtt_integration.py b/backend/mqtt_integration.py index ffba378..7f8886d 100644 --- a/backend/mqtt_integration.py +++ b/backend/mqtt_integration.py @@ -1,7 +1,7 @@ import os import json import asyncio -from typing import Optional, Callable +from typing import Optional, Callable, Union from gmqtt import Client as MQTTClient import logging @@ -102,9 +102,10 @@ class HomeAssistantMQTT: logger.info("Connected to MQTT broker") self._connected = True try: - # Subscribe to command topic - await self.client.subscribe([{'topic': self.command_topic, 'qos': 1}]) - logger.info(f"Subscribed to {self.command_topic}") + # Subscribe to command topic using gmqtt's Subscription class + from gmqtt.mqtt.constants import QOS_1 + await self.client.subscribe([(self.command_topic, QOS_1)]) + logger.info(f"Subscribed to command topic: {self.command_topic}") # Publish discovery config config = { @@ -128,17 +129,21 @@ class HomeAssistantMQTT: ) logger.info("Published Home Assistant discovery config") - # Publish initial availability + # Publish initial availability and state await self.client.publish( self.availability_topic, "online", qos=1, retain=True ) - logger.info("Published initial availability state") + logger.info("Published availability: online") + + await self.publish_state("closed") + logger.info("Published initial state: closed") except Exception as e: - logger.error(f"Error in post-connect setup: {e}", exc_info=True) + logger.error(f"Failed in post-connect setup: {e}", exc_info=True) + await self.client.disconnect() async def connect(self): """Connect to MQTT broker""" @@ -192,9 +197,11 @@ class HomeAssistantMQTT: except Exception as e: logger.error(f"Failed to subscribe to topic: {e}") - async def publish_state(self, state: str): + async def publish_state(self, state: Union[bool, str]): """Publish gate state""" - await self.publish(self.state_topic, state) + if isinstance(state, bool): + state = "open" if state else "closed" + await self.publish(self.state_topic, state, retain=True) def set_command_callback(self, callback: Callable): """Set callback for handling commands"""