Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 36 additions & 7 deletions docs/DEVICES.md
Original file line number Diff line number Diff line change
Expand Up @@ -498,18 +498,47 @@ For each V1 command:
| **Channel Class** | `V1Channel` | `MqttChannel` directly |
| **RPC Abstraction** | `RpcChannel` with strategies | Helper functions |
| **Strategy Pattern** | ✅ Multi-strategy (Local → MQTT) | ❌ Direct MQTT only |
| **Health Manager** | ✅ Tracks local/MQTT health | ❌ Not needed |
| **MQTT Health Reporting** | ✅ MQTT requests | ✅ A01 requests; ❌ B01 not yet |
| **Code Location** | `v1_channel.py` | `a01_channel.py`, `b01_q7_channel.py` |

#### Health Management (V1 Only)
#### Local Connection Recovery (V1 Only)

Each V1 RPC strategy can have a `HealthManager` that tracks success/failure:
`V1Channel` keeps the local connection alive in the background:

- **Exponential Backoff**: After failures, wait before retrying
- **Automatic Recovery**: Periodically attempt to restore failed connections
- **Network Info Refresh**: Refresh local IP addresses after extended periods
- **Exponential Backoff**: After a failed local connection, wait before retrying (1 to 10 minutes)
- **Automatic Recovery**: Check the local connection periodically and reconnect when it drops
- **Network Info Refresh**: Refresh the device's local IP address after 12 hours

A01/B01 devices don't need health management since they only use MQTT (no fallback).
#### MQTT Health Management

The broker can stop delivering one device's messages while the MQTT connection itself stays up and
other devices on the shared session keep working. The client keepalive can't detect this, so the
outcome of MQTT requests is tracked instead. Subscribing to the device's topic again on the same
connection doesn't bring its messages back; a new connection does.

The session's `HealthManager` receives the result of every MQTT request through a per-device
`DeviceHealthManager`, and restarts the whole session (a new connection with all subscriptions
re-established) when:

- **One device fails**: 3 of its requests in a row time out. Only that device's own response resets
its count, so other devices' responses can't hide its timeouts.
- **The session fails**: 3 requests in a row time out across more than one device. A device that
is waiting out its restart interval (see below) may be offline, so its timeouts don't count here.

Only timeouts on the current connection count: every new connection, whether forced or after the
session reconnected on its own, starts counting from zero.

Restarts are paced so that a device that is really offline doesn't keep interrupting the others:

- At most one restart every 30 minutes.
- After a device restarts the session, it may restart it again only after 1 hour, then 2 and
4 hours, then every 6 hours. The interval is reset when the device responds again.
- Timeouts while the session is already reconnecting don't restart it.
- A forced restart reconnects right away; other disconnects keep the exponential backoff.

V1 devices answer most requests over the local connection, so their MQTT topic may carry no traffic
for hours. A broken topic is then noticed when the map (only available over MQTT) is requested
again, and the session is restarted after the first few map requests time out.

### Protocol Versions

