idotmatrix-api-client 0.2.2__tar.gz → 0.3.0__tar.gz

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 (67) hide show
  1. {idotmatrix_api_client-0.2.2 → idotmatrix_api_client-0.3.0}/PKG-INFO +9 -1
  2. {idotmatrix_api_client-0.2.2 → idotmatrix_api_client-0.3.0}/README.md +8 -0
  3. {idotmatrix_api_client-0.2.2 → idotmatrix_api_client-0.3.0}/idotmatrix/client.py +9 -0
  4. {idotmatrix_api_client-0.2.2 → idotmatrix_api_client-0.3.0}/idotmatrix/connection_manager.py +23 -6
  5. {idotmatrix_api_client-0.2.2 → idotmatrix_api_client-0.3.0}/idotmatrix/modules/gif.py +202 -31
  6. {idotmatrix_api_client-0.2.2 → idotmatrix_api_client-0.3.0}/idotmatrix/modules/image.py +63 -15
  7. idotmatrix_api_client-0.3.0/idotmatrix/modules/materials.py +213 -0
  8. {idotmatrix_api_client-0.2.2 → idotmatrix_api_client-0.3.0}/idotmatrix/util/command_ack.py +1 -0
  9. idotmatrix_api_client-0.3.0/idotmatrix/util/device_material.py +36 -0
  10. {idotmatrix_api_client-0.2.2 → idotmatrix_api_client-0.3.0}/idotmatrix/util/image_utils.py +37 -2
  11. idotmatrix_api_client-0.3.0/idotmatrix/util/overlay.py +95 -0
  12. idotmatrix_api_client-0.3.0/idotmatrix/util/quality.py +50 -0
  13. {idotmatrix_api_client-0.2.2 → idotmatrix_api_client-0.3.0}/pyproject.toml +1 -1
  14. idotmatrix_api_client-0.2.2/idotmatrix/util/device_material.py +0 -16
  15. {idotmatrix_api_client-0.2.2 → idotmatrix_api_client-0.3.0}/LICENSE +0 -0
  16. {idotmatrix_api_client-0.2.2 → idotmatrix_api_client-0.3.0}/idotmatrix/__init__.py +0 -0
  17. {idotmatrix_api_client-0.2.2 → idotmatrix_api_client-0.3.0}/idotmatrix/apps/__init__.py +0 -0
  18. {idotmatrix_api_client-0.2.2 → idotmatrix_api_client-0.3.0}/idotmatrix/apps/digital_picture_frame.py +0 -0
  19. {idotmatrix_api_client-0.2.2 → idotmatrix_api_client-0.3.0}/idotmatrix/const.py +0 -0
  20. {idotmatrix_api_client-0.2.2 → idotmatrix_api_client-0.3.0}/idotmatrix/fonts/16-ErbosDraco1StOpenNbpRegular-l5wX.ttf +0 -0
  21. {idotmatrix_api_client-0.2.2 → idotmatrix_api_client-0.3.0}/idotmatrix/fonts/16-MinecraftStandard.otf +0 -0
  22. {idotmatrix_api_client-0.2.2 → idotmatrix_api_client-0.3.0}/idotmatrix/fonts/16-MinecraftStandardBoldOblique.otf +0 -0
  23. {idotmatrix_api_client-0.2.2 → idotmatrix_api_client-0.3.0}/idotmatrix/fonts/16-PixelOperator8-Bold.ttf +0 -0
  24. {idotmatrix_api_client-0.2.2 → idotmatrix_api_client-0.3.0}/idotmatrix/fonts/16-PixelOperator8.ttf +0 -0
  25. {idotmatrix_api_client-0.2.2 → idotmatrix_api_client-0.3.0}/idotmatrix/fonts/16-PixelifySans-Regular.ttf +0 -0
  26. {idotmatrix_api_client-0.2.2 → idotmatrix_api_client-0.3.0}/idotmatrix/fonts/16-PressStart2P-Regular.ttf +0 -0
  27. {idotmatrix_api_client-0.2.2 → idotmatrix_api_client-0.3.0}/idotmatrix/fonts/16-dogica.ttf +0 -0
  28. {idotmatrix_api_client-0.2.2 → idotmatrix_api_client-0.3.0}/idotmatrix/fonts/16-dogicabold.ttf +0 -0
  29. {idotmatrix_api_client-0.2.2 → idotmatrix_api_client-0.3.0}/idotmatrix/fonts/16-dogicapixel.ttf +0 -0
  30. {idotmatrix_api_client-0.2.2 → idotmatrix_api_client-0.3.0}/idotmatrix/fonts/16-dogicapixelbold.ttf +0 -0
  31. {idotmatrix_api_client-0.2.2 → idotmatrix_api_client-0.3.0}/idotmatrix/fonts/16_32-HomeVideo-BLG6G.ttf +0 -0
  32. {idotmatrix_api_client-0.2.2 → idotmatrix_api_client-0.3.0}/idotmatrix/fonts/16_32-HomeVideoBold-R90Dv.ttf +0 -0
  33. {idotmatrix_api_client-0.2.2 → idotmatrix_api_client-0.3.0}/idotmatrix/fonts/16_32-MayfairNbpBold-gAA4.ttf +0 -0
  34. {idotmatrix_api_client-0.2.2 → idotmatrix_api_client-0.3.0}/idotmatrix/fonts/32-Jersey10-Regular.ttf +0 -0
  35. {idotmatrix_api_client-0.2.2 → idotmatrix_api_client-0.3.0}/idotmatrix/fonts/CC-BY-SA-4.0-License.txt +0 -0
  36. {idotmatrix_api_client-0.2.2 → idotmatrix_api_client-0.3.0}/idotmatrix/fonts/ErbosDraco-License.txt +0 -0
  37. {idotmatrix_api_client-0.2.2 → idotmatrix_api_client-0.3.0}/idotmatrix/fonts/HomeVideo-License.txt +0 -0
  38. {idotmatrix_api_client-0.2.2 → idotmatrix_api_client-0.3.0}/idotmatrix/fonts/Jersey10-Regular-License.txt +0 -0
  39. {idotmatrix_api_client-0.2.2 → idotmatrix_api_client-0.3.0}/idotmatrix/fonts/MayfairNbpBold-License.txt +0 -0
  40. {idotmatrix_api_client-0.2.2 → idotmatrix_api_client-0.3.0}/idotmatrix/fonts/MinecraftStandard-License.txt +0 -0
  41. {idotmatrix_api_client-0.2.2 → idotmatrix_api_client-0.3.0}/idotmatrix/fonts/PixelOperator-License.txt +0 -0
  42. {idotmatrix_api_client-0.2.2 → idotmatrix_api_client-0.3.0}/idotmatrix/fonts/PixelifySans-License.txt +0 -0
  43. {idotmatrix_api_client-0.2.2 → idotmatrix_api_client-0.3.0}/idotmatrix/fonts/PressStart2P-Regular-License.txt +0 -0
  44. {idotmatrix_api_client-0.2.2 → idotmatrix_api_client-0.3.0}/idotmatrix/fonts/Rain-DRM3-License.txt +0 -0
  45. {idotmatrix_api_client-0.2.2 → idotmatrix_api_client-0.3.0}/idotmatrix/fonts/Rain-DRM3.otf +0 -0
  46. {idotmatrix_api_client-0.2.2 → idotmatrix_api_client-0.3.0}/idotmatrix/fonts/dogica_license.txt +0 -0
  47. {idotmatrix_api_client-0.2.2 → idotmatrix_api_client-0.3.0}/idotmatrix/modules/__init__.py +0 -0
  48. {idotmatrix_api_client-0.2.2 → idotmatrix_api_client-0.3.0}/idotmatrix/modules/chronograph.py +0 -0
  49. {idotmatrix_api_client-0.2.2 → idotmatrix_api_client-0.3.0}/idotmatrix/modules/clock.py +0 -0
  50. {idotmatrix_api_client-0.2.2 → idotmatrix_api_client-0.3.0}/idotmatrix/modules/common.py +0 -0
  51. {idotmatrix_api_client-0.2.2 → idotmatrix_api_client-0.3.0}/idotmatrix/modules/countdown.py +0 -0
  52. {idotmatrix_api_client-0.2.2 → idotmatrix_api_client-0.3.0}/idotmatrix/modules/eco.py +0 -0
  53. {idotmatrix_api_client-0.2.2 → idotmatrix_api_client-0.3.0}/idotmatrix/modules/effect.py +0 -0
  54. {idotmatrix_api_client-0.2.2 → idotmatrix_api_client-0.3.0}/idotmatrix/modules/fullscreen_color.py +0 -0
  55. {idotmatrix_api_client-0.2.2 → idotmatrix_api_client-0.3.0}/idotmatrix/modules/graffiti.py +0 -0
  56. {idotmatrix_api_client-0.2.2 → idotmatrix_api_client-0.3.0}/idotmatrix/modules/music_sync.py +0 -0
  57. {idotmatrix_api_client-0.2.2 → idotmatrix_api_client-0.3.0}/idotmatrix/modules/scoreboard.py +0 -0
  58. {idotmatrix_api_client-0.2.2 → idotmatrix_api_client-0.3.0}/idotmatrix/modules/system.py +0 -0
  59. {idotmatrix_api_client-0.2.2 → idotmatrix_api_client-0.3.0}/idotmatrix/modules/text.py +0 -0
  60. {idotmatrix_api_client-0.2.2 → idotmatrix_api_client-0.3.0}/idotmatrix/protocol.py +0 -0
  61. {idotmatrix_api_client-0.2.2 → idotmatrix_api_client-0.3.0}/idotmatrix/screensize.py +0 -0
  62. {idotmatrix_api_client-0.2.2 → idotmatrix_api_client-0.3.0}/idotmatrix/transport.py +0 -0
  63. {idotmatrix_api_client-0.2.2 → idotmatrix_api_client-0.3.0}/idotmatrix/util/__init__.py +0 -0
  64. {idotmatrix_api_client-0.2.2 → idotmatrix_api_client-0.3.0}/idotmatrix/util/color_utils.py +0 -0
  65. {idotmatrix_api_client-0.2.2 → idotmatrix_api_client-0.3.0}/idotmatrix/util/device_info.py +0 -0
  66. {idotmatrix_api_client-0.2.2 → idotmatrix_api_client-0.3.0}/idotmatrix/util/file_watch.py +0 -0
  67. {idotmatrix_api_client-0.2.2 → idotmatrix_api_client-0.3.0}/idotmatrix/util/upload_ack.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: idotmatrix-api-client
