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

feat: add Meter Pro comfort and alarm settings (#430)

* Added settings for Meter Pro Co2

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

* Feedback and Tests

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

* Removed Humidity and Temperature Alert

* Covererage

* Match Errormessage

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

* renamed tests

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

* escape

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

* Return types and seconds

* feat(meter-pro): add comfort level settings

* feat(meter-pro): add audible and visual alarm settings

* feat(meter-pro): add CO2 concentration alarm settings

* feat(meter-pro): add temperature and humidity threshold alarms

* fix(meter-pro): mask temperature and humidity alarm states

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: J. Nick Koston <nick@koston.org>
Co-authored-by: zerzhang <916250497@qq.com>
ahrmn 2 дней назад
Родитель
Сommit
6e862cad0f

+ 14 - 0
switchbot/__init__.py

@@ -24,9 +24,16 @@ from .const import (
     HumidifierMode,
     HumidifierWaterLevel,
     LockStatus,
+    MeterProAlarmMode,
+    MeterProAlarmVolume,
+    MeterProCO2AlarmMode,
+    MeterProCO2AlarmStatus,
+    MeterProComfortStatus,
     MeterProDateFormat,
     MeterProDisplaySource,
     MeterProDisplayZone,
+    MeterProTemperatureHumidityAlarmMode,
+    MeterProTemperatureHumidityAlarmStatus,
     MeterProWeatherIcon,
     MeterProZoneIcon,
     NightLightState,
@@ -115,9 +122,16 @@ __all__ = [
     "HumidifierMode",
     "HumidifierWaterLevel",
     "LockStatus",
+    "MeterProAlarmMode",
+    "MeterProAlarmVolume",
+    "MeterProCO2AlarmMode",
+    "MeterProCO2AlarmStatus",
+    "MeterProComfortStatus",
     "MeterProDateFormat",
     "MeterProDisplaySource",
     "MeterProDisplayZone",
+    "MeterProTemperatureHumidityAlarmMode",
+    "MeterProTemperatureHumidityAlarmStatus",
     "MeterProWeatherIcon",
     "MeterProZoneIcon",
     "NightLightState",

+ 14 - 0
switchbot/const/__init__.py

@@ -28,9 +28,16 @@ from .light import (
 # Preserve old LockStatus export for backwards compatibility
 from .lock import LockStatus, QuickKeyFunction
 from .meter_pro import (
+    MeterProAlarmMode,
+    MeterProAlarmVolume,
+    MeterProCO2AlarmMode,
+    MeterProCO2AlarmStatus,
+    MeterProComfortStatus,
     MeterProDateFormat,
     MeterProDisplaySource,
     MeterProDisplayZone,
+    MeterProTemperatureHumidityAlarmMode,
+    MeterProTemperatureHumidityAlarmStatus,
     MeterProWeatherIcon,
     MeterProZoneIcon,
 )
@@ -173,9 +180,16 @@ __all__ = [
     "HumidifierMode",
     "HumidifierWaterLevel",
     "LockStatus",
+    "MeterProAlarmMode",
+    "MeterProAlarmVolume",
+    "MeterProCO2AlarmMode",
+    "MeterProCO2AlarmStatus",
+    "MeterProComfortStatus",
     "MeterProDateFormat",
     "MeterProDisplaySource",
     "MeterProDisplayZone",
+    "MeterProTemperatureHumidityAlarmMode",
+    "MeterProTemperatureHumidityAlarmStatus",
     "MeterProWeatherIcon",
     "MeterProZoneIcon",
     "NightLightState",

+ 67 - 1
switchbot/const/meter_pro.py

@@ -1,4 +1,4 @@
-from enum import Enum
+from enum import Enum, IntFlag
 
 
 class MeterProWeatherIcon(Enum):
@@ -47,3 +47,69 @@ class MeterProDateFormat(Enum):
 
     MONTH_DAY = 0
     DAY_MONTH = 1
+
+
+class MeterProComfortStatus(Enum):
+    """The device's current temperature and humidity comfort status."""
+
+    COMFORTABLE = 0
+    DRY = 1
+    WET = 2
+    UNAVAILABLE = 3
+
+
+class MeterProAlarmMode(Enum):
+    """How the meter signals a local threshold alarm."""
+
+    DISABLED = 0
+    FLASH_ONLY = 1
+    SOUND_AND_FLASH = 2
+
+
+class MeterProAlarmVolume(Enum):
+    """Alarm buzzer volume."""
+
+    OFF = 1
+    LOW = 2
+    MEDIUM = 3
+    HIGH = 4
+
+
+class MeterProCO2AlarmMode(IntFlag):
+    """CO2 alarm conditions and the protocol's custom-setting bit."""
+
+    DISABLED = 0
+    LOW = 1
+    HIGH = 2
+    IN_RANGE = 4
+    CUSTOM = 8
+
+
+class MeterProCO2AlarmStatus(Enum):
+    """Current CO2 alarm reported by the meter."""
+
+    NONE = 0
+    LOW = 1
+    HIGH = 2
+    IN_RANGE = 3
+
+
+class MeterProTemperatureHumidityAlarmMode(IntFlag):
+    """Local alarm conditions for the temperature and humidity limits."""
+
+    DISABLED = 0
+    TEMPERATURE_LOW = 0x01
+    TEMPERATURE_HIGH = 0x02
+    TEMPERATURE_IN_RANGE = 0x04
+    HUMIDITY_LOW = 0x10
+    HUMIDITY_HIGH = 0x20
+    HUMIDITY_IN_RANGE = 0x40
+
+
+class MeterProTemperatureHumidityAlarmStatus(Enum):
+    """Current alarm state of the temperature or humidity measurement."""
+
+    NONE = 0
+    LOW = 1
+    HIGH = 2
+    IN_RANGE = 3

+ 268 - 0
switchbot/devices/meter_pro.py

@@ -2,9 +2,16 @@ from decimal import ROUND_HALF_UP, Decimal
 from typing import Any
 
 from ..const.meter_pro import (
+    MeterProAlarmMode,
+    MeterProAlarmVolume,
+    MeterProCO2AlarmMode,
+    MeterProCO2AlarmStatus,
+    MeterProComfortStatus,
     MeterProDateFormat,
     MeterProDisplaySource,
     MeterProDisplayZone,
+    MeterProTemperatureHumidityAlarmMode,
+    MeterProTemperatureHumidityAlarmStatus,
     MeterProWeatherIcon,
     MeterProZoneIcon,
 )
@@ -19,6 +26,11 @@ COMMAND_GET_DEVICE_DATETIME = "570f6901"
 COMMAND_SET_DEVICE_DATETIME = "57000503"
 COMMAND_SET_DISPLAY_FORMAT = "570f680505"
 
+COMMAND_GET_COMFORT_LEVEL = "570f69020101"
+COMMAND_GET_TEMPERATURE_HUMIDITY_ALARM = "570f69020100"
+COMMAND_SET_TEMPERATURE_HUMIDITY_LIMITS = "570f680201"
+COMMAND_GET_ALARM_SETTINGS = "570f690204"
+COMMAND_SET_ALARM_SETTINGS = "570f680204"
 COMMAND_GET_CALIBRATION = "570f6903"
 COMMAND_SET_CALIBRATION = "570f6803"
 COMMAND_GET_DISPLAY_SETTINGS = "570f690701"
@@ -38,6 +50,8 @@ NO_MAC = "000000000000"
 KEEP_ZONE_ICON = 0xFF
 KEEP_ICON = 0x0F
 KEEP_BUTTON_FUNCTION = 0xFF
+KEEP_ALARM_VOLUME = 0xFF
+TEMPERATURE_HUMIDITY_ALARM_MASK = 0x77
 SOURCES_WITHOUT_MAC = {MeterProDisplaySource.NONE, MeterProDisplaySource.NETWORK}
 COMMAND_GET_WEATHER = "570f6906"
 COMMAND_SET_WEATHER = "570f680601"
@@ -49,6 +63,8 @@ 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_ALARM = "570f69020301"
+COMMAND_SET_CO2_ALARM = "570f68020301"
 COMMAND_GET_CO2_LEVEL_THRESHOLDS = "570f69020302"
 COMMAND_SET_CO2_LEVEL_THRESHOLDS = "570f68020302"
 
@@ -73,6 +89,44 @@ def _encode_weather_temperature(temperature_c: float | Decimal) -> bytes:
     return bytes((decimal, integer | (0x80 if temperature >= 0 else 0)))
 
 
+def _decode_threshold_temperature(signed_degrees: int, tenths: int) -> float:
+    magnitude = (signed_degrees & 0x7F) * 10 + tenths
+    return (magnitude if signed_degrees & 0x80 else -magnitude) / 10
+
+
+def _decode_temperature_humidity_limits(data: bytes) -> tuple[float, float, int, int]:
+    high, humid, decimals, low, dry = data
+    high_tenths, low_tenths = decimals >> 4, decimals & 0x0F
+    humid &= 0x7F
+    dry &= 0x7F
+    if max(high_tenths, low_tenths) > 9 or max(humid, dry) > 99:
+        raise ValueError("Invalid temperature or humidity limits")
+    return (
+        _decode_threshold_temperature(low, low_tenths),
+        _decode_threshold_temperature(high, high_tenths),
+        dry,
+        humid,
+    )
+
+
+def _encode_temperature_humidity_limits(
+    temperature_low_c: float | Decimal,
+    temperature_high_c: float | Decimal,
+    humidity_low: int,
+    humidity_high: int,
+) -> bytes:
+    low_tenths, low = _encode_weather_temperature(temperature_low_c)
+    high_tenths, high = _encode_weather_temperature(temperature_high_c)
+    if any(
+        isinstance(limit, bool) or not isinstance(limit, int) or not 0 <= limit <= 99
+        for limit in (humidity_low, humidity_high)
+    ):
+        raise ValueError("Humidity limits must be integers from 0 to 99")
+    return bytes(
+        (high, humidity_high, (high_tenths << 4) | low_tenths, low, humidity_low)
+    )
+
+
 def _encode_weather_humidity(humidity: float | Decimal) -> int:
     relative_humidity = _weather_decimal(humidity, "humidity")
     if not 1 <= relative_humidity <= 99:
@@ -250,6 +304,174 @@ class SwitchbotMeterPro(SwitchbotDevice):
         result = await self._send_command(payload)
         self._validate_result("set_time_display_format", result)
 
+    async def get_comfort_level(
+        self,
+    ) -> dict[str, float | int | bool | MeterProComfortStatus]:
+        """Read the comfort mode, Celsius and %RH limits, and current status."""
+        result = await self._send_command(COMMAND_GET_COMFORT_LEVEL)
+        data = self._validate_result("get_comfort_level", result, min_length=8)
+        mode = data[1]
+        if mode not in (0, 1):
+            raise SwitchbotOperationError(
+                f"{self.name}: Invalid comfort level response (result={data.hex()})"
+            )
+        try:
+            low, high, dry, humid = _decode_temperature_humidity_limits(data[2:7])
+        except ValueError as exc:
+            raise SwitchbotOperationError(
+                f"{self.name}: Invalid comfort level response (result={data.hex()})"
+            ) from exc
+        return {
+            "custom": mode == 1,
+            "temperature_low_c": low,
+            "temperature_high_c": high,
+            "humidity_low": dry,
+            "humidity_high": humid,
+            "status": MeterProComfortStatus(data[7] & 0x03),
+        }
+
+    async def set_comfort_level(
+        self,
+        temperature_low_c: float | Decimal,
+        temperature_high_c: float | Decimal,
+        humidity_low: int,
+        humidity_high: int,
+        *,
+        custom: bool = True,
+    ) -> None:
+        """Set comfort limits in °C (half-up to tenths) and %RH, or select default mode."""
+        try:
+            limits = _encode_temperature_humidity_limits(
+                temperature_low_c, temperature_high_c, humidity_low, humidity_high
+            )
+        except (TypeError, ValueError) as exc:
+            raise SwitchbotOperationError(f"{self.name}: {exc}") from exc
+        if not isinstance(custom, bool):
+            raise SwitchbotOperationError(f"{self.name}: custom must be a boolean")
+        if custom:
+            low, high, dry, humid = _decode_temperature_humidity_limits(limits)
+            if low >= high or dry >= humid:
+                raise SwitchbotOperationError(
+                    f"{self.name}: Lower comfort limits must be below upper limits"
+                )
+
+        flags = 0x88 if custom else 0x80
+        result = await self._send_command(
+            f"{COMMAND_SET_TEMPERATURE_HUMIDITY_LIMITS}{flags:02x}{limits.hex()}"
+        )
+        self._validate_result("set_comfort_level", result)
+
+    async def get_temperature_humidity_alarm(
+        self,
+    ) -> dict[
+        str,
+        float
+        | int
+        | MeterProTemperatureHumidityAlarmMode
+        | MeterProTemperatureHumidityAlarmStatus,
+    ]:
+        """Read local alarm conditions, thresholds in °C and %RH, and both states."""
+        result = await self._send_command(COMMAND_GET_TEMPERATURE_HUMIDITY_ALARM)
+        data = self._validate_result(
+            "get_temperature_humidity_alarm", result, min_length=8
+        )
+        try:
+            low, high, dry, humid = _decode_temperature_humidity_limits(data[2:7])
+        except ValueError as exc:
+            raise SwitchbotOperationError(
+                f"{self.name}: Invalid temperature and humidity alarm response (result={data.hex()})"
+            ) from exc
+        # The latest confirmed protocol uses bits 5:4 for the temperature alarm
+        # state and bits 1:0 for the humidity alarm state.
+        status = data[7]
+        temperature_status = MeterProTemperatureHumidityAlarmStatus(
+            (status >> 4) & 0x03
+        )
+        humidity_status = MeterProTemperatureHumidityAlarmStatus(status & 0x03)
+        return {
+            "mode": MeterProTemperatureHumidityAlarmMode(data[1]),
+            "temperature_low_c": low,
+            "temperature_high_c": high,
+            "humidity_low": dry,
+            "humidity_high": humid,
+            "temperature_status": temperature_status,
+            "humidity_status": humidity_status,
+        }
+
+    async def set_temperature_humidity_alarm(
+        self,
+        mode: MeterProTemperatureHumidityAlarmMode,
+        temperature_low_c: float | Decimal,
+        temperature_high_c: float | Decimal,
+        humidity_low: int,
+        humidity_high: int,
+    ) -> None:
+        """Set both sets of local alarm limits and the enabled conditions together."""
+        # Bit 7 selects comfort settings on the shared write command.
+        if (
+            not isinstance(mode, MeterProTemperatureHumidityAlarmMode)
+            or mode.value & ~TEMPERATURE_HUMIDITY_ALARM_MASK
+        ):
+            raise SwitchbotOperationError(
+                f"{self.name}: Invalid temperature and humidity alarm mode {mode!r}"
+            )
+        try:
+            limits = _encode_temperature_humidity_limits(
+                temperature_low_c, temperature_high_c, humidity_low, humidity_high
+            )
+        except (TypeError, ValueError) as exc:
+            raise SwitchbotOperationError(f"{self.name}: {exc}") from exc
+        low, high, dry, humid = _decode_temperature_humidity_limits(limits)
+        if (
+            mode & MeterProTemperatureHumidityAlarmMode.TEMPERATURE_IN_RANGE
+            and low > high
+        ) or (
+            mode & MeterProTemperatureHumidityAlarmMode.HUMIDITY_IN_RANGE
+            and dry > humid
+        ):
+            raise SwitchbotOperationError(
+                f"{self.name}: Lower in-range alarm limits must not exceed upper limits"
+            )
+        result = await self._send_command(
+            f"{COMMAND_SET_TEMPERATURE_HUMIDITY_LIMITS}{mode.value:02x}{limits.hex()}"
+        )
+        self._validate_result("set_temperature_humidity_alarm", result)
+
+    async def get_alarm_settings(
+        self,
+    ) -> dict[str, MeterProAlarmMode | MeterProAlarmVolume | None]:
+        """Read the local alarm mode and volume, with None for an unrecognized volume."""
+        result = await self._send_command(COMMAND_GET_ALARM_SETTINGS)
+        data = self._validate_result("get_alarm_settings", result, min_length=3)
+        try:
+            mode = MeterProAlarmMode(data[2])
+        except ValueError as exc:
+            raise SwitchbotOperationError(
+                f"{self.name}: Unknown alarm mode {data[2]:02x}"
+            ) from exc
+        volume = next(
+            (level for level in MeterProAlarmVolume if level.value == data[1]), None
+        )
+        return {"mode": mode, "volume": volume}
+
+    async def set_alarm_settings(
+        self, mode: MeterProAlarmMode, volume: MeterProAlarmVolume | None = None
+    ) -> None:
+        """Set the local alarm mode and optionally change the buzzer volume."""
+        if not isinstance(mode, MeterProAlarmMode):
+            raise SwitchbotOperationError(
+                f"{self.name}: mode must be a MeterProAlarmMode"
+            )
+        if volume is not None and not isinstance(volume, MeterProAlarmVolume):
+            raise SwitchbotOperationError(
+                f"{self.name}: volume must be a MeterProAlarmVolume or None"
+            )
+        volume_byte = KEEP_ALARM_VOLUME if volume is None else volume.value
+        result = await self._send_command(
+            f"{COMMAND_SET_ALARM_SETTINGS}{volume_byte:02x}{mode.value:02x}"
+        )
+        self._validate_result("set_alarm_settings", result)
+
     async def get_calibration(self) -> dict[str, Any]:
         """Get the temperature (C) and humidity (%RH) corrections."""
         # [status][temp sign|int][hum sign|value][temp tenths]; sign bit = positive
@@ -631,6 +853,52 @@ class SwitchbotMeterProCO2(SwitchbotMeterPro):
         result = await self._send_command(command + seconds.to_bytes(2, "big").hex())
         self._validate_result(operation, result)
 
+    async def get_co2_alarm(
+        self,
+    ) -> dict[str, MeterProCO2AlarmMode | MeterProCO2AlarmStatus | int]:
+        """Read CO2 alarm conditions, limits in ppm, and current alarm status."""
+        result = await self._send_command(COMMAND_GET_CO2_ALARM)
+        data = self._validate_result("get_co2_alarm", result, min_length=7)
+        return {
+            "mode": MeterProCO2AlarmMode(data[1]),
+            "high_ppm": int.from_bytes(data[2:4], "big"),
+            "low_ppm": int.from_bytes(data[4:6], "big"),
+            "status": MeterProCO2AlarmStatus(data[6] & 0x03),
+        }
+
+    async def set_co2_alarm(
+        self, mode: MeterProCO2AlarmMode, low_ppm: int, high_ppm: int
+    ) -> None:
+        """
+        Set CO2 alarm conditions and limits in ppm.
+
+        Pass the existing limits when disabling an alarm to keep them configured.
+        """
+        if not isinstance(mode, MeterProCO2AlarmMode) or mode.value & ~0x0F:
+            raise SwitchbotOperationError(
+                f"{self.name}: Invalid CO2 alarm mode {mode!r}"
+            )
+        if any(
+            isinstance(limit, bool)
+            or not isinstance(limit, int)
+            or not 0 <= limit <= 0xFFFF
+            for limit in (low_ppm, high_ppm)
+        ):
+            raise SwitchbotOperationError(
+                f"{self.name}: CO2 alarm limits must be unsigned 16-bit integers"
+            )
+        if low_ppm > high_ppm:
+            raise SwitchbotOperationError(
+                f"{self.name}: Lower CO2 alarm limit must not exceed the upper limit"
+            )
+        payload = (
+            bytes((mode.value,))
+            + high_ppm.to_bytes(2, "big")
+            + low_ppm.to_bytes(2, "big")
+        )
+        result = await self._send_command(COMMAND_SET_CO2_ALARM + payload.hex())
+        self._validate_result("set_co2_alarm", 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)

+ 516 - 0
tests/test_meter_pro_settings.py

@@ -6,9 +6,16 @@ import pytest
 from bleak.backends.device import BLEDevice
 
 from switchbot import (
+    MeterProAlarmMode,
+    MeterProAlarmVolume,
+    MeterProCO2AlarmMode,
+    MeterProCO2AlarmStatus,
+    MeterProComfortStatus,
     MeterProDateFormat,
     MeterProDisplaySource,
     MeterProDisplayZone,
+    MeterProTemperatureHumidityAlarmMode,
+    MeterProTemperatureHumidityAlarmStatus,
     MeterProZoneIcon,
     SwitchbotOperationError,
 )
@@ -478,3 +485,512 @@ async def test_co2_variant_shares_display_settings(
     await getattr(device, method)(*args)
 
     device._send_command.assert_called_with(expected_payload)
+
+
+@pytest.mark.asyncio
+@pytest.mark.parametrize(
+    ("device_class", "response", "expected"),
+    [
+        (
+            SwitchbotMeterPro,
+            "01009c4600921e00",
+            {
+                "custom": False,
+                "temperature_low_c": 18.0,
+                "temperature_high_c": 28.0,
+                "humidity_low": 30,
+                "humidity_high": 70,
+                "status": MeterProComfortStatus.COMFORTABLE,
+            },
+        ),
+        (
+            SwitchbotMeterProCO2,
+            "010180e3730080fe",
+            {
+                "custom": True,
+                "temperature_low_c": -0.3,
+                "temperature_high_c": 0.7,
+                "humidity_low": 0,
+                "humidity_high": 99,
+                "status": MeterProComfortStatus.WET,
+            },
+        ),
+    ],
+)
+async def test_get_comfort_level(
+    device_class: type[SwitchbotMeterPro],
+    response: str,
+    expected: dict[str, float | int | bool | MeterProComfortStatus],
+):
+    device = create_device(device_class)
+    device._send_command.return_value = bytes.fromhex(response)
+
+    assert await device.get_comfort_level() == expected
+    device._send_command.assert_awaited_once_with("570f69020101")
+
+
+@pytest.mark.asyncio
+@pytest.mark.parametrize(
+    ("limits", "custom", "expected"),
+    [
+        ((0.5, 22.34, 40, 82), True, "889652358028"),
+        ((-0.5, 0.66, 0, 99), True, "888063750000"),
+        ((18.0, 28.0, 30, 70), False, "809c4600921e"),
+    ],
+)
+async def test_set_comfort_level(
+    limits: tuple[float, float, int, int], custom: bool, expected: str
+):
+    device = create_device()
+
+    await device.set_comfort_level(*limits, custom=custom)
+
+    device._send_command.assert_awaited_once_with("570f680201" + expected)
+
+
+@pytest.mark.asyncio
+@pytest.mark.parametrize(
+    ("limits", "custom", "message"),
+    [
+        ((-128, 28.0, 30, 70), True, "Temperature must be"),
+        ((True, 28.0, 30, 70), True, "Temperature must be"),
+        ((18.01, 18.04, 30, 70), True, "Lower comfort limits"),
+        ((18, 28, 30, 100), True, "Humidity limits"),
+        ((18, 28, True, 70), True, "Humidity limits"),
+        ((18, 28, 70, 70), True, "Lower comfort limits"),
+        ((18, 28, 30, 70), 1, "custom must be a boolean"),
+    ],
+)
+async def test_set_comfort_level_rejects_invalid_input(
+    limits: tuple[float, float, int, int], custom: bool, message: str
+):
+    device = create_device()
+    with pytest.raises(SwitchbotOperationError, match=message):
+        await device.set_comfort_level(*limits, custom=custom)
+    device._send_command.assert_not_awaited()
+
+
+@pytest.mark.asyncio
+@pytest.mark.parametrize(
+    "response", ["02", "01", "01029c4600921e00", "01009c460a921e00", "01009c6400921e00"]
+)
+async def test_get_comfort_level_rejects_invalid_response(response: str):
+    device = create_device()
+    device._send_command.return_value = bytes.fromhex(response)
+    with pytest.raises(SwitchbotOperationError):
+        await device.get_comfort_level()
+
+
+@pytest.mark.asyncio
+async def test_set_comfort_level_rejects_device_error():
+    device = create_device()
+    device._send_command.return_value = b"\x02"
+    with pytest.raises(SwitchbotOperationError, match="set_comfort_level"):
+        await device.set_comfort_level(18, 28, 30, 70)
+
+
+@pytest.mark.asyncio
+@pytest.mark.parametrize(
+    ("device_class", "response", "mode", "volume"),
+    [
+        (SwitchbotMeterPro, "010000", MeterProAlarmMode.DISABLED, None),
+        (
+            SwitchbotMeterProCO2,
+            "010402",
+            MeterProAlarmMode.SOUND_AND_FLASH,
+            MeterProAlarmVolume.HIGH,
+        ),
+        (SwitchbotMeterPro, "01ff01", MeterProAlarmMode.FLASH_ONLY, None),
+    ],
+)
+async def test_get_alarm_settings(
+    device_class: type[SwitchbotMeterPro],
+    response: str,
+    mode: MeterProAlarmMode,
+    volume: MeterProAlarmVolume | None,
+):
+    device = create_device(device_class)
+    device._send_command.return_value = bytes.fromhex(response)
+
+    assert await device.get_alarm_settings() == {"mode": mode, "volume": volume}
+    device._send_command.assert_awaited_once_with("570f690204")
+
+
+@pytest.mark.asyncio
+@pytest.mark.parametrize(
+    ("mode", "volume", "payload"),
+    [
+        (MeterProAlarmMode.DISABLED, None, "ff00"),
+        (MeterProAlarmMode.FLASH_ONLY, MeterProAlarmVolume.OFF, "0101"),
+        (MeterProAlarmMode.SOUND_AND_FLASH, MeterProAlarmVolume.LOW, "0202"),
+        (MeterProAlarmMode.SOUND_AND_FLASH, MeterProAlarmVolume.MEDIUM, "0302"),
+        (MeterProAlarmMode.SOUND_AND_FLASH, MeterProAlarmVolume.HIGH, "0402"),
+    ],
+)
+async def test_set_alarm_settings(
+    mode: MeterProAlarmMode, volume: MeterProAlarmVolume | None, payload: str
+):
+    device = create_device()
+
+    await device.set_alarm_settings(mode, volume)
+
+    device._send_command.assert_awaited_once_with("570f680204" + payload)
+
+
+@pytest.mark.asyncio
+@pytest.mark.parametrize("response", ["02", "0100", "010403"])
+async def test_get_alarm_settings_rejects_invalid_response(response: str):
+    device = create_device()
+    device._send_command.return_value = bytes.fromhex(response)
+
+    with pytest.raises(SwitchbotOperationError):
+        await device.get_alarm_settings()
+
+
+@pytest.mark.asyncio
+@pytest.mark.parametrize(
+    ("mode", "volume", "message"),
+    [(True, None, "mode must be"), (MeterProAlarmMode.DISABLED, 5, "volume must be")],
+)
+async def test_set_alarm_settings_rejects_invalid_input(
+    mode: object, volume: object, message: str
+):
+    device = create_device()
+
+    with pytest.raises(SwitchbotOperationError, match=message):
+        await device.set_alarm_settings(mode, volume)
+
+    device._send_command.assert_not_awaited()
+
+
+@pytest.mark.asyncio
+async def test_set_alarm_settings_rejects_device_error():
+    device = create_device()
+    device._send_command.return_value = b"\x02"
+
+    with pytest.raises(SwitchbotOperationError, match="set_alarm_settings"):
+        await device.set_alarm_settings(MeterProAlarmMode.DISABLED)
+
+
+@pytest.mark.asyncio
+@pytest.mark.parametrize(
+    ("response", "mode", "status"),
+    [
+        ("01000578019000", MeterProCO2AlarmMode.DISABLED, MeterProCO2AlarmStatus.NONE),
+        (
+            "010b05780190fe",
+            MeterProCO2AlarmMode.CUSTOM
+            | MeterProCO2AlarmMode.LOW
+            | MeterProCO2AlarmMode.HIGH,
+            MeterProCO2AlarmStatus.HIGH,
+        ),
+        (
+            "01840578019003",
+            MeterProCO2AlarmMode(0x84),
+            MeterProCO2AlarmStatus.IN_RANGE,
+        ),
+    ],
+)
+async def test_get_co2_alarm(
+    response: str, mode: MeterProCO2AlarmMode, status: MeterProCO2AlarmStatus
+):
+    device = create_device(SwitchbotMeterProCO2)
+    device._send_command.return_value = bytes.fromhex(response)
+
+    assert await device.get_co2_alarm() == {
+        "mode": mode,
+        "low_ppm": 400,
+        "high_ppm": 1400,
+        "status": status,
+    }
+    device._send_command.assert_awaited_once_with("570f69020301")
+
+
+@pytest.mark.asyncio
+@pytest.mark.parametrize(
+    ("mode", "low", "high", "payload"),
+    [
+        (MeterProCO2AlarmMode.DISABLED, 400, 1400, "0005780190"),
+        (MeterProCO2AlarmMode.LOW, 401, 1101, "01044d0191"),
+        (MeterProCO2AlarmMode.HIGH, 0, 0xFFFF, "02ffff0000"),
+        (
+            MeterProCO2AlarmMode.LOW | MeterProCO2AlarmMode.HIGH,
+            425,
+            2000,
+            "0307d001a9",
+        ),
+        (MeterProCO2AlarmMode.IN_RANGE, 1200, 1200, "0404b004b0"),
+        (
+            MeterProCO2AlarmMode.HIGH | MeterProCO2AlarmMode.CUSTOM,
+            425,
+            2000,
+            "0a07d001a9",
+        ),
+    ],
+)
+async def test_set_co2_alarm(
+    mode: MeterProCO2AlarmMode, low: int, high: int, payload: str
+):
+    device = create_device(SwitchbotMeterProCO2)
+
+    await device.set_co2_alarm(mode, low, high)
+
+    device._send_command.assert_awaited_once_with("570f68020301" + payload)
+
+
+@pytest.mark.asyncio
+@pytest.mark.parametrize("response", ["02", "010005780190"])
+async def test_get_co2_alarm_rejects_invalid_response(response: str):
+    device = create_device(SwitchbotMeterProCO2)
+    device._send_command.return_value = bytes.fromhex(response)
+
+    with pytest.raises(SwitchbotOperationError, match="get_co2_alarm"):
+        await device.get_co2_alarm()
+
+
+@pytest.mark.asyncio
+@pytest.mark.parametrize(
+    ("mode", "low", "high", "message"),
+    [
+        (True, 400, 1400, "Invalid CO2 alarm mode"),
+        (MeterProCO2AlarmMode(0x10), 400, 1400, "Invalid CO2 alarm mode"),
+        (MeterProCO2AlarmMode.LOW, True, 1400, "unsigned 16-bit integers"),
+        (MeterProCO2AlarmMode.LOW, -1, 1400, "unsigned 16-bit integers"),
+        (MeterProCO2AlarmMode.LOW, 400, 0x10000, "unsigned 16-bit integers"),
+        (MeterProCO2AlarmMode.LOW, 400, 1400.0, "unsigned 16-bit integers"),
+        (MeterProCO2AlarmMode.IN_RANGE, 1400, 400, "Lower CO2 alarm limit"),
+    ],
+)
+async def test_set_co2_alarm_rejects_invalid_input(
+    mode: object, low: object, high: object, message: str
+):
+    device = create_device(SwitchbotMeterProCO2)
+
+    with pytest.raises(SwitchbotOperationError, match=message):
+        await device.set_co2_alarm(mode, low, high)
+
+    device._send_command.assert_not_awaited()
+
+
+@pytest.mark.asyncio
+async def test_set_co2_alarm_rejects_device_error():
+    device = create_device(SwitchbotMeterProCO2)
+    device._send_command.return_value = b"\x02"
+
+    with pytest.raises(SwitchbotOperationError, match="set_co2_alarm"):
+        await device.set_co2_alarm(MeterProCO2AlarmMode.DISABLED, 400, 1400)
+
+
+def test_co2_alarm_is_only_available_on_the_co2_model():
+    device = create_device()
+
+    assert not hasattr(device, "get_co2_alarm")
+    assert not hasattr(device, "set_co2_alarm")
+
+
+@pytest.mark.asyncio
+@pytest.mark.parametrize(
+    ("device_class", "response", "expected"),
+    [
+        (
+            SwitchbotMeterPro,
+            "0100000000000000",
+            {
+                "mode": MeterProTemperatureHumidityAlarmMode.DISABLED,
+                "temperature_low_c": 0.0,
+                "temperature_high_c": 0.0,
+                "humidity_low": 0,
+                "humidity_high": 0,
+                "temperature_status": MeterProTemperatureHumidityAlarmStatus.NONE,
+                "humidity_status": MeterProTemperatureHumidityAlarmStatus.NONE,
+            },
+        ),
+        (
+            SwitchbotMeterProCO2,
+            "014297a745009423",
+            {
+                "mode": (
+                    MeterProTemperatureHumidityAlarmMode.TEMPERATURE_HIGH
+                    | MeterProTemperatureHumidityAlarmMode.HUMIDITY_IN_RANGE
+                ),
+                "temperature_low_c": -0.5,
+                "temperature_high_c": 23.4,
+                "humidity_low": 20,
+                "humidity_high": 39,
+                "temperature_status": MeterProTemperatureHumidityAlarmStatus.HIGH,
+                "humidity_status": MeterProTemperatureHumidityAlarmStatus.IN_RANGE,
+            },
+        ),
+    ],
+)
+async def test_get_temperature_humidity_alarm(
+    device_class: type[SwitchbotMeterPro], response: str, expected: dict[str, object]
+):
+    device = create_device(device_class)
+    device._send_command.return_value = bytes.fromhex(response)
+
+    assert await device.get_temperature_humidity_alarm() == expected
+    device._send_command.assert_awaited_once_with("570f69020100")
+
+
+@pytest.mark.asyncio
+@pytest.mark.parametrize(
+    ("response", "temperature_status", "humidity_status"),
+    [
+        (
+            "0122963695000a20",
+            MeterProTemperatureHumidityAlarmStatus.HIGH,
+            MeterProTemperatureHumidityAlarmStatus.NONE,
+        ),
+        (
+            "0122a32795000a02",
+            MeterProTemperatureHumidityAlarmStatus.NONE,
+            MeterProTemperatureHumidityAlarmStatus.HIGH,
+        ),
+        (
+            "0122972735001822",
+            MeterProTemperatureHumidityAlarmStatus.HIGH,
+            MeterProTemperatureHumidityAlarmStatus.HIGH,
+        ),
+        (
+            "0122963695000aec",
+            MeterProTemperatureHumidityAlarmStatus.HIGH,
+            MeterProTemperatureHumidityAlarmStatus.NONE,
+        ),
+        (
+            "0122a32795000ace",
+            MeterProTemperatureHumidityAlarmStatus.NONE,
+            MeterProTemperatureHumidityAlarmStatus.HIGH,
+        ),
+        (
+            "014297a7450094ff",
+            MeterProTemperatureHumidityAlarmStatus.IN_RANGE,
+            MeterProTemperatureHumidityAlarmStatus.IN_RANGE,
+        ),
+    ],
+)
+async def test_get_temperature_humidity_alarm_status(
+    response: str,
+    temperature_status: MeterProTemperatureHumidityAlarmStatus,
+    humidity_status: MeterProTemperatureHumidityAlarmStatus,
+):
+    device = create_device()
+    device._send_command.return_value = bytes.fromhex(response)
+
+    result = await device.get_temperature_humidity_alarm()
+
+    assert result["temperature_status"] is temperature_status
+    assert result["humidity_status"] is humidity_status
+
+
+@pytest.mark.asyncio
+@pytest.mark.parametrize(
+    ("mode", "limits", "payload"),
+    [
+        (MeterProTemperatureHumidityAlarmMode.DISABLED, (0, 0, 0, 0), "008000008000"),
+        (
+            MeterProTemperatureHumidityAlarmMode.TEMPERATURE_HIGH
+            | MeterProTemperatureHumidityAlarmMode.HUMIDITY_HIGH,
+            (-0.5, 23.34, 20, 39),
+            "229727350014",
+        ),
+        (
+            MeterProTemperatureHumidityAlarmMode.TEMPERATURE_IN_RANGE
+            | MeterProTemperatureHumidityAlarmMode.HUMIDITY_IN_RANGE,
+            (0.5, 0.5, 0, 99),
+            "448063558000",
+        ),
+    ],
+)
+async def test_set_temperature_humidity_alarm(
+    mode: MeterProTemperatureHumidityAlarmMode,
+    limits: tuple[float, float, int, int],
+    payload: str,
+):
+    device = create_device()
+
+    await device.set_temperature_humidity_alarm(mode, *limits)
+
+    device._send_command.assert_awaited_once_with("570f680201" + payload)
+
+
+@pytest.mark.asyncio
+@pytest.mark.parametrize(
+    ("mode", "limits", "message"),
+    [
+        (True, (18, 28, 30, 70), "Invalid temperature and humidity alarm mode"),
+        (
+            MeterProTemperatureHumidityAlarmMode(0x88),
+            (18, 28, 30, 70),
+            "Invalid temperature and humidity alarm mode",
+        ),
+        (
+            MeterProTemperatureHumidityAlarmMode(0x08),
+            (18, 28, 30, 70),
+            "Invalid temperature and humidity alarm mode",
+        ),
+        (
+            MeterProTemperatureHumidityAlarmMode.DISABLED,
+            (-128, 28, 30, 70),
+            "Temperature must be",
+        ),
+        (
+            MeterProTemperatureHumidityAlarmMode.DISABLED,
+            (18, 28, True, 70),
+            "Humidity limits",
+        ),
+        (
+            MeterProTemperatureHumidityAlarmMode.DISABLED,
+            (18, 28, 30, 100),
+            "Humidity limits",
+        ),
+        (
+            MeterProTemperatureHumidityAlarmMode.TEMPERATURE_IN_RANGE,
+            (28, 18, 30, 70),
+            "Lower in-range alarm limits",
+        ),
+        (
+            MeterProTemperatureHumidityAlarmMode.HUMIDITY_IN_RANGE,
+            (18, 28, 70, 30),
+            "Lower in-range alarm limits",
+        ),
+    ],
+)
+async def test_set_temperature_humidity_alarm_rejects_invalid_inputs(
+    mode: object, limits: tuple[float, float, int, int], message: str
+):
+    device = create_device()
+
+    with pytest.raises(SwitchbotOperationError, match=message):
+        await device.set_temperature_humidity_alarm(mode, *limits)
+
+    device._send_command.assert_not_awaited()
+
+
+@pytest.mark.asyncio
+@pytest.mark.parametrize(
+    "response",
+    [
+        "02",
+        "01000000000000",
+        "01009c460a921e00",
+        "01009c6400921e00",
+    ],
+)
+async def test_get_temperature_humidity_alarm_rejects_invalid_response(response: str):
+    device = create_device()
+    device._send_command.return_value = bytes.fromhex(response)
+
+    with pytest.raises(SwitchbotOperationError):
+        await device.get_temperature_humidity_alarm()
+
+
+@pytest.mark.asyncio
+async def test_set_temperature_humidity_alarm_rejects_device_error():
+    device = create_device()
+    device._send_command.return_value = b"\x02"
+
+    with pytest.raises(SwitchbotOperationError, match="set_temperature_humidity_alarm"):
+        await device.set_temperature_humidity_alarm(
+            MeterProTemperatureHumidityAlarmMode.DISABLED, 0, 0, 0, 0
+        )