Expand Down
4 changes: 2 additions & 2 deletions roborock/devices/rpc/v1_channel.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
from roborock.devices.transport.local_channel import LocalChannel, LocalSession, create_local_session
from roborock.devices.transport.mqtt_channel import MqttChannel
from roborock.exceptions import RoborockException
from roborock.mqtt.health_manager import HealthManager
from roborock.mqtt.health_manager import DeviceHealthManager
from roborock.mqtt.session import MqttParams, MqttSession
from roborock.protocols.v1_protocol import (
CommandType,
Expand Down Expand Up @@ -73,7 +73,7 @@ class RpcStrategy:
channel: LocalChannel | MqttChannel
encoder: Callable[[RequestMessage], RoborockMessage]
decoder: Callable[[RoborockMessage], ResponseMessage | MapResponse | None]
health_manager: HealthManager | None = None
health_manager: DeviceHealthManager | None = None


class RpcChannel(V1RpcChannel):
Expand Down
8 changes: 4 additions & 4 deletions roborock/devices/transport/mqtt_channel.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
from roborock.callbacks import decoder_callback
from roborock.data import HomeDataDevice, RRiot, UserData
from roborock.exceptions import RoborockException
from roborock.mqtt.health_manager import HealthManager
from roborock.mqtt.health_manager import DeviceHealthManager
from roborock.mqtt.session import MqttParams, MqttQos, MqttSession, MqttSessionException
from roborock.protocol import create_mqtt_decoder, create_mqtt_encoder
from roborock.roborock_message import RoborockMessage
Expand Down Expand Up @@ -45,9 +45,9 @@ def is_connected(self) -> bool:
return self._mqtt_session.connected

@property
def health_manager(self) -> HealthManager:
"""Return the health manager for the session."""
return self._mqtt_session.health_manager
def health_manager(self) -> DeviceHealthManager:
"""Return the health manager that reports this device's events to the session."""
return DeviceHealthManager(self._mqtt_session.health_manager, self._duid)

@property
def is_local_connected(self) -> bool:
Expand Down
150 changes: 133 additions & 17 deletions roborock/mqtt/health_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,18 @@
We observe a problem where sometimes the MQTT connection appears to be alive but
no messages are being received. To mitigate this, we track consecutive timeouts
and restart the connection if too many timeouts occur in succession.

The broker can also stop delivering a single device's messages while other devices
on the same connection keep working, so consecutive timeouts are also counted per
device. Only a new connection brings the messages back.
"""

import datetime
import logging
from collections.abc import Awaitable, Callable
from dataclasses import dataclass

from roborock.diagnostics import redact_device_uid

_LOGGER = logging.getLogger(__name__)

Expand All @@ -17,44 +24,153 @@
# We won't restart the session more often than this interval.
RESTART_COOLDOWN = datetime.timedelta(minutes=30)

# A single failing device may simply be offline, which a restart can't fix. After it
# restarts the session, it may restart it again only after this interval, which doubles
# with each restart up to MAX_DEVICE_RESTART_COOLDOWN until the device responds.
DEVICE_RESTART_COOLDOWN = datetime.timedelta(hours=1)
MAX_DEVICE_RESTART_COOLDOWN = datetime.timedelta(hours=6)


@dataclass
class _DeviceHealth:
"""The MQTT request state of a single device."""

consecutive_timeouts: int = 0
restart_cooldown_start: datetime.datetime | None = None
restart_cooldown: datetime.timedelta | None = None


def _duration(value: datetime.timedelta) -> datetime.timedelta:
"""Round a duration to whole seconds for logs."""
return datetime.timedelta(seconds=round(value.total_seconds()))


class HealthManager:
"""Manager for monitoring the health of MQTT connections.

This tracks communication timeouts and can trigger restarts of the MQTT
session if too many timeouts occur in succession.
session if too many timeouts occur in succession, either for a single
device or across several devices.
"""

def __init__(self, restart: Callable[[], Awaitable[None]]) -> None:
def __init__(
self,
restart: Callable[[], Awaitable[None]],
is_connected: Callable[[], bool] = lambda: True,
) -> None:
"""Initialize the health manager.

Args:
restart: A callable to restart the MQTT session.
is_connected: A callable returning whether the session is connected. While it
isn't, the session is already reconnecting, so timeouts don't restart it.
"""
self._consecutive_timeouts = 0
self._timed_out_devices: set[str] = set()
self._devices: dict[str, _DeviceHealth] = {}
self._restart = restart
self._is_connected = is_connected
self._last_restart: datetime.datetime | None = None

async def on_success(self) -> None:
"""Record a successful communication event."""
def _device(self, device_id: str) -> _DeviceHealth:
"""Return the state of a device, creating it on first use."""
return self._devices.setdefault(device_id, _DeviceHealth())

def _reset_timeouts(self) -> None:
"""Forget the timeouts counted so far."""
self._consecutive_timeouts = 0
self._timed_out_devices.clear()
for device in self._devices.values():
device.consecutive_timeouts = 0

async def on_timeout(self) -> None:
"""Record a timeout event.
def on_connected(self) -> None:
"""Forget the timeouts counted on a previous connection."""
self._reset_timeouts()

async def on_success(self, device_id: str) -> None:
"""Record a successful communication event for a device."""
self._consecutive_timeouts = 0
self._timed_out_devices.clear()
device = self._device(device_id)
device.consecutive_timeouts = 0
device.restart_cooldown_start = None
device.restart_cooldown = None

async def on_timeout(self, device_id: str) -> None:
"""Record a timeout event for a device.

This may trigger a restart of the MQTT session if too many timeouts
have occurred in succession.
"""
self._consecutive_timeouts += 1
if self._consecutive_timeouts >= TIMEOUT_THRESHOLD:
now = datetime.datetime.now(datetime.UTC)
since_last = (now - self._last_restart) if self._last_restart else None
if since_last is None or since_last >= RESTART_COOLDOWN:
now = datetime.datetime.now(datetime.UTC)
device = self._device(device_id)
device.consecutive_timeouts += 1
cooldown_start, cooldown = device.restart_cooldown_start, device.restart_cooldown
in_cooldown = cooldown_start is not None and cooldown is not None and now - cooldown_start < cooldown
# A device in its restart cooldown may be offline, so its timeouts don't implicate the session.
if not in_cooldown:
self._consecutive_timeouts += 1
self._timed_out_devices.add(device_id)

# Only timeouts from several devices implicate the session itself.
session_unhealthy = self._consecutive_timeouts >= TIMEOUT_THRESHOLD and len(self._timed_out_devices) > 1
if not session_unhealthy and device.consecutive_timeouts < TIMEOUT_THRESHOLD:
return

device_name = redact_device_uid(device_id)
if not self._is_connected():
_LOGGER.debug("Not restarting MQTT session for device %s, it is already reconnecting", device_name)
return

since_last = (now - self._last_restart) if self._last_restart else None
if since_last is not None and since_last < RESTART_COOLDOWN:
_LOGGER.debug(
"Not restarting MQTT session for device %s, last restart was %s ago", device_name, _duration(since_last)
)
return

if session_unhealthy:
reason = f"{self._consecutive_timeouts} timeouts in a row across {len(self._timed_out_devices)} devices"
else:
if in_cooldown and cooldown_start is not None and cooldown is not None:
_LOGGER.debug(
"Restarting MQTT session after %d consecutive timeouts (duration since last restart %s)",
self._consecutive_timeouts,
since_last,
"Not restarting MQTT session for device %s, it may restart it again in %s",
device_name,
_duration(cooldown_start + cooldown - now),
)
await self._restart()
self._last_restart = now
self._consecutive_timeouts = 0
return
device.restart_cooldown_start = now
device.restart_cooldown = (
min(cooldown * 2, MAX_DEVICE_RESTART_COOLDOWN) if cooldown is not None else DEVICE_RESTART_COOLDOWN
)
reason = (
f"device {device_name} timed out {device.consecutive_timeouts} times in a row; "
f"it may restart the session again in {device.restart_cooldown} if it keeps failing"
)

_LOGGER.info(
"Restarting MQTT session: %s (last restart: %s)",
reason,
f"{_duration(since_last)} ago" if since_last is not None else "never",
)
# Update the state before awaiting, so timeouts arriving meanwhile don't restart again.
self._last_restart = now
self._reset_timeouts()
await self._restart()


class DeviceHealthManager:
"""Reports the outcome of a single device's MQTT requests to the session's health manager."""

def __init__(self, health_manager: HealthManager, device_id: str) -> None:
"""Initialize the device health manager."""
self._health_manager = health_manager
self._device_id = device_id

async def on_success(self) -> None:
"""Record a successful communication event."""
await self._health_manager.on_success(self._device_id)

async def on_timeout(self) -> None:
"""Record a timeout event."""
await self._health_manager.on_timeout(self._device_id)
18 changes: 14 additions & 4 deletions roborock/mqtt/roborock_session.py
Original file line number Diff line number Diff line change
Expand Up @@ -79,10 +79,11 @@ def __init__(
self._client_lock = asyncio.Lock()
self._listeners: CallbackMap[str, bytes] = CallbackMap(_LOGGER)
self._connection_task: asyncio.Task[None] | None = None
self._restart_requested = False
self._topic_idle_timeout = topic_idle_timeout
self._idle_timers: dict[str, asyncio.Task[None]] = {}
self._diagnostics = params.diagnostics
self._health_manager = HealthManager(self.restart)
self._health_manager = HealthManager(self.restart, is_connected=lambda: self._healthy)
self._unauthorized_hook = params.unauthorized_hook

@property
Expand Down Expand Up @@ -145,12 +146,15 @@ async def close(self) -> None:
async def restart(self) -> None:
"""Force the session to disconnect and reconnect.

The active connection task will be cancelled and restarted in the background, retried by
the reconnect loop. This is a no-op if there is no active connection.
The active connection task will be cancelled and restarted in the background by the
reconnect loop. If the session was connected, the broker was reachable, so the first
reconnect attempt is made right away instead of after the backoff interval. This is a
no-op if there is no active connection.
"""
_LOGGER.info("Forcing MQTT session restart")
self._diagnostics.increment("restart")
if self._connection_task:
if self._connection_task and not self._connection_task.done():
self._restart_requested = self._healthy
self._connection_task.cancel()
else:
_LOGGER.debug("No message loop task to cancel")
Expand All @@ -175,6 +179,7 @@ async def _run_reconnect_loop(self, start_future: asyncio.Future[None] | None) -

self._healthy = False
start_future = None
restart_requested, self._restart_requested = self._restart_requested, False
if self._stop:
_LOGGER.debug("MQTT session closed, stopping retry loop")
return
Expand All @@ -188,6 +193,10 @@ async def _run_reconnect_loop(self, start_future: asyncio.Future[None] | None) -
return
self._backoff = MIN_BACKOFF_INTERVAL
continue
if restart_requested:
_LOGGER.info("MQTT session disconnected for a restart, reconnecting now")
self._diagnostics.increment("reconnect_restart")
continue
_LOGGER.info("MQTT session disconnected, retrying in %s seconds", self._backoff.total_seconds())
self._diagnostics.increment("reconnect_wait")
await asyncio.sleep(self._backoff.total_seconds())
Expand All @@ -205,6 +214,7 @@ async def _run_connection(self, start_future: asyncio.Future[None] | None) -> No
async with self._mqtt_client(self._params) as client:
self._backoff = MIN_BACKOFF_INTERVAL
self._healthy = True
self._health_manager.on_connected()
_LOGGER.info("MQTT Session connected.")
if start_future and not start_future.done():
start_future.set_result(None)
Expand Down
4 changes: 2 additions & 2 deletions roborock/testing/channel.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
from unittest.mock import AsyncMock, MagicMock

from roborock.devices.transport.channel import Channel
from roborock.mqtt.health_manager import HealthManager
from roborock.mqtt.health_manager import DeviceHealthManager, HealthManager
from roborock.mqtt.session import MqttQos
from roborock.protocols.v1_protocol import LocalProtocolVersion
from roborock.roborock_message import RoborockMessage
Expand Down Expand Up @@ -86,7 +86,7 @@ def __init__(self, is_local: bool = False):
self.protocol_version = LocalProtocolVersion.V1

self.restart = AsyncMock()
self.health_manager = HealthManager(self.restart)
self.health_manager = DeviceHealthManager(HealthManager(self.restart), "fake-device")

async def _connect(self) -> None:
self._is_connected = True
Expand Down
20 changes: 20 additions & 0 deletions tests/devices/transport/test_mqtt_channel.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@

from roborock.data import HomeData, UserData
from roborock.devices.transport.mqtt_channel import MqttChannel
from roborock.mqtt.health_manager import HealthManager
from roborock.mqtt.session import MqttParams
from roborock.protocol import create_mqtt_decoder, create_mqtt_encoder
from roborock.roborock_message import RoborockMessage, RoborockMessageProtocol
Expand Down Expand Up @@ -268,3 +269,22 @@ def failing_callback(message: RoborockMessage) -> None:
# Unsubscribe all remaining subscribers
unsub1()
unsub2()


async def test_health_is_tracked_per_device(mqtt_session: Mock) -> None:
"""Test that a working device on the session does not hide a failing device's timeouts."""
restart = AsyncMock()
mqtt_session.health_manager = HealthManager(restart)
failing, working = (
MqttChannel(
mqtt_session, duid=duid, local_key=TEST_LOCAL_KEY, rriot=USER_DATA.rriot, mqtt_params=TEST_MQTT_PARAMS
)
for duid in ("failing", "working")
)

for _ in range(3):
restart.assert_not_called()
await working.health_manager.on_success()
await failing.health_manager.on_timeout()

restart.assert_called_once()
Loading
Loading