ソースを参照

feat: add support for E Ink Photo Magnet (#608)

* feat: add support for ai-memory-frame

* refactor: rename image frame base to ArtFrame2

* docs: update shared frame product name

* fix: display AI Memory Frame as E Ink Photo Magnet

* refactor: rename E Ink Photo Magnet device class and model

* refactor: group E Ink Photo Magnet with Art Frame 2
Onero-testdev 2 日 前
親
コミット
8611f182b8

+ 3 - 0
switchbot/__init__.py

@@ -37,6 +37,7 @@ from .const import (
 )
 from .devices.air_purifier import SwitchbotAirPurifier
 from .devices.art_frame import SwitchbotArtFrame
+from .devices.art_frame2 import SwitchbotArtFrame2, SwitchbotEInkPhotoMagnet
 from .devices.base_light import SwitchbotBaseLight
 from .devices.blind_tilt import SwitchbotBlindTilt
 from .devices.bot import Switchbot
@@ -120,6 +121,7 @@ __all__ = [
     "SwitchbotAirPurifier",
     "SwitchbotApiError",
     "SwitchbotArtFrame",
+    "SwitchbotArtFrame2",
     "SwitchbotAuthenticationError",
     "SwitchbotBaseLight",
     "SwitchbotBlindTilt",
@@ -129,6 +131,7 @@ __all__ = [
     "SwitchbotCirculatorFanPro",
     "SwitchbotCurtain",
     "SwitchbotDevice",
+    "SwitchbotEInkPhotoMagnet",
     "SwitchbotEncryptedDevice",
     "SwitchbotEvaporativeHumidifier",
     "SwitchbotFan",

+ 13 - 0
switchbot/adv_parser.py

@@ -30,6 +30,7 @@ from .adv_parsers.hub3 import process_hub3
 from .adv_parsers.hub4 import process_hub4
 from .adv_parsers.hubmini_matter import process_hubmini_matter
 from .adv_parsers.humidifier import process_evaporative_humidifier, process_wohumidifier
+from .adv_parsers.image_frame import process_image_frame
 from .adv_parsers.keypad import process_wokeypad
 from .adv_parsers.keypad_vision import process_keypad_vision, process_keypad_vision_pro
 from .adv_parsers.leak import process_leak
@@ -840,6 +841,18 @@ SUPPORTED_TYPES: dict[str | bytes, SwitchbotSupportedType] = {
         "func": process_presence_sensor,
         "manufacturer_id": 2409,
     },
+    b"\x00\x12\x95\xd0": {
+        "modelName": SwitchbotModel.E_INK_PHOTO_MAGNET,
+        "modelFriendlyName": "E Ink Photo Magnet",
+        "func": process_image_frame,
+        "manufacturer_id": 2409,
+    },
+    b"\x01\x12\x95\xd0": {
+        "modelName": SwitchbotModel.E_INK_PHOTO_MAGNET,
+        "modelFriendlyName": "E Ink Photo Magnet",
+        "func": process_image_frame,
+        "manufacturer_id": 2409,
+    },
     b"\x00\x11>\x10": {
         "modelName": SwitchbotModel.ART_FRAME,
         "modelFriendlyName": "Art Frame",

+ 20 - 0
switchbot/adv_parsers/image_frame.py

@@ -0,0 +1,20 @@
+"""Advertisement parser for Art Frame 2 and E Ink Photo Magnet."""
+
+
+def process_image_frame(
+    data: bytes | None, mfr_data: bytes | None
+) -> dict[str, bool | int | str]:
+    """Parse the frame's two-byte image index and display flags."""
+    if mfr_data is None or len(mfr_data) < 11:
+        return {}
+    flags = mfr_data[10]
+    return {
+        "sequence_number": mfr_data[6],
+        "battery_charging": bool(mfr_data[7] & 0x80),
+        "battery": mfr_data[7] & 0x7F,
+        "image_index": int.from_bytes(mfr_data[8:10], "little"),
+        "display_size": flags >> 4,
+        "display_mode": (flags >> 3) & 1,
+        "last_network_status": (flags >> 2) & 1,
+        "orientation": (flags >> 1) & 1,
+    }

+ 1 - 0
switchbot/const/__init__.py

@@ -135,6 +135,7 @@ class SwitchbotModel(StrEnum):
     S20_VACUUM = "S20 Vacuum"
     PRESENCE_SENSOR = "Presence Sensor"
     ART_FRAME = "Art Frame"
+    E_INK_PHOTO_MAGNET = "E Ink Photo Magnet"
     KEYPAD_VISION = "Keypad Vision"
     KEYPAD_VISION_PRO = "Keypad Vision Pro"
     LOCK_VISION_PRO = "Lock Vision Pro"

+ 109 - 0
switchbot/devices/art_frame2.py

@@ -0,0 +1,109 @@
+"""Device handlers for Art Frame 2 and E Ink Photo Magnet."""
+
+import secrets
+from typing import Any
+
+from ..const import SwitchbotModel
+from .device import (
+    SwitchbotEncryptedDevice,
+    SwitchbotOperationError,
+    SwitchbotSequenceDevice,
+    update_after_operation,
+)
+
+
+class SwitchbotArtFrame2(SwitchbotSequenceDevice, SwitchbotEncryptedDevice):
+    """Handle image frames with 16-bit image indexes."""
+
+    response_flag: bool = True
+
+    async def get_basic_info(self) -> dict[str, Any] | None:
+        """Read device settings without downloading the image bitmap."""
+        data = await self._get_basic_info()
+        if not data or len(data) < 10 or data[0] != 1:
+            return None
+        return {
+            "battery_charging": bool(data[1] & 0x80),
+            "battery": data[1] & 0x7F,
+            "firmware": data[2] / 10.0,
+            "hardware": data[3],
+            "display_size": data[4] >> 4,
+            "display_mode": (data[4] >> 3) & 1,
+            "last_network_status": (data[4] >> 2) & 1,
+            "current_image_index": int.from_bytes(data[5:7], "little"),
+            "total_num_of_images": int.from_bytes(data[7:9], "little"),
+            "orientation": data[9],
+        }
+
+    async def _get_image_indexes(self) -> list[int]:
+        """Read the complete, packet-ordered user image bitmap."""
+        bitmap = bytearray()
+        packet = 0
+        total_packets = 1
+        while packet < total_packets:
+            data = await self._send_command(f"570F7B07{packet:02X}")
+            if (
+                not data
+                or len(data) < 4
+                or data[0] != 1
+                or data[1] == 0
+                or data[2] != packet
+                or (packet > 0 and data[1] != total_packets)
+                or len(bitmap) + len(data) - 3 > 2560
+            ):
+                raise SwitchbotOperationError("Invalid image bitmap response")
+            total_packets = data[1]
+            bitmap.extend(data[3:])
+            packet += 1
+        return [
+            byte_index * 8 + bit + 1
+            for byte_index, value in enumerate(bitmap)
+            for bit in range(8)
+            if value & (1 << bit)
+        ]
+
+    async def _set_image_id(self, image_id: int) -> bool:
+        result = await self._send_command(
+            "570F7A02" + image_id.to_bytes(2, "little").hex()
+        )
+        return self._check_command_result(result, 0, {1})
+
+    @update_after_operation
+    async def next_image(self) -> bool:
+        """Display the next stored image."""
+        result = await self._send_command("570F7A0701")
+        return self._check_command_result(result, 0, {1})
+
+    @update_after_operation
+    async def prev_image(self) -> bool:
+        """Display the previous stored image."""
+        result = await self._send_command("570F7A0700")
+        return self._check_command_result(result, 0, {1})
+
+    @update_after_operation
+    async def random_image(self) -> bool:
+        """Display a random stored user image other than the current image."""
+        if not (info := await self.get_basic_info()):
+            raise SwitchbotOperationError("Failed to retrieve frame settings")
+        choices = [
+            index
+            for index in await self._get_image_indexes()
+            if index != info["current_image_index"]
+        ]
+        if not choices:
+            raise RuntimeError("No images available to select from.")
+        return await self._set_image_id(secrets.choice(choices))
+
+    @update_after_operation
+    async def set_image(self, index: int) -> bool:
+        """Select a user image by its zero-based position in the stored list."""
+        indexes = await self._get_image_indexes()
+        if index < 0 or index >= len(indexes):
+            raise ValueError(f"Image index {index} is out of range.")
+        return await self._set_image_id(indexes[index])
+
+
+class SwitchbotEInkPhotoMagnet(SwitchbotArtFrame2):
+    """Represent an E Ink Photo Magnet."""
+
+    _model = SwitchbotModel.E_INK_PHOTO_MAGNET

+ 1 - 0
switchbot/devices/device.py

@@ -125,6 +125,7 @@ API_MODEL_TO_ENUM: dict[str, SwitchbotModel] = {
     "W1128000": SwitchbotModel.SMART_THERMOSTAT_RADIATOR,
     "W1111000": SwitchbotModel.CLIMATE_PANEL,
     "W1130000": SwitchbotModel.ART_FRAME,
+    "W1218000": SwitchbotModel.E_INK_PHOTO_MAGNET,
     "W1189000": SwitchbotModel.LOCK_NANO,
     "W1141001": SwitchbotModel.LOCK_VISION_PRO,
     "W1141000": SwitchbotModel.LOCK_VISION,

+ 27 - 0
tests/test_device.py

@@ -1097,3 +1097,30 @@ async def test_plug_mini_it_cloud_model_cache(mock_user_info: dict[str, Any]) ->
         )
         assert devices == {"E6:A1:CD:1F:5B:65": SwitchbotModel.PLUG_MINI_IT}
         assert _MODEL_TO_MAC_CACHE["E6:A1:CD:1F:5B:65"] is SwitchbotModel.PLUG_MINI_IT
+
+
+@pytest.mark.asyncio
+async def test_e_ink_photo_magnet_cloud_model_cache(
+    mock_user_info: dict[str, Any],
+) -> None:
+    """Resolve the numeric cloud product ID and populate the model cache."""
+    response = {
+        "Items": [
+            {"device_mac": "e6a1cd1f5b65", "device_detail": {"device_type": "W1218000"}}
+        ]
+    }
+    with (
+        patch.dict(_MODEL_TO_MAC_CACHE, {}, clear=True),
+        patch.object(
+            SwitchbotBaseDevice, "_async_get_user_info", return_value=mock_user_info
+        ),
+        patch.object(SwitchbotBaseDevice, "api_request", return_value=response),
+    ):
+        devices = await fetch_cloud_devices_by_token(
+            MagicMock(spec=aiohttp.ClientSession), "test-token"
+        )
+        assert devices == {"E6:A1:CD:1F:5B:65": SwitchbotModel.E_INK_PHOTO_MAGNET}
+        assert (
+            _MODEL_TO_MAC_CACHE["E6:A1:CD:1F:5B:65"]
+            is SwitchbotModel.E_INK_PHOTO_MAGNET
+        )

+ 170 - 0
tests/test_e_ink_photo_magnet.py

@@ -0,0 +1,170 @@
+from unittest.mock import AsyncMock
+
+import pytest
+
+from switchbot import SwitchbotEInkPhotoMagnet, SwitchbotModel
+from switchbot.adv_parser import parse_advertisement_data
+from switchbot.adv_parsers.image_frame import process_image_frame
+from switchbot.devices.device import SwitchbotOperationError
+
+from .test_adv_parser import generate_advertisement_data, generate_ble_device
+
+
+@pytest.fixture(params=[SwitchbotEInkPhotoMagnet])
+def device(request):
+    frame = request.param(
+        generate_ble_device("AA:BB:CC:DD:EE:FF", "Frame"), "ff", "ff" * 16
+    )
+    frame._send_command = AsyncMock(return_value=b"\x01")
+    frame.update = AsyncMock()
+    return frame
+
+
+@pytest.mark.parametrize(
+    ("model", "suffix"),
+    [
+        (SwitchbotModel.E_INK_PHOTO_MAGNET, "1295d0"),
+    ],
+)
+@pytest.mark.parametrize("pairing", [0, 1])
+def test_discovery(model, suffix, pairing):
+    adv = parse_advertisement_data(
+        generate_ble_device("AA:BB:CC:DD:EE:FF", "Frame"),
+        generate_advertisement_data(
+            service_data={
+                "0000fd3d-0000-1000-8000-00805f9b34fb": bytes([0, 0, 54, pairing])
+                + bytes.fromhex(suffix)
+            },
+            manufacturer_data={2409: bytes.fromhex("aabbccddeeff01b634125e")},
+        ),
+    )
+    assert adv.data["modelName"] == model
+    assert adv.data["data"] == {
+        "sequence_number": 1,
+        "battery_charging": True,
+        "battery": 54,
+        "image_index": 0x1234,
+        "display_size": 5,
+        "display_mode": 1,
+        "last_network_status": 1,
+        "orientation": 1,
+    }
+
+
+@pytest.mark.parametrize("data", [None] + [bytes(n) for n in range(11)])
+def test_short_advertisements(data):
+    assert process_image_frame(None, data) == {}
+
+
+@pytest.mark.asyncio
+async def test_basic_info(device):
+    device._get_basic_info = AsyncMock(
+        return_value=bytes.fromhex("01b607015c34f1010101")
+    )
+    assert await device.get_basic_info() == {
+        "battery_charging": True,
+        "battery": 54,
+        "firmware": 0.7,
+        "hardware": 1,
+        "display_size": 5,
+        "display_mode": 1,
+        "last_network_status": 1,
+        "current_image_index": 0xF134,
+        "total_num_of_images": 257,
+        "orientation": 1,
+    }
+    device._send_command.assert_not_awaited()
+
+
+@pytest.mark.asyncio
+@pytest.mark.parametrize("data", [None, b"", bytes(9), bytes(10)])
+async def test_invalid_basic_info(device, data):
+    device._get_basic_info = AsyncMock(return_value=data)
+    assert await device.get_basic_info() is None
+
+
+@pytest.mark.asyncio
+@pytest.mark.parametrize(
+    ("method", "command"), [("next_image", "570F7A0701"), ("prev_image", "570F7A0700")]
+)
+@pytest.mark.parametrize(("status", "expected"), [(b"\x01", True), (b"\x09", False)])
+async def test_navigation(device, method, command, status, expected):
+    device._send_command.return_value = status
+    assert await getattr(device, method)() is expected
+    device._send_command.assert_awaited_once_with(command)
+
+
+@pytest.mark.asyncio
+async def test_paginated_bitmap(device):
+    device._send_command.side_effect = [b"\x01\x02\x00\x81\x01", b"\x01\x02\x01\x02"]
+    assert await device._get_image_indexes() == [1, 8, 9, 18]
+    assert [call.args[0] for call in device._send_command.await_args_list] == [
+        "570F7B0700",
+        "570F7B0701",
+    ]
+
+
+@pytest.mark.asyncio
+@pytest.mark.parametrize(
+    "responses",
+    [
+        [None],
+        [b"\x01"],
+        [b"\x09\x01\x00\x01"],
+        [b"\x01\x00\x00\x01"],
+        [b"\x01\x01\x01\x01"],
+        [b"\x01\x02\x00\x01", b"\x01\x03\x01\x01"],
+        [b"\x01\x02\x00\x01", b"\x01\x02\x00\x01"],
+        [b"\x01\x01\x00" + bytes(2561)],
+    ],
+)
+async def test_invalid_bitmap(device, responses):
+    device._send_command.side_effect = responses
+    with pytest.raises(SwitchbotOperationError, match="Invalid image bitmap"):
+        await device._get_image_indexes()
+
+
+@pytest.mark.asyncio
+async def test_random_sparse_image(device):
+    device.get_basic_info = AsyncMock(return_value={"current_image_index": 1})
+    device._send_command.side_effect = [
+        b"\x01\x01\x00\x01" + bytes(31) + b"\x01",
+        b"\x01",
+    ]
+    assert await device.random_image()
+    device._send_command.assert_awaited_with("570F7A020101")
+
+
+@pytest.mark.asyncio
+@pytest.mark.parametrize("bitmap", [b"\x00", b"\x01"])
+async def test_random_without_alternative(device, bitmap):
+    device.get_basic_info = AsyncMock(return_value={"current_image_index": 1})
+    device._send_command.return_value = b"\x01\x01\x00" + bitmap
+    with pytest.raises(RuntimeError, match="No images"):
+        await device.random_image()
+
+
+@pytest.mark.asyncio
+async def test_random_without_info(device):
+    device.get_basic_info = AsyncMock(return_value=None)
+    with pytest.raises(SwitchbotOperationError, match="Failed to retrieve"):
+        await device.random_image()
+    device._send_command.assert_not_awaited()
+
+
+@pytest.mark.asyncio
+async def test_set_image(device):
+    device._send_command.side_effect = [
+        b"\x01\x01\x00" + bytes(2559) + b"\x80",
+        b"\x01",
+    ]
+    assert await device.set_image(0)
+    device._send_command.assert_awaited_with("570F7A020050")
+
+
+@pytest.mark.asyncio
+@pytest.mark.parametrize("index", [-1, 1])
+async def test_set_out_of_range(device, index):
+    device._send_command.return_value = b"\x01\x01\x00\x01"
+    with pytest.raises(ValueError, match="out of range"):
+        await device.set_image(index)