MqttClientService¶
Транспортный слой: персистентное MQTT-соединение к брокеру Sber, цикл
реконнекта с экспоненциальным backoff, примитивы publish / subscribe.
Извлечён из SberBridge в рамках рефакторинга v1.25.1 для изоляции
транспортных забот от оркестрации моста (SRP).
Сервис управляется через SberMqttCredentials (value object с учётными
данными) и MqttServiceHooks (коллбэки для on_message / on_connected /
on_disconnected). Не знает о сущностях, командах или состоянии HA — вся
высокоуровневая логика инжектируется через хуки.
Async MQTT transport layer for the Sber Smart Home bridge.
Owns the persistent connection to the Sber MQTT broker, the reconnect
loop with exponential backoff, the topic subscriptions and the raw
publish operations. Extracted from :class:SberBridge to isolate
transport concerns from bridge orchestration (SRP).
The service is driven by a SberMqttCredentials value object and a
MqttServiceHooks struct of callbacks, so it does NOT know about
entities, commands or HA state. All higher-level logic (initial
publish, ack-guard, message routing) is injected via hooks.
SberMqttCredentials
dataclass
¶
Connection credentials for the Sber MQTT broker.
MqttServiceHooks
dataclass
¶
Callbacks invoked by :class:MqttClientService.
Attributes:
| Name | Type | Description |
|---|---|---|
on_message |
Callable[[str, bytes], Awaitable[None]]
|
Invoked for every incoming MQTT message (topic, payload). |
on_connected |
Callable[[Client], Awaitable[None]]
|
Invoked once per successful handshake; used by the bridge to perform initial publish + subscription setup. |
on_disconnected |
Callable[[Exception, bool], Awaitable[bool]]
|
Invoked after an MQTT / network error; returns
|
get_connected_since |
Callable[[Exception, bool], Awaitable[bool]]
|
Stats hook — called when the connection is established so callers can tag the timestamp. |
MqttClientService
¶
Async MQTT transport with exponential backoff reconnect.
Typical usage (inside SberBridge.async_start)::
self._mqtt = MqttClientService(
hass=hass,
credentials=SberMqttCredentials(...),
hooks=MqttServiceHooks(
on_message=self._handle_mqtt_message,
on_connected=self._handle_connected,
on_disconnected=self._handle_disconnect,
),
reconnect_min=reconnect_min,
reconnect_max=reconnect_max,
)
self._connection_task = hass.async_create_task(
self._mqtt.run(), eager_start=True,
)
Initialize the service.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hass
|
HomeAssistant
|
Home Assistant core instance (used for executor offload). |
required |
credentials
|
SberMqttCredentials
|
Broker connection credentials. |
required |
hooks
|
MqttServiceHooks
|
Higher-level callbacks injected by the bridge. |
required |
reconnect_min
|
int
|
Initial reconnect backoff in seconds. |
required |
reconnect_max
|
int
|
Upper bound for exponential backoff in seconds. |
required |
Source code in custom_components/sber_mqtt_bridge/mqtt_client_service.py
reconnect_interval
property
¶
Return the current exponential-backoff delay (read-only).
update_backoff_limits
¶
Update exponential-backoff bounds at runtime.
The new minimum takes effect on the next connect; the new maximum clamps subsequent backoff steps immediately.
Source code in custom_components/sber_mqtt_bridge/mqtt_client_service.py
update_verify_ssl
¶
Update the verify_ssl flag for the next reconnect.
Source code in custom_components/sber_mqtt_bridge/mqtt_client_service.py
run
async
¶
Maintain a persistent MQTT connection until stop() is called.
On successful handshake, invokes hooks.on_connected(client) and
then blocks on the inbound message stream, delegating each message
to hooks.on_message. On error, invokes hooks.on_disconnected
and applies exponential backoff before retrying.
Source code in custom_components/sber_mqtt_bridge/mqtt_client_service.py
stop
async
¶
publish
async
¶
Publish a raw payload to the given topic.
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If called while disconnected. |
MqttError
|
Propagated on transport errors. |
Source code in custom_components/sber_mqtt_bridge/mqtt_client_service.py
subscribe
async
¶
Subscribe to a topic / topic pattern on the active session.