Преглед изворни кода

fix(lock): ignore unknown connected lock statuses (#596)

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Co-authored-by: zerzhang <916250497@qq.com>
Francesco Montorsi пре 11 часа
родитељ
комит
81352faae8
3 измењених фајлова са 108 додато и 6 уклоњено
  1. 8 0
      README.md
  2. 17 6
      switchbot/devices/lock.py
  3. 83 0
      tests/test_lock.py

+ 8 - 0
README.md

@@ -114,6 +114,14 @@ password. The most common failures are account-side, not bugs in this library:
 The key only needs to be fetched once; store the `key_id` and encryption key
 and reuse them — there is no need to call the script on every connection.
 
+### Unknown lock status
+
+An unrecognized connected lock status is ignored and logged as a warning
+instead of updating the lock state. Enable DEBUG logging for
+`switchbot.devices.lock` to include the decrypted lock data and, for
+notifications, the raw notification. These logs can contain sensitive device
+information and lock activity; review them before sharing.
+
 ## Examples:
 
 #### WoLock (Lock-Pro)

+ 17 - 6
switchbot/devices/lock.py

@@ -392,9 +392,10 @@ class SwitchbotLock(SwitchbotSequenceDevice, SwitchbotEncryptedDevice):
         _LOGGER.debug(
             "basic_data: %s, address: %s", basic_data.hex(), self._device.address
         )
-        return self._parse_lock_data(
-            lock_raw_data[1:], self._model
-        ) | self._parse_basic_data(basic_data)
+        lock_data = self._parse_lock_data(lock_raw_data[1:], self._model)
+        if lock_data is None:
+            return None
+        return lock_data | self._parse_basic_data(basic_data)
 
     def is_calibrated(self) -> Any:
         """Return True if lock is calibrated."""
@@ -466,6 +467,9 @@ class SwitchbotLock(SwitchbotSequenceDevice, SwitchbotEncryptedDevice):
 
     def _update_lock_status(self, data: bytearray) -> None:
         lock_data = self._parse_lock_data(self._decrypt(data[4:]), self._model)
+        if lock_data is None:
+            _LOGGER.debug("%s: Ignoring lock notification: %s", self.name, data.hex())
+            return
         if self._update_parsed_data(lock_data):
             # We leave notifications enabled in case
             # the lock is operated manually before we
@@ -474,7 +478,7 @@ class SwitchbotLock(SwitchbotSequenceDevice, SwitchbotEncryptedDevice):
             self._fire_callbacks()
 
     @staticmethod
-    def _parse_lock_data(data: bytes, model: SwitchbotModel) -> dict[str, Any]:
+    def _parse_lock_data(data: bytes, model: SwitchbotModel) -> dict[str, Any] | None:
         if model in {SwitchbotModel.LOCK, SwitchbotModel.LOCK_VISION_PRO}:
             return {
                 "calibration": bool(data[0] & 0b10000000),
@@ -489,16 +493,23 @@ class SwitchbotLock(SwitchbotSequenceDevice, SwitchbotEncryptedDevice):
                 "status": LockStatus((data[0] & 0b01110000) >> 4),
                 "unlocked_alarm": bool(data[1] & 0b00010000),
             }
+        status_value = (data[0] & 0b01111000) >> 3
+        try:
+            status = LockStatus(status_value)
+        except ValueError:
+            _LOGGER.warning("Unknown lock status %s for model %s", status_value, model)
+            _LOGGER.debug("Unrecognized lock data: %s", data.hex())
+            return None
         if model is SwitchbotModel.LOCK_NANO:
             return {
                 "calibration": bool(data[0] & 0b10000000),
-                "status": LockStatus((data[0] & 0b01111000) >> 3),
+                "status": status,
                 "auto_lock_paused": bool(data[1] & 0b00001000),
                 "unlocked_alarm": bool(data[5] & 0b01000000),
             }
         result = {
             "calibration": bool(data[0] & 0b10000000),
-            "status": LockStatus((data[0] & 0b01111000) >> 3),
+            "status": status,
             "door_open": bool(data[1] & 0b00010000),
             "unclosed_alarm": bool(data[5] & 0b10000000),
             "unlocked_alarm": bool(data[5] & 0b01000000),

+ 83 - 0
tests/test_lock.py

@@ -341,6 +341,35 @@ async def test_get_basic_info_no_basic_data(model: str):
         assert result is None
 
 
+@pytest.mark.asyncio
+@pytest.mark.parametrize(
+    "model",
+    [
+        SwitchbotModel.LOCK_PRO,
+        SwitchbotModel.LOCK_ULTRA,
+        SwitchbotModel.LOCK_ULTRA_MAX,
+        SwitchbotModel.LOCK_PRO_WIFI,
+        SwitchbotModel.LOCK_NANO,
+        SwitchbotModel.UWB_LOCK,
+    ],
+)
+@pytest.mark.parametrize("status", range(8, 16))
+async def test_get_basic_info_unknown_lock_status(
+    model: SwitchbotModel, status: int, caplog: pytest.LogCaptureFixture
+):
+    """Ignore an unknown status in a lock info response."""
+    device = create_device_for_command_testing(model)
+    lock_data = bytes([1, 0x80 | status << 3, 0, 0, 0, 0, 0])
+    with (
+        patch.object(device, "_get_lock_info", return_value=lock_data),
+        patch.object(device, "_get_basic_info", return_value=b"\x01\x64\x28\x21\x14"),
+        caplog.at_level(logging.DEBUG),
+    ):
+        assert await device.get_basic_info() is None
+    assert f"Unknown lock status {status}" in caplog.text
+    assert lock_data[1:].hex() in caplog.text
+
+
 @pytest.mark.parametrize("battery", [100, 255])
 def test_parse_basic_data(battery):
     """Test _parse_basic_data method."""
@@ -774,6 +803,60 @@ def test_update_lock_status(model: str):
         device._update_lock_status(data)
 
 
+@pytest.mark.parametrize(
+    "model",
+    [
+        SwitchbotModel.LOCK_PRO,
+        SwitchbotModel.LOCK_ULTRA,
+        SwitchbotModel.LOCK_ULTRA_MAX,
+        SwitchbotModel.LOCK_PRO_WIFI,
+        SwitchbotModel.LOCK_NANO,
+        SwitchbotModel.UWB_LOCK,
+    ],
+)
+@pytest.mark.parametrize("status", range(8, 16))
+def test_notification_handler_unknown_lock_status(
+    model: SwitchbotModel, status: int, caplog: pytest.LogCaptureFixture
+) -> None:
+    """Ignore unknown statuses without updating data or firing callbacks."""
+    device = create_device_for_command_testing(model)
+    previous_data = {"status": LockStatus.UNLOCKED, "battery": 95}
+    device.update_from_advertisement(
+        SwitchBotAdvertisement(
+            device._device.address, {"data": previous_data}, device._device, -60
+        )
+    )
+    notification = bytearray(b"\x0f\x00\x00\x00\x01\x02\x03\x04\x05\x06")
+    decrypted = bytes([0x80 | status << 3, 0, 0, 0, 0, 0])
+    with (
+        patch.object(
+            device, "_decrypt", side_effect=[decrypted, b"\x80\x00\x00\x00\x00\x00"]
+        ),
+        patch.object(
+            device, "_update_parsed_data", wraps=device._update_parsed_data
+        ) as update,
+        patch.object(device, "_reset_disconnect_timer") as reset_timer,
+        patch.object(device, "_fire_callbacks") as fire_callbacks,
+        caplog.at_level(logging.DEBUG),
+    ):
+        device._notification_handler(0, notification)
+        update.assert_not_called()
+        reset_timer.assert_not_called()
+        fire_callbacks.assert_not_called()
+        assert device.parsed_data == previous_data
+        assert f"Unknown lock status {status}" in caplog.text
+        assert decrypted.hex() in caplog.text
+        assert notification.hex() in caplog.text
+
+        device._notification_handler(0, notification)
+        update.assert_called_once()
+        assert update.call_args.args[0]["status"] is LockStatus.LOCKED
+        assert device.get_lock_status() is LockStatus.LOCKED
+        assert device.get_battery_percent() == 95
+        reset_timer.assert_called_once()
+        fire_callbacks.assert_called_once()
+
+
 @pytest.mark.parametrize(
     ("model", "data", "expected"),
     [