art_frame2.py 3.9 KB

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