-
Notifications
You must be signed in to change notification settings - Fork 43
feat: Update device manager and device to establish an MQTT subscription #409
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
allenporter
wants to merge
9
commits into
Python-roborock:main
Choose a base branch
from
allenporter:device-mqtt
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+541
−43
Open
Changes from all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
e640e47
feat: Update device manager and device to establish an MQTT subscription
allenporter 8d16c95
feat: Add test coverage to device modules
allenporter e49fd95
feat: Add test coverage for device manager close
allenporter 5c33055
feat: Update roborock/devices/mqtt_channel.py
allenporter 341d96d
feat: Apply suggestions from code review
allenporter 06b9178
feat: Add support for sending/recieving messages
allenporter 364e88e
feat: Simplify rpc handling and tests
allenporter a558e12
feat: Gather tasks
allenporter 63d7bba
feat: Add debug lines
allenporter File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be
10000
interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,115 @@ | ||
"""Modules for communicating with specific Roborock devices over MQTT.""" | ||
|
||
import asyncio | ||
import logging | ||
from collections.abc import Callable | ||
from json import JSONDecodeError | ||
|
||
from roborock.containers import RRiot | ||
from roborock.exceptions import RoborockException | ||
from roborock.mqtt.session import MqttParams, MqttSession | ||
from roborock.protocol import create_mqtt_decoder, create_mqtt_encoder | ||
from roborock.roborock_message import RoborockMessage | ||
|
||
_LOGGER = logging.getLogger(__name__) | ||
|
||
|
||
class MqttChannel: | ||
"""Simple RPC-style channel for communicating with a device over MQTT. | ||
|
||
Handles request/response correlation and timeouts, but leaves message | ||
format most parsing to higher-level components. | ||
""" | ||
|
||
def __init__(self, mqtt_session: MqttSession, duid: str, local_key: str, rriot: RRiot, mqtt_params: MqttParams): | ||
self._mqtt_session = mqtt_session | ||
self._duid = duid | ||
self._local_key = local_key | ||
self._rriot = rriot | ||
self._mqtt_params = mqtt_params | ||
|
||
# RPC support | ||
self._waiting_queue: dict[int, asyncio.Future[RoborockMessage]] = {} | ||
self._decoder = create_mqtt_decoder(local_key) | ||
self._encoder = create_mqtt_encoder(local_key) | ||
self._queue_lock = asyncio.Lock() | ||
|
||
@property | ||
def _publish_topic(self) -> str: | ||
"""Topic to send commands to the device.""" | ||
return f"rr/m/i/{self._rriot.u}/{self._mqtt_params.username}/{self._duid}" | ||
|
||
@property | ||
def _subscribe_topic(self) -> str: | ||
"""Topic to receive responses from the device.""" | ||
return f"rr/m/o/{self._rriot.u}/{self._mqtt_params.username}/{self._duid}" | ||
|
||
async def subscribe(self, callback: Callable[[RoborockMessage], None]) -> Callable[[], None]: | ||
"""Subscribe to the device's response topic. | ||
|
||
The callback will be called with the message payload when a message is received. | ||
|
||
All messages received will be processed through the provided callback, even | ||
those sent in response to the `send_command` command. | ||
|
||
Returns a callable that can be used to unsubscribe from the topic. | ||
""" | ||
|
||
def message_handler(payload: bytes) -> None: | ||
if not (messages := self._decoder(payload)): | ||
_LOGGER.warning("Failed to decode MQTT message: %s", payload) | ||
return | ||
for message in messages: | ||
_LOGGER.debug("Received message: %s", message) | ||
asyncio.create_task(self._resolve_future_with_lock(message)) | ||
try: | ||
callback(message) | ||
except Exception as e: | ||
_LOGGER.exception("Uncaught error in message handler callback: %s", e) | ||
|
||
return await self._mqtt_session.subscribe(self._subscribe_topic, message_handler) | ||
|
||
async def _resolve_future_with_lock(self, message: RoborockMessage) -> None: | ||
"""Resolve waiting future with proper locking.""" | ||
if (request_id := message.get_request_id()) is None: | ||
allenporter marked this conversation as resolved.
Show resolved
Hide resolved
|
||
_LOGGER.debug("Received message with no request_id") | ||
return | ||
allenporter marked this conversation as resolved.
Show resolved
Hide resolved
|
||
async with self._queue_lock: | ||
if (future := self._waiting_queue.pop(request_id, None)) is not None: | ||
future.set_result(message) | ||
else: | ||
_LOGGER.debug("Received message with no waiting handler: request_id=%s", request_id) | ||
|
||
async def send_command(self, message: RoborockMessage, timeout: float = 10.0) -> RoborockMessage: | ||
"""Send a command message and wait for the response message. | ||
|
||
Returns the raw response message - caller is responsible for parsing. | ||
""" | ||
try: | ||
if (request_id := message.get_request_id()) is None: | ||
raise RoborockException("Message must have a request_id for RPC calls") | ||
except (ValueError, JSONDecodeError) as err: | ||
_LOGGER.exception("Error getting request_id from message: %s", err) | ||
raise RoborockException(f"Invalid message format, Message must have a request_id: {err}") from err | ||
|
||
future: asyncio.Future[RoborockMessage] = asyncio.Future() | ||
async with self._queue_lock: | ||
if request_id in self._waiting_queue: | ||
raise RoborockException(f"Request ID {request_id} already pending, cannot send command") | ||
self._waiting_queue[request_id] = future | ||
|
||
try: | ||
encoded_msg = self._encoder(message) | ||
await self._mqtt_session.publish(self._publish_topic, encoded_msg) | ||
|
||
return await asyncio.wait_for(future, timeout=timeout) | ||
|
||
except asyncio.TimeoutError as ex: | ||
async with self._queue_lock: | ||
self._waiting_queue.pop(request_id, None) | ||
raise RoborockException(f"Command timed out after {timeout}s") from ex | ||
except Exception: | ||
logging.exception("Uncaught error sending command") | ||
async with self._queue_lock: | ||
self._waiting_queue.pop(request_id, None) | ||
raise |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,40 @@ | ||
"""Tests for the Device class.""" | ||
|
||
from unittest.mock import AsyncMock, Mock | ||
|
||
from roborock.containers import HomeData, UserData | ||
from roborock.devices.device import DeviceVersion, RoborockDevice | ||
|
||
from .. import mock_data | ||
|
||
USER_DATA = UserData.from_dict(mock_data.USER_DATA) | ||
HOME_DATA = HomeData.from_dict(mock_data.HOME_DATA_RAW) | ||
|
||
|
||
async def test_device_connection() -> None: | ||
"""Test the Device connection setup.""" | ||
|
||
unsub = Mock() | ||
subscribe = AsyncMock() | ||
subscribe.return_value = unsub | ||
mqtt_channel = AsyncMock() | ||
mqtt_channel.subscribe = subscribe | ||
|
||
device = RoborockDevice( | ||
USER_DATA, | ||
device_info=HOME_DATA.devices[0], | ||
product_info=HOME_DATA.products[0], | ||
mqtt_channel=mqtt_channel, | ||
) | ||
assert device.duid == "abc123" | ||
assert device.name == "Roborock S7 MaxV" | ||
assert device.device_version == DeviceVersion.V1 | ||
|
||
assert not subscribe.called | ||
|
||
await device.connect() | ||
assert subscribe.called | ||
assert not unsub.called | ||
|
||
await device.close() | ||
assert unsub.called |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Should we gather? Or are you attempting to help prevent any kind of mqtt load
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
i think connecting serially to avoid overloading mqtt makes sense., but if we see latency is too high we can revisit. Added a comment for now.