|
| 1 | +"""Camera control and WebRTC signaling through the existing V1 RPC channel.""" |
| 2 | + |
| 3 | +from roborock.data.camera import CameraIceCandidate, CameraQuality, CameraSdpDescription, CameraTurnServer |
| 4 | +from roborock.exceptions import RoborockException, RoborockParsingException |
| 5 | +from roborock.protocols.camera_signaling import ( |
| 6 | + decode_ice_candidates, |
| 7 | + decode_sdp_answer, |
| 8 | + encode_ice_candidate, |
| 9 | + encode_sdp_offer, |
| 10 | + hash_camera_password, |
| 11 | +) |
| 12 | +from roborock.protocols.v1_protocol import ParamsType, V1RpcChannel |
| 13 | +from roborock.roborock_typing import RoborockCommand |
| 14 | + |
| 15 | + |
| 16 | +class CameraTrait: |
| 17 | + """Control a camera session without owning a WebRTC connection. |
| 18 | +
|
| 19 | + Callers own session ordering, bounded SDP/ICE polling and cleanup: pair |
| 20 | + a successful ``start_preview`` with ``stop_preview`` in a ``finally`` block, and stop |
| 21 | + voice chat if started. This trait creates no tasks, listeners or sockets. |
| 22 | + Only one viewer can use the robot's camera at a time. |
| 23 | + """ |
| 24 | + |
| 25 | + requires_feature = "is_video_monitor_supported" |
| 26 | + # Use one existing channel strategy so a rejected PIN is not retried via |
| 27 | + # local/cloud fallback. Local camera signaling can be exposed separately. |
| 28 | + mqtt_rpc_channel = True |
| 29 | + |
| 30 | + def __init__(self) -> None: |
| 31 | + """Initialize the trait; device discovery supplies its RPC channel.""" |
| 32 | + self._rpc_channel: V1RpcChannel | None = None |
| 33 | + |
| 34 | + @property |
| 35 | + def rpc_channel(self) -> V1RpcChannel: |
| 36 | + """Return the channel supplied by the device.""" |
| 37 | + if self._rpc_channel is None: |
| 38 | + raise RoborockException("Camera trait has no RPC channel") |
| 39 | + return self._rpc_channel |
| 40 | + |
| 41 | + async def check_password(self, password: str) -> None: |
| 42 | + """Check PIN/pattern digits, raising if rejected; never retry a bad PIN.""" |
| 43 | + await self._send_ack(RoborockCommand.CHECK_HOMESEC_PASSWORD, {"password": hash_camera_password(password)}) |
| 44 | + |
| 45 | + async def start_preview(self, client_id: str, password: str, quality: CameraQuality = CameraQuality.HD) -> None: |
| 46 | + """Start preview using PIN/pattern digits and a caller-owned session ID.""" |
| 47 | + if not client_id.strip(): |
| 48 | + raise ValueError("Camera client ID cannot be empty") |
| 49 | + await self._send_ack( |
| 50 | + RoborockCommand.START_CAMERA_PREVIEW, |
| 51 | + {"client_id": client_id, "quality": quality.value, "password": hash_camera_password(password)}, |
| 52 | + ) |
| 53 | + |
| 54 | + async def stop_preview(self) -> None: |
| 55 | + """Stop the active preview; the command is not scoped to a client ID.""" |
| 56 | + await self._send_ack(RoborockCommand.STOP_CAMERA_PREVIEW) |
| 57 | + |
| 58 | + async def set_quality(self, quality: CameraQuality) -> None: |
| 59 | + """Switch the active preview's video quality.""" |
| 60 | + await self._send_ack(RoborockCommand.SWITCH_VIDEO_QUALITY, {"quality": quality.value}) |
| 61 | + |
| 62 | + async def get_turn_server(self) -> CameraTurnServer: |
| 63 | + """Fetch ephemeral TURN credentials without retaining them on the trait.""" |
| 64 | + response = await self.rpc_channel.send_command(RoborockCommand.GET_TURN_SERVER) |
| 65 | + try: |
| 66 | + if not isinstance(response, dict | list): |
| 67 | + raise TypeError("Expected a TURN response object or list") |
| 68 | + return CameraTurnServer.from_dict(response) |
| 69 | + except (TypeError, ValueError): |
| 70 | + # TURN parser errors may include credentials or URLs supplied by firmware. |
| 71 | + raise RoborockParsingException( |
| 72 | + trait_name=type(self).__name__, |
| 73 | + command=RoborockCommand.GET_TURN_SERVER, |
| 74 | + payload={"type": type(response).__name__}, |
| 75 | + inner_error="Invalid TURN server response", |
| 76 | + ) from None |
| 77 | + |
| 78 | + async def send_sdp_offer(self, sdp: str) -> None: |
| 79 | + """Send an SDP offer, preserving its line endings.""" |
| 80 | + await self._send_ack(RoborockCommand.SEND_SDP_TO_ROBOT, {"app_sdp": encode_sdp_offer(sdp)}) |
| 81 | + |
| 82 | + async def get_sdp_answer(self) -> CameraSdpDescription | None: |
| 83 | + """Fetch once; return None while the robot reports ``retry``.""" |
| 84 | + response = await self.rpc_channel.send_command(RoborockCommand.GET_DEVICE_SDP) |
| 85 | + if not isinstance(response, str | dict | list): |
| 86 | + raise RoborockParsingException( |
| 87 | + trait_name=type(self).__name__, |
| 88 | + command=RoborockCommand.GET_DEVICE_SDP, |
| 89 | + payload={"type": type(response).__name__}, |
| 90 | + inner_error="Expected an SDP response object, list or string", |
| 91 | + ) |
| 92 | + return decode_sdp_answer(response) |
| 93 | + |
| 94 | + async def send_ice_candidate(self, candidate: CameraIceCandidate) -> None: |
| 95 | + """Send one local ICE candidate, including its media identifiers.""" |
| 96 | + await self._send_ack(RoborockCommand.SEND_ICE_TO_ROBOT, {"app_ice": encode_ice_candidate(candidate)}) |
| 97 | + |
| 98 | + async def get_ice_candidates(self) -> list[CameraIceCandidate]: |
| 99 | + """Fetch remote ICE candidates once; the caller handles deduplication.""" |
| 100 | + response = await self.rpc_channel.send_command(RoborockCommand.GET_DEVICE_ICE) |
| 101 | + if not isinstance(response, str | dict | list): |
| 102 | + raise RoborockParsingException( |
| 103 | + trait_name=type(self).__name__, |
| 104 | + command=RoborockCommand.GET_DEVICE_ICE, |
| 105 | + payload={"type": type(response).__name__}, |
| 106 | + inner_error="Expected an ICE response object, list or string", |
| 107 | + ) |
| 108 | + return decode_ice_candidates(response) |
| 109 | + |
| 110 | + async def start_voice_chat(self) -> None: |
| 111 | + """Enable the robot's microphone for the active WebRTC session.""" |
| 112 | + await self._send_ack(RoborockCommand.START_VOICE_CHAT) |
| 113 | + |
| 114 | + async def stop_voice_chat(self) -> None: |
| 115 | + """Stop voice chat for the active session.""" |
| 116 | + await self._send_ack(RoborockCommand.STOP_VOICE_CHAT) |
| 117 | + |
| 118 | + async def _send_ack(self, command: RoborockCommand, params: ParamsType = None) -> None: |
| 119 | + response = await self.rpc_channel.send_command(command, params=params) |
| 120 | + # decode_rpc_response normalizes a bare "ok" to {}; other firmware |
| 121 | + # sends ["ok"]. Do not treat arbitrary result dictionaries as success. |
| 122 | + if response not in ({}, ["ok"]): |
| 123 | + raise RoborockException(f"Camera command {command.value} was not accepted") |
0 commit comments