|
| 1 | +"""V1 Channel for Roborock devices. |
| 2 | +
|
| 3 | +This module provides a unified channel interface for V1 protocol devices, |
| 4 | +handling both MQTT and local connections with automatic fallback. |
| 5 | +""" |
| 6 | + |
| 7 | +import logging |
| 8 | +from collections.abc import Callable |
| 9 | +from typing import Any, TypeVar |
| 10 | + |
| 11 | +from roborock.containers import HomeDataDevice, NetworkInfo, RoborockBase, UserData |
| 12 | +from roborock.exceptions import RoborockException |
| 13 | +from roborock.mqtt.session import MqttParams, MqttSession |
| 14 | +from roborock.protocols.v1_protocol import ( |
| 15 | + CommandType, |
| 16 | + ParamsType, |
| 17 | + SecurityData, |
| 18 | + create_mqtt_payload_encoder, |
| 19 | + create_security_data, |
| 20 | + decode_rpc_response, |
| 21 | + encode_local_payload, |
| 22 | +) |
| 23 | +from roborock.roborock_message import RoborockMessage |
| 24 | +from roborock.roborock_typing import RoborockCommand |
| 25 | + |
| 26 | +from .local_channel import LocalChannel, LocalSession, create_local_session |
| 27 | +from .mqtt_channel import MqttChannel |
| 28 | + |
| 29 | +_LOGGER = logging.getLogger(__name__) |
| 30 | + |
| 31 | +__all__ = [ |
| 32 | + "V1Channel", |
| 33 | +] |
| 34 | + |
| 35 | +_T = TypeVar("_T", bound=RoborockBase) |
| 36 | + |
| 37 | + |
| 38 | +class V1Channel: |
| 39 | + """Unified V1 protocol channel with automatic MQTT/local connection handling. |
| 40 | +
|
| 41 | + This channel abstracts away the complexity of choosing between MQTT and local |
| 42 | + connections, and provides high-level V1 protocol methods. It automatically |
| 43 | + handles connection setup, fallback logic, and protocol encoding/decoding. |
| 44 | + """ |
| 45 | + |
| 46 | + def __init__( |
| 47 | + self, |
| 48 | + device_uid: str, |
| 49 | + security_data: SecurityData, |
| 50 | + mqtt_channel: MqttChannel, |
| 51 | + local_session: LocalSession, |
| 52 | + ) -> None: |
| 53 | + """Initialize the V1Channel. |
| 54 | +
|
| 55 | + Args: |
| 56 | + mqtt_channel: MQTT channel for cloud communication |
| 57 | + local_session: Factory that creates LocalChannels for a hostname. |
| 58 | + """ |
| 59 | + self._device_uid = device_uid |
| 60 | + self._mqtt_channel = mqtt_channel |
| 61 | + self._mqtt_payload_encoder = create_mqtt_payload_encoder(security_data) |
| 62 | + self._local_session = local_session |
| 63 | + self._local_channel: LocalChannel | None = None |
| 64 | + self._mqtt_unsub: Callable[[], None] | None = None |
| 65 | + self._local_unsub: Callable[[], None] | None = None |
| 66 | + self._callback: Callable[[RoborockMessage], None] | None = None |
| 67 | + self._networking_info: NetworkInfo | None = None |
| 68 | + |
| 69 | + @property |
| 70 | + def is_local_connected(self) -> bool: |
| 71 | + """Return whether local connection is available.""" |
| 72 | + return self._local_unsub is not None |
| 73 | + |
| 74 | + @property |
| 75 | + def is_mqtt_connected(self) -> bool: |
| 76 | + """Return whether MQTT connection is available.""" |
| 77 | + return self._mqtt_unsub is not None |
| 78 | + |
| 79 | + async def subscribe(self, callback: Callable[[RoborockMessage], None]) -> Callable[[], None]: |
| 80 | + """Subscribe to all messages from the device. |
| 81 | +
|
| 82 | + This will establish MQTT connection first, and also attempt to set up |
| 83 | + local connection if possible. Any failures to subscribe to MQTT will raise |
| 84 | + a RoborockException. A local connection failure will not raise an exception, |
| 85 | + since the local connection is optional. |
| 86 | + """ |
| 87 | + |
| 88 | + if self._mqtt_unsub: |
| 89 | + raise ValueError("Already connected to the device") |
| 90 | + self._callback = callback |
| 91 | + |
| 92 | + # First establish MQTT connection |
| 93 | + self._mqtt_unsub = await self._mqtt_channel.subscribe(self._on_mqtt_message) |
| 94 | + _LOGGER.debug("V1Channel connected to device %s via MQTT", self._device_uid) |
| 95 | + |
| 96 | + # Try to establish an optional local connection as well. |
| 97 | + try: |
| 98 | + self._local_unsub = await self._local_connect() |
| 99 | + except RoborockException as err: |
| 100 | + _LOGGER.warning("Could not establish local connection for device %s: %s", self._device_uid, err) |
| 101 | + else: |
| 102 | + _LOGGER.debug("Local connection established for device %s", self._device_uid) |
| 103 | + |
| 104 | + def unsub() -> None: |
| 105 | + """Unsubscribe from all messages.""" |
| 106 | + if self._mqtt_unsub: |
| 107 | + self._mqtt_unsub() |
| 108 | + self._mqtt_unsub = None |
| 109 | + if self._local_unsub: |
| 110 | + self._local_unsub() |
| 111 | + self._local_unsub = None |
| 112 | + _LOGGER.debug("Unsubscribed from device %s", self._device_uid) |
| 113 | + |
| 114 | + return unsub |
| 115 | + |
| 116 | + async def _get_networking_info(self) -> NetworkInfo: |
| 117 | + """Retrieve networking information for the device. |
| 118 | +
|
| 119 | + This is a cloud only command used to get the local device's IP address. |
| 120 | + """ |
| 121 | + try: |
| 122 | + return await self._send_mqtt_decoded_command(RoborockCommand.GET_NETWORK_INFO, response_type=NetworkInfo) |
| 123 | + except RoborockException as e: |
| 124 | + raise RoborockException(f"Network info failed for device {self._device_uid}") from e |
| 125 | + |
| 126 | + async def _local_connect(self) -> Callable[[], None]: |
| 127 | + """Set up local connection if possible.""" |
| 128 | + _LOGGER.debug("Attempting to connect to local channel for device %s", self._device_uid) |
| 129 | + if self._networking_info is None: |
| 130 | + self._networking_info = await self._get_networking_info() |
| 131 | + host = self._networking_info.ip |
| 132 | + _LOGGER.debug("Connecting to local channel at %s", host) |
| 133 | + self._local_channel = self._local_session(host) |
| 134 | + try: |
| 135 | + await self._local_channel.connect() |
| 136 | + except RoborockException as e: |
| 137 | + self._local_channel = None |
| 138 | + raise RoborockException(f"Error connecting to local device {self._device_uid}: {e}") from e |
| 139 | + |
| 140 | + return await self._local_channel.subscribe(self._on_local_message) |
| 141 | + |
| 142 | + async def send_decoded_command( |
| 143 | + self, |
| 144 | + method: CommandType, |
| 145 | + *, |
| 146 | + response_type: type[_T], |
| 147 | + params: ParamsType = None, |
| 148 | + ) -> _T: |
| 149 | + """Send a command using the best available transport. |
| 150 | +
|
| 151 | + Will prefer local connection if available, falling back to MQTT. |
| 152 | + """ |
| 153 | + connection = "local" if self.is_local_connected else "mqtt" |
| 154 | + _LOGGER.debug("Sending command (%s): %s, params=%s", connection, method, params) |
| 155 | + if self._local_channel: |
| 156 | + return await self._send_local_decoded_command(method, response_type=response_type, params=params) |
| 157 | + return await self._send_mqtt_decoded_command(method, response_type=response_type, params=params) |
| 158 | + |
| 159 | + async def _send_mqtt_raw_command(self, method: CommandType, params: ParamsType | None = None) -> dict[str, Any]: |
| 160 | + """Send a raw command and return a raw unparsed response.""" |
| 161 | + message = self._mqtt_payload_encoder(method, params) |
| 162 | + _LOGGER.debug("Sending MQTT message for device %s: %s", self._device_uid, message) |
| 163 | + response = await self._mqtt_channel.send_command(message) |
| 164 | + return decode_rpc_response(response) |
| 165 | + |
| 166 | + async def _send_mqtt_decoded_command( |
| 167 | + self, method: CommandType, *, response_type: type[_T], params: ParamsType | None = None |
| 168 | + ) -> _T: |
| 169 | + """Send a command over MQTT and decode the response.""" |
| 170 | + decoded_response = await self._send_mqtt_raw_command(method, params) |
| 171 | + return response_type.from_dict(decoded_response) |
| 172 | + |
| 173 | + async def _send_local_raw_command(self, method: CommandType, params: ParamsType | None = None) -> dict[str, Any]: |
| 174 | + """Send a raw command over local connection.""" |
| 175 | + if not self._local_channel: |
| 176 | + raise RoborockException("Local channel is not connected") |
| 177 | + |
| 178 | + message = encode_local_payload(method, params) |
| 179 | + _LOGGER.debug("Sending local message for device %s: %s", self._device_uid, message) |
| 180 | + response = await self._local_channel.send_command(message) |
| 181 | + return decode_rpc_response(response) |
| 182 | + |
| 183 | + async def _send_local_decoded_command( |
| 184 | + self, method: CommandType, *, response_type: type[_T], params: ParamsType | None = None |
| 185 | + ) -> _T: |
| 186 | + """Send a command over local connection and decode the response.""" |
| 187 | + if not self._local_channel: |
| 188 | + raise RoborockException("Local channel is not connected") |
| 189 | + decoded_response = await self._send_local_raw_command(method, params) |
| 190 | + return response_type.from_dict(decoded_response) |
| 191 | + |
| 192 | + def _on_mqtt_message(self, message: RoborockMessage) -> None: |
| 193 | + """Handle incoming MQTT messages.""" |
| 194 | + _LOGGER.debug("V1Channel received MQTT message from device %s: %s", self._device_uid, message) |
| 195 | + if self._callback: |
| 196 | + self._callback(message) |
| 197 | + |
| 198 | + def _on_local_message(self, message: RoborockMessage) -> None: |
| 199 | + """Handle incoming local messages.""" |
| 200 | + _LOGGER.debug("V1Channel received local message from device %s: %s", self._device_uid, message) |
| 201 | + if self._callback: |
| 202 | + self._callback(message) |
| 203 | + |
| 204 | + |
| 205 | +def create_v1_channel( |
| 206 | + user_data: UserData, mqtt_params: MqttParams, mqtt_session: MqttSession, device: HomeDataDevice |
| 207 | +) -> V1Channel: |
| 208 | + """Create a V1Channel for the given device.""" |
| 209 | + security_data = create_security_data(user_data.rriot) |
| 210 | + mqtt_channel = MqttChannel(mqtt_session, device.duid, device.local_key, user_data.rriot, mqtt_params) |
| 211 | + local_session = create_local_session(device.local_key) |
| 212 | + return V1Channel(device.duid, security_data, mqtt_channel, local_session=local_session) |
0 commit comments