art_frame2.py 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. """Device handlers for Art Frame 2 and E Ink Photo Magnet."""
  2. import secrets
  3. from typing import Any
  4. from ..const import SwitchbotModel
  5. from .device import (
  6. SwitchbotEncryptedDevice,
  7. SwitchbotOperationError,
  8. SwitchbotSequenceDevice,
  9. update_after_operation,
  10. )
  11. class SwitchbotArtFrame2(SwitchbotSequenceDevice, SwitchbotEncryptedDevice):
  12. """Handle image frames with 16-bit image indexes."""
  13. _model = SwitchbotModel.ART_FRAME_2
  14. response_flag: bool = True
  15. async def get_basic_info(self) -> dict[str, Any] | None:
  16. """Read device settings without downloading the image bitmap."""
  17. data = await self._get_basic_info()
  18. if not data or len(data) < 10 or data[0] != 1:
  19. return None
  20. return {
  21. "battery_charging": bool(data[1] & 0x80),
  22. "battery": data[1] & 0x7F,
  23. "firmware": data[2] / 10.0,
  24. "hardware": data[3],
  25. "display_size": data[4] >> 4,
  26. "display_mode": (data[4] >> 3) & 1,
  27. "last_network_status": (data[4] >> 2) & 1,
  28. "current_image_index": int.from_bytes(data[5:7], "little"),
  29. "total_num_of_images": int.from_bytes(data[7:9], "little"),
  30. "orientation": data[9],
  31. }
  32. async def _get_image_indexes(self) -> list[int]:
  33. """Read the complete, packet-ordered user image bitmap."""
  34. bitmap = bytearray()
  35. packet = 0
  36. total_packets = 1
  37. while packet < total_packets:
  38. data = await self._send_command(f"570F7B07{packet:02X}")
  39. if (
  40. not data
  41. or len(data) < 4
  42. or data[0] != 1
  43. or data[1] == 0
  44. or data[2] != packet
  45. or (packet > 0 and data[1] != total_packets)
  46. or len(bitmap) + len(data) - 3 > 2560
  47. ):
  48. raise SwitchbotOperationError("Invalid image bitmap response")
  49. total_packets = data[1]
  50. bitmap.extend(data[3:])
  51. packet += 1
  52. return [
  53. byte_index * 8 + bit + 1
  54. for byte_index, value in enumerate(bitmap)
  55. for bit in range(8)
  56. if value & (1 << bit)
  57. ]
  58. async def _set_image_id(self, image_id: int) -> bool:
  59. result = await self._send_command(
  60. "570F7A02" + image_id.to_bytes(2, "little").hex()
  61. )
  62. return self._check_command_result(result, 0, {1})
  63. @update_after_operation
  64. async def next_image(self) -> bool:
  65. """Display the next stored image."""
  66. result = await self._send_command("570F7A0701")
  67. return self._check_command_result(result, 0, {1})
  68. @update_after_operation
  69. async def prev_image(self) -> bool:
  70. """Display the previous stored image."""
  71. result = await self._send_command("570F7A0700")
  72. return self._check_command_result(result, 0, {1})
  73. @update_after_operation
  74. async def random_image(self) -> bool:
  75. """Display a random stored user image other than the current image."""
  76. if not (info := await self.get_basic_info()):
  77. raise SwitchbotOperationError("Failed to retrieve frame settings")
  78. choices = [
  79. index
  80. for index in await self._get_image_indexes()
  81. if index != info["current_image_index"]
  82. ]
  83. if not choices:
  84. raise RuntimeError("No images available to select from.")
  85. return await self._set_image_id(secrets.choice(choices))
  86. @update_after_operation
  87. async def set_image(self, index: int) -> bool:
  88. """Select a user image by its zero-based position in the stored list."""
  89. indexes = await self._get_image_indexes()
  90. if index < 0 or index >= len(indexes):
  91. raise ValueError(f"Image index {index} is out of range.")
  92. return await self._set_image_id(indexes[index])
  93. class SwitchbotEInkPhotoMagnet(SwitchbotArtFrame2):
  94. """Represent an E Ink Photo Magnet."""
  95. _model = SwitchbotModel.E_INK_PHOTO_MAGNET