|
| 1 | +"""B01 Q10 MQTT helpers (send + async inbound routing). |
| 2 | +
|
| 3 | +Q10 devices do not reliably correlate request/response via the message sequence |
| 4 | +number. Additionally, DP updates ("prop updates") can arrive at any time. |
| 5 | +
|
| 6 | +To avoid race conditions, we route inbound messages through a single async |
| 7 | +consumer and then dispatch: |
| 8 | +- prop updates (DP changes) -> trait update callbacks + DP waiters |
| 9 | +- other response types -> placeholders for future routing |
| 10 | +""" |
| 11 | + |
| 12 | +import asyncio |
| 13 | +import logging |
| 14 | +from collections.abc import Callable |
| 15 | +from typing import Any, Final |
| 16 | + |
| 17 | +from roborock.exceptions import RoborockException |
| 18 | +from roborock.protocols.b01_protocol import decode_rpc_response, encode_b01_mqtt_payload |
| 19 | +from roborock.roborock_message import RoborockMessage, RoborockMessageProtocol |
| 20 | + |
| 21 | +from .mqtt_channel import MqttChannel |
| 22 | + |
| 23 | +_LOGGER = logging.getLogger(__name__) |
| 24 | + |
| 25 | + |
| 26 | +class B01Q10MessageRouter: |
| 27 | + """Async router for inbound B01 Q10 messages.""" |
| 28 | + |
| 29 | + def __init__(self) -> None: |
| 30 | + self._queue: asyncio.Queue[RoborockMessage] = asyncio.Queue() |
| 31 | + self._task: asyncio.Task[None] | None = None |
| 32 | + self._prop_update_callbacks: list[Callable[[dict[int, Any]], None]] = [] |
| 33 | + |
| 34 | + def add_prop_update_callback(self, callback: Callable[[dict[int, Any]], None]) -> Callable[[], None]: |
| 35 | + """Register a callback for prop updates (decoded DP dict).""" |
| 36 | + self._prop_update_callbacks.append(callback) |
| 37 | + |
| 38 | + def remove() -> None: |
| 39 | + try: |
| 40 | + self._prop_update_callbacks.remove(callback) |
| 41 | + except ValueError: |
| 42 | + pass |
| 43 | + |
| 44 | + return remove |
| 45 | + |
| 46 | + def feed(self, message: RoborockMessage) -> None: |
| 47 | + """Feed an inbound message into the router (non-async safe).""" |
| 48 | + if self._task is None or self._task.done(): |
| 49 | + self._task = asyncio.create_task(self._run(), name="b01-q10-message-router") |
| 50 | + self._queue.put_nowait(message) |
| 51 | + |
| 52 | + def close(self) -> None: |
| 53 | + """Stop the router task.""" |
| 54 | + if self._task and not self._task.done(): |
| 55 | + self._task.cancel() |
| 56 | + |
| 57 | + async def _run(self) -> None: |
| 58 | + while True: |
| 59 | + message = await self._queue.get() |
| 60 | + try: |
| 61 | + self._handle_message(message) |
| 62 | + except Exception as ex: # noqa: BLE001 |
| 63 | + _LOGGER.debug("Unhandled error routing B01 Q10 message: %s", ex) |
| 64 | + |
| 65 | + def _handle_message(self, message: RoborockMessage) -> None: |
| 66 | + # Placeholder for additional response types. |
| 67 | + match message.protocol: |
| 68 | + case RoborockMessageProtocol.RPC_RESPONSE: |
| 69 | + self._handle_rpc_response(message) |
| 70 | + case RoborockMessageProtocol.MAP_RESPONSE: |
| 71 | + _LOGGER.debug("B01 Q10 map response received (unrouted placeholder)") |
| 72 | + case _: |
| 73 | + _LOGGER.debug("B01 Q10 message protocol %s received (unrouted placeholder)", message.protocol) |
| 74 | + |
| 75 | + def _handle_rpc_response(self, message: RoborockMessage) -> None: |
| 76 | + try: |
| 77 | + decoded = decode_rpc_response(message) |
| 78 | + except RoborockException as ex: |
| 79 | + _LOGGER.info("Failed to decode B01 Q10 message: %s: %s", message, ex) |
| 80 | + return |
| 81 | + |
| 82 | + # Identify response type and route accordingly. |
| 83 | + # |
| 84 | + # Based on Hermes Q10: DP changes are delivered as "deviceDpChanged" events. |
| 85 | + # Many DPs are delivered nested inside dpCommon (101), so we flatten that |
| 86 | + # envelope into regular DP keys for downstream trait updates. |
| 87 | + dps = _flatten_q10_dps(decoded) |
| 88 | + if not dps: |
| 89 | + return |
| 90 | + |
| 91 | + for cb in list(self._prop_update_callbacks): |
| 92 | + try: |
| 93 | + cb(dps) |
| 94 | + except Exception as ex: # noqa: BLE001 |
| 95 | + _LOGGER.debug("Error in B01 Q10 prop update callback: %s", ex) |
| 96 | + |
| 97 | + |
| 98 | +_ROUTER_ATTR: Final[str] = "_b01_q10_router" |
| 99 | + |
| 100 | + |
| 101 | +def get_b01_q10_router(mqtt_channel: MqttChannel) -> B01Q10MessageRouter: |
| 102 | + """Get (or create) the per-channel B01 Q10 router.""" |
| 103 | + router = getattr(mqtt_channel, _ROUTER_ATTR, None) |
| 104 | + if router is None: |
| 105 | + router = B01Q10MessageRouter() |
| 106 | + setattr(mqtt_channel, _ROUTER_ATTR, router) |
| 107 | + return router |
| 108 | + |
| 109 | + |
| 110 | +def _flatten_q10_dps(decoded: dict[int, Any]) -> dict[int, Any]: |
| 111 | + """Flatten Q10 dpCommon (101) payload into normal DP keys. |
| 112 | +
|
| 113 | + Example input from device: |
| 114 | + {101: {"25": 1, "26": 54, "6": 876}, 122: 88, 123: 2, ...} |
| 115 | +
|
| 116 | + Output: |
| 117 | + {25: 1, 26: 54, 6: 876, 122: 88, 123: 2, ...} |
| 118 | + """ |
| 119 | + flat: dict[int, Any] = {} |
| 120 | + for dp, value in decoded.items(): |
| 121 | + if dp == 101 and isinstance(value, dict): |
| 122 | + for inner_k, inner_v in value.items(): |
| 123 | + try: |
| 124 | + inner_dp = int(inner_k) |
| 125 | + except (TypeError, ValueError): |
| 126 | + continue |
| 127 | + flat[inner_dp] = inner_v |
| 128 | + continue |
| 129 | + flat[dp] = value |
| 130 | + return flat |
| 131 | + |
| 132 | + |
| 133 | +async def send_b01_dp_command( |
| 134 | + mqtt_channel: MqttChannel, |
| 135 | + dps: dict[int, Any], |
| 136 | +) -> None: |
| 137 | + """Send a raw DP command on the MQTT channel. |
| 138 | +
|
| 139 | + Q10 devices can emit DP updates at any time, and do not reliably correlate |
| 140 | + request/response via the message sequence number. |
| 141 | +
|
| 142 | + For Q10 we treat **all** outbound messages as fire-and-forget: |
| 143 | + - We publish the DP command. |
| 144 | + - We do not wait for any response payload. |
| 145 | + - Traits are updated via async prop updates routed by `B01Q10MessageRouter`. |
| 146 | +
|
| 147 | + """ |
| 148 | + _LOGGER.debug("Sending MQTT DP command: %s", dps) |
| 149 | + msg = encode_b01_mqtt_payload(dps) |
| 150 | + |
| 151 | + _LOGGER.debug("Publishing B01 Q10 MQTT message: %s", msg) |
| 152 | + try: |
| 153 | + await mqtt_channel.publish(msg) |
| 154 | + await mqtt_channel.health_manager.on_success() |
| 155 | + except TimeoutError: |
| 156 | + await mqtt_channel.health_manager.on_timeout() |
| 157 | + _LOGGER.debug("B01 Q10 MQTT publish timed out for dps=%s", dps) |
| 158 | + except Exception as ex: # noqa: BLE001 |
| 159 | + # Fire-and-forget means callers never see errors; keep the task quiet. |
| 160 | + _LOGGER.debug("B01 Q10 MQTT publish failed for dps=%s: %s", dps, ex) |
| 161 | + |
| 162 | + return None |
0 commit comments