Auto-reconnect MQTT

This commit is contained in:
Edward Brown 2023-09-08 13:23:50 +01:00
parent 4744efeb09
commit 4db6b29b22
4 changed files with 18 additions and 10 deletions

View file

@ -7,6 +7,9 @@ SEPS = '_- /'
BRANCH = 'release'
CAPABILITY_DEFAULT = 'default'
RECONNECT_DELAY_SEC = 5
ON = 'ON'
OFF = 'OFF'
CONFIGS_PATH = Path(os.environ['HACO_CONFIGS_PATH'])
OPTIONS_PATH = Path(os.environ['HACO_OPTIONS_PATH'])

View file

@ -1,7 +1,8 @@
import logging
from functools import partial
from haco import schema, tools, constants
import haco.constants
from haco import tools, constants
from haco.callback import Callback
from haco.schema import Schema, Platform, Tasmota, HomeAssistant, AnnounceTopic, Capability
from haco.tools import log_publish
@ -72,9 +73,9 @@ class Control:
"unique_id": f"{self.device.name_sanitized}-{self.device.mac_short}-{self.name_sanitized}",
"name": self.name,
"availability_topic": f"tele/{self.device.topic}/LWT",
"payload_off": schema.OFF,
"payload_off": haco.constants.OFF,
"payload_available": "Online",
"payload_on": schema.ON,
"payload_on": haco.constants.ON,
"payload_not_available": "Offline",
"force_update": True,
"icon": self.icon,

View file

@ -7,7 +7,7 @@ from haco import constants, tools
from haco.constants import MQTT_PASSWORD, MQTT_HOST, MQTT_PORT, MQTT_USERNAME
from haco.device import Device
from haco.load_configs import load_devices
from haco.tools import log_received
from haco.tools import log_received, logger
async def listen(client, devices):
@ -59,6 +59,13 @@ async def start_mqtt():
devices = load_devices()
devices = {device.identifier: device for device in devices}
async with aiomqtt.Client(hostname=MQTT_HOST, port=MQTT_PORT, username=MQTT_USERNAME,
password=MQTT_PASSWORD) as client:
await asyncio.gather(listen(client, devices))
while True:
client = aiomqtt.Client(hostname=MQTT_HOST, port=MQTT_PORT, username=MQTT_USERNAME,
password=MQTT_PASSWORD)
try:
async with client:
await asyncio.gather(listen(client, devices))
except aiomqtt.MqttError:
msg = f"MQTT: Connection lost; Reconnecting in {constants.RECONNECT_DELAY_SEC} seconds ..."
logger.info(msg)
await asyncio.sleep(constants.RECONNECT_DELAY_SEC)

View file

@ -9,9 +9,6 @@ from haco import tools, constants, callback
DEVICE = 'development-eth'
CONTROL = 'DEVELOPMENT-DEHUMIDIFIER'
ON = 'ON'
OFF = 'OFF'
class ControlType:
...