3
- Version: 0.2.2
3
+ Version: 0.3.0
4
4
  Summary: A library for controlling iDotMatrix displays.
5
5
  License-Expression: GPL-3.0-or-later
6
6
  License-File: LICENSE
@@ -151,6 +151,14 @@ await client.image.show_image_file("photo.jpg", resize_mode=ResizeMode.FILL)
151
151
 
152
152
  # show an animated GIF
153
153
  await client.gif.upload_gif_file("animation.gif")
154
+
155
+ # label a picture or every frame of a GIF (the text is drawn at the size of the screen, before the colors are reduced)
156
+ from idotmatrix.util.overlay import TextOverlay
157
+ await client.gif.upload_gif_file("animation.gif", overlay=TextOverlay("64c", position="top-right"))
158
+
159
+ # store files in the slots of the device, which then cycles through them on its own (no uploads during the show)
160
+ await client.materials.store(["a.gif", "b.png", "c.gif"], slots=[1, 2, 3], display_time=30)
161
+ # the module remembers what is in which slot: storing again only transfers what is new, in any order
154
162
  ```
155
163
 
156
164
  Both can be mixed freely, no mode switching is needed in between. They work like the official app, which waits
@@ -133,6 +133,14 @@ await client.image.show_image_file("photo.jpg", resize_mode=ResizeMode.FILL)
133
133
 
134
134
  # show an animated GIF
135
135
  await client.gif.upload_gif_file("animation.gif")
136
+
137
+ # label a picture or every frame of a GIF (the text is drawn at the size of the screen, before the colors are reduced)
138
+ from idotmatrix.util.overlay import TextOverlay
139
+ await client.gif.upload_gif_file("animation.gif", overlay=TextOverlay("64c", position="top-right"))
140
+
141
+ # store files in the slots of the device, which then cycles through them on its own (no uploads during the show)
142
+ await client.materials.store(["a.gif", "b.png", "c.gif"], slots=[1, 2, 3], display_time=30)
143
+ # the module remembers what is in which slot: storing again only transfers what is new, in any order
136
144
  ```
