-
Notifications
You must be signed in to change notification settings - Fork 94
feat: add photo for obstacle avoidance #880
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
Changes from 1 commit
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,112 @@ | ||
| """Trait for fetching obstacle photos from V1 vacuums.""" | ||
|
|
||
| from dataclasses import dataclass | ||
|
|
||
| from roborock.data import RoborockBase | ||
| from roborock.devices.traits.v1 import common | ||
| from roborock.exceptions import RoborockException | ||
| from roborock.protocols.v1_protocol import SecurityData, V1RpcChannel | ||
| from roborock.roborock_typing import RoborockCommand | ||
|
|
||
| _PHOTO_TYPE_SMALL = 1 | ||
| _PHOTO_DATA_BLOCK_TYPE = 3 | ||
| _MAP_OBJECT_PHOTO_ENABLED_BIT = 10 | ||
| _TYPE_SIZE = 2 | ||
| _HEADER_SIZE_SIZE = 2 | ||
| _PAYLOAD_SIZE_SIZE = 4 | ||
| _MIN_BLOCK_HEADER_SIZE = _TYPE_SIZE + _HEADER_SIZE_SIZE + _PAYLOAD_SIZE_SIZE | ||
| _IMAGE_HEADERS = (b"\x89PNG\r\n\x1a\n", b"\xff\xd8\xff") | ||
|
|
||
|
|
||
| @dataclass | ||
| class ObstaclePhoto(RoborockBase): | ||
| """Obstacle photo content.""" | ||
|
|
||
| photo_id: str | ||
| image_content: bytes | ||
|
|
||
|
|
||
| class ObstaclePhotoConverter(common.V1TraitDataConverter): | ||
| """Convert a decrypted get_photo payload to an obstacle photo.""" | ||
|
|
||
| def convert(self, response: common.V1ResponseData) -> ObstaclePhoto: | ||
| """Parse the response from the device into an obstacle photo.""" | ||
| if not isinstance(response, bytes): | ||
| raise ValueError(f"Unexpected ObstaclePhotoTrait response format: {type(response)}") | ||
| return ObstaclePhoto(photo_id="", image_content=parse_photo_data(response)) | ||
|
|
||
|
|
||
| def parse_photo_data(response: bytes) -> bytes: | ||
| """Parse the get_photo response payload and return image bytes. | ||
|
|
||
| Roborock's app parses get_photo as a sequence of little-endian typed blocks. | ||
| Block type 3 contains the image bytes. | ||
| """ | ||
| offset = 0 | ||
| while offset + _MIN_BLOCK_HEADER_SIZE <= len(response): | ||
| block_type = int.from_bytes(response[offset : offset + _TYPE_SIZE], "little") | ||
| header_size = int.from_bytes( | ||
| response[offset + _TYPE_SIZE : offset + _TYPE_SIZE + _HEADER_SIZE_SIZE], | ||
| "little", | ||
| ) | ||
| payload_size = int.from_bytes( | ||
| response[offset + _TYPE_SIZE + _HEADER_SIZE_SIZE : offset + _MIN_BLOCK_HEADER_SIZE], | ||
| "little", | ||
| ) | ||
| next_offset = offset + header_size + payload_size | ||
| if header_size < _MIN_BLOCK_HEADER_SIZE or next_offset > len(response): | ||
| raise RoborockException("Invalid obstacle photo payload") | ||
|
|
||
| if block_type == _PHOTO_DATA_BLOCK_TYPE: | ||
| image_content = response[offset + header_size : next_offset] | ||
| if not image_content.startswith(_IMAGE_HEADERS): | ||
| raise RoborockException("Obstacle photo payload is not a supported image") | ||
| return image_content | ||
|
|
||
| offset = next_offset | ||
|
|
||
| raise RoborockException("Obstacle photo payload does not contain photo data") | ||
|
|
||
|
|
||
| class ObstaclePhotoTrait(RoborockBase, common.V1TraitMixin): | ||
| """Trait for fetching obstacle photos.""" | ||
|
|
||
| command = RoborockCommand.GET_PHOTO | ||
| converter = ObstaclePhotoConverter() | ||
| blob_rpc_channel = True | ||
| requires_feature = "is_ai_recognition_obstacle_supported" | ||
|
|
||
| def __init__(self, standard_rpc_channel: V1RpcChannel, security_data: SecurityData) -> None: | ||
| """Initialize the obstacle photo trait.""" | ||
| super().__init__() | ||
| self._standard_rpc_channel = standard_rpc_channel | ||
| self._security_data = security_data | ||
|
|
||
| async def get_enabled(self) -> bool: | ||
| """Return whether map object photo capture is enabled on the vacuum.""" | ||
| response = await self._standard_rpc_channel.send_command(RoborockCommand.GET_CAMERA_STATUS) | ||
| if not isinstance(response, list) or not response or not isinstance(response[0], int): | ||
| raise RoborockException("get_camera_status response did not contain camera status") | ||
| return bool((response[0] >> _MAP_OBJECT_PHOTO_ENABLED_BIT) & 1) | ||
|
|
||
| async def get_photo(self, photo_id: str, photo_type: int = _PHOTO_TYPE_SMALL) -> ObstaclePhoto: | ||
| """Fetch an obstacle photo by its map photo id.""" | ||
| public_key = await self._standard_rpc_channel.send_command(RoborockCommand.GET_RANDOM_PKEY) | ||
| if not isinstance(public_key, dict) or not isinstance(public_key.get("pub_key"), dict): | ||
| raise RoborockException("get_random_pkey response did not contain a public key") | ||
| security = self._security_data.to_dict()["security"] | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Can we put this behind the blob rpc channel? That is, it can handle wrapping the payload adding necessary lower level security information given a higher level command + params. Or there can be two things, a blob channel and a blob rpc channel, if you want to keep the internal layers separate.
Collaborator
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. How is that? |
||
| response = await self.rpc_channel.send_command( | ||
| self.command, | ||
| params={ | ||
| "security": { | ||
| "pub_key": public_key["pub_key"], | ||
| "cipher_suite": 0, | ||
| }, | ||
| "endpoint": security["endpoint"], | ||
| "nonce": security["nonce"], | ||
| "data_filter": {"img_id": photo_id, "type": photo_type}, | ||
| }, | ||
| ) | ||
| photo = self.converter.convert(response) | ||
| photo.photo_id = photo_id | ||
| return photo | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -24,6 +24,7 @@ | |
| __all__ = [ | ||
| "SecurityData", | ||
| "create_security_data", | ||
| "create_blob_response_decoder", | ||
| "decode_data_protocol_message", | ||
| "decode_rpc_response", | ||
| "V1RpcChannel", | ||
|
|
@@ -261,6 +262,48 @@ class MapResponse: | |
| """The map data, decrypted and decompressed.""" | ||
|
|
||
|
|
||
| @dataclass | ||
| class BlobResponse: | ||
| """Data structure for V1 blob responses.""" | ||
|
|
||
| request_id: int | ||
| """The request ID of the blob response.""" | ||
|
|
||
| data: bytes | ||
| """The blob data, decompressed.""" | ||
|
|
||
|
|
||
| def create_blob_response_decoder() -> Callable[[RoborockMessage], BlobResponse | None]: | ||
| """Create a decoder for V1 blob response messages. | ||
|
|
||
| Obstacle photos are acknowledged through the normal RPC response with | ||
| ``["ok"]`` and delivered later as a protocol-301 blob frame. The frame starts | ||
| with ``ROBOROCK``, stores the RPC request id at bytes 8-11, the header size | ||
| at bytes 16-17, and the gzip payload length at bytes 20-23. | ||
| """ | ||
|
|
||
| def _decode_blob_response(message: RoborockMessage) -> BlobResponse | None: | ||
| """Decode a V1 blob response message.""" | ||
| if message.protocol != RoborockMessageProtocol.MAP_RESPONSE: | ||
| return None | ||
| payload = message.payload | ||
| if not payload or not payload.startswith(b"ROBOROCK") or len(payload) < 24: | ||
| return None | ||
| request_id = int.from_bytes(payload[8:12], "little") | ||
| header_size = int.from_bytes(payload[16:18], "little") | ||
| payload_size = int.from_bytes(payload[20:24], "little") | ||
| end_offset = header_size + payload_size | ||
| if header_size < 24 or end_offset > len(payload): | ||
| raise RoborockException("Invalid V1 blob response format") | ||
| try: | ||
| data = Utils.decompress(payload[header_size:end_offset]) | ||
| except Exception as err: | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. i think we can probably make this more narrow to just exceptions that we're expecting here |
||
| raise RoborockException("Failed to decode blob message payload") from err | ||
| return BlobResponse(request_id=request_id, data=data) | ||
|
|
||
| return _decode_blob_response | ||
|
|
||
|
|
||
| def create_map_response_decoder(security_data: SecurityData) -> Callable[[RoborockMessage], MapResponse | None]: | ||
| """Create a decoder for V1 map response messages.""" | ||
|
|
||
|
|
||
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.
can you include details in the get photo pydoc about how you obtain these photo ids or photo types? (should photo type be an enum, or not exposed at all?)