idotmatrix-api-client 0.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (63) hide show
  1. idotmatrix/__init__.py +15 -0
  2. idotmatrix/apps/__init__.py +0 -0
  3. idotmatrix/apps/digital_picture_frame.py +541 -0
  4. idotmatrix/client.py +284 -0
  5. idotmatrix/connection_manager.py +702 -0
  6. idotmatrix/const.py +30 -0
  7. idotmatrix/fonts/16-ErbosDraco1StOpenNbpRegular-l5wX.ttf +0 -0
  8. idotmatrix/fonts/16-MinecraftStandard.otf +0 -0
  9. idotmatrix/fonts/16-MinecraftStandardBoldOblique.otf +0 -0
  10. idotmatrix/fonts/16-PixelOperator8-Bold.ttf +0 -0
  11. idotmatrix/fonts/16-PixelOperator8.ttf +0 -0
  12. idotmatrix/fonts/16-PixelifySans-Regular.ttf +0 -0
  13. idotmatrix/fonts/16-PressStart2P-Regular.ttf +0 -0
  14. idotmatrix/fonts/16-dogica.ttf +0 -0
  15. idotmatrix/fonts/16-dogicabold.ttf +0 -0
  16. idotmatrix/fonts/16-dogicapixel.ttf +0 -0
  17. idotmatrix/fonts/16-dogicapixelbold.ttf +0 -0
  18. idotmatrix/fonts/16_32-HomeVideo-BLG6G.ttf +0 -0
  19. idotmatrix/fonts/16_32-HomeVideoBold-R90Dv.ttf +0 -0
  20. idotmatrix/fonts/16_32-MayfairNbpBold-gAA4.ttf +0 -0
  21. idotmatrix/fonts/32-Jersey10-Regular.ttf +0 -0
  22. idotmatrix/fonts/CC-BY-SA-4.0-License.txt +428 -0
  23. idotmatrix/fonts/ErbosDraco-License.txt +3 -0
  24. idotmatrix/fonts/HomeVideo-License.txt +2 -0
  25. idotmatrix/fonts/Jersey10-Regular-License.txt +93 -0
  26. idotmatrix/fonts/MayfairNbpBold-License.txt +3 -0
  27. idotmatrix/fonts/MinecraftStandard-License.txt +5 -0
  28. idotmatrix/fonts/PixelOperator-License.txt +121 -0
  29. idotmatrix/fonts/PixelifySans-License.txt +93 -0
  30. idotmatrix/fonts/PressStart2P-Regular-License.txt +93 -0
  31. idotmatrix/fonts/Rain-DRM3-License.txt +44 -0
  32. idotmatrix/fonts/Rain-DRM3.otf +0 -0
  33. idotmatrix/fonts/dogica_license.txt +94 -0
  34. idotmatrix/modules/__init__.py +64 -0
  35. idotmatrix/modules/chronograph.py +50 -0
  36. idotmatrix/modules/clock.py +101 -0
  37. idotmatrix/modules/common.py +176 -0
  38. idotmatrix/modules/countdown.py +70 -0
  39. idotmatrix/modules/eco.py +63 -0
  40. idotmatrix/modules/effect.py +79 -0
  41. idotmatrix/modules/fullscreen_color.py +55 -0
  42. idotmatrix/modules/gif.py +403 -0
  43. idotmatrix/modules/graffiti.py +71 -0
  44. idotmatrix/modules/image.py +383 -0
  45. idotmatrix/modules/music_sync.py +67 -0
  46. idotmatrix/modules/scoreboard.py +38 -0
  47. idotmatrix/modules/system.py +65 -0
  48. idotmatrix/modules/text.py +232 -0
  49. idotmatrix/protocol.py +52 -0
  50. idotmatrix/screensize.py +8 -0
  51. idotmatrix/transport.py +137 -0
  52. idotmatrix/util/__init__.py +0 -0
  53. idotmatrix/util/color_utils.py +64 -0
  54. idotmatrix/util/command_ack.py +23 -0
  55. idotmatrix/util/device_info.py +38 -0
  56. idotmatrix/util/device_material.py +16 -0
  57. idotmatrix/util/file_watch.py +57 -0
  58. idotmatrix/util/image_utils.py +139 -0
  59. idotmatrix/util/upload_ack.py +42 -0
  60. idotmatrix_api_client-0.2.0.dist-info/METADATA +375 -0
  61. idotmatrix_api_client-0.2.0.dist-info/RECORD +63 -0
  62. idotmatrix_api_client-0.2.0.dist-info/WHEEL +4 -0
  63. idotmatrix_api_client-0.2.0.dist-info/licenses/LICENSE +674 -0