137
145
 
138
146
  Both can be mixed freely, no mode switching is needed in between. They work like the official app, which waits
@@ -15,6 +15,7 @@ from idotmatrix.modules.fullscreen_color import FullscreenColorModule
15
15
  from idotmatrix.modules.gif import GifModule
16
16
  from idotmatrix.modules.graffiti import GraffitiModule
17
17
  from idotmatrix.modules.image import ImageModule
18
+ from idotmatrix.modules.materials import MaterialsModule
18
19
  from idotmatrix.modules.music_sync import MusicSyncModule
19
20
  from idotmatrix.modules.scoreboard import ScoreboardModule
20
21
  from idotmatrix.modules.system import SystemModule
@@ -152,6 +153,14 @@ class IDotMatrixClient:
152
153
  screen_size=self.screen_size
153
154
  )
154
155
 
156
+ @cached_property
157
+ def materials(self) -> MaterialsModule:
158
+ return MaterialsModule(
159
+ connection_manager=self._connection_manager,
160
+ gif=self.gif,
161
+ image=self.image,
162
+ )
163
+
155
164
  @cached_property
156
165
  def music_sync(self) -> MusicSyncModule:
157
166
  return MusicSyncModule(
@@ -462,20 +462,33 @@ class ConnectionManager:
462
462
  f"sending {len(packets)} packet(s) in chunks of size {len(packets[0][0])} bytes to device, for a total size of {total_byte_count} bytes"
463
463
  )
464
464
 
465
- # All but the last BLE packet of each packet are sent without response,
465
+ wait_for_ack = wait_for_ack and self._notifications_available
466
+ # Uploads write every BLE packet with response, like the official app: each write is answered by the device,
467
+ # so the Bluetooth stack (f.e. an ESPHome proxy) cannot drop packets of a burst, which the device answers
468
+ # by never acknowledging the chunk or by rebooting.
469
+ every_packet_with_response = wait_for_ack and response
470
+
471
+ # Otherwise all but the last BLE packet of each packet are sent without response,
466
472
  # so every one of them has to fit into a single write-without-response.
467
- ble_packet_size = await self.get_max_bytes_per_chunk(response=False)
473
+ ble_packet_size = await self.get_max_bytes_per_chunk(response=every_packet_with_response)
474
+ if every_packet_with_response:
475
+ ble_packet_size = min(ble_packet_size, await self.get_max_bytes_per_chunk(response=False))
468
476
  self.logging.debug(f"ble_packet_size size is {ble_packet_size} bytes")
469
477
  packets = self._split_oversized_ble_packets(packets, ble_packet_size)
470
478
 
471
- wait_for_ack = wait_for_ack and self._notifications_available
472
479
  if wait_for_ack:
473
480
  # leftovers of earlier commands must not be taken for the acknowledgement of the first packet
474
481
  self._notifications = asyncio.Queue()
475
482
 
476
483
  for i, packet in enumerate(packets):
477
484
  deadline = asyncio.get_running_loop().time() + UPLOAD_ACK_TIMEOUT_SECONDS
478
- await self._write_chunk(packet, response, paced=wait_for_ack, label=f"{i + 1} of {len(packets)}")
485
+ await self._write_chunk(
486
+ packet,
487
+ response,
488
+ all_with_response=every_packet_with_response,
489
+ paced=wait_for_ack and not every_packet_with_response,
490
+ label=f"{i + 1} of {len(packets)}",
491
+ )
479
492
  if wait_for_ack:
480
493
  status = await self._wait_for_upload_status(deadline)
481
494
  if status == UploadStatus.FINISHED and i < len(packets) - 1:
@@ -483,12 +496,15 @@ class ConnectionManager:
483
496
  self.logging.debug("the device reports the upload as finished, skipping the remaining packets")
484
497
  return
485
498
 
486
- async def _write_chunk(self, packet: List[bytearray | bytes], response: bool, paced: bool, label: str):
499
+ async def _write_chunk(
500
+ self, packet: List[bytearray | bytes], response: bool, all_with_response: bool, paced: bool, label: str
501
+ ):
487
502
  """
488
503
  Writes the BLE packets of one packet. Only the last one is written with a response, if requested.
489
504
  Args:
490
505
  packet: The BLE packets to write.
491
506
  response: If True, the last BLE packet is written with response.
507
+ all_with_response: If True, every BLE packet is written with response.
492
508
  paced: If True, the writes are spaced `UPLOAD_WRITE_INTERVAL_SECONDS` apart.
493
509
  label: Describes the packet in the log.
494
510
  """
