M5-T11: add HA discovery and state publishing wired to polling

This commit is contained in:
2026-06-22 15:32:43 +02:00
parent 9d05f5ea62
commit 35b95f5c88
7 changed files with 1657 additions and 23 deletions
+25
View File
@@ -31,6 +31,7 @@ from app.config import Settings
from app.integrations.modbus import driver, profiles
from app.models.modbus import ModbusDevice, ModbusReading
from app.services.config_page import build_runtime_settings
from app.services.ha_discovery import publish_device_offline, publish_device_state
logger = logging.getLogger(__name__)
@@ -84,6 +85,19 @@ def poll_device(session: Session, device: ModbusDevice) -> ModbusReading | None:
len(payload),
now.isoformat(),
)
# Best-effort: push MQTT state after successful poll.
# Must never let MQTT errors crash the poll loop.
try:
publish_device_state(session, device)
except Exception: # noqa: BLE001
logger.exception(
"poll_device: MQTT state publish failed for device %r (id=%d); "
"continuing (poll itself succeeded)",
device.friendly_name,
device.id,
)
return reading
except Exception: # noqa: BLE001
@@ -115,6 +129,17 @@ def poll_device(session: Session, device: ModbusDevice) -> ModbusReading | None:
logger.exception(
"Also failed to persist last_poll_ok=False for device id=%d", device.id
)
# Best-effort: publish "offline" availability after failed poll.
try:
publish_device_offline(device.uuid)
except Exception: # noqa: BLE001
logger.exception(
"poll_device: MQTT offline publish failed for device %r (id=%d)",
device.friendly_name,
device.id,
)
return None