Просмотр исходного кода

feat: add CO2 controls for SwitchBot Meter Pro CO2 (#559)

* feat: Add CO2 Settings to SwitchbotMeterProCO2

* chore(pre-commit.ci): auto fixes

* Botfeedback

* chore(pre-commit.ci): auto fixes

* coverage

* chore(pre-commit.ci): auto fixes

* fix(meter-pro): clarify CO2 sampling and calibration commands

* feat(meter-pro): add CO2 update intervals and USB power detection

* feat(meter-pro): read and validate CO2 level thresholds

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: zerzhang <916250497@qq.com>
ahrmn 1 день назад
Родитель
Сommit
1e147b4806
2 измененных файлов с 326 добавлено и 0 удалено
  1. 116 0
      switchbot/devices/meter_pro.py
  2. 210 0
      tests/test_meter_pro.py

+ 116 - 0
switchbot/devices/meter_pro.py

@@ -15,6 +15,16 @@ COMMAND_SET_DISPLAY_FORMAT = "570f680505"
 COMMAND_GET_WEATHER = "570f6906"
 COMMAND_SET_WEATHER = "570f680601"
 
+COMMAND_TRIGGER_CO2_SAMPLING = "570f680b04"
+COMMAND_START_CO2_CALIBRATION = "570f680b02"
+COMMAND_GET_USB_POWER_STATE = "570f690b02"
+COMMAND_GET_CO2_USB_UPDATE_INTERVAL = "570f690b03"
+COMMAND_SET_CO2_USB_UPDATE_INTERVAL = "570f680b01"
+COMMAND_GET_CO2_BATTERY_UPDATE_INTERVAL = "570f690b04"
+COMMAND_SET_CO2_BATTERY_UPDATE_INTERVAL = "570f680b06"
+COMMAND_GET_CO2_LEVEL_THRESHOLDS = "570f69020302"
+COMMAND_SET_CO2_LEVEL_THRESHOLDS = "570f68020302"
+
 
 def _weather_decimal(value: float | Decimal, name: str) -> Decimal:
     if isinstance(value, bool):
@@ -311,3 +321,109 @@ class SwitchbotMeterPro(SwitchbotDevice):
 
 class SwitchbotMeterProCO2(SwitchbotMeterPro):
     """Control the CO2 variant of the SwitchBot Meter Pro."""
+
+    async def trigger_co2_sampling(self) -> None:
+        """Request a CO2 sample and wait for the device to acknowledge the request."""
+        result = await self._send_command(COMMAND_TRIGGER_CO2_SAMPLING, retry=0)
+        self._validate_result("trigger_co2_sampling", result)
+
+    async def start_co2_calibration(self) -> None:
+        """
+        Start manual calibration and wait for acknowledgement.
+
+        Place the meter outdoors in a well-ventilated area for one minute first.
+        Keep it still during the five-minute calibration.
+        """
+        result = await self._send_command(COMMAND_START_CO2_CALIBRATION, retry=0)
+        self._validate_result("start_co2_calibration", result)
+
+    async def is_usb_powered(self) -> bool:
+        """Read whether USB-C power is connected."""
+        result = await self._send_command(COMMAND_GET_USB_POWER_STATE)
+        data = self._validate_result("is_usb_powered", result, min_length=2)
+        if data[1] not in (0, 1):
+            raise SwitchbotOperationError(
+                f"{self.name}: Unexpected USB power state {data[1]:02x}"
+            )
+        return data[1] == 1
+
+    async def get_co2_battery_update_interval(self) -> int:
+        """Read the battery-powered CO2 update interval in seconds."""
+        return await self._get_co2_update_interval(
+            COMMAND_GET_CO2_BATTERY_UPDATE_INTERVAL, "get_co2_battery_update_interval"
+        )
+
+    async def set_co2_battery_update_interval(self, seconds: int) -> None:
+        """Set the battery-powered CO2 update interval in seconds."""
+        await self._set_co2_update_interval(
+            COMMAND_SET_CO2_BATTERY_UPDATE_INTERVAL,
+            "set_co2_battery_update_interval",
+            seconds,
+        )
+
+    async def get_co2_usb_update_interval(self) -> int:
+        """Read the USB-powered CO2 update interval in seconds."""
+        return await self._get_co2_update_interval(
+            COMMAND_GET_CO2_USB_UPDATE_INTERVAL, "get_co2_usb_update_interval"
+        )
+
+    async def set_co2_usb_update_interval(self, seconds: int) -> None:
+        """Set the USB-powered CO2 update interval in seconds."""
+        await self._set_co2_update_interval(
+            COMMAND_SET_CO2_USB_UPDATE_INTERVAL, "set_co2_usb_update_interval", seconds
+        )
+
+    async def _get_co2_update_interval(self, command: str, operation: str) -> int:
+        result = await self._send_command(command)
+        data = self._validate_result(operation, result, min_length=3)
+        return int.from_bytes(data[1:3], "big")
+
+    async def _set_co2_update_interval(
+        self, command: str, operation: str, seconds: int
+    ) -> None:
+        if (
+            isinstance(seconds, bool)
+            or not isinstance(seconds, int)
+            or not 1 <= seconds <= 0xFFFF
+        ):
+            raise SwitchbotOperationError(
+                f"{self.name}: CO2 update interval must be an integer from 1 to 65535 seconds"
+            )
+
+        result = await self._send_command(command + seconds.to_bytes(2, "big").hex())
+        self._validate_result(operation, result)
+
+    async def get_co2_level_thresholds(self) -> tuple[int, int]:
+        """Read the green-to-yellow and yellow-to-red CO2 thresholds in ppm."""
+        result = await self._send_command(COMMAND_GET_CO2_LEVEL_THRESHOLDS)
+        data = self._validate_result("get_co2_level_thresholds", result, min_length=5)
+        return int.from_bytes(data[1:3], "big"), int.from_bytes(data[3:5], "big")
+
+    async def set_co2_level_thresholds(
+        self, green_to_yellow_ppm: int, yellow_to_red_ppm: int
+    ) -> None:
+        """Set the green-to-yellow and yellow-to-red CO2 thresholds in 100 ppm steps."""
+        if any(
+            isinstance(threshold, bool)
+            or not isinstance(threshold, int)
+            or not 0 <= threshold <= 0xFFFF
+            or threshold % 100
+            for threshold in (green_to_yellow_ppm, yellow_to_red_ppm)
+        ):
+            raise SwitchbotOperationError(
+                f"{self.name}: CO2 level thresholds must be unsigned 16-bit integers in 100 ppm steps"
+            )
+        if green_to_yellow_ppm >= yellow_to_red_ppm:
+            raise SwitchbotOperationError(
+                f"{self.name}: The green-to-yellow CO2 threshold must be below the yellow-to-red threshold"
+            )
+
+        payload = (
+            COMMAND_SET_CO2_LEVEL_THRESHOLDS
+            + (
+                green_to_yellow_ppm.to_bytes(2, "big")
+                + yellow_to_red_ppm.to_bytes(2, "big")
+            ).hex()
+        )
+        result = await self._send_command(payload)
+        self._validate_result("set_co2_level_thresholds", result)

+ 210 - 0
tests/test_meter_pro.py

@@ -269,3 +269,213 @@ async def test_meter_pro_shares_datetime_protocol_with_co2_variant():
     device._send_command.assert_called_with(
         "57000503" + "0c" + "65e11a80".zfill(16) + "00"
     )
+
+
+@pytest.mark.asyncio
+async def test_trigger_co2_sampling():
+    device = create_device()
+    device._send_command.return_value = b"\x01"
+
+    await device.trigger_co2_sampling()
+
+    device._send_command.assert_awaited_once_with("570f680b04", retry=0)
+
+
+@pytest.mark.asyncio
+async def test_start_co2_calibration():
+    device = create_device()
+    device._send_command.return_value = b"\x01"
+
+    await device.start_co2_calibration()
+
+    device._send_command.assert_awaited_once_with("570f680b02", retry=0)
+
+
+@pytest.mark.asyncio
+@pytest.mark.parametrize(("response", "powered"), [("0100", False), ("0101", True)])
+async def test_is_usb_powered(response: str, powered: bool):
+    device = create_device()
+    device._send_command.return_value = bytes.fromhex(response)
+
+    assert await device.is_usb_powered() is powered
+    device._send_command.assert_awaited_once_with("570f690b02")
+
+
+@pytest.mark.asyncio
+async def test_is_usb_powered_rejects_unknown_state():
+    device = create_device()
+    device._send_command.return_value = bytes.fromhex("0102")
+
+    with pytest.raises(SwitchbotOperationError, match="Unexpected USB power state 02"):
+        await device.is_usb_powered()
+
+
+@pytest.mark.asyncio
+@pytest.mark.parametrize(
+    ("mode", "command", "response", "expected_seconds"),
+    [
+        ("battery", "570f690b04", "010258", 600),
+        ("battery", "570f690b04", "010708", 1800),
+        ("usb", "570f690b03", "01003c", 60),
+        ("usb", "570f690b03", "010078", 120),
+    ],
+)
+async def test_get_co2_update_interval(
+    mode: str, command: str, response: str, expected_seconds: int
+):
+    device = create_device()
+    device._send_command.return_value = bytes.fromhex(response)
+
+    assert (
+        await getattr(device, f"get_co2_{mode}_update_interval")() == expected_seconds
+    )
+    device._send_command.assert_awaited_once_with(command)
+
+
+@pytest.mark.asyncio
+@pytest.mark.parametrize(
+    ("mode", "command"),
+    [("battery", "570f680b06"), ("usb", "570f680b01")],
+)
+@pytest.mark.parametrize(
+    ("seconds", "expected_payload"),
+    [
+        (1, "0001"),
+        (60, "003c"),
+        (120, "0078"),
+        (600, "0258"),
+        (1800, "0708"),
+        (65535, "ffff"),
+    ],
+)
+async def test_set_co2_update_interval(
+    mode: str, command: str, seconds: int, expected_payload: str
+):
+    device = create_device()
+    device._send_command.return_value = b"\x01"
+
+    await getattr(device, f"set_co2_{mode}_update_interval")(seconds)
+
+    device._send_command.assert_awaited_once_with(command + expected_payload)
+
+
+@pytest.mark.asyncio
+@pytest.mark.parametrize("mode", ["battery", "usb"])
+@pytest.mark.parametrize("seconds", [True, "600", 600.0, -1, 0, 65536, 0x100000])
+async def test_set_co2_update_interval_rejects_invalid_input(
+    mode: str, seconds: object
+):
+    device = create_device()
+
+    with pytest.raises(SwitchbotOperationError, match="1 to 65535 seconds"):
+        await getattr(device, f"set_co2_{mode}_update_interval")(seconds)
+
+    device._send_command.assert_not_awaited()
+
+
+@pytest.mark.asyncio
+@pytest.mark.parametrize(
+    ("response", "expected_thresholds"),
+    [("0103e80578", (1000, 1400)), ("01044c0578", (1100, 1400))],
+)
+async def test_get_co2_level_thresholds(
+    response: str, expected_thresholds: tuple[int, int]
+):
+    device = create_device()
+    device._send_command.return_value = bytes.fromhex(response)
+
+    assert await device.get_co2_level_thresholds() == expected_thresholds
+    device._send_command.assert_awaited_once_with("570f69020302")
+
+
+@pytest.mark.asyncio
+@pytest.mark.parametrize(
+    ("green_to_yellow", "yellow_to_red", "expected_payload"),
+    [(500, 1000, "01f403e8"), (1100, 1400, "044c0578"), (1900, 2000, "076c07d0")],
+)
+async def test_set_co2_level_thresholds(
+    green_to_yellow: int, yellow_to_red: int, expected_payload: str
+):
+    device = create_device()
+    device._send_command.return_value = b"\x01"
+
+    await device.set_co2_level_thresholds(
+        green_to_yellow_ppm=green_to_yellow, yellow_to_red_ppm=yellow_to_red
+    )
+
+    device._send_command.assert_awaited_once_with("570f68020302" + expected_payload)
+
+
+@pytest.mark.asyncio
+@pytest.mark.parametrize(
+    ("green_to_yellow", "yellow_to_red", "expected_error"),
+    [
+        (600, 500, "must be below"),
+        (500, 500, "must be below"),
+        (550, 1000, "100 ppm steps"),
+        (500, 1050, "100 ppm steps"),
+        (-100, 1000, "100 ppm steps"),
+        (500, 65600, "100 ppm steps"),
+        (True, 1000, "100 ppm steps"),
+        (500, "1000", "100 ppm steps"),
+        (500.0, 1000, "100 ppm steps"),
+    ],
+)
+async def test_set_co2_level_thresholds_rejects_invalid_input(
+    green_to_yellow: object, yellow_to_red: object, expected_error: str
+):
+    device = create_device()
+
+    with pytest.raises(SwitchbotOperationError, match=expected_error):
+        await device.set_co2_level_thresholds(green_to_yellow, yellow_to_red)
+
+    device._send_command.assert_not_awaited()
+
+
+@pytest.mark.asyncio
+@pytest.mark.parametrize(
+    ("method", "args"),
+    [
+        ("trigger_co2_sampling", ()),
+        ("start_co2_calibration", ()),
+        ("is_usb_powered", ()),
+        ("get_co2_battery_update_interval", ()),
+        ("get_co2_usb_update_interval", ()),
+        ("set_co2_usb_update_interval", (120,)),
+        ("set_co2_battery_update_interval", (600,)),
+        ("get_co2_level_thresholds", ()),
+        ("set_co2_level_thresholds", (1000, 1400)),
+    ],
+)
+@pytest.mark.parametrize(
+    ("response", "response_hex"),
+    [(None, "None"), (b"\x02", "02"), (b"\x03", "03"), (b"\x05", "05")],
+)
+async def test_co2_rejects_unsuccessful_responses(
+    method: str, args: tuple[int, ...], response: bytes | None, response_hex: str
+):
+    device = create_device()
+    device._send_command.return_value = response
+
+    with pytest.raises(SwitchbotOperationError, match=f"result={response_hex}"):
+        await getattr(device, method)(*args)
+
+
+@pytest.mark.asyncio
+@pytest.mark.parametrize(
+    ("method", "response"),
+    [
+        ("is_usb_powered", "01"),
+        ("get_co2_battery_update_interval", "0102"),
+        ("get_co2_usb_update_interval", "0100"),
+        ("get_co2_level_thresholds", "0103e805"),
+    ],
+)
+async def test_co2_getters_reject_short_responses(method: str, response: str):
+    device = create_device()
+    device._send_command.return_value = bytes.fromhex(response)
+
+    with pytest.raises(
+        SwitchbotOperationError, match=f"Unexpected response len for {method}"
+    ):
+        await getattr(device, method)()