@@ -496,7 +512,8 @@ class ConnectionManager:
496
512
  if paced and j > 0:
497
513
  await asyncio.sleep(UPLOAD_WRITE_INTERVAL_SECONDS)
498
514
  self.logging.debug(f"sending packet {label}.{j + 1} of {len(packet)}")
499
- await self._transport.write(ble_packet, response=response if j == len(packet) - 1 else False)
515
+ with_response = all_with_response or (response and j == len(packet) - 1)
516
+ await self._transport.write(ble_packet, response=with_response)
500
517
 
501
518
  @staticmethod
502
519
  def _split_oversized_ble_packets(
@@ -13,14 +13,21 @@ from idotmatrix.modules import IDotMatrixModule
13
13
  from idotmatrix.protocol import build_command
14
14
  from idotmatrix.screensize import ScreenSize
15
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
16
+ from idotmatrix.util.device_material import (
17
+ DEFAULT_DISPLAY_TIME_SECONDS, INDEX_SHOW_NOW, convert_display_time, validate_display_time, validate_slot,
18
+ )
19
+ from idotmatrix.util.image_utils import ResizeMode, validate_colors
20
+ from idotmatrix.util.overlay import TextOverlay
21
+ from idotmatrix.util.quality import DEFAULT_MAX_COLOR_ERROR, color_error, color_score
18
22
 
19
23
  ANIMATION_MAX_FRAME_COUNT = 64 # Maximum number of frames in a GIF animation
20
24
  DEFAULT_DURATION_PER_FRAME_MS = 200 # Default duration per frame in milliseconds if not specified in the GIF file
21
25
  ANIMATION_TOTAL_DURATION_LIMIT_MS = 2000
22
26
  DEFAULT_ANIMATION_TOTAL_DURATION_MS = ANIMATION_TOTAL_DURATION_LIMIT_MS
23
27
 
28
+ AUTO_COLORS = "auto"
29
+ AUTO_COLOR_STEPS = (256, 128, 64, 32, 16)
30
+
24
31
  # --- Constants based on the Java code ---
25
32
  CHUNK_SIZE_4096 = 4096
26
33
  HEADER_SIZE_GIF = 16 # As per sendImageData logic in GifAgreement.java
@@ -47,9 +54,16 @@ class GifModule(IDotMatrixModule):
47
54
  palletize: bool = True,
48
55
  background_color: Tuple[int, int, int] | int | str = (0, 0, 0),
49
56
  duration_per_frame_in_ms: int = None,
57
+ slot: int | None = None,
58
+ display_time: int = DEFAULT_DISPLAY_TIME_SECONDS,
59
+ colors: int | str = 256,
60
+ max_size_kb: int | None = None,
61
+ overlay: TextOverlay | None = None,
62
+ shared_palette: bool = False,
63
+ max_color_error: float = DEFAULT_MAX_COLOR_ERROR,
50
64
  ):
51
65
  """
52
- Uploads a GIF file to the device.
66
+ Uploads a GIF file to the device. It is shown right away, unless a slot is given.
53
67
 
54
68
  Args:
55
69
  file_path (str): path to the image file
@@ -58,7 +72,35 @@ class GifModule(IDotMatrixModule):
58
72
  high detail (like photos) but good for pixel-art or other content with high contrasts. Defaults to True.
59
73
  background_color (Tuple[int, int, int]): RGB color to fill transparent pixels. Defaults to black (0, 0, 0).
60
74
  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.
75
+ slot (int, optional): If given (0 to 11), the GIF is stored in that slot of the device instead of being shown
76
+ right away. The device cycles through the stored items by itself, see `MaterialsModule`.
77
+ display_time (int): Seconds the stored item stays on screen in that cycle. Only used with a slot.
78
+ colors (int | str): The number of colors of the palette (2 to 256), or "auto". Fewer colors make the
79
+ upload smaller and
80
+ faster (16 colors are about a third of the size of 256 for a photo-like animation), at the price of
81
+ rougher colors. Less than 256 reduces the colors even if `palletize` is off.
82
+ max_size_kb (int, optional): The most the converted GIF may have, which is what is transferred (a large
83
+ one takes 10 s or more). If it is bigger, quality is given up until it fits, in this order: colors
84
+ (down to 32), frames (every 2nd, 3rd, ... frame, the animation takes as long as before), then colors
85
+ down to 8 and frames again. If it still does not fit the smallest version is used and a warning is
86
+ logged.
87
+ overlay (TextOverlay, optional): A text that is drawn on top of every frame, f.e. to label it.
88
+ shared_palette (bool): One palette for all frames instead of one for each, which can flicker when the
89
+ colors differ from frame to frame (it also changes the colors a little more). Not for "auto".
90
+ max_color_error (float): With colors="auto": the GIF with the fewest bytes whose color error is at most
91
+ this is used. The error is the mean color difference to the GIF with 256 colors (delta E) plus 8 times the
92
+ flicker. On a 64x64 up to 5 looks good, up to 9 is still acceptable but duller, more looks broken
93
+ (about 3 is nearly lossless). The palette sizes 256 to 16 are tried, with a palette for each frame
94
+ and with a shared one.
61
95
  """
