Quellcode durchsuchen

fix: ignore truncated status replies in the light parsers (#591)

* fix: ignore truncated status replies in the light parsers

A SwitchBot RGBIC Neon Rope Light answered a status request with a reply
shorter than the parser reads, and `get_basic_info()` raised IndexError
out of the update path (seen from Home Assistant: `_state["r"] = _data[3]`,
`bytearray index out of range`). `_get_multi_commands_results()` now takes
the minimum reply length each parser needs and drops anything shorter,
along with a version reply under three bytes, so a short frame is logged
at debug and treated like a missing reply.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* test(light): cover truncated status reply boundaries

---------

Co-authored-by: x <property@tomrl.com>
Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
Co-authored-by: zerzhang <916250497@qq.com>
Co-authored-by: Retha Runolfsson <137745329+zerzhang@users.noreply.github.com>
tomrx vor 1 Tag
Ursprung
Commit
c777da0032

+ 16 - 2
switchbot/devices/base_light.py

@@ -137,9 +137,15 @@ class SwitchbotBaseLight(SwitchbotDevice):
         return result
 
     async def _get_multi_commands_results(
-        self, commands: list[str]
+        self, commands: list[str], min_data_length: int = 0
     ) -> tuple[bytes, bytes] | None:
-        """Check results after sending multiple commands."""
+        """
+        Check results after sending multiple commands.
+
+        A reply shorter than ``min_data_length`` is dropped: the device
+        occasionally answers a status request with a truncated frame, and
+        indexing into it raised IndexError out of the update path.
+        """
         if not (results := await self._get_basic_info_by_multi_commands(commands)):
             return None
 
@@ -150,6 +156,14 @@ class SwitchbotBaseLight(SwitchbotDevice):
             _data,
             self._device.address,
         )
