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,403 @@
1
+ import asyncio
2
+ import binascii
3
+ import io
4
+ import logging
5
+ from os import PathLike
6
+ from typing import List, Tuple
7
+
8
+ from PIL import Image as PILImage
9
+
10
+ from idotmatrix import protocol
11
+ from idotmatrix.connection_manager import ConnectionManager
12
+ from idotmatrix.modules import IDotMatrixModule
13
+ from idotmatrix.protocol import build_command
14
+ from idotmatrix.screensize import ScreenSize
15
+ from idotmatrix.util import image_utils, color_utils
16
+ from idotmatrix.util.device_material import INDEX_SHOW_NOW, convert_display_time
17
+ from idotmatrix.util.image_utils import ResizeMode
18
+
19
+ ANIMATION_MAX_FRAME_COUNT = 64 # Maximum number of frames in a GIF animation
20
+ DEFAULT_DURATION_PER_FRAME_MS = 200 # Default duration per frame in milliseconds if not specified in the GIF file
21
+ ANIMATION_TOTAL_DURATION_LIMIT_MS = 2000
22
+ DEFAULT_ANIMATION_TOTAL_DURATION_MS = ANIMATION_TOTAL_DURATION_LIMIT_MS
23
+
24
+ # --- Constants based on the Java code ---
25
+ CHUNK_SIZE_4096 = 4096
26
+ HEADER_SIZE_GIF = 16 # As per sendImageData logic in GifAgreement.java
27
+
28
+
29
+ class GifModule(IDotMatrixModule):
30
+ """
31
+ This class handles GIF file uploads to the iDotMatrix device.
32
+ """
33
+ logging = logging.getLogger(__name__)
34
+
35
+ def __init__(
36
+ self,
37
+ connection_manager: ConnectionManager,
38
+ screen_size: ScreenSize,
39
+ ) -> None:
40
+ super().__init__(connection_manager=connection_manager)
41
+ self.screen_size = screen_size
42
+
43
+ async def upload_gif_file(
44
+ self,
45
+ file_path: PathLike | str,
46
+ resize_mode: ResizeMode = ResizeMode.FIT,
47
+ palletize: bool = True,
48
+ background_color: Tuple[int, int, int] | int | str = (0, 0, 0),
49
+ duration_per_frame_in_ms: int = None,
50
+ ):
51
+ """
52
+ Uploads a GIF file to the device.
53
+
54
+ Args:
55
+ file_path (str): path to the image file
56
+ resize_mode (ResizeMode): The mode to resize the image.
57
+ palletize (bool): Whether to convert the image to a color palette. Usually bad for images with
58
+ high detail (like photos) but good for pixel-art or other content with high contrasts. Defaults to True.
59
+ background_color (Tuple[int, int, int]): RGB color to fill transparent pixels. Defaults to black (0, 0, 0).
60
+ duration_per_frame_in_ms (int, optional): Duration of each frame in milliseconds. If not provided, defaults to the duration specified in the GIF file, or 200ms if not set.
61
+ """
62
+ screen_width = self.screen_size.value[0] # assuming square canvas, so width == height
63
+ background_color = color_utils.parse_color_rgb(background_color)
64
+
65
+ # reading and converting the file takes a while, the event loop must not be blocked
66
+ gif_data = await asyncio.to_thread(
67
+ self._load_gif_and_adapt_to_canvas,
68
+ file_path=file_path,
69
+ canvas_size=screen_width,
70
+ resize_mode=resize_mode,
71
+ palletize=palletize,
72
+ background_color=background_color,
73
+ duration_per_frame_in_ms=duration_per_frame_in_ms,
74
+ )
75
+
76
+ # If the device already has the exact same GIF stored, it answers the first chunk with "finished"
77
+ # and skips the rest of the upload, which is why uploading the same file twice is fast.
78
+
79
+ packets = self.create_gif_data_packets(
80
+ gif_data=gif_data,
81
+ # TODO: figure out what this does
82
+ # this might be the index that this GIF will be stored within the device's memory :think:
83
+ # it doesn't seem to have an effect when sending a single GIF like it is done here though
84
+ # shows the GIF right away, like the official app does
85
+ gif_type=INDEX_SHOW_NOW,
86
+ time_sign=0,
87
+ )
88
+ await self._send_packets(packets=packets, response=True, wait_for_ack=True)
89
+
90
+ async def clear_storage(self) -> None:
91
+ """
92
+ Deletes all materials that are stored on the device. This is the command the official app
93
+ sends when the user deletes the materials on the device. Not verified on a real device yet.
94
+
95
+ Uploading a GIF the device already has is fast, because the device skips the transfer.
96
+ """
97
+ data = build_command(protocol.DELETE_MATERIALS, 12, 0, *range(1, 12))
98
+ await self._send_bytes(data=data, response=True)
99
+
100
+ def _load_gif_and_adapt_to_canvas(
101
+ self,
102
+ file_path: PathLike | str,
103
+ canvas_size: int,
104
+ resize_mode: ResizeMode,
105
+ palletize: bool = True,
106
+ background_color: Tuple[int, int, int] = (0, 0, 0),
107
+ duration_per_frame_in_ms: int = None,
108
+ ) -> bytes:
109
+ """
110
+ Loads a GIF file and adapts it to the pixel size of the device's canvas.
111
+
112
+ Args:
113
+ file_path (PathLike): Path to the GIF file.
114
+ canvas_size (int): Size of the pixel in the device's canvas.
115
+ resize_mode (ResizeMode): The mode to resize the image. Options are:
116
+ - ResizeMode.FIT: Resize to fit within the canvas while maintaining aspect ratio.
117
+ - ResizeMode.FILL: Resize to fill the canvas, may crop the image.
118
+ - ResizeMode.STRETCH: Stretch the image to fit the canvas, may distort the image.
119
+ - ResizeMode.CROP: Crop the image to fit the canvas without resizing.
120
+ palletize (bool): Whether to convert the image to a color palette. Defaults to True.
121
+ background_color (Tuple[int, int, int]): Background color to fill transparent pixels.
122
+ duration_per_frame_in_ms (int, optional): Duration of each frame in milliseconds. If not provided, defaults to the duration specified in the GIF file, or 200ms if not set.
123
+ Returns:
124
+ bytes: A byte representation of the GIF file, adapted to fit the pixel size.
125
+ """
126
+ from PIL import GifImagePlugin
127
+ GifImagePlugin.LOADING_STRATEGY = GifImagePlugin.LoadingStrategy.RGB_AFTER_DIFFERENT_PALETTE_ONLY
128
+
129
+ with PILImage.open(file_path) as img:
130
+ frames = []
131
+ try:
132
+ # There doesn't seem to be a frame limit in the app, but too many frames cause problems.
133
+ # To be on the safe side, we limit it to 64 frames.
134
+ while True:
135
+ frame = img.copy()
136
+
137
+ if frame.size != (canvas_size, canvas_size):
138
+ # needs to use NEAREST to to avoid color distortion
139
+ resample_mode = PILImage.Resampling.NEAREST
140
+ frame = image_utils.resize_image(
141
+ image=frame,
142
+ canvas_size=canvas_size,
143
+ resize_mode=resize_mode,
144
+ resample_mode=resample_mode,
145
+ background_color=background_color,
146
+ mode="RGBA",
147
+ )
148
+ if palletize:
149
+ frame = image_utils.palettize(frame)
150
+
151
+ frames.append(frame.copy())
152
+ img.seek(img.tell() + 1)
153
+ except EOFError:
154
+ pass
155
+
156
+ frames, duration_per_frame_in_ms = self._ensure_reasonable_frame_count(
157
+ img, frames, duration_per_frame_in_ms
158
+ )
159
+
160
+ # TODO: there are still some cases where
161
+ # - the GIF is not animating all frames
162
+
163
+ # all frames need color tables of the same size, or the device garbles / drops frames
164
+ frames = [image_utils.pad_palette(frame) for frame in frames]
165
+
166
+ gif_buffer = io.BytesIO()
167
+ # take the first frame, append the rest as additional frames and save as GIF into gif_buffer
168
+ frames[0].save(
169
+ gif_buffer,
170
+ format="GIF",
171
+ save_all=True,
172
+ optimize=False, # True would shrink the color tables to the number of used colors again
173
+ append_images=frames[1:],
174
+ loop=0, # loop forever
175
+ duration=duration_per_frame_in_ms,
176
+ disposal=2, # Restore to background color after each frame
177
+ )
178
+ gif_buffer.seek(0)
179
+ return gif_buffer.getvalue()
180
+
181
+ def _int_to_bytes_le(self, value: int, length: int = 4) -> bytearray:
182
+ """Converts an integer to a little-endian bytearray of specified length."""
183
+ return bytearray(value.to_bytes(length, byteorder='little'))
184
+
185
+ def _short_to_bytes_le(self, value: int) -> bytearray:
186
+ """Converts a short (2 bytes) to a little-endian bytearray."""
187
+ return bytearray(value.to_bytes(2, byteorder='little'))
188
+
189
+ def _chunk_data_by_size(self, data: bytes, chunk_size: int) -> list[bytearray]:
190
+ """
191
+ Chunks data into smaller pieces of a specified size.
192
+ Corresponds to getSendData4096.
193
+ """
194
+ if not data:
195
+ return []
196
+
197
+ chunks = []
198
+ num_chunks = (len(data) + chunk_size - 1) // chunk_size # Ceiling division
199
+
200
+ for i in range(num_chunks):
201
+ start = i * chunk_size
202
+ end = min((i + 1) * chunk_size, len(data))
203
+ chunks.append(bytearray(data[start:end]))
204
+ return chunks
205
+
206
+ def create_gif_data_packets(
207
+ self,
208
+ gif_data: bytes,
209
+ gif_type: int,
210
+ time_sign: int, # Assuming this is the raw time signature before DeviceMaterialTimeConvert.ConvertTime
211
+ ble_device_mtu_enabled: bool = True
212
+ ) -> list[list[bytearray]]:
213
+ """
214
+ Creates packets for sending GIF data, mirroring the Java GifAgreement logic.
215
+
216
+ Args:
217
+ gif_data: The raw byte array of the GIF data.
218
+ gif_type: The type parameter (e.g., 12 or other values from sendImageData). Values up until 19 display an image on the device.
219
+ time_sign: 0: "0", 1: "10", 2: "30", 3: "60", 4: "300", else: "5".
220
+ ble_device_mtu_enabled: Boolean indicating if MTU is enabled on the BLE device.
221
+
222
+ Returns:
223
+ A list of lists of byte arrays. The outer list represents "4K chunks with headers",
224
+ and the inner lists contain the actual BLE packets for each of those chunks.
225
+ """
226
+ send_data_3 = []
227
+
228
+ if not gif_data:
229
+ raise ValueError("gif_data cannot be empty or None.")
230
+
231
+ # Calculate CRC32 for the entire GIF data
232
+ # Ensure this CRC32 matches the Java CrcUtils.CRC32.CRC32 implementation
233
+ crc32_val = self.calculate_crc32_java_equivalent(gif_data)
234
+ crc32_bytes = self._int_to_bytes_le(crc32_val) # Little-endian int (4 bytes)
235
+
236
+ # Get the total length of the GIF data as bytes
237
+ total_length_bytes = self._int_to_bytes_le(len(gif_data)) # Little-endian int (4 bytes)
238
+
239
+ # 1. Chunk the gif_data into 4096-byte chunks
240
+ chunks_4096 = self._chunk_data_by_size(gif_data, CHUNK_SIZE_4096)
241
+
242
+ processed_large_packets_with_headers = []
243
+ for i, current_chunk in enumerate(chunks_4096):
244
+ packet_data_length = len(current_chunk) + HEADER_SIZE_GIF
245
+ packet_data_length_bytes_be = bytearray(self._int_to_bytes_le(packet_data_length))
246
+
247
+ header = bytearray(HEADER_SIZE_GIF)
248
+
249
+ header[0] = packet_data_length_bytes_be[0] # Packet Length (Big Endian short)
250
+ header[1] = packet_data_length_bytes_be[1]
251
+ header[2] = 1 # Command or type (fixed value from sendImageData)
252
+ header[3] = 0 # Sub-command or subtype (fixed value)
253
+
254
+ if i > 0:
255
+ header[4] = 2 # Continuation packet
256
+ else:
257
+ header[4] = 0 # First packet
258
+
259
+ # Total GIF data length (Little Endian int)
260
+ header[5:9] = total_length_bytes[0:4]
261
+
262
+ # CRC32 of GIF data (Little Endian int)
263
+ header[9:13] = crc32_bytes[0:4]
264
+
265
+ # Time signature or fixed bytes based on 'gif_type'
266
+ if gif_type == 12: # Assuming 12 is a special type
267
+ header[13] = 0
268
+ header[14] = 0
269
+ else:
270
+ # Java: DeviceMaterialTimeConvert.ConvertTime(AppData.getInstance().getTimeSign())
271
+ # 'time_sign' passed to create_gif_data_packets is the input_key
272
+ converted_time_value = convert_display_time(time_sign) # time_sign is the key (0,1,2,3,4...)
273
+
274
+ time_sign_bytes_be = bytearray(converted_time_value.to_bytes(2, byteorder='big'))
275
+ header[13] = time_sign_bytes_be[0]
276
+ header[14] = time_sign_bytes_be[1]
277
+
278
+ header[15] = gif_type & 0xFF # Ensure it's a byte
279
+
280
+ large_packet_with_header = bytes(header) + current_chunk
281
+ processed_large_packets_with_headers.append(large_packet_with_header)
282
+
283
+ # 3. Split each "large packet with header" into smaller BLE packets
284
+ for i, large_packet in enumerate(processed_large_packets_with_headers):
285
+ ble_packets_for_chunk = self._create_ble_packets(large_packet, ble_device_mtu_enabled)
286
+ if ble_packets_for_chunk:
287
+ send_data_3.append(ble_packets_for_chunk)
288
+
289
+ return send_data_3
290
+
291
+ @staticmethod
292
+ def _create_ble_packets(data_packet: bytes, ble_device_mtu_enabled: bool = True) -> list[bytearray]:
293
+ """
294
+ Splits a single data packet into smaller packets suitable for BLE transmission.
295
+ Corresponds to getSendData.
296
+ MTU values (509, 18) are from GifAgreement.java.
297
+ """
298
+ if not data_packet:
299
+ return []
300
+
301
+ ble_packets = []
302
+ mtu_packet_size = 509 if ble_device_mtu_enabled else 18
303
+
304
+ num_ble_packets = (len(data_packet) + mtu_packet_size - 1) // mtu_packet_size
305
+
306
+ for i in range(num_ble_packets):
307
+ start = i * mtu_packet_size
308
+ end = min((i + 1) * mtu_packet_size, len(data_packet))
309
+ ble_packets.append(bytearray(data_packet[start:end]))
310
+ return ble_packets
311
+
312
+ # --- Placeholder for a CRC32 function ---
313
+ # The Java code uses CrcUtils.CRC32.CRC32. Python's built-in binascii.crc32
314
+ # might behave differently (e.g., signed vs. unsigned, initial value, polynomial).
315
+ # For a direct equivalent, you might need a specific library or to implement
316
+ # the exact CRC32 variant used in your Java code.
317
+ # For this example, we'll use binascii.crc32 and note the potential difference.
318
+ def calculate_crc32_java_equivalent(self, data: bytes) -> int:
319
+ """
320
+ Calculates CRC32. Note: binascii.crc32 might differ from Java's specific CRC32.
321
+ The Java CrcUtils.CRC32.CRC32(bArr, 0, bArr.length) implies a standard CRC32.
322
+ binascii.crc32 returns a signed 32-bit integer on some Python versions/platforms,
323
+ Java usually deals with it as unsigned when converting to bytes.
324
+ """
325
+ # Initialize with 0xFFFFFFFF, XOR output with 0xFFFFFFFF
326
+ # This is a common CRC32/MPEG-2 variant.
327
+ # Python's binascii.crc32(data) is equivalent to binascii.crc32(data, 0)
328
+ # The result should be masked to get an unsigned 32-bit value.
329
+ crc = binascii.crc32(data) & 0xFFFFFFFF
330
+ return crc
331
+
332
+ @staticmethod
333
+ def _ensure_reasonable_frame_count(
334
+ img: PILImage.Image,
335
+ frames: List[PILImage.Image],
336
+ duration_per_frame_in_ms: int = None,
337
+ default_total_duration: int = DEFAULT_ANIMATION_TOTAL_DURATION_MS,
338
+ default_duration_per_frame: int = DEFAULT_DURATION_PER_FRAME_MS,
339
+ total_duration_limit_ms: int = ANIMATION_TOTAL_DURATION_LIMIT_MS,
340
+ max_total_frame_count: int = ANIMATION_MAX_FRAME_COUNT,
341
+ ) -> Tuple[List[PILImage.Image], int]:
342
+ """
343
+ The device can only handle a limited number of frames in a GIF animation, due to limited processing power and memory.
344
+ This function ensures that the number of frames does not exceed the maximum allowed frames (64) and adjusts the duration per frame if necessary.
345
+
346
+ Args:
347
+ img (PILImage.Image): The image object of the GIF.
348
+ frames (List[PILImage.Image]): List of frames in the GIF.
349
+ duration_per_frame_in_ms (int, optional): Duration of each frame in milliseconds. If not provided, defaults to the duration specified in the GIF file, or 200ms if not set.
350
+ Returns:
351
+ Tuple[List[PILImage.Image], int]: A tuple containing the list of frames and the duration per frame in milliseconds.
352
+ """
353
+ # determine the optimal duration per frame if not provided
354
+ if duration_per_frame_in_ms is None:
355
+ duration_per_frame_in_ms = img.info.get("duration", default_duration_per_frame)
356
+ # if the value we get is not reasonable, compute alternative value
357
+ if (
358
+ not isinstance(duration_per_frame_in_ms, int)
359
+ or not duration_per_frame_in_ms
360
+ or duration_per_frame_in_ms <= 0
361
+ ):
362
+ if len(frames) > max_total_frame_count:
363
+ # if the number of frames exceeds the maximum allowed frames, set the duration so that exactly max_total_frame_count frames fit into the total duration limit
364
+ duration_per_frame_in_ms = total_duration_limit_ms / max_total_frame_count
365
+ else:
366
+ # compute the duration per frame based on the number of frames and the default total duration
367
+ duration_per_frame_in_ms = default_total_duration / len(frames)
368
+
369
+ if duration_per_frame_in_ms < 16:
370
+ # make sure the duration is at least 16ms (60fps), otherwise the device might not be able to handle it
371
+ duration_per_frame_in_ms = 16
372
+
373
+ # make sure the duration of the full animation doesn't exceed (duration_per_frame_in_ms * 64)
374
+ # because otherwise the upload takes a very long time. If using the given duration_per_frame_in_ms exceeds the limit,
375
+ # intermediate frames are skipped to keep the total count of frames below max_total_frame_count.
376
+ original_frame_count = len(frames)
377
+ original_duration = original_frame_count * duration_per_frame_in_ms
378
+ if original_duration > total_duration_limit_ms:
379
+ # if the total duration limit is exceeded, skip frames (except for the first and last one) to stay within the limit
380
+ result_frames = [frames[0], frames[-1]] # always keep the first and last frame
381
+
382
+ number_of_frames_to_keep = int(
383
+ total_duration_limit_ms / duration_per_frame_in_ms) - 2 # -2 because we keep the first and last frame
384
+ number_of_frames_to_keep = min(max_total_frame_count - 2, number_of_frames_to_keep)
385
+
386
+ if number_of_frames_to_keep >= original_frame_count:
387
+ # if the number of frames to keep is greater than or equal to the available frames, do nothing
388
+ return frames, duration_per_frame_in_ms
389
+
390
+ frames_excluding_first_and_last = frames[1:-1]
391
+ # evenly select number_of_frames_to_keep frames from frames_excluding_first_and_last and insert them into result_frames between the first and last frame
392
+ step = len(frames_excluding_first_and_last) // number_of_frames_to_keep
393
+ for i in range(0, len(frames_excluding_first_and_last), step):
394
+ if len(result_frames) < max_total_frame_count - 1:
395
+ result_frames.insert(-1, frames_excluding_first_and_last[i])
396
+ frames = result_frames
397
+
398
+ logging.debug(f"GIF original frame count: {original_frame_count}")
399
+ logging.debug(f"GIF adjusted frame count: {len(frames)}")
400
+ logging.debug(f"GIF duration per frame: {duration_per_frame_in_ms} ms")
401
+ logging.debug(f"GIF total duration: {len(frames) * duration_per_frame_in_ms} ms")
402
+
403
+ return frames, duration_per_frame_in_ms
@@ -0,0 +1,71 @@
1
+ import logging
2
+
3
+ from idotmatrix import protocol
4
+ from idotmatrix.modules import IDotMatrixModule
5
+ from idotmatrix.protocol import build_command
6
+ from idotmatrix.util import color_utils
7
+
8
+ MAX_PIXEL_LIST_LENGTH = 255 # trial and error
9
+
10
+
11
+ class GraffitiModule(IDotMatrixModule):
12
+ """This class contains the Graffiti controls for the iDotMatrix device."""
13
+
14
+ logging = logging.getLogger(__name__)
15
+
16
+ async def set_pixel(
17
+ self,
18
+ color: tuple[int, int, int] | int | str,
19
+ xy: tuple[int, int],
20
+ ):
21
+ """
22
+ Set a pixel on the device to the given color
23
+
24
+ Args:
25
+ color (tuple or str): Color in RGB format as a tuple of three integers (r, g, b) or a string in hex format (#RRGGBB or 0xRRGGBB).
26
+ xy (tuple): Coordinates on the screen as a tuple of two integers (x, y).
27
+ """
28
+ color = color_utils.parse_color_rgb(color)
29
+ data = self._create_payload(
30
+ r=color[0], g=color[1], b=color[2],
31
+ xys=[xy]
32
+ )
33
+
34
+ await self._send_bytes(data=data, sleep_after=0.02)
35
+
36
+ async def set_pixels(
37
+ self,
38
+ color: tuple[int, int, int] | int | str,
39
+ xys: list[tuple[int, int]]
40
+ ):
41
+ """
42
+ Set multiple pixels on the device to the given color
43
+
44
+ Args:
45
+ color (tuple or str): Color in RGB format as a tuple of three integers (r, g, b) or a string in hex format (#RRGGBB or 0xRRGGBB).
46
+ xys (list of tuples): List of coordinates on the screen as tuples of two integers (x, y).
47
+ """
48
+ color = color_utils.parse_color_rgb(color)
49
+ data = self._create_payload(
50
+ r=color[0], g=color[1], b=color[2],
51
+ xys=xys
52
+ )
53
+
54
+ # using response=True here works better than trying to time the sleep
55
+ await self._send_bytes(data=data, response=True)
56
+
57
+ @staticmethod
58
+ def _create_payload(
59
+ r: int, g: int, b: int,
60
+ xys: list[tuple[int, int]]
61
+ ) -> bytearray:
62
+ if len(xys) > MAX_PIXEL_LIST_LENGTH:
63
+ raise ValueError("xys coordinate list must have length <= {}".format(MAX_PIXEL_LIST_LENGTH))
64
+
65
+ # the subcommand is the mirroring mode 1-4; TODO: support these
66
+ return build_command(
67
+ protocol.GRAFFITI,
68
+ 0, # ???
69
+ r % 256, g % 256, b % 256, # R, G, B and the coordinates have to be within byte range
70
+ *[coordinate for xy in xys for coordinate in xy],
71
+ )