96
+ if colors != AUTO_COLORS:
97
+ validate_colors(colors)
98
+ if max_size_kb is not None and (isinstance(max_size_kb, bool) or not isinstance(max_size_kb, int)
99
+ or max_size_kb < 1):
100
+ raise ValueError(f"max_size_kb must be a positive number, got: {max_size_kb!r}")
101
+ if slot is not None:
102
+ validate_slot(slot)
103
+ validate_display_time(display_time)
62
104
  screen_width = self.screen_size.value[0] # assuming square canvas, so width == height
63
105
  background_color = color_utils.parse_color_rgb(background_color)
64
106
 
@@ -71,6 +113,11 @@ class GifModule(IDotMatrixModule):
71
113
  palletize=palletize,
72
114
  background_color=background_color,
73
115
  duration_per_frame_in_ms=duration_per_frame_in_ms,
116
+ colors=colors,
117
+ max_size_kb=max_size_kb,
118
+ overlay=overlay,
119
+ shared_palette=shared_palette,
120
+ max_color_error=max_color_error,
74
121
  )
75
122
 
76
123
  # If the device already has the exact same GIF stored, it answers the first chunk with "finished"
@@ -82,8 +129,9 @@ class GifModule(IDotMatrixModule):
82
129
  # this might be the index that this GIF will be stored within the device's memory :think:
83
130
  # it doesn't seem to have an effect when sending a single GIF like it is done here though
84
131
  # shows the GIF right away, like the official app does
85
- gif_type=INDEX_SHOW_NOW,
132
+ gif_type=INDEX_SHOW_NOW if slot is None else slot,
86
133
  time_sign=0,
134
+ display_time=None if slot is None else display_time,
87
135
  )
88
136
  await self._send_packets(packets=packets, response=True, wait_for_ack=True)
89
137
 
@@ -105,6 +153,11 @@ class GifModule(IDotMatrixModule):
105
153
  palletize: bool = True,
106
154
  background_color: Tuple[int, int, int] = (0, 0, 0),
107
155
  duration_per_frame_in_ms: int = None,
156
+ colors: int | str = 256,
157
+ max_size_kb: int | None = None,
158
+ overlay: TextOverlay | None = None,
159
+ shared_palette: bool = False,
160
+ max_color_error: float = DEFAULT_MAX_COLOR_ERROR,
108
161
  ) -> bytes:
109
162
  """
110
163
  Loads a GIF file and adapts it to the pixel size of the device's canvas.
@@ -120,6 +173,11 @@ class GifModule(IDotMatrixModule):
120
173
  palletize (bool): Whether to convert the image to a color palette. Defaults to True.
121
174
  background_color (Tuple[int, int, int]): Background color to fill transparent pixels.
122
175
  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.
176
+ colors (int): The number of colors of the palette (2 to 256).
177
+ max_size_kb (int, optional): The size the GIF may have at most, see `upload_gif_file`.
178
+ overlay (TextOverlay, optional): A text that is drawn on top of every frame.
179
+ shared_palette (bool): One palette for all frames.
180
+ max_color_error (float): The limit for colors="auto", see `upload_gif_file`.
123
181
  Returns:
124
182
  bytes: A byte representation of the GIF file, adapted to fit the pixel size.
125
183
  """
@@ -145,8 +203,8 @@ class GifModule(IDotMatrixModule):
145
203
  background_color=background_color,
146
204
  mode="RGBA",
147
205
  )
148
- if palletize:
149
- frame = image_utils.palettize(frame)
206
+ if overlay is not None:
207
+ frame = overlay.apply(frame)
150
208
 
151
209
  frames.append(frame.copy())
152
210
  img.seek(img.tell() + 1)
@@ -157,26 +215,138 @@ class GifModule(IDotMatrixModule):
157
215
  img, frames, duration_per_frame_in_ms
158
216
  )
