Ver Fonte

feat: add weather display support for Meter Pro and Meter Pro CO2 (#581)

* feat: add Meter Pro CO2 weather display support

Add BLE weather reads and partial updates for icon, temperature, and humidity. Preserve omitted fields using nine-byte writes, serialize updates, and verify device readback.

Add input validation and protocol tests.

* fix: refine Meter Pro CO2 weather update handling

Retry weather reads without replaying writes and accept trailing response data while validating known fields.

Keep raw network bytes internal, reject non-numeric inputs, and align type annotations with supported values.

Add regression tests for retries, response variations, and inputs.

* fix: clarify Meter Pro CO2 weather readings and diagnostics

Return None for unset humidity while keeping temperature independent, and normalize negative zero to 0.0.

Include response data in parsing errors and expected versus actual values in readback mismatches.

Add regression coverage for reading semantics and diagnostics, and consolidate redundant weather tests.

* feat(meter-pro): share weather controls across Meter Pro models

* fix(meter-pro): align weather icon names with the protocol

---------

Co-authored-by: zerzhang <916250497@qq.com>
Pablo Maceda há 1 dia atrás
pai
commit
21ae755f53

+ 2 - 0
switchbot/__init__.py

@@ -24,6 +24,7 @@ from .const import (
     HumidifierMode,
     HumidifierWaterLevel,
     LockStatus,
+    MeterProWeatherIcon,
     NightLightState,
     QuickKeyFunction,
     SmartThermostatRadiatorMode,
@@ -110,6 +111,7 @@ __all__ = [
     "HumidifierMode",
     "HumidifierWaterLevel",
     "LockStatus",
+    "MeterProWeatherIcon",
     "NightLightState",
     "QuickKeyFunction",
     "SmartThermostatRadiatorMode",

+ 2 - 0
switchbot/const/__init__.py

@@ -27,6 +27,7 @@ from .light import (
 
 # Preserve old LockStatus export for backwards compatibility
 from .lock import LockStatus, QuickKeyFunction
+from .meter_pro import MeterProWeatherIcon
 
 DEFAULT_RETRY_COUNT = 3
 DEFAULT_RETRY_TIMEOUT = 1
@@ -166,6 +167,7 @@ __all__ = [
     "HumidifierMode",
     "HumidifierWaterLevel",
     "LockStatus",
+    "MeterProWeatherIcon",
     "NightLightState",
     "QuickKeyFunction",
     "SmartThermostatRadiatorMode",

+ 14 - 0
switchbot/const/meter_pro.py

@@ -0,0 +1,14 @@
+from enum import Enum
+
+
+class MeterProWeatherIcon(Enum):
+    """Weather icons supported by the Meter Pro and Meter Pro CO2 displays."""
+
+    NONE = 0
+    SUNNY = 1
+    CLOUDY = 2
+    OVERCAST = 3
+    LIGHT_RAIN = 4
+    HEAVY_RAIN = 5
+    LIGHT_SNOW = 6
+    HEAVY_SNOW = 7

+ 139 - 2
switchbot/devices/meter_pro.py

@@ -1,5 +1,7 @@
+from decimal import ROUND_HALF_UP, Decimal
 from typing import Any
 
+from ..const.meter_pro import MeterProWeatherIcon
 from ..helpers import parse_uint24_be
 from .device import SwitchbotDevice, SwitchbotOperationError
 
@@ -10,10 +12,47 @@ MAX_TIME_OFFSET = (1 << 24) - 1
 COMMAND_GET_DEVICE_DATETIME = "570f6901"
 COMMAND_SET_DEVICE_DATETIME = "57000503"
 COMMAND_SET_DISPLAY_FORMAT = "570f680505"
+COMMAND_GET_WEATHER = "570f6906"
+COMMAND_SET_WEATHER = "570f680601"
+
+
+def _weather_decimal(value: float | Decimal, name: str) -> Decimal:
+    if isinstance(value, bool):
+        raise TypeError(f"{name} must be a number, not a boolean")
+    if not isinstance(value, (int, float, Decimal)):
+        raise TypeError(f"{name} must be a number")
+    number = value if isinstance(value, Decimal) else Decimal(str(value))
+    if not number.is_finite():
+        raise ValueError(f"{name} must be finite")
+    return number
+
+
+def _encode_weather_temperature(temperature_c: float | Decimal) -> bytes:
+    temperature = _weather_decimal(temperature_c, "Temperature")
+    if abs(temperature) > Decimal("127.9"):
+        raise ValueError("Temperature must be -127.9..127.9 C")
+    temperature = temperature.quantize(Decimal("0.1"), rounding=ROUND_HALF_UP)
+    integer, decimal = divmod(int(abs(temperature) * 10), 10)
+    return bytes((decimal, integer | (0x80 if temperature >= 0 else 0)))
+
+
+def _encode_weather_humidity(humidity: float | Decimal) -> int:
+    relative_humidity = _weather_decimal(humidity, "humidity")
+    if not 1 <= relative_humidity <= 99:
+        raise ValueError("humidity must be 1..99%")
+    return int(relative_humidity.quantize(Decimal(1), rounding=ROUND_HALF_UP))
+
+
+def _encode_weather_icon(icon: MeterProWeatherIcon | int) -> MeterProWeatherIcon:
+    if isinstance(icon, MeterProWeatherIcon):
+        return icon
+    if isinstance(icon, bool) or not isinstance(icon, int):
+        raise TypeError("Weather icon must be a MeterProWeatherIcon or integer")
+    return MeterProWeatherIcon(icon)
 
 
 class SwitchbotMeterPro(SwitchbotDevice):
-    """API to control Switchbot Meter Pro (and Meter Pro CO2, which shares the same datetime protocol)."""
+    """Implement the shared protocol for SwitchBot Meter Pro and Meter Pro CO2."""
 
     async def get_time_offset(self) -> int:
         """
@@ -171,6 +210,104 @@ class SwitchbotMeterPro(SwitchbotDevice):
             )
         return result
 
+    def _parse_weather(self, result: bytes | None) -> tuple[MeterProWeatherIcon, bytes]:
+        result = self._validate_result("get_weather", result, min_length=5)
+        # Only the first five bytes are documented; firmware may append other data.
+        try:
+            icon = MeterProWeatherIcon(result[1])
+        except ValueError as exc:
+            raise SwitchbotOperationError(
+                f"{self.name}: Unknown weather icon {result[1]} "
+                f"(result={result.hex()} rssi={self.rssi})"
+            ) from exc
+        if result[2] & 0x0F > 9 or result[4] & 0x7F > 99:
+            raise SwitchbotOperationError(
+                f"{self.name}: Invalid weather measurements "
+                f"(result={result.hex()} rssi={self.rssi})"
+            )
+        return icon, bytes(result[2:5])
+
+    async def get_weather(self) -> dict[str, Any]:
+        """Read network weather; unset humidity is None, temperature is independent."""
+        icon, network_data = self._parse_weather(
+            await self._send_command(COMMAND_GET_WEATHER)
+        )
+        magnitude = (network_data[1] & 0x7F) + (network_data[0] & 0x0F) / 10
+        temperature = magnitude if network_data[1] & 0x80 else -magnitude
+        return {
+            "icon": icon,
+            "temperature_c": temperature if magnitude else 0.0,
+            "humidity": (network_data[2] & 0x7F) or None,
+            "fahrenheit_display": bool(network_data[2] & 0x80),
+        }
+
+    async def _weather_command_locked(self, key: str, retry: int) -> bytes | None:
+        command = bytearray.fromhex(self._commandkey(key))
+        return await self._send_command_locked_with_retry(
+            key, command, retry, retry + 1
+        )
+
+    async def set_weather(
+        self,
+        icon: MeterProWeatherIcon | int | None = None,
+        *,
+        temperature_c: float | Decimal | None = None,
+        humidity: float | Decimal | None = None,
+    ) -> None:
+        """
+        Set supplied weather fields and verify them; preserve omitted fields.
+
+        This does not change display sources or paired external sensor data.
+        Updates from other clients can race with the read/write sequence.
+        """
+        if icon is None and temperature_c is None and humidity is None:
+            raise SwitchbotOperationError(
+                f"{self.name}: Supply at least one weather field"
+            )
+        try:
+            icon = _encode_weather_icon(icon) if icon is not None else None
+            temperature = (
+                _encode_weather_temperature(temperature_c)
+                if temperature_c is not None
+                else None
+            )
+            relative_humidity = (
+                _encode_weather_humidity(humidity) if humidity is not None else None
+            )
+        except (ValueError, TypeError) as exc:
+            raise SwitchbotOperationError(f"{self.name}: {exc}") from exc
+        async with self._operation_lock:
+            current_icon, network_data = self._parse_weather(
+                await self._weather_command_locked(
+                    COMMAND_GET_WEATHER, self._retry_count
+                )
+            )
+            icon = current_icon if icon is None else icon
+            network = bytearray(network_data)
+            if temperature is not None:
+                network[0] = (network[0] & 0xF0) | temperature[0]
+                network[1] = temperature[1]
+            if relative_humidity is not None:
+                network[2] = (network[2] & 0x80) | relative_humidity
+            # Six-byte writes reset network readings; omit only external blocks.
+            payload = f"{COMMAND_SET_WEATHER}{icon.value:02x}{network.hex()}"
+            # A lost ACK can follow a successful write; do not replay stale readings.
+            self._validate_result(
+                "set_weather", await self._weather_command_locked(payload, 0)
+            )
+            updated_icon, updated_network = self._parse_weather(
+                await self._weather_command_locked(
+                    COMMAND_GET_WEATHER, self._retry_count
+                )
+            )
+            if updated_icon != icon or updated_network != network:
+                raise SwitchbotOperationError(
+                    f"{self.name}: Weather readback mismatch; no rollback attempted "
+                    f"(expected_icon={icon.value} expected_network={network.hex()} "
+                    f"actual_icon={updated_icon.value} actual_network={updated_network.hex()} "
+                    f"rssi={self.rssi})"
+                )
+
 
 class SwitchbotMeterProCO2(SwitchbotMeterPro):
-    """API to control Switchbot Meter Pro CO2."""
+    """Control the CO2 variant of the SwitchBot Meter Pro."""

+ 479 - 0
tests/test_meter_pro_weather.py

@@ -0,0 +1,479 @@
+import asyncio
+from decimal import Decimal
+from unittest.mock import AsyncMock
+
+import pytest
+from bleak.backends.device import BLEDevice
+from bleak.exc import BleakError
+
+from switchbot import (
+    MeterProWeatherIcon,
+    SwitchbotDevice,
+    SwitchbotMeterPro,
+    SwitchbotMeterProCO2,
+    SwitchbotOperationError,
+)
+from switchbot.adv_parsers._sensor_th import decode_temp_humidity
+from switchbot.devices.meter_pro import _encode_weather_temperature
+
+READ = "570f6906"
+BASELINE = bytes.fromhex("01003292b5008000008000000080000000")
+
+
+@pytest.mark.parametrize(
+    ("temperature", "expected"),
+    [(tenths / 10, tenths / 10) for tenths in range(-9, 10)]
+    + [
+        (19.3, 19.3),
+        (-11.7, -11.7),
+        (127.9, 127.9),
+        (-127.9, -127.9),
+        (18.25, 18.3),
+        (-18.25, -18.3),
+        (0.04, 0.0),
+        (-0.04, 0.0),
+    ],
+)
+def test_temperature_round_trip_with_sensor_decoder(temperature, expected):
+    encoded = _encode_weather_temperature(temperature)
+    assert len(encoded) == 2
+    assert encoded[0] <= 9
+    assert bool(encoded[1] & 0x80) == (expected >= 0)
+    decoded = decode_temp_humidity(encoded + bytes((53,)), None)
+    assert decoded["temperature"] == expected
+    assert decoded["humidity"] == 53
+
+
+@pytest.mark.parametrize(
+    ("temperature", "expected_bytes"),
+    [(0.5, "0580"), (-0.5, "0500"), (0, "0080")],
+)
+def test_sub_degree_temperature_sign_bytes(temperature, expected_bytes):
+    assert _encode_weather_temperature(temperature).hex() == expected_bytes
+
+
+def create_device(device_class: type[SwitchbotMeterPro] = SwitchbotMeterProCO2):
+    device = device_class(BLEDevice("aa:bb:cc:dd:ee:ff", "meter", {}))
+    device._send_command = AsyncMock(return_value=BASELINE)
+    device._send_command_locked_with_retry = AsyncMock()
+    return device
+
+
+def configure_write(device, icon=1, network=BASELINE[2:5]):
+    after = bytes((1, icon)) + network + BASELINE[5:]
+    device._send_command_locked_with_retry.side_effect = [BASELINE, b"\x01", after]
+    return after
+
+
+def sent_keys(device):
+    return [
+        entry.args[0] for entry in device._send_command_locked_with_retry.call_args_list
+    ]
+
+
+@pytest.mark.asyncio
+@pytest.mark.parametrize(
+    "response", [BASELINE, BASELINE[:5], BASELINE[:5] + b"\xff", BASELINE + b"\xff"]
+)
+@pytest.mark.parametrize("device_class", [SwitchbotMeterPro, SwitchbotMeterProCO2])
+async def test_get_weather(response: bytes, device_class: type[SwitchbotMeterPro]):
+    device = create_device(device_class)
+    device._send_command.return_value = response
+    state = await device.get_weather()
+    assert state == {
+        "icon": MeterProWeatherIcon.NONE,
+        "temperature_c": 18.2,
+        "humidity": 53,
+        "fahrenheit_display": True,
+    }
+    device._send_command.assert_awaited_once_with(READ)
+
+
+@pytest.mark.asyncio
+@pytest.mark.parametrize(
+    ("network", "temperature", "humidity", "fahrenheit"),
+    [
+        ("008000", 0.0, None, False),
+        ("000000", 0.0, None, False),
+        ("008080", 0.0, None, True),
+        ("079200", 18.7, None, False),
+        ("070b00", -11.7, None, False),
+        ("008035", 0.0, 53, False),
+        ("000035", 0.0, 53, False),
+        ("050001", -0.5, 1, False),
+    ],
+)
+async def test_get_weather_unset_humidity_and_independent_temperature(
+    network, temperature, humidity, fahrenheit
+):
+    device = create_device()
+    device._send_command.return_value = bytes.fromhex("0101" + network)
+    state = await device.get_weather()
+    assert state["temperature_c"] == temperature
+    assert state["humidity"] == humidity
+    assert state["fahrenheit_display"] == fahrenheit
+    if temperature == 0:
+        assert str(state["temperature_c"]) == "0.0"
+
+
+@pytest.mark.asyncio
+@pytest.mark.parametrize(
+    ("response", "message"),
+    [
+        ("0108008000", "Unknown weather icon 8"),
+        ("01000a8000", "Invalid weather measurements"),
+        ("0100008064", "Invalid weather measurements"),
+    ],
+)
+async def test_weather_parse_error_includes_response_context(response, message):
+    device = create_device()
+    device._send_command.return_value = bytes.fromhex(response)
+    with pytest.raises(SwitchbotOperationError, match=message) as exc_info:
+        await device.get_weather()
+    assert f"result={response}" in str(exc_info.value)
+    assert f"rssi={device.rssi}" in str(exc_info.value)
+
+
+@pytest.mark.asyncio
+@pytest.mark.parametrize(
+    "response",
+    [
+        None,
+        b"",
+        b"\x00",
+        b"\x01",
+        bytes.fromhex("01008000"),
+    ],
+)
+async def test_bad_weather_response(response):
+    device = create_device()
+    device._send_command.return_value = response
+    with pytest.raises(SwitchbotOperationError):
+        await device.get_weather()
+
+
+@pytest.mark.asyncio
+@pytest.mark.parametrize(
+    ("icon", "protocol_value"),
+    [
+        (MeterProWeatherIcon.NONE, 0),
+        (MeterProWeatherIcon.SUNNY, 1),
+        (MeterProWeatherIcon.CLOUDY, 2),
+        (MeterProWeatherIcon.OVERCAST, 3),
+        (MeterProWeatherIcon.LIGHT_RAIN, 4),
+        (MeterProWeatherIcon.HEAVY_RAIN, 5),
+        (MeterProWeatherIcon.LIGHT_SNOW, 6),
+        (MeterProWeatherIcon.HEAVY_SNOW, 7),
+    ],
+)
+@pytest.mark.parametrize("device_class", [SwitchbotMeterPro, SwitchbotMeterProCO2])
+async def test_set_icon_preserves_network(
+    icon: MeterProWeatherIcon,
+    protocol_value: int,
+    device_class: type[SwitchbotMeterPro],
+):
+    device = create_device(device_class)
+    configure_write(device, protocol_value)
+    assert await device.set_weather(icon) is None
+    payload = f"570f680601{protocol_value:02x}3292b5"
+    assert len(bytes.fromhex(payload)) == 9
+    assert sent_keys(device) == [READ, payload, READ]
+
+
+@pytest.mark.asyncio
+@pytest.mark.parametrize(
+    ("temperature", "humidity", "encoded"),
+    [
+        (18.2, 53, "3292b5"),
+        (-11.7, 57, "370bb9"),
+        (-0.5, 1, "350081"),
+        (0.5, 1, "358081"),
+        (0, 99, "3080e3"),
+        (127.9, 99, "39ffe3"),
+        (-127.9, 1, "397f81"),
+        (18.25, 53.5, "3392b6"),
+        (Decimal("18.25"), Decimal("53.5"), "3392b6"),
+    ],
+)
+async def test_explicit_values_preserve_flags(temperature, humidity, encoded):
+    device = create_device()
+    configure_write(device, network=bytes.fromhex(encoded))
+    result = await device.set_weather(
+        MeterProWeatherIcon.SUNNY, temperature_c=temperature, humidity=humidity
+    )
+    assert result is None
+    assert sent_keys(device) == [READ, "570f68060101" + encoded, READ]
+
+
+@pytest.mark.asyncio
+@pytest.mark.parametrize("icon", [-1, 8, True, "sunny", 1.0])
+async def test_invalid_icon_before_io(icon):
+    device = create_device()
+    with pytest.raises(
+        SwitchbotOperationError, match=r"Weather icon|MeterProWeatherIcon"
+    ):
+        await device.set_weather(icon)
+    device._send_command_locked_with_retry.assert_not_awaited()
+
+
+@pytest.mark.asyncio
+@pytest.mark.parametrize(
+    ("temperature", "humidity"),
+    [
+        (128, 53),
+        (-128, 53),
+        (0, 0),
+        (0, 100),
+        (float("nan"), 53),
+        (float("inf"), 53),
+        (0, float("nan")),
+        (True, 53),
+        (0, False),
+        ("invalid", 53),
+        ("18.2", 53),
+        (18.2, "53"),
+        (object(), 53),
+        (18.2, object()),
+        (float("nan"), None),
+        (None, 100),
+        (Decimal("NaN"), 53),
+        (18.2, Decimal("Infinity")),
+    ],
+)
+async def test_invalid_values_before_io(temperature, humidity):
+    device = create_device()
+    with pytest.raises(
+        SwitchbotOperationError, match=r"Temperature|temperature|humidity"
+    ):
+        await device.set_weather(
+            MeterProWeatherIcon.SUNNY, temperature_c=temperature, humidity=humidity
+        )
+    device._send_command_locked_with_retry.assert_not_awaited()
+
+
+@pytest.mark.asyncio
+async def test_no_fields_rejected_before_io():
+    device = create_device()
+    with pytest.raises(
+        SwitchbotOperationError, match="Supply at least one weather field"
+    ):
+        await device.set_weather()
+    device._send_command_locked_with_retry.assert_not_awaited()
+
+
+@pytest.mark.asyncio
+@pytest.mark.parametrize(
+    ("kwargs", "expected_icon", "network"),
+    [
+        ({"temperature_c": -11.7}, 0, "370bb5"),
+        ({"humidity": 57}, 0, "3292b9"),
+        ({"temperature_c": -11.7, "humidity": 57}, 0, "370bb9"),
+        ({"icon": MeterProWeatherIcon.SUNNY, "temperature_c": -11.7}, 1, "370bb5"),
+        ({"icon": MeterProWeatherIcon.SUNNY, "humidity": 57}, 1, "3292b9"),
+        ({"temperature_c": 0}, 0, "3080b5"),
+        ({"icon": MeterProWeatherIcon.NONE, "humidity": 57}, 0, "3292b9"),
+    ],
+)
+async def test_partial_updates(kwargs, expected_icon, network):
+    device = create_device()
+    configure_write(device, expected_icon, bytes.fromhex(network))
+    assert await device.set_weather(**kwargs) is None
+    assert sent_keys(device) == [READ, f"570f680601{expected_icon:02x}{network}", READ]
+
+
+@pytest.mark.asyncio
+@pytest.mark.parametrize(
+    ("kwargs", "network"),
+    [({"temperature_c": -0.5}, "050000"), ({"humidity": 57}, "008039")],
+)
+async def test_partial_updates_preserve_unavailable_fields(kwargs, network):
+    device = create_device()
+    before = bytes.fromhex("0106008000")
+    after = bytes((1, 6)) + bytes.fromhex(network)
+    device._send_command_locked_with_retry.side_effect = [before, b"\x01", after]
+    assert await device.set_weather(**kwargs) is None
+    assert sent_keys(device) == [READ, "570f68060106" + network, READ]
+
+
+@pytest.mark.asyncio
+@pytest.mark.parametrize(
+    ("responses", "count"),
+    [
+        ([b"\x00"], 1),
+        ([BASELINE, b"\x00"], 2),
+    ],
+)
+async def test_failures_do_not_rollback(responses, count):
+    device = create_device()
+    device._send_command_locked_with_retry.side_effect = responses
+    with pytest.raises(SwitchbotOperationError):
+        await device.set_weather(MeterProWeatherIcon.SUNNY)
+    assert device._send_command_locked_with_retry.await_count == count
+    assert not device._operation_lock.locked()
+
+
+@pytest.mark.asyncio
+@pytest.mark.parametrize(
+    ("after", "actual_icon", "actual_network"),
+    [(BASELINE, 0, "3292b5"), (bytes.fromhex("01013293b5"), 1, "3293b5")],
+)
+async def test_readback_mismatch_includes_expected_and_actual_values(
+    after, actual_icon, actual_network
+):
+    device = create_device()
+    device._send_command_locked_with_retry.side_effect = [BASELINE, b"\x01", after]
+    with pytest.raises(
+        SwitchbotOperationError, match="Weather readback mismatch"
+    ) as exc_info:
+        await device.set_weather(MeterProWeatherIcon.SUNNY)
+    message = str(exc_info.value)
+    assert "expected_icon=1 expected_network=3292b5" in message
+    assert f"actual_icon={actual_icon} actual_network={actual_network}" in message
+    assert "no rollback attempted" in message
+    assert device._send_command_locked_with_retry.await_count == 3
+    assert not device._operation_lock.locked()
+
+
+@pytest.mark.asyncio
+@pytest.mark.parametrize("icon", [0, 7])
+async def test_integer_icon_supported(icon):
+    device = create_device()
+    configure_write(device, icon)
+    await device.set_weather(icon)
+    assert sent_keys(device) == [READ, f"570f680601{icon:02x}3292b5", READ]
+
+
+@pytest.mark.asyncio
+@pytest.mark.parametrize("read_step", ["before", "after"])
+async def test_transient_read_failure_retries_without_replaying_write(read_step):
+    device = create_device()
+    device._send_command_locked_with_retry = (
+        SwitchbotDevice._send_command_locked_with_retry.__get__(device)
+    )
+    after = bytes((1, 1)) + BASELINE[2:]
+    if read_step == "before":
+        responses = [BleakError("transient read error"), BASELINE, b"\x01", after]
+        expected_keys = [READ, READ, "570f680601013292b5", READ]
+    else:
+        responses = [BASELINE, b"\x01", BleakError("transient read error"), after]
+        expected_keys = [READ, "570f680601013292b5", READ, READ]
+    device._send_command_locked = AsyncMock(side_effect=responses)
+    await device.set_weather(MeterProWeatherIcon.SUNNY)
+    assert [
+        entry.args[0] for entry in device._send_command_locked.call_args_list
+    ] == expected_keys
+    assert not device._operation_lock.locked()
+
+
+@pytest.mark.asyncio
+@pytest.mark.parametrize("error_type", [BleakError, TimeoutError])
+async def test_actual_retry_engine_does_not_replay_failed_write(error_type):
+    device = create_device()
+    device._send_command_locked_with_retry = (
+        SwitchbotDevice._send_command_locked_with_retry.__get__(device)
+    )
+    device._send_command_locked = AsyncMock(
+        side_effect=[BASELINE, error_type("lost write acknowledgement")]
+    )
+    with pytest.raises(error_type, match="lost write acknowledgement"):
+        await device.set_weather(MeterProWeatherIcon.SUNNY)
+    assert [entry.args[0] for entry in device._send_command_locked.call_args_list] == [
+        READ,
+        "570f680601013292b5",
+    ]
+    assert not device._operation_lock.locked()
+
+
+@pytest.mark.asyncio
+@pytest.mark.parametrize("read_step", ["before", "after"])
+async def test_read_retry_exhaustion_does_not_replay_write(read_step):
+    device = create_device()
+    device._retry_count = 2
+    device._send_command_locked_with_retry = (
+        SwitchbotDevice._send_command_locked_with_retry.__get__(device)
+    )
+    failures = [BleakError("persistent read error") for _ in range(3)]
+    prefix = [] if read_step == "before" else [BASELINE, b"\x01"]
+    device._send_command_locked = AsyncMock(side_effect=prefix + failures)
+    with pytest.raises(BleakError, match="persistent read error"):
+        await device.set_weather(MeterProWeatherIcon.SUNNY)
+    expected_keys = [] if read_step == "before" else [READ, "570f680601013292b5"]
+    expected_keys += [READ] * 3
+    assert [
+        entry.args[0] for entry in device._send_command_locked.call_args_list
+    ] == expected_keys
+    assert not device._operation_lock.locked()
+
+
+@pytest.mark.asyncio
+async def test_update_ignores_extra_response_bytes():
+    device = create_device()
+    before = BASELINE[:5] + b"\x11\x22"
+    after = bytes((1, 1)) + BASELINE[2:5] + bytes(range(20))
+    device._send_command_locked_with_retry.side_effect = [before, b"\x01", after]
+    await device.set_weather(MeterProWeatherIcon.SUNNY)
+    assert sent_keys(device) == [READ, "570f680601013292b5", READ]
+
+
+@pytest.mark.asyncio
+async def test_cancellation_releases_lock():
+    device = create_device()
+    started = asyncio.Event()
+
+    async def command(*_args):
+        started.set()
+        await asyncio.Future()
+
+    device._send_command_locked_with_retry.side_effect = command
+    task = asyncio.create_task(device.set_weather(MeterProWeatherIcon.SUNNY))
+    await started.wait()
+    task.cancel()
+    with pytest.raises(asyncio.CancelledError):
+        await task
+    assert not device._operation_lock.locked()
+
+
+@pytest.mark.asyncio
+async def test_concurrent_updates_do_not_interleave():
+    device = create_device()
+    responses = iter(
+        [
+            BASELINE,
+            b"\x01",
+            bytes((1, 1)) + BASELINE[2:],
+            bytes((1, 1)) + BASELINE[2:],
+            b"\x01",
+            bytes((1, 2)) + BASELINE[2:],
+        ]
+    )
+    keys = []
+
+    async def command(key, _payload, retry, max_attempts):
+        assert device._operation_lock.locked()
+        expected_retry = device._retry_count if key == READ else 0
+        assert (retry, max_attempts) == (expected_retry, expected_retry + 1)
+        keys.append(key)
+        await asyncio.sleep(0)
+        return next(responses)
+
+    device._send_command_locked_with_retry.side_effect = command
+    first, second = await asyncio.gather(
+        device.set_weather(MeterProWeatherIcon.SUNNY),
+        device.set_weather(MeterProWeatherIcon.CLOUDY),
+    )
+    assert (first, second) == (None, None)
+    assert keys == [READ, "570f680601013292b5", READ, READ, "570f680601023292b5", READ]
+    assert not device._operation_lock.locked()
+
+
+@pytest.mark.asyncio
+async def test_unavailable_measurements_are_preserved():
+    device = create_device()
+    before = bytes.fromhex("0100008000")
+    device._send_command_locked_with_retry.side_effect = [
+        before,
+        b"\x01",
+        bytes.fromhex("0101008000"),
+    ]
+    assert await device.set_weather(MeterProWeatherIcon.SUNNY) is None
+    assert sent_keys(device) == [READ, "570f68060101008000", READ]