+        if len(_version_info) < 3 or len(_data) < min_data_length:
+            _LOGGER.debug(
+                "Ignoring short status reply from %s: version %s, data %s",
+                self._device.address,
+                _version_info,
+                _data,
+            )
+            return None
         return _version_info, _data
 
     async def _get_basic_info_by_multi_commands(

+ 3 - 1
switchbot/devices/bulb.py

@@ -44,7 +44,9 @@ class SwitchbotBulb(SwitchbotSequenceBaseLight):
     async def get_basic_info(self) -> dict[str, Any] | None:
         """Get device basic settings."""
         if not (
-            res := await self._get_multi_commands_results(self._get_basic_info_command)
+            res := await self._get_multi_commands_results(
+                self._get_basic_info_command, min_data_length=11
+            )
         ):
             return None
         _version_info, _data = res

+ 3 - 1
switchbot/devices/ceiling_light.py

@@ -89,7 +89,9 @@ class SwitchbotCeilingLight(SwitchbotSequenceBaseLight):
     async def get_basic_info(self) -> dict[str, Any] | None:
         """Get device basic settings."""
         if not (
-            res := await self._get_multi_commands_results(self._get_basic_info_command)
+            res := await self._get_multi_commands_results(
+                self._get_basic_info_command, min_data_length=5
+            )
         ):
             return None
         _version_info, _data = res

+ 9 - 3
switchbot/devices/light_strip.py

@@ -263,7 +263,9 @@ class SwitchbotLightStrip(SwitchbotSequenceBaseLight):
     async def get_basic_info(self) -> dict[str, Any] | None:
         """Get device basic settings."""
         if not (
-            res := await self._get_multi_commands_results(self._get_basic_info_command)
+            res := await self._get_multi_commands_results(
+                self._get_basic_info_command, min_data_length=11
+            )
         ):
             return None
 
@@ -317,7 +319,9 @@ class SwitchbotCandleWarmerLamp(SwitchbotEncryptedDevice, SwitchbotLightStrip):
     async def get_basic_info(self) -> dict[str, Any] | None:
         """Get device basic settings."""
         if not (
-            res := await self._get_multi_commands_results(self._get_basic_info_command)
+            res := await self._get_multi_commands_results(
+                self._get_basic_info_command, min_data_length=3
+            )
         ):
             return None
         _version_info, _data = res
@@ -482,7 +486,9 @@ class SwitchbotRgbicwwCeilingLight(SwitchbotEncryptedDevice, SwitchbotLightStrip
         here, otherwise update() would clobber the correct advertised values.
         """
         if not (
-            res := await self._get_multi_commands_results(self._get_basic_info_command)
+            res := await self._get_multi_commands_results(
+                self._get_basic_info_command, min_data_length=9
+            )
         ):
             return None
 

+ 92 - 3
tests/test_strip_light.py

@@ -1,13 +1,13 @@
-from unittest.mock import AsyncMock, MagicMock
+from unittest.mock import AsyncMock, MagicMock, patch
 
 import pytest
 from bleak.backends.device import BLEDevice
 
 from switchbot import SwitchBotAdvertisement, SwitchbotModel
 from switchbot.const.light import ColorMode
-from switchbot.devices import light_strip
+from switchbot.devices import bulb, ceiling_light, light_strip
 from switchbot.devices.base_light import SwitchbotBaseLight
-from switchbot.devices.device import SwitchbotOperationError
+from switchbot.devices.device import SwitchbotEncryptedDevice, SwitchbotOperationError
 
 from . import (
     CANDLE_WARMER_LAMP_INFO,
@@ -194,6 +194,95 @@ async def test_get_basic_info_returns_none(
     assert await device.get_basic_info() is None
 
 
+@pytest.fixture(
+    params=[
+        pytest.param(
+            (
+                light_strip.SwitchbotRgbicNeonLight,
+                bytes.fromhex("01 80 4e 4b ff 3a 00 19 64 ff 02"),
+            ),
+            id="strip-light",
+        ),
+        pytest.param(
+            (bulb.SwitchbotBulb, bytes.fromhex("01 80 3b 00 00 00 0c 99 ff ff 01")),
+            id="bulb",
+        ),
+        pytest.param(
+            (
+                light_strip.SwitchbotRgbicwwCeilingLight,
+                bytes.fromhex("01 00 00 4b ff 3a 00 19 64"),
+            ),
+            id="rgbicww-ceiling-light",
+        ),
+        pytest.param(
+            (ceiling_light.SwitchbotCeilingLight, bytes.fromhex("01 80 3d 0f a1")),
+            id="ceiling-light",
+        ),
+        pytest.param(
+            (light_strip.SwitchbotCandleWarmerLamp, bytes.fromhex("01 80 3d")),
+            id="candle-warmer",
+        ),
+    ]
+)
+def light_status_reply(
+    request: pytest.FixtureRequest,
+) -> tuple[SwitchbotBaseLight, bytes]:
+    device_type, status_reply = request.param
+    ble_device = generate_ble_device("aa:bb:cc:dd:ee:ff", "any")
+    if issubclass(device_type, SwitchbotEncryptedDevice):
+        return device_type(ble_device, "ff", "ff" * 16), status_reply
+    return device_type(ble_device), status_reply
+
+
+@pytest.mark.asyncio
+async def test_get_basic_info_status_reply_length_boundary(
+    light_status_reply: tuple[SwitchbotBaseLight, bytes],
+) -> None:
+    device, status_reply = light_status_reply
+    version_reply = b"\x01\x01\x0a"
+    with patch.object(
+        device,
+        "_send_command",
+        side_effect=[version_reply, status_reply[:-1], version_reply, status_reply],
+    ):
+        assert await device.get_basic_info() is None
+        info = await device.get_basic_info()
+
+    assert info is not None
+    assert info["firmware"] == 1.0
+
+
+@pytest.mark.asyncio
+@pytest.mark.parametrize("version_reply", [b"\x01", b"\x01\x01"])
+async def test_get_basic_info_short_version_reply_returns_none(
+    light_status_reply: tuple[SwitchbotBaseLight, bytes], version_reply: bytes
+) -> None:
+    device, status_reply = light_status_reply
+    with patch.object(
+        device, "_send_command", side_effect=[version_reply, status_reply]
+    ):
+        assert await device.get_basic_info() is None
+
+
+@pytest.mark.asyncio
+@pytest.mark.parametrize(
+    "replies",
+    [
+        pytest.param([b""], id="version"),
+        pytest.param([b"\x01\x01\x0a", b""], id="status"),
+    ],
+)
+async def test_get_basic_info_empty_reply_raises(
+    light_status_reply: tuple[SwitchbotBaseLight, bytes], replies: list[bytes]
+) -> None:
+    device, _ = light_status_reply
+    with (
+        patch.object(device, "_send_command", side_effect=replies),
+        pytest.raises(SwitchbotOperationError, match="Sending command failed"),
+    ):
+        await device.get_basic_info()
+
+
 @pytest.mark.asyncio
 @pytest.mark.parametrize(
     "device_case",