159
217
 
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()
218
+ # TODO: there are still some cases where
219
+ # - the GIF is not animating all frames
220
+
221
+ shared = shared_palette
222
+ if colors == AUTO_COLORS:
223
+ data, colors, shared = self._encode_gif_auto(frames, duration_per_frame_in_ms, max_color_error)
224
+ if max_size_kb is None or len(data) <= max_size_kb * 1024:
225
+ return data
226
+ palletize = True
227
+ if max_size_kb is None:
228
+ return self._encode_gif(frames, duration_per_frame_in_ms, colors, palletize, shared)
229
+ return self._encode_gif_within(frames, duration_per_frame_in_ms, colors, palletize, max_size_kb, shared)
230
+
231
+ @staticmethod
232
+ def _reduce_colors(
233
+ frames: List[PILImage.Image], colors: int, palletize: bool, shared: bool = False
234
+ ) -> List[PILImage.Image]:
235
+ """Gives the frames a palette of `colors` colors, one for each frame or a shared one."""
236
+ if shared:
237
+ return image_utils.palettize_together(frames, colors=colors)
238
+ if palletize or colors < 256:
239
+ return [image_utils.palettize(frame, colors=colors) for frame in frames]
240
+ return frames
241
+
242
+ @staticmethod
243
+ def _save_gif(frames: List[PILImage.Image], duration_per_frame_in_ms: int, colors: int) -> bytes:
244
+ """Writes the frames as a GIF whose frames all have a color table of the same size."""
245
+ # all frames need color tables of the same size, or the device garbles / drops frames
246
+ table_size = image_utils.palette_table_size(colors)
247
+ frames = [image_utils.pad_palette(frame, table_size) for frame in frames]
248
+
249
+ gif_buffer = io.BytesIO()
250
+ # take the first frame, append the rest as additional frames and save as GIF into gif_buffer
251
+ frames[0].save(
252
+ gif_buffer,
253
+ format="GIF",
254
+ save_all=True,
255
+ optimize=False, # True would shrink the color tables to the number of used colors again
256
+ append_images=frames[1:],
257
+ loop=0, # loop forever
258
+ duration=duration_per_frame_in_ms,
259
+ disposal=2, # Restore to background color after each frame
260
+ )
261
+ gif_buffer.seek(0)
262
+ return gif_buffer.getvalue()
263
+
264
+ def _encode_gif(
265
+ self, frames: List[PILImage.Image], duration_per_frame_in_ms: int, colors: int, palletize: bool,
266
+ shared: bool = False
267
+ ) -> bytes:
268
+ """Encodes the frames as a GIF whose frames all have a color table of the same size."""
269
+ return self._save_gif(self._reduce_colors(frames, colors, palletize, shared), duration_per_frame_in_ms, colors)
270
+
271
+ def _encode_gif_auto(
272
+ self, frames: List[PILImage.Image], duration_per_frame_in_ms: int, max_color_error: float
273
+ ) -> Tuple[bytes, int, bool]:
274
+ """
275
+ Finds the GIF with the fewest bytes whose color error (compared to the same GIF with 256 colors for each
276
+ frame) is at most `max_color_error`, among palettes of 256 to 16 colors, for each frame or shared. If none is
277
+ good enough the one with the lowest error is used.
278
+ Returns the GIF, its number of colors and whether the palette is shared.
279
+ """
280
+ # compared to the GIF with all colors, which is what the limit was calibrated on
281
+ reference = [frame.convert("RGB") for frame in self._reduce_colors(frames, 256, True)]
282
+ best = None # (size, data, colors, shared) of the smallest that is good enough
283
+ closest = None # (score, data, colors, shared)
284
+ for colors in AUTO_COLOR_STEPS:
285
+ for shared in (False, True):
286
+ reduced = self._reduce_colors(frames, colors, True, shared)
287
+ data = self._save_gif(reduced, duration_per_frame_in_ms, colors)
288
+ score = color_score(*color_error(reference, [frame.convert("RGB") for frame in reduced]))
289
+ if score <= max_color_error and (best is None or len(data) < best[0]):
290
+ best = (len(data), data, colors, shared)
291
+ if closest is None or score < closest[0]:
292
+ closest = (score, data, colors, shared)
293
+ if best is not None:
294
+ _, data, colors, shared = best
295
+ else:
296
+ score, data, colors, shared = closest
297
+ self.logging.warning(
298
+ f"no palette is within the color error {max_color_error}, using the best ({score:.1f})")
299
+ self.logging.info(f"{colors} colors{', shared palette' if shared else ''} ({len(data) / 1024:.0f} KB)")
300
+ return data, colors, shared
301
+
302
+ def _encode_gif_within(
303
+ self,
304
+ frames: List[PILImage.Image],
305
+ duration_per_frame_in_ms: int,
306
+ colors: int,
307
+ palletize: bool,
308
+ max_size_kb: int,
309
+ shared: bool = False,
310
+ ) -> bytes:
311
+ """
312
+ Encodes the frames as a GIF of at most `max_size_kb` KB if that is possible, by taking the first of
313
+ `_size_reductions` that fits, and the smallest one otherwise.
314
+ """
315
+ limit = max_size_kb * 1024
316
+ smallest = None
317
+ for step_colors, every in self._size_reductions(colors, len(frames)):
318
+ kept = frames[::every]
319
+ if every > 1 and frames[-1] is not kept[-1] and len(kept) > 1:
320
+ kept[-1] = frames[-1] # the animation still ends where it did
321
+ data = self._encode_gif(kept, duration_per_frame_in_ms * every, step_colors, palletize, shared)
322
+ if len(data) <= limit:
323
+ if (step_colors, every) != (colors, 1):
324
+ self.logging.info(
325
+ f"GIF reduced to {step_colors} colors and every {every}. frame to fit {max_size_kb} KB "
326
+ f"({len(data) / 1024:.0f} KB)")
327
+ return data
328
+ if smallest is None or len(data) < len(smallest):
329
+ smallest = data
330
+ self.logging.warning(f"GIF does not fit {max_size_kb} KB, using the smallest version ({len(smallest) / 1024:.0f} KB)")
331
+ return smallest
332
+
333
+ @staticmethod
334
+ def _size_reductions(colors: int, frame_count: int) -> List[Tuple[int, int]]:
335
+ """
336
+ What to give up to make a GIF smaller, from the least to the most visible: first colors down to 32, then every
337
+ second, third, ... frame (the duration of the animation stays the same), then fewer colors with all frames
338
+ again. Returns (colors, keep every n-th frame), starting with what was asked for.
339
+ """
340
+ steps = [(c, 1) for c in (256, 128, 64, 32) if c <= colors]
341
+ if not steps or steps[0][0] != colors:
342
+ steps.insert(0, (colors, 1))
343
+ floor = min(colors, 32)
344
+ every_steps = [n for n in (2, 3, 4, 6, 8) if frame_count // n >= 2]
345
+ steps += [(floor, n) for n in every_steps]
346
+ for fewer in (16, 8):
347
+ if fewer < floor:
348
+ steps += [(fewer, 1)] + [(fewer, n) for n in every_steps]
349
+ return steps
180
350
 
181
351
  def _int_to_bytes_le(self, value: int, length: int = 4) -> bytearray:
182
352
  """Converts an integer to a little-endian bytearray of specified length."""
@@ -208,7 +378,8 @@ class GifModule(IDotMatrixModule):
208
378
  gif_data: bytes,
209
379
  gif_type: int,
210
380
  time_sign: int, # Assuming this is the raw time signature before DeviceMaterialTimeConvert.ConvertTime
211
- ble_device_mtu_enabled: bool = True
381
+ ble_device_mtu_enabled: bool = True,
382
+ display_time: int | None = None,
212
383
  ) -> list[list[bytearray]]:
213
384
  """
214
385
  Creates packets for sending GIF data, mirroring the Java GifAgreement logic.
@@ -217,6 +388,7 @@ class GifModule(IDotMatrixModule):
217
388
  gif_data: The raw byte array of the GIF data.
218
389
  gif_type: The type parameter (e.g., 12 or other values from sendImageData). Values up until 19 display an image on the device.
219
390
  time_sign: 0: "0", 1: "10", 2: "30", 3: "60", 4: "300", else: "5".
391
+ display_time: The display time in seconds. If given it is used instead of the one `time_sign` stands for.
220
392
  ble_device_mtu_enabled: Boolean indicating if MTU is enabled on the BLE device.
221
393
 
222
394
  Returns:
@@ -269,11 +441,10 @@ class GifModule(IDotMatrixModule):
269
441
  else:
270
442
  # Java: DeviceMaterialTimeConvert.ConvertTime(AppData.getInstance().getTimeSign())
271
443
  # '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...)
444
+ converted_time_value = display_time if display_time is not None else convert_display_time(time_sign)
273
445
 
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]
446
+ # little endian, like every other number of the header (the app does the same)
447
+ header[13:15] = converted_time_value.to_bytes(2, byteorder='little')
277
448
 
278
449
  header[15] = gif_type & 0xFF # Ensure it's a byte
279
450
 
@@ -13,7 +13,11 @@ from idotmatrix.connection_manager import ConnectionManager
13
13
  from idotmatrix.modules import IDotMatrixModule
14
14
  from idotmatrix.screensize import ScreenSize
15
15
  from idotmatrix.util import image_utils, color_utils
16
- from idotmatrix.util.device_material import INDEX_SHOW_NOW, convert_display_time
16
+ from idotmatrix.util.device_material import (
17
+ DEFAULT_DISPLAY_TIME_SECONDS, INDEX_SHOW_NOW, convert_display_time, validate_display_time, validate_slot,
18
+ )
19
+ from idotmatrix.util.image_utils import validate_colors
20
+ from idotmatrix.util.overlay import TextOverlay
17
21
 
18
22
  MTU_SIZE_IF_ENABLED = 509
19
23
  MTU_SIZE_IF_DISABLED = 18
@@ -94,6 +98,8 @@ class ImageModule(IDotMatrixModule):
94
98
  resize_mode: image_utils.ResizeMode,
95
99
  palletize: bool,
96
100
  background_color: Tuple[int, int, int],
101
+ colors: int = 256,
102
+ overlay: TextOverlay | None = None,
97
103
  ) -> bytearray:
98
104
  """
99
105
  Loads an image from a file, resizes it to fit within a square canvas of pixel_size x pixel_size,
@@ -103,6 +109,8 @@ class ImageModule(IDotMatrixModule):
103
109
  canvas_size (int): Size of the square canvas in pixels.
104
110
  palletize (bool): If True, the image will be converted to a palette-based image.
105
111
  background_color (Tuple[int, int, int]): RGB color for the background, which is only visible if the input
112
+ colors (int): The number of colors of the palette that `palletize` reduces the image to.
113
+ overlay (TextOverlay, optional): A text that is drawn on top of the image.
106
114
  Returns:
107
115
  bytearray: A bytearray containing the raw pixel data of the processed image in RGB format.
108
116
  """
@@ -121,11 +129,15 @@ class ImageModule(IDotMatrixModule):
121
129
  canvas_size=canvas_size,
122
130
  resize_mode=resize_mode,
123
131
  resample_mode=resample_mode,
132
+ background_color=background_color,
124
133
  mode="RGB", # ensure the image is in RGB mode
125
134
  )
126
135
 
136
+ if overlay is not None:
137
+ img = overlay.apply(img).convert("RGB")
138
+
127
139
  if palletize:
128
- img = image_utils.palettize(img)
140
+ img = image_utils.palettize(img, colors=colors)
129
141
 
130
142
  # Convert to RGB if not already in that mode, to get the pixel data in RGB format
131
143
  mode = "RGB"
@@ -141,10 +153,15 @@ class ImageModule(IDotMatrixModule):
141
153
  resize_mode: image_utils.ResizeMode = image_utils.ResizeMode.FIT,
142
154
  palletize: bool = False,
143
155
  background_color: Tuple[int, int, int] | int | str = (0, 0, 0),
144
- png: bool = False,
156
+ png: bool = True,
157
+ slot: int | None = None,
158
+ display_time: int = DEFAULT_DISPLAY_TIME_SECONDS,
159
+ colors: int = 256,
160
+ overlay: TextOverlay | None = None,
145
161
  ) -> None:
146
162
  """
147
- Shows an image file on the device, the way the official app does it for photos.
163
+ Shows an image file on the device, the way the official app does it for photos. It is shown right away, unless
164
+ a slot is given.
148
165
 
149
166
  In contrast to `upload_image_file` this does not need `set_mode`, and it can be mixed with
150
167
  GIF uploads without any mode switching in between.
@@ -157,9 +174,22 @@ class ImageModule(IDotMatrixModule):
157
174
  background_color (Tuple[int, int, int]): RGB color for the background, which is only visible if the input
158
175
  image doesn't match the devices aspect ratio. Defaults to black (0, 0, 0).