@@ -0,0 +1,232 @@
1
+ import asyncio
2
+ import logging
3
+ import os
4
+ import zlib
5
+ from enum import Enum
6
+ from typing import Tuple, Optional
7
+
8
+ from PIL import Image, ImageDraw, ImageFont
9
+
10
+ from idotmatrix.modules import IDotMatrixModule
11
+ from idotmatrix.util import color_utils
12
+
13
+
14
+ class TextMode(Enum):
15
+ REPLACE = 0
16
+ MARQUEE = 1
17
+ REVERSED_MARQUEE = 2
18
+ VERTICAL_RISING_MARQUEE = 3
19
+ VERTICAL_LOWERING_MARQUEE = 4
20
+ BLINKING = 5
21
+ FADING = 6
22
+ TETRIS = 7
23
+ FILLING = 8
24
+
25
+
26
+ class TextColorMode(Enum):
27
+ WHITE = 0
28
+ RGB = 1
29
+ RAINBOW_1 = 2
30
+ RAINBOW_2 = 3
31
+ RAINBOW_3 = 4
32
+ RAINBOW_4 = 5
33
+
34
+
35
+ class TextModule(IDotMatrixModule):
36
+ """Manages text processing and packet creation for iDotMatrix devices. With help from https://github.com/8none1/idotmatrix/ :)"""
37
+
38
+ logging = logging.getLogger(__name__)
39
+ # must be 16x32 or 8x16
40
+ image_width = 16
41
+ image_height = 32
42
+ # must be x05 for 16x32 or x02 for 8x16
43
+ separator = b"\x05\xff\xff\xff"
44
+
45
+ async def show_text(
46
+ self,
47
+ text: str,
48
+ font_size: int = 16,
49
+ font_path: Optional[str] = None,
50
+ text_mode: TextMode | int = TextMode.MARQUEE,
51
+ speed: int = 95,
52
+ text_color_mode: TextColorMode | int = TextColorMode.WHITE,
53
+ text_color: Tuple[int, int, int] | int | str = None,
54
+ text_bg_color: Optional[Tuple[int, int, int] | int | str] = None,
55
+ ):
56
+ """
57
+ Displays text on the iDotMatrix device with specified settings.
58
+ Args:
59
+ text (str): The text to display.
60
+ font_size (int): Size of the font. Defaults to 16.
61
+ font_path (Optional[str]): Path to the font file. Defaults to None, which uses a default font.
62
+ text_mode (TextMode | int): Mode for displaying text. Defaults to TextMode.MARQUEE.
63
+ speed (int): Speed of the text display. Defaults to 95.
64
+ text_color_mode (TextColorMode | int): Color mode for the text. Defaults to TextColorMode.WHITE.
65
+ text_color (Tuple[int, int, int]): RGB color for the text. Defaults to None, which uses white.
66
+ text_bg_color (Optional[Tuple[int, int, int]]): RGB color for the background. Defaults to None, which uses black.
67
+ Raises:
68
+ ValueError: If text_color is None and text_color_mode is RGB.
69
+ Raises:
70
+ TypeError: If text_mode or text_color_mode is not an instance of TextMode or TextColorMode.
71
+ Raises:
72
+ ValueError: If text_color is None when text_color_mode is RGB.
73
+ """
74
+ if isinstance(text_mode, TextMode):
75
+ text_mode = text_mode.value
76
+
77
+ if isinstance(text_color_mode, TextColorMode):
78
+ text_color_mode = text_color_mode.value
79
+
80
+ if text_color is None:
81
+ if text_color_mode == TextColorMode.RGB.value:
82
+ raise ValueError("text_color must be provided when text_color_mode is RGB")
83
+ text_color = (255, 255, 255)
84
+ else:
85
+ text_color = color_utils.parse_color_rgb(text_color)
86
+
87
+ text_bg_mode = 0 if text_bg_color is None else 1
88
+ if text_bg_color is None:
89
+ text_bg_color = (0, 0, 0)
90
+ else:
91
+ text_bg_color = color_utils.parse_color_rgb(text_bg_color)
92
+
93
+ data = self._build_string_packet(
94
+ num_chars=len(text),
95
+ text_mode=text_mode,
96
+ speed=speed,
97
+ text_color_mode=text_color_mode,
98
+ text_color=text_color,
99
+ text_bg_mode=text_bg_mode,
100
+ text_bg_color=text_bg_color,
101
+ # loads the font file and draws the characters
102
+ text_bitmaps=await asyncio.to_thread(
103
+ self._string_to_bitmaps,
104
+ text=text,
105
+ font_size=font_size,
106
+ font_path=font_path,
107
+ ),
108
+ )
109
+ await self._send_bytes(data=data)
110
+
111
+ def _build_string_packet(
112
+ self,
113
+ text_bitmaps: bytearray,
114
+ num_chars: int,
115
+ text_mode: int,
116
+ speed: int = 95,
117
+ text_color_mode: int = 0,
118
+ text_color: Tuple[int, int, int] = (255, 255, 255),
119
+ text_bg_mode: int = 0,
120
+ text_bg_color: Tuple[int, int, int] = (0, 255, 0),
121
+ ) -> bytearray:
122
+ """Constructs a packet with the settings and bitmaps for iDotMatrix devices.
123
+
124
+ Args:
125
+ text_bitmaps (bytearray): bitmap list of the text characters
126
+ num_chars (int): number of characters in text_bitmaps
127
+ text_mode (int, optional): Text mode. 0 = replace text, 1 = marquee, 2 = reversed marquee, 3 = vertical rising marquee, 4 = vertical lowering marquee, 5 = blinking, 6 = fading, 7 = tetris, 8 = filling
128
+ speed (int, optional): Speed of Text. Defaults to 95.
129
+ text_color_mode (int, optional): Text Color Mode. Defaults to 0. 0 = white, 1 = use given RGB color, 2,3,4,5 = rainbow modes
130
+ text_color (Tuple[int, int, int], optional): Text RGB Color. Defaults to (255, 0, 0).
131
+ text_bg_mode (int, optional): Text Background Mode. Defaults to 0. 0 = black, 1 = use given RGB color
132
+ text_bg_color (Tuple[int, int, int], optional): Background RGB Color. Defaults to (0, 0, 0).
133
+
134
+ Returns:
135
+ bytearray: A bytearray containing the complete packet to be sent to the iDotMatrix device.
136
+ """
137
+ text_metadata = bytearray(
138
+ [
139
+ 0,
140
+ 0, # Placeholder for num_chars, to be set below
141
+ 0,
142
+ 1, # Static values
143
+ text_mode,
144
+ speed,
145
+ text_color_mode,
146
+ *text_color,
147
+ text_bg_mode,
148
+ *text_bg_color,
149
+ ]
150
+ )
151
+ text_metadata[:2] = num_chars.to_bytes(2, byteorder="little")
152
+
153
+ packet = text_metadata + text_bitmaps
154
+
155
+ header = bytearray(
156
+ [
157
+ 0,
158
+ 0, # total_len placeholder
159
+ 3,
160
+ 0,
161
+ 0, # Static header values
162
+ 0,
163
+ 0,
164
+ 0,
165
+ 0, # Placeholder for packet length
166
+ 0,
167
+ 0,
168
+ 0,
169
+ 0, # Placeholder for CRC
170
+ 0,
171
+ 0,
172
+ 12, # Static footer values
173
+ ]
174
+ )
175
+ total_len = len(packet) + len(header)
176
+ header[:2] = total_len.to_bytes(2, byteorder="little")
177
+ header[5:9] = len(packet).to_bytes(4, byteorder="little")
178
+ header[9:13] = zlib.crc32(packet).to_bytes(4, byteorder="little")
179
+
180
+ return header + packet
181
+
182
+ def _string_to_bitmaps(
183
+ self, text: str, font_path: Optional[str] = None, font_size: Optional[int] = 20
184
+ ) -> bytearray:
185
+ """Converts text to bitmap images suitable for iDotMatrix devices."""
186
+ if not font_path:
187
+ # using open source font from https://www.fontspace.com/rain-font-f22577
188
+ font_path = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "fonts", "Rain-DRM3.otf")
189
+ font_path = os.path.normpath(font_path)
190
+ font = ImageFont.truetype(font_path, font_size)
191
+
192
+ # The device protocol supports two fixed per-character cell sizes: a
193
+ # compact 8x16 cell (separator 0x02) and the full 16x32 cell
194
+ # (separator 0x05, this class's `image_width`/`image_height`
195
+ # defaults). Confirmed via a real BLE capture of the official
196
+ # Android app: at its default ~16px font, every character was sent
197
+ # using the compact 8x16 cell, giving much tighter spacing than
198
+ # always using the 16x32 cell. Probe every character's bounding box
199
+ # first and use the compact cell for the whole string whenever it
200
+ # fits, to avoid clipping wider/bold fonts that need the full cell.
201
+ probe_image = Image.new("1", (1, 1), 0)
202
+ probe_draw = ImageDraw.Draw(probe_image)
203
+ max_width = max_height = 0
204
+ for char in text:
205
+ _, _, w, h = probe_draw.textbbox((0, 0), text=char, font=font)
206
+ max_width = max(max_width, w)
207
+ max_height = max(max_height, h)
208
+
209
+ if max_width <= 8 and max_height <= 16:
210
+ cell_width, cell_height, separator = 8, 16, bytes([0x02, 0xFF, 0xFF, 0xFF])
211
+ else:
212
+ cell_width, cell_height, separator = self.image_width, self.image_height, self.separator
213
+
214
+ byte_stream = bytearray()
215
+ for char in text:
216
+ image = Image.new("1", (cell_width, cell_height), 0)
217
+ draw = ImageDraw.Draw(image)
218
+ _, _, text_width, text_height = draw.textbbox((0, 0), text=char, font=font)
219
+ text_x = (cell_width - text_width) // 2
220
+ text_y = (cell_height - text_height) // 2
221
+ draw.text((text_x, text_y), char, fill=1, font=font)
222
+ bitmap = bytearray()
223
+ for y in range(cell_height):
224
+ for x in range(cell_width):
225
+ if x % 8 == 0:
226
+ byte = 0
227
+ pixel = image.getpixel((x, y))
228
+ byte |= (pixel & 1) << (x % 8)
229
+ if x % 8 == 7 or x == cell_width - 1:
230
+ bitmap.append(byte)
231
+ byte_stream.extend(separator + bitmap)
232
+ return byte_stream
idotmatrix/protocol.py ADDED
@@ -0,0 +1,52 @@
1
+ from typing import NamedTuple
2
+
3
+
4
+ class Command(NamedTuple):
5
+ """
6
+ A command of the device, identified by its command and subcommand byte (the third and fourth byte of a message).
7
+ See docs/DEVICE-PROTOCOL.md for what is known about them.
8
+ """
9
+ opcode: int
10
+ subcommand: int
11
+
12
+
13
+ # generic
14
+ FREEZE_SCREEN = Command(3, 0) # toggles
15
+ RESET = Command(3, 0x80)
16
+ SET_SPEED = Command(3, 1) # not acknowledged
17
+ SET_TIME = Command(1, 0x80)
18
+ SET_PASSWORD = Command(4, 2)
19
+ BRIGHTNESS = Command(4, 0x80)
20
+ SCREEN_FLIP = Command(6, 0x80)
21
+ SCREEN_ON_OFF = Command(7, 1)
22
+ SET_JOINT = Command(12, 0x80) # not acknowledged
23
+ DELETE_MATERIALS = Command(2, 1)
24
+
25
+ # modes
26
+ CLOCK = Command(6, 1)
27
+ CLOCK_TIME_INDICATOR = Command(7, 0x80)
28
+ FULLSCREEN_COLOR = Command(2, 2)
29
+ EFFECT = Command(3, 2)
30
+ COUNTDOWN = Command(8, 0x80)
31
+ CHRONOGRAPH = Command(9, 0x80)
32
+ SCOREBOARD = Command(10, 0x80)
33
+ ECO = Command(2, 0x80)
34
+ GRAFFITI = Command(5, 1) # pixels, the length is two bytes
35
+ MICROPHONE_MODE = Command(11, 0x80)
36
+ IMAGE_RHYTHM = Command(0, 2) # phone microphone data
37
+
38
+
39
+ def build_command(command: Command, *payload: int, length: int | None = None) -> bytearray:
40
+ """
41
+ Builds a command message: the length of the message (two bytes, little endian), the command and subcommand
42
+ byte and the payload.
43
+
44
+ Args:
45
+ command: The command.
46
+ payload: The bytes behind the command, they have to be between 0 and 255.
47
+ length: The length to write into the message, if it differs from the real one (the effect command does that).
48
+ """
49
+ real_length = 4 + len(payload)
50
+ if length is None:
51
+ length = real_length
52
+ return bytearray([length % 256, length // 256, command.opcode, command.subcommand, *payload])
@@ -0,0 +1,8 @@
1
+ from enum import Enum
2
+
3
+
4
+ class ScreenSize(Enum):
5
+ """Enum for screen sizes."""
6
+ SIZE_64x64 = (64, 64)
7
+ SIZE_32x32 = (32, 32)
8
+ SIZE_16x16 = (16, 16)
@@ -0,0 +1,137 @@
1
+ import logging
2
+ from collections.abc import Awaitable, Callable
3
+ from typing import Optional, Protocol
4
+
5
+ from bleak import BleakClient
6
+ from bleak.backends.device import BLEDevice
7
+
8
+ from .const import UUID_READ_DATA, UUID_CHARACTERISTIC_WRITE_DATA
9
+
10
+
11
+ class Transport(Protocol):
12
+ """
13
+ The link to one device, as far as the `ConnectionManager` needs it. `BleakTransport` talks to a real device over
14
+ Bluetooth LE, a fake can stand in for it in tests (see `tests/fake_transport.py`).
15
+ """
16
+
17
+ @property
18
+ def is_connected(self) -> bool:
19
+ """Whether the link is up, according to the underlying stack."""
20
+
21
+ async def connect(self) -> None:
22
+ """Opens the link."""
23
+
24
+ async def disconnect(self) -> None:
25
+ """Closes the link."""
26
+
27
+ async def write(self, data: bytes | bytearray, response: bool) -> None:
28
+ """
29
+ Writes data to the write characteristic of the device.
30
+ Args:
31
+ data: At most `max_write_without_response_size()` bytes if `response` is False, otherwise at most 512.
32
+ response: True for a write with response, False for a write without response.
33
+ """
34
+
35
+ async def read(self) -> bytes:
36
+ """Reads the read characteristic of the device."""
37
+
38
+ async def start_notify(self, callback: Callable[[bytes], None]) -> None:
39
+ """Calls `callback` with the payload of every notification of the device."""
40
+
41
+ async def max_write_without_response_size(self) -> int:
42
+ """The maximum payload of a single write without response on the current connection."""
43
+
44
+
45
+ class BleakTransport:
46
+ """A `Transport` for a real device, based on `bleak`."""
47
+
48
+ logging = logging.getLogger(__name__)
49
+
50
+ def __init__(
51
+ self,
52
+ address_or_device: str | BLEDevice,
53
+ on_disconnected: Callable[[], None],
54
+ connector: Optional[Callable[[str | BLEDevice, Callable[[BleakClient], None]], Awaitable[BleakClient]]] = None,
55
+ ) -> None:
56
+ """
57
+ Args:
58
+ address_or_device: The Bluetooth address (MAC) of the device, or a `BLEDevice` that a scanner found. The
59
+ latter is what Home Assistant provides, it knows how to reach the device (f.e. over a Bluetooth proxy).
60
+ on_disconnected: Called when the connection was lost.
61
+ connector: Connects in a different way than `BleakClient.connect()`. It gets the address or device and a
62
+ callback for the disconnect, and returns a connected `BleakClient`, f.e. `establish_connection` of
63
+ `bleak-retry-connector`, which Home Assistant integrations use to connect over Bluetooth proxies.
64
+ """
65
+ self.address = address_or_device if isinstance(address_or_device, str) else address_or_device.address
66
+ self._address_or_device = address_or_device
67
+ self._on_disconnected = on_disconnected
68
+ self._connector = connector
69
+ self._client: Optional[BleakClient] = None
70
+ if connector is None:
71
+ self._client = BleakClient(
72
+ address_or_ble_device=address_or_device,
73
+ disconnected_callback=lambda _client: on_disconnected(),
74
+ )
75
+
76
+ @property
77
+ def is_connected(self) -> bool:
78
+ return self._client is not None and self._client.is_connected
79
+
80
+ async def connect(self) -> None:
81
+ if self._connector is not None:
82
+ self._client = await self._connector(self._address_or_device, lambda _client: self._on_disconnected())
83
+ else:
84
+ await self._client.connect()
85
+ # print service and characteristic information for debugging
86
+ for service in self._client.services:
87
+ self.logging.debug(f"Service: {service.uuid} ({service.handle})")
88
+ for characteristic in service.characteristics:
89
+ self.logging.debug(
90
+ f" Characteristic: {characteristic.uuid} ({characteristic.handle}): {characteristic.description}")
91
+ self.logging.debug(f" Properties: {characteristic.properties}")
92
+ self.logging.debug(
93
+ f" Max Write Without Response Size: {characteristic.max_write_without_response_size}")
94
+
95
+ async def disconnect(self) -> None:
96
+ if self._client is not None:
97
+ await self._client.disconnect()
98
+
99
+ async def write(self, data: bytes | bytearray, response: bool) -> None:
100
+ await self._client.write_gatt_char(
101
+ char_specifier=UUID_CHARACTERISTIC_WRITE_DATA, data=data, response=response)
102
+
103
+ async def read(self) -> bytes:
104
+ return await self._client.read_gatt_char(UUID_READ_DATA)
105
+
106
+ async def start_notify(self, callback: Callable[[bytes], None]) -> None:
107
+ await self._client.start_notify(UUID_READ_DATA, lambda _characteristic, data: callback(bytes(data)))
108
+
109
+ async def max_write_without_response_size(self) -> int:
110
+ """
111
+ Writes above this size are silently truncated or dropped by some BLE stacks (f.e. macOS Catalina
112
+ negotiates an ATT MTU of 104), so the negotiated MTU is preferred whenever the stack reports one.
113
+ """
114
+ char = self._client.services.get_characteristic(UUID_CHARACTERISTIC_WRITE_DATA)
115
+ size = char.max_write_without_response_size
116
+ if size > 20:
117
+ return size
118
+
119
+ # 20 is the default before the MTU exchange has completed. On BlueZ the exchange can be forced.
120
+ acquire_mtu = getattr(self._client._backend, "_acquire_mtu", None)
121
+ if acquire_mtu is not None:
122
+ try:
123
+ await acquire_mtu()
124
+ size = char.max_write_without_response_size
125
+ if size > 20:
126
+ return size
127
+ except Exception as e:
128
+ self.logging.debug(f"could not acquire MTU: {e}")
129
+
130
+ mtu_size = self._client.mtu_size
131
+ if mtu_size and mtu_size > 23:
132
+ # 3 bytes of the ATT MTU are used by the ATT header
133
+ return mtu_size - 3
134
+
135
+ # the stack reports no usable MTU at all: keep the previous default,
136
+ # my 64x64 device reports a max_write_without_response_size of 514 bytes, most of the time
137
+ return 514
File without changes
@@ -0,0 +1,64 @@
1
+ from typing import Tuple
2
+
3
+ from PIL import ImageColor
4
+
5
+
6
+ def parse_color_rgb(color: Tuple[int, int, int] | int | str) -> Tuple[int, int, int]:
7
+ """
8
+ Parses a color input and returns it as an RGB tuple.
9
+ Args:
10
+ color (tuple, int, str): Color in RGB format as a tuple of three integers (r, g, b),
11
+ an integer (0 to 16777215), or a string in hex format (#RRGGBB or 0xRRGGBB)
12
+ or a named color.
13
+ """
14
+ if color is None:
15
+ return None
16
+ if isinstance(color, bool):
17
+ raise ValueError("Color must be an integer, a string, or a tuple of three integers (r, g, b)")
18
+ if isinstance(color, int):
19
+ if not (0 <= color < 16777216):
20
+ raise ValueError("Color integer must be between 0 and 16777215 (0xFFFFFF)")
21
+ # Convert integer to RGB tuple
22
+ r = (color >> 16) & 0xFF
23
+ g = (color >> 8) & 0xFF
24
+ b = color & 0xFF
25
+ color = (r, g, b)
26
+ elif isinstance(color, str):
27
+ if color.startswith("#") or color.startswith("0x"):
28
+ digits = color[1:] if color.startswith("#") else color[2:]
29
+ if len(digits) == 3 and color.startswith("#"):
30
+ # expand shorthand notation (#rgb -> #rrggbb)
31
+ digits = "".join(d * 2 for d in digits)
32
+ if len(digits) != 6:
33
+ raise ValueError("Invalid hex color. Use #RRGGBB, #RGB or 0xRRGGBB.")
34
+ color = tuple(int(digits[i:i + 2], 16) for i in (0, 2, 4))
35
+ else:
36
+ try:
37
+ # drop the alpha channel PIL returns for rgba() strings
38
+ color = tuple(ImageColor.getrgb(color)[:3])
39
+ except ValueError:
40
+ raise ValueError(
41
+ "Invalid color string. Use hex format (#RRGGBB), '0xRRGGBB', or a named color."
42
+ )
43
+ elif isinstance(color, tuple):
44
+ if len(color) != 3:
45
+ raise ValueError("Color tuple must contain three integers (r, g, b)")
46
+ if not all(isinstance(c, int) for c in color):
47
+ raise ValueError("Color tuple must contain three integers (r, g, b)")
48
+ if not all(0 <= c < 256 for c in color):
49
+ raise ValueError("Color values must be between 0 and 255")
50
+ else:
51
+ raise ValueError("Color must be an integer, a string, or a tuple of three integers (r, g, b)")
52
+
53
+ return color
54
+
55
+
56
+ def parse_color_rgb_list(colors: list[Tuple[int, int, int] | int | str]) -> list[Tuple[int, int, int]]:
57
+ """
58
+ Parses a list of color inputs and returns them as a list of RGB tuples.
59
+ Args:
60
+ colors (list): List of colors in RGB format as tuples of three integers (r, g, b),
61
+ integers (0 to 16777215), or strings in hex format (#RRGGBB or 0xRRGGBB)
62
+ or named colors.
63
+ """
64
+ return [parse_color_rgb(color) for color in colors]
@@ -0,0 +1,23 @@
1
+ from idotmatrix import protocol
2
+
3
+ # Commands (identified by their command and subcommand byte, the third and fourth byte) that the device
4
+ # acknowledges with `05 00 <command> <subcommand> <status>`, verified on a 64x64. See docs/DEVICE-PROTOCOL.md,
5
+ # and add a command here once it was verified. Commands that are not in here are never waited for:
6
+ # `set_speed` and `set_joint` are not acknowledged, freeze, text and set_time are answered differently.
7
+ ACKNOWLEDGED_COMMANDS = frozenset({
8
+ protocol.BRIGHTNESS,
9
+ protocol.SCREEN_FLIP,
10
+ protocol.SCREEN_ON_OFF,
11
+ protocol.CLOCK,
12
+ protocol.FULLSCREEN_COLOR,
13
+ protocol.EFFECT,
14
+ protocol.COUNTDOWN,
15
+ protocol.CHRONOGRAPH,
16
+ protocol.SCOREBOARD,
17
+ protocol.MICROPHONE_MODE,
18
+ })
19
+
20
+
21
+ def is_acknowledged_command(data: bytes | bytearray) -> bool:
22
+ """Tells if the device is known to acknowledge a command."""
23
+ return len(data) >= 5 and protocol.Command(data[2], data[3]) in ACKNOWLEDGED_COMMANDS
@@ -0,0 +1,38 @@
1
+ from dataclasses import dataclass
2
+ from typing import Optional
3
+
4
+ from idotmatrix import protocol
5
+ from idotmatrix.screensize import ScreenSize
6
+
7
+ # the screen type the device reports, 2 (8x32) and 11 (16x64) exist, but are not supported by this library
8
+ SCREEN_TYPES = {
9
+ 1: ScreenSize.SIZE_16x16,
10
+ 3: ScreenSize.SIZE_32x32,
11
+ 4: ScreenSize.SIZE_64x64,
12
+ }
13
+
14
+
15
+ @dataclass(frozen=True)
16
+ class DeviceInfo:
17
+ """What the device tells about itself when its time is set (`09 00 01 80 <major> <minor> <?> <type> <password>`)."""
18
+ firmware_version: str
19
+ screen_type: int
20
+ password_protected: bool
21
+ switch_status: int
22
+
23
+ @property
24
+ def screen_size(self) -> Optional[ScreenSize]:
25
+ """The size of the screen, or None if the type is not supported by this library."""
26
+ return SCREEN_TYPES.get(self.screen_type)
27
+
28
+
29
+ def parse_device_info(notification: bytes) -> Optional[DeviceInfo]:
30
+ """Parses the reply to the set time command. Returns None for any other notification."""
31
+ if len(notification) < 9 or (notification[2], notification[3]) != (protocol.SET_TIME.opcode, protocol.SET_TIME.subcommand):
32
+ return None
33
+ return DeviceInfo(
34
+ firmware_version=f"{notification[4]}.{notification[5]:02d}",
35
+ switch_status=notification[6],
36
+ screen_type=notification[7],
37
+ password_protected=notification[8] == 1,
38
+ )
@@ -0,0 +1,16 @@
1
+ # Index (the last byte of the header) of an upload to the device. 0 to 11 are slots the device keeps
2
+ # and cycles through, 13 is the one the official app uses to show something on the device right away.
3
+ INDEX_SHOW_NOW = 13
4
+
5
+
6
+ def convert_display_time(time_sign: int) -> int:
7
+ """
8
+ Python equivalent of DeviceMaterialTimeConvert.ConvertTime(int i).
9
+ The time sign corresponds to AppData.getInstance().getTimeSign() of the official app, which is the
10
+ display time of an item in the list of stored materials of the device. It originates from
11
+ SharedPreferences, and 0 is the default.
12
+
13
+ Returns:
14
+ The display time in seconds.
15
+ """
16
+ return {1: 10, 2: 30, 3: 60, 4: 300}.get(time_sign, 5)
@@ -0,0 +1,57 @@
1
+ import re
2
+ from collections.abc import Callable
3
+ from pathlib import Path
4
+ from typing import Dict
5
+
6
+ from watchdog.events import FileSystemEventHandler, EVENT_TYPE_MODIFIED, EVENT_TYPE_MOVED, EVENT_TYPE_CREATED, \
7
+ EVENT_TYPE_DELETED, FileSystemEvent
8
+
9
+
10
+ class ImageFileEventHandler(FileSystemEventHandler):
11
+
12
+ def __init__(
13
+ self,
14
+ file_filter: re.Pattern | None,
15
+ on_created: Callable[[Path], None] = None,
16
+ on_modified: Callable[[Path], None] = None,
17
+ on_moved: Callable[[Path, Path], None] = None,
18
+ on_deleted: Callable[[Path], None] = None,
19
+ ):
20
+ super().__init__()
21
+ self._file_filter = file_filter
22
+ self._on_created_callback = on_created if on_created else lambda _: None
23
+ self._on_modified_callback = on_modified if on_modified else lambda _: None
24
+ self._on_moved_callback = on_moved if on_moved else lambda _, __: None
25
+ self._on_deleted_callback = on_deleted if on_deleted else lambda _: None
26
+
27
+ def on_any_event(self, event: FileSystemEvent):
28
+ # TODO: Implement filtering logic if needed
29
+ if not self._event_matches_filter(event):
30
+ return
31
+
32
+ _actions: Dict[str, Callable[[FileSystemEvent], None]] = {
33
+ EVENT_TYPE_CREATED: self.created,
34
+ EVENT_TYPE_MODIFIED: self.modified,
35
+ EVENT_TYPE_MOVED: self.moved,
36
+ EVENT_TYPE_DELETED: self.deleted,
37
+ }
38
+ _actions.get(event.event_type, lambda x: None)(event)
39
+
40
+ def created(self, event: FileSystemEvent):
41
+ self._on_created_callback(Path(event.src_path))
42
+
43
+ def modified(self, event: FileSystemEvent):
44
+ self._on_modified_callback(Path(event.src_path))
45
+
46
+ def moved(self, event: FileSystemEvent):
47
+ self._on_moved_callback(Path(event.src_path), Path(event.dest_path))
48
+
49
+ def deleted(self, event: FileSystemEvent):
50
+ self._on_deleted_callback(Path(event.src_path))
51
+
52
+ def _event_matches_filter(self, event: FileSystemEvent) -> bool:
53
+ if event.is_directory:
54
+ return False
55
+ # dest_path is only set for moved events
56
+ path = event.dest_path if event.event_type == EVENT_TYPE_MOVED else event.src_path
57
+ return self._file_filter is None or bool(self._file_filter.match(str(path)))