From 87138ed4c6c8f66a877c9371b184a985b30daa18 Mon Sep 17 00:00:00 2001 From: Vedant saruk Date: Sun, 22 Nov 2026 18:50:16 +0530 Subject: [PATCH 1/3] feat(q7): add CLI vacuum commands for B01 Q7 devices --- roborock/cli.py | 165 ++++++++++++++++++++++++++++++ roborock/const.py | 2 + tests/test_cli.py | 254 +++++++++++++++++++++++++++++++++++++++++++++- 3 files changed, 418 insertions(+), 3 deletions(-) diff --git a/roborock/cli.py b/roborock/cli.py index 8a8d46a10..7e04bf4eb 100644 --- a/roborock/cli.py +++ b/roborock/cli.py @@ -63,6 +63,7 @@ from roborock.devices.device import RoborockDevice from roborock.devices.device_manager import DeviceManager, UserParams, create_device_manager from roborock.devices.traits import Trait +from roborock.devices.traits.b01.q7 import Q7PropertiesApi from roborock.devices.traits.b01.q10 import Q10PropertiesApi from roborock.devices.traits.b01.q10.vacuum import VacuumTrait from roborock.devices.traits.v1 import V1TraitMixin @@ -70,6 +71,8 @@ from roborock.devices.traits.v1.map_content import MapContentTrait from roborock.exceptions import RoborockException, RoborockUnsupportedFeature from roborock.protocol import MessageParser +from roborock.roborock_message import RoborockB01Props +from roborock.roborock_typing import RoborockB01Q7Methods from roborock.web_api import RoborockApiClient _LOGGER = logging.getLogger(__name__) @@ -494,6 +497,44 @@ async def _q10_vacuum_trait(context: RoborockContext, device_id: str) -> VacuumT return (await _q10_properties(context, device_id)).vacuum +async def _q7_properties(context: RoborockContext, device_id: str) -> Q7PropertiesApi: + """Get the B01 Q7 properties API for a device.""" + device_manager = await context.get_device_manager() + device = await device_manager.get_device(device_id) + if device.b01_q7_properties is None: + raise RoborockUnsupportedFeature("Device does not support B01 Q7 protocol. Is it a Q7?") + return device.b01_q7_properties + + +async def _display_q7_status(context: RoborockContext, device_id: str) -> None: + """Query and display the current status of a B01 Q7 device. + + Unlike V1 devices, the Q7 reports its state through ``prop.get``: the + requested properties come back in a single response, so there is no + push stream to wait on as with the Q10. + """ + properties = await _q7_properties(context, device_id) + props = await properties.query_values( + [ + RoborockB01Props.STATUS, + RoborockB01Props.FAULT, + RoborockB01Props.QUANTITY, + RoborockB01Props.WORK_MODE, + RoborockB01Props.STATION_ACT, + RoborockB01Props.CHARGE_STATE, + RoborockB01Props.CLEANING_TIME, + RoborockB01Props.CLEANING_AREA, + RoborockB01Props.WIND, + RoborockB01Props.WATER, + RoborockB01Props.MODE, + ] + ) + if props is None: + click.echo("Feature not supported by device") + return + click.echo(dump_json(props.as_dict())) + + async def _display_q10_status(context: RoborockContext, device_id: str) -> None: """Refresh and display the full status of a B01 Q10 device. @@ -556,6 +597,8 @@ async def status(ctx, device_id: str): await _display_v1_trait(context, device_id, lambda v1: v1.status) elif device.b01_q10_properties is not None: await _display_q10_status(context, device_id) + elif device.b01_q7_properties is not None: + await _display_q7_status(context, device_id) else: click.echo("Feature not supported by device") @@ -1002,6 +1045,17 @@ async def command(ctx, cmd, device_id, params): click.echo("Command sent successfully; Enable debug logging (-d) to see responses.") # Q10 commands don't have a specific time to respond, so wait a bit and log await asyncio.sleep(5) + elif device.b01_q7_properties is not None: + try: + method = RoborockB01Q7Methods(cmd) + except ValueError as err: + raise RoborockException(f"Invalid command {cmd} for B01_Q7 device") from err + properties = device.b01_q7_properties + result = await properties.send(method, json.loads(params) if params is not None else None) + if result: + click.echo(dump_json(result)) + else: + click.echo("Command sent successfully; Enable debug logging (-d) to see responses.") @click.command() @@ -1724,6 +1778,117 @@ async def q10_set_fan_level(ctx: click.Context, device_id: str, level: str) -> N click.echo(f"Error: {e}") +# --- Q7 session commands --- +# +# The Q7 API exposes its cleaning commands directly on Q7PropertiesApi +# (there is no separate vacuum trait as on the Q10), so these commands call +# the API methods. There is intentionally no resume or spot command: the Q7 +# firmware has no resume control value (SCDeviceCleanParam only defines +# start, pause and stop) and no spot clean task type, so a paused clean is +# restarted with q7-vacuum-start. + + +@session.command() +@click.option("--device_id", required=True, help="Device ID") +@click.pass_context +@async_command +async def q7_vacuum_start(ctx: click.Context, device_id: str) -> None: + """Start vacuum cleaning on Q7 device.""" + context: RoborockContext = ctx.obj + try: + properties = await _q7_properties(context, device_id) + await properties.start_clean() + click.echo("Starting vacuum cleaning...") + except RoborockUnsupportedFeature: + click.echo("Device does not support B01 Q7 protocol. Is it a Q7?") + except RoborockException as e: + click.echo(f"Error: {e}") + + +@session.command() +@click.option("--device_id", required=True, help="Device ID") +@click.pass_context +@async_command +async def q7_vacuum_pause(ctx: click.Context, device_id: str) -> None: + """Pause vacuum cleaning on Q7 device.""" + context: RoborockContext = ctx.obj + try: + properties = await _q7_properties(context, device_id) + await properties.pause_clean() + click.echo("Pausing vacuum cleaning...") + except RoborockUnsupportedFeature: + click.echo("Device does not support B01 Q7 protocol. Is it a Q7?") + except RoborockException as e: + click.echo(f"Error: {e}") + + +@session.command() +@click.option("--device_id", required=True, help="Device ID") +@click.pass_context +@async_command +async def q7_vacuum_stop(ctx: click.Context, device_id: str) -> None: + """Stop vacuum cleaning on Q7 device.""" + context: RoborockContext = ctx.obj + try: + properties = await _q7_properties(context, device_id) + await properties.stop_clean() + click.echo("Stopping vacuum cleaning...") + except RoborockUnsupportedFeature: + click.echo("Device does not support B01 Q7 protocol. Is it a Q7?") + except RoborockException as e: + click.echo(f"Error: {e}") + + +@session.command() +@click.option("--device_id", required=True, help="Device ID") +@click.pass_context +@async_command +async def q7_vacuum_dock(ctx: click.Context, device_id: str) -> None: + """Return vacuum to dock on Q7 device.""" + context: RoborockContext = ctx.obj + try: + properties = await _q7_properties(context, device_id) + await properties.return_to_dock() + click.echo("Returning vacuum to dock...") + except RoborockUnsupportedFeature: + click.echo("Device does not support B01 Q7 protocol. Is it a Q7?") + except RoborockException as e: + click.echo(f"Error: {e}") + + +@session.command() +@click.option("--device_id", required=True, help="Device ID") +@click.option( + "--segments", + required=True, + help="Comma-separated room/segment ids to clean (see the `rooms` command), e.g. 9,2", +) +@click.pass_context +@async_command +async def q7_clean_segments(ctx: click.Context, device_id: str, segments: str) -> None: + """Start a room / segment clean on a Q7 device. + + Room ids come from the `rooms` command (the device's map rooms). + """ + context: RoborockContext = ctx.obj + try: + segment_ids = [int(s) for s in segments.split(",") if s.strip()] + except ValueError: + click.echo("--segments must be comma-separated integers, e.g. 9,2") + return + if not segment_ids: + click.echo("No segment ids provided") + return + try: + properties = await _q7_properties(context, device_id) + await properties.clean_segments(segment_ids) + click.echo(f"Starting room clean of segments {segment_ids}...") + except RoborockUnsupportedFeature: + click.echo("Device does not support B01 Q7 protocol. Is it a Q7?") + except RoborockException as e: + click.echo(f"Error: {e}") + + def main(): return cli() diff --git a/roborock/const.py b/roborock/const.py index a5f72e963..3056032f7 100644 --- a/roborock/const.py +++ b/roborock/const.py @@ -29,6 +29,7 @@ ROBOROCK_Q5_PRO = "roborock.vacuum.a72" ROBOROCK_Q7 = "roborock.vacuum.a40" ROBOROCK_Q7_MAX = "roborock.vacuum.a38" +ROBOROCK_Q7_TF_PLUS = "roborock.vacuum.sc05" ROBOROCK_Q7PLUS = "roborock.vacuum.a40" ROBOROCK_QREVO_MASTER = "roborock.vacuum.a117" ROBOROCK_QREVO_CURV = "roborock.vacuum.a135" @@ -67,6 +68,7 @@ ROBOROCK_Q5, ROBOROCK_Q7, ROBOROCK_Q7_MAX, + ROBOROCK_Q7_TF_PLUS, ROBOROCK_S4, ROBOROCK_S5_MAX, ROBOROCK_S6, diff --git a/tests/test_cli.py b/tests/test_cli.py index 444e5e8b0..d9bff6409 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -2,20 +2,39 @@ import json from pathlib import Path +from types import SimpleNamespace from typing import Any from unittest.mock import AsyncMock, Mock +import click import pytest import yaml from click.testing import CliRunner -from roborock.cli import ConnectionCache, DeviceConnectionManager, RoborockContext, cli -from roborock.data import HomeDataProduct, HomeDataSchedule, RoborockCategory, UserData +from roborock.cli import ( + ConnectionCache, + DeviceConnectionManager, + RoborockContext, + cli, + q7_clean_segments, + q7_vacuum_dock, + q7_vacuum_pause, + q7_vacuum_start, + q7_vacuum_stop, + session, + status, +) +from roborock.data import HomeDataDevice, HomeDataProduct, HomeDataSchedule, RoborockCategory, UserData +from roborock.data.b01_q7 import CleanTaskTypeMapping, SCDeviceCleanParam from roborock.devices.device import RoborockDevice from roborock.devices.device_manager import DeviceManager +from roborock.devices.traits.b01.q7 import Q7PropertiesApi +from roborock.devices.traits.b01.q7 import create as create_q7_api from roborock.exceptions import RoborockException -from roborock.roborock_typing import RoborockCommand +from roborock.roborock_message import RoborockB01Props +from roborock.roborock_typing import RoborockB01Q7Methods, RoborockCommand from roborock.web_api import RoborockApiClient +from tests.devices.traits.b01.q7.conftest import FakeQ7Channel from tests.mock_data import USER_DATA, USER_EMAIL @@ -135,3 +154,232 @@ def test_get_device_info_product_nickname(monkeypatch: pytest.MonkeyPatch, model } } send_command.assert_awaited_once_with(RoborockCommand.APP_GET_INIT_STATUS) + + +@pytest.fixture +def q7_fake_channel() -> FakeQ7Channel: + """A plaintext mock for the Q7 RPC and map channels.""" + return FakeQ7Channel() + + +@pytest.fixture +def q7_api(q7_fake_channel: FakeQ7Channel) -> Q7PropertiesApi: + """A Q7 API for the Q7 TF+ (roborock.vacuum.sc05) from the issue report.""" + product = HomeDataProduct( + id="product-id-q7", + name="Roborock Q7", + model="roborock.vacuum.sc05", + category=RoborockCategory.VACUUM, + ) + device = HomeDataDevice( + duid="abc123", + name="Q7", + local_key="key123key123key1", + product_id="product-id-q7", + sn="testsn012345", + ) + return create_q7_api(product, device, q7_fake_channel, q7_fake_channel) + + +def _mock_device(monkeypatch: pytest.MonkeyPatch, q7_api: Q7PropertiesApi | None) -> SimpleNamespace: + """Route RoborockContext.get_device_manager to a device with the given Q7 API.""" + device = SimpleNamespace(v1_properties=None, b01_q10_properties=None, b01_q7_properties=q7_api) + connection_manager = AsyncMock() + connection_manager.get_device.return_value = device + monkeypatch.setattr(RoborockContext, "get_device_manager", AsyncMock(return_value=connection_manager)) + return device + + +def _invoke_session_command(command: click.Command, device_id: str = "abc123", **kwargs: Any) -> None: + """Invoke a session command callback directly with a fresh context. + + The command is wrapped by ``click.pass_context``, so the context must be + pushed onto the click stack and the device id passed as a keyword: the + decorator injects the active context as the first argument itself. + """ + ctx = click.Context(command, obj=RoborockContext()) + with ctx: + assert command.callback is not None + command.callback(device_id=device_id, **kwargs) + + +def test_q7_session_commands_registered() -> None: + """The Q7 vacuum commands are available in the session shell.""" + assert { + "q7-vacuum-start", + "q7-vacuum-pause", + "q7-vacuum-stop", + "q7-vacuum-dock", + "q7-clean-segments", + } <= set(session.commands) + + +@pytest.mark.parametrize( + ("command", "method", "params", "message"), + [ + ( + q7_vacuum_start, + RoborockB01Q7Methods.SET_ROOM_CLEAN, + {"clean_type": CleanTaskTypeMapping.ALL.code, "ctrl_value": SCDeviceCleanParam.START.code, "room_ids": []}, + "Starting vacuum cleaning...", + ), + ( + q7_vacuum_pause, + RoborockB01Q7Methods.SET_ROOM_CLEAN, + {"clean_type": CleanTaskTypeMapping.ALL.code, "ctrl_value": SCDeviceCleanParam.PAUSE.code, "room_ids": []}, + "Pausing vacuum cleaning...", + ), + ( + q7_vacuum_stop, + RoborockB01Q7Methods.SET_ROOM_CLEAN, + {"clean_type": CleanTaskTypeMapping.ALL.code, "ctrl_value": SCDeviceCleanParam.STOP.code, "room_ids": []}, + "Stopping vacuum cleaning...", + ), + ( + q7_vacuum_dock, + RoborockB01Q7Methods.START_RECHARGE, + {}, + "Returning vacuum to dock...", + ), + ], +) +def test_q7_vacuum_commands( + monkeypatch: pytest.MonkeyPatch, + q7_api: Q7PropertiesApi, + q7_fake_channel: FakeQ7Channel, + capsys: pytest.CaptureFixture[str], + command: click.Command, + method: RoborockB01Q7Methods, + params: dict[str, Any], + message: str, +) -> None: + """Each Q7 vacuum command sends the matching B01 Q7 command to the device.""" + _mock_device(monkeypatch, q7_api) + + _invoke_session_command(command) + + assert q7_fake_channel.published_commands == [(method, params)] + assert message in capsys.readouterr().out + + +def test_q7_vacuum_command_without_q7_support( + monkeypatch: pytest.MonkeyPatch, + capsys: pytest.CaptureFixture[str], +) -> None: + """A device without a Q7 API reports the Q7 protocol as unsupported and sends nothing.""" + _mock_device(monkeypatch, None) + + _invoke_session_command(q7_vacuum_start) + + assert "Device does not support B01 Q7 protocol. Is it a Q7?" in capsys.readouterr().out + + +def test_q7_clean_segments( + monkeypatch: pytest.MonkeyPatch, + q7_api: Q7PropertiesApi, + q7_fake_channel: FakeQ7Channel, + capsys: pytest.CaptureFixture[str], +) -> None: + """Segment cleaning on a Q7 sends a room clean for the given room ids.""" + _mock_device(monkeypatch, q7_api) + + _invoke_session_command(q7_clean_segments, segments="10,11") + + assert q7_fake_channel.published_commands == [ + ( + RoborockB01Q7Methods.SET_ROOM_CLEAN, + { + "clean_type": CleanTaskTypeMapping.ROOM.code, + "ctrl_value": SCDeviceCleanParam.START.code, + "room_ids": [10, 11], + }, + ) + ] + assert "Starting room clean of segments [10, 11]..." in capsys.readouterr().out + + +@pytest.mark.parametrize( + ("segments", "message"), + [ + ("9,x", "--segments must be comma-separated integers, e.g. 9,2"), + ("", "No segment ids provided"), + ], +) +def test_q7_clean_segments_invalid_input( + monkeypatch: pytest.MonkeyPatch, + q7_api: Q7PropertiesApi, + q7_fake_channel: FakeQ7Channel, + capsys: pytest.CaptureFixture[str], + segments: str, + message: str, +) -> None: + """Bad segment input is rejected before anything is sent to the device.""" + _mock_device(monkeypatch, q7_api) + + _invoke_session_command(q7_clean_segments, segments=segments) + + assert q7_fake_channel.published_commands == [] + assert message in capsys.readouterr().out + + +def test_q7_status( + monkeypatch: pytest.MonkeyPatch, + q7_api: Q7PropertiesApi, + q7_fake_channel: FakeQ7Channel, + capsys: pytest.CaptureFixture[str], +) -> None: + """Status on a Q7 queries the device properties and prints them as JSON.""" + q7_fake_channel.response_queue.append({"status": 1, "quantity": 87}) + _mock_device(monkeypatch, q7_api) + + _invoke_session_command(status) + + command, params = q7_fake_channel.published_commands[0] + assert command == RoborockB01Q7Methods.GET_PROP + assert RoborockB01Props.STATUS in params["property"] + assert RoborockB01Props.QUANTITY in params["property"] + data = json.loads(capsys.readouterr().out) + assert data["quantity"] == 87 + + +def test_status_without_supported_device( + monkeypatch: pytest.MonkeyPatch, + capsys: pytest.CaptureFixture[str], +) -> None: + """Status on a device with no supported protocol reports the feature as unsupported.""" + _mock_device(monkeypatch, None) + + _invoke_session_command(status) + + assert "Feature not supported by device" in capsys.readouterr().out + + +def test_q7_raw_command( + monkeypatch: pytest.MonkeyPatch, + q7_api: Q7PropertiesApi, + q7_fake_channel: FakeQ7Channel, +) -> None: + """The raw command sends a named B01 Q7 method and prints the device reply.""" + q7_fake_channel.response_queue.append({"result": "ok"}) + _mock_device(monkeypatch, q7_api) + + result = CliRunner().invoke(cli, ["command", "--device_id", "abc123", "--cmd", "service.find_device"]) + + assert result.exit_code == 0, result.output + assert q7_fake_channel.published_commands == [(RoborockB01Q7Methods.FIND_DEVICE, None)] + assert '"result": "ok"' in result.output + + +def test_q7_raw_command_invalid( + monkeypatch: pytest.MonkeyPatch, + q7_api: Q7PropertiesApi, + q7_fake_channel: FakeQ7Channel, +) -> None: + """An unknown method name is rejected before anything is sent to the device.""" + _mock_device(monkeypatch, q7_api) + + result = CliRunner().invoke(cli, ["command", "--device_id", "abc123", "--cmd", "service.nope"]) + + assert result.exit_code == 0, result.output + assert "Invalid command service.nope for B01_Q7 device" in result.output + assert q7_fake_channel.published_commands == [] From d53d0d47c257d1ad994f1cdb01fb7dc6c6ec6b9d Mon Sep 17 00:00:00 2001 From: Vedant saruk Date: Mon, 23 Nov 2026 08:58:04 +0530 Subject: [PATCH 2/3] fix(cli): default omitted Q7 command params to {} and drop rooms pointer from q7-clean-segments --- roborock/cli.py | 6 +++--- tests/test_cli.py | 43 ++++++++++++++++++++++++++++++++++++++++++- 2 files changed, 45 insertions(+), 4 deletions(-) diff --git a/roborock/cli.py b/roborock/cli.py index 7e04bf4eb..abc29b6e8 100644 --- a/roborock/cli.py +++ b/roborock/cli.py @@ -1051,7 +1051,7 @@ async def command(ctx, cmd, device_id, params): except ValueError as err: raise RoborockException(f"Invalid command {cmd} for B01_Q7 device") from err properties = device.b01_q7_properties - result = await properties.send(method, json.loads(params) if params is not None else None) + result = await properties.send(method, json.loads(params) if params is not None else {}) if result: click.echo(dump_json(result)) else: @@ -1861,14 +1861,14 @@ async def q7_vacuum_dock(ctx: click.Context, device_id: str) -> None: @click.option( "--segments", required=True, - help="Comma-separated room/segment ids to clean (see the `rooms` command), e.g. 9,2", + help="Comma-separated room/segment ids to clean, e.g. 9,2", ) @click.pass_context @async_command async def q7_clean_segments(ctx: click.Context, device_id: str, segments: str) -> None: """Start a room / segment clean on a Q7 device. - Room ids come from the `rooms` command (the device's map rooms). + Room ids are the segment ids from the device's map rooms. """ context: RoborockContext = ctx.obj try: diff --git a/tests/test_cli.py b/tests/test_cli.py index d9bff6409..d641c1302 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -366,10 +366,51 @@ def test_q7_raw_command( result = CliRunner().invoke(cli, ["command", "--device_id", "abc123", "--cmd", "service.find_device"]) assert result.exit_code == 0, result.output - assert q7_fake_channel.published_commands == [(RoborockB01Q7Methods.FIND_DEVICE, None)] + assert q7_fake_channel.published_commands == [(RoborockB01Q7Methods.FIND_DEVICE, {})] assert '"result": "ok"' in result.output +def test_q7_raw_command_explicit_empty_list_params( + monkeypatch: pytest.MonkeyPatch, + q7_api: Q7PropertiesApi, + q7_fake_channel: FakeQ7Channel, +) -> None: + """An explicit --params '[]' still sends an empty list, not the {} default.""" + q7_fake_channel.response_queue.append({"result": "ok"}) + _mock_device(monkeypatch, q7_api) + + result = CliRunner().invoke( + cli, ["command", "--device_id", "abc123", "--cmd", "service.find_device", "--params", "[]"] + ) + + assert result.exit_code == 0, result.output + assert q7_fake_channel.published_commands == [(RoborockB01Q7Methods.FIND_DEVICE, [])] + + +def test_q7_raw_command_explicit_params( + monkeypatch: pytest.MonkeyPatch, + q7_api: Q7PropertiesApi, + q7_fake_channel: FakeQ7Channel, +) -> None: + """An explicit --params value is parsed as JSON and sent as-is.""" + q7_fake_channel.response_queue.append({"result": "ok"}) + _mock_device(monkeypatch, q7_api) + + result = CliRunner().invoke( + cli, ["command", "--device_id", "abc123", "--cmd", "service.find_device", "--params", '{"mode": 1}'] + ) + + assert result.exit_code == 0, result.output + assert q7_fake_channel.published_commands == [(RoborockB01Q7Methods.FIND_DEVICE, {"mode": 1})] + + +def test_q7_clean_segments_help_does_not_reference_rooms() -> None: + """The Q7 segment help does not point at the rooms command, which has no Q7 branch.""" + segments_option = next(p for p in q7_clean_segments.params if p.name == "segments") + assert "`rooms`" not in (segments_option.help or "") + assert "`rooms`" not in (q7_clean_segments.callback.__doc__ or "") + + def test_q7_raw_command_invalid( monkeypatch: pytest.MonkeyPatch, q7_api: Q7PropertiesApi, From 305cdf92c597fd74421238d0c67578ab01df375e Mon Sep 17 00:00:00 2001 From: Vedant saruk Date: Thu, 26 Nov 2026 07:03:54 +0530 Subject: [PATCH 3/3] docs(cli): reword Q7 resume comment to note the app's unconfirmed puaseFalse value --- roborock/cli.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/roborock/cli.py b/roborock/cli.py index 060fa55cb..35500e07b 100644 --- a/roborock/cli.py +++ b/roborock/cli.py @@ -1788,9 +1788,9 @@ async def q10_set_fan_level(ctx: click.Context, device_id: str, level: str) -> N # # The Q7 API exposes its cleaning commands directly on Q7PropertiesApi # (there is no separate vacuum trait as on the Q10), so these commands call -# the API methods. There is intentionally no resume or spot command: the Q7 -# firmware has no resume control value (SCDeviceCleanParam only defines -# start, pause and stop) and no spot clean task type, so a paused clean is +# the API methods. There is intentionally no resume or spot command: the +# library does not map a resume value yet (the app defines an unconfirmed +# puaseFalse = 3) and no spot clean task type, so a paused clean is # restarted with q7-vacuum-start.