159
176
  png (bool): If True, the image is sent as a PNG file instead of raw RGB data. That is smaller (about 25-45%
160
- for photos, more for pixel-art, and a palette PNG with `palletize`), which saves a little upload time.
161
- Experimental: tested on a 64x64 device only, the official app sends raw RGB. Defaults to False.
177
+ for photos, more for pixel-art, and a palette PNG with `palletize`), which saves a little upload time,
178
+ and it avoids a stray dark red pixel in the top row that the device draws after a raw upload. Tested
179
+ on a 64x64 device only, the official app sends raw RGB. Defaults to True.
180
+ slot (int, optional): If given (0 to 11), the image is stored in that slot of the device instead of being
181
+ shown right away. The device cycles through the stored items by itself, see `MaterialsModule`.
182
+ display_time (int): Seconds the stored item stays on screen in that cycle. Only used with a slot.
183
+ colors (int): The number of colors of the palette (2 to 256) that `palletize` reduces the image to. The
184
+ raw upload has the same size either way, with `png` fewer colors make it smaller. Less than 256 reduces
185
+ the colors even if `palletize` is off.
186
+ overlay (TextOverlay, optional): A text that is drawn on top of the image, f.e. to label it.
162
187
  """
188
+ validate_colors(colors)
189
+ palletize = palletize or colors < 256
190
+ if slot is not None:
191
+ validate_slot(slot)
192
+ validate_display_time(display_time)
163
193
  background_color = color_utils.parse_color_rgb(background_color)
164
194
  # reading and converting the file takes a while, the event loop must not be blocked
165
195
  pixel_data = await asyncio.to_thread(
@@ -169,23 +199,26 @@ class ImageModule(IDotMatrixModule):
169
199
  resize_mode=resize_mode,
170
200
  palletize=palletize,
171
201
  background_color=background_color,
202
+ colors=colors,
203
+ overlay=overlay,
172
204
  )
173
- await self._send_static_image_data(pixel_data, png=png, palette=palletize)
205
+ await self._send_static_image_data(
206
+ pixel_data, png=png, palette=palletize, slot=slot, display_time=display_time, colors=colors)
174
207
 
175
208
  async def show_image_pixeldata(
176
209
  self,
177
210
  pixel_colors: List[Tuple[int, int, int] | int | str],
178
- png: bool = False,
211
+ png: bool = True,
179
212
  ) -> None:
180
213
  """
181
214
  Shows pixel data on the device, the way the official app does it for photos. See `show_image_file`.
182
215
  Args:
183
216
  pixel_colors: One color for each pixel of the screen, row by row.
184
- png (bool): If True, the pixels are sent as a PNG file. See `show_image_file`.
217
+ png (bool): If True (the default), the pixels are sent as a PNG file. See `show_image_file`.
185
218
  """
186
219
  await self._send_static_image_data(self._pixel_colors_to_bytes(pixel_colors), png=png)
187
220
 
188
- def _encode_png(self, pixel_data: bytearray, palette: bool = False) -> bytearray:
221
+ def _encode_png(self, pixel_data: bytearray, palette: bool = False, colors: int = 256) -> bytearray:
189
222
  """
190
223
  Encodes raw RGB pixel data of the whole screen as a PNG file.
191
224
 
@@ -197,15 +230,27 @@ class ImageModule(IDotMatrixModule):
197
230
  size = self.screen_size.value[0]
198
231
  img = PILImage.frombytes("RGB", (size, size), bytes(pixel_data))
199
232
  if palette:
200
- img = img.quantize(256, dither=PILImage.Dither.NONE)
233
+ img = img.quantize(colors, dither=PILImage.Dither.NONE)
201
234
  buffer = io.BytesIO()
202
235
  img.save(buffer, "PNG", optimize=True)
203
236
  return bytearray(buffer.getvalue())
204
237
 
205
- async def _send_static_image_data(self, pixel_data: bytearray, png: bool = False, palette: bool = False) -> None:
238
+ async def _send_static_image_data(
239
+ self,
240
+ pixel_data: bytearray,
241
+ png: bool = True,
242
+ palette: bool = False,
243
+ slot: int | None = None,
244
+ display_time: int = DEFAULT_DISPLAY_TIME_SECONDS,
245
+ colors: int = 256,
246
+ ) -> None:
206
247
  if png:
207
- pixel_data = self._encode_png(pixel_data, palette=palette)
208
- packets = self._create_static_image_data_packets(pixel_data)
248
+ pixel_data = self._encode_png(pixel_data, palette=palette, colors=colors)
249
+ packets = self._create_static_image_data_packets(
250
+ pixel_data,
251
+ index=INDEX_SHOW_NOW if slot is None else slot,
252
+ display_time=None if slot is None else display_time,
253
+ )
209
254
  await self._send_packets(packets, response=True, wait_for_ack=True)
210
255
 
211
256
  def _create_static_image_data_packets(
@@ -213,6 +258,7 @@ class ImageModule(IDotMatrixModule):
213
258
  image_data: bytearray,
214
259
  index: int = INDEX_SHOW_NOW,
215
260
  time_sign: int = 0,
261
+ display_time: int | None = None,
216
262
  ) -> List[List[bytearray]]:
217
263
  """
218
264
  Creates the packets of a static image upload. This corresponds to `sendImageData` of the official app,
@@ -234,7 +280,9 @@ class ImageModule(IDotMatrixModule):
234
280
  header[4] = 2 if i > 0 else 0 # continuation / first chunk
235
281
  header[5:9] = total_length
236
282
  header[9:13] = crc32
237
- header[13:15] = convert_display_time(time_sign).to_bytes(2, "big")
283
+ header[13:15] = (
284
+ display_time if display_time is not None else convert_display_time(time_sign)
285
+ ).to_bytes(2, "little")
238
286
  header[15] = index
239
287
 
240
288
  packets.append(self._create_ble_packets(bytes(header) + chunk))