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,702 @@
1
+ import asyncio
2
+ import logging
3
+ import time
4
+ from asyncio import Task
5
+ from collections.abc import Callable
6
+ from typing import List, Optional, Awaitable, Any
7
+
8
+ from bleak import BleakScanner, AdvertisementData
9
+ from bleak.backends.device import BLEDevice
10
+
11
+ from . import protocol
12
+ from .const import BLUETOOTH_DEVICE_NAME
13
+ from .protocol import build_command
14
+ from .transport import Transport, BleakTransport
15
+ from .util.command_ack import is_acknowledged_command
16
+ from .util.upload_ack import UploadStatus, parse_upload_notification
17
+
18
+
19
+ class ConnectionListener:
20
+ def __init__(
21
+ self,
22
+ on_connected: Optional[Callable[[], Awaitable[Any]]],
23
+ on_disconnected: Optional[Callable[[], Awaitable[Any]]],
24
+ ):
25
+ """
26
+ Initializes the ConnectionListener with optional callbacks for connection events.
27
+ Args:
28
+ on_connected (Optional[Callable[None, Awaitable[Any]]]): Async callback function to be called when connected.
29
+ on_disconnected (Optional[Callable[None, Awaitable[Any]]]): Async callback function to be called when disconnected.
30
+ """
31
+ self.on_connected = on_connected
32
+ self.on_disconnected = on_disconnected
33
+
34
+
35
+ # the official app gives up on an upload if the device does not acknowledge a chunk within 5 seconds
36
+ UPLOAD_ACK_TIMEOUT_SECONDS = 5
37
+
38
+ # the device answers normal commands within a few milliseconds
39
+ COMMAND_ACK_TIMEOUT_SECONDS = 1
40
+
41
+ # a command that the device rejects (status 0) on purpose: it changes nothing, but its answer proves that the device is alive
42
+ HEARTBEAT_COMMAND = bytes(build_command(protocol.BRIGHTNESS, 255))
43
+ HEARTBEAT_ACK_TIMEOUT_SECONDS = 3
44
+
45
+ RECONNECT_INITIAL_DELAY_SECONDS = 5
46
+ RECONNECT_MAX_DELAY_SECONDS = 60
47
+
48
+
49
+ class UploadError(Exception):
50
+ """The device rejected an upload or did not acknowledge it."""
51
+
52
+
53
+ class CommandRejectedError(Exception):
54
+ """The device rejected the arguments of a command."""
55
+
56
+
57
+ class ConnectionManager:
58
+ logging = logging.getLogger(__name__)
59
+
60
+ def __init__(
61
+ self,
62
+ address: Optional[str] = None,
63
+ max_ble_packet_size: Optional[int] = None,
64
+ transport_factory: Optional[Callable[[str | BLEDevice, Callable[[], None]], Transport]] = None,
65
+ install_signal_handlers: bool = True,
66
+ ) -> None:
67
+ """
68
+ Initializes the ConnectionManager with an optional Bluetooth address.
69
+ Args:
70
+ address (Optional[str]): The Bluetooth address (MAC) of the iDotMatrix device, f.e. "00:11:22:33:44:55".
71
+ If no address is provided, the instance can be used to discover devices and set the address later.
72
+ max_ble_packet_size (Optional[int]): Overrides the maximum payload size of a single write-without-response.
73
+ Only needed if the BLE stack misreports the negotiated MTU. By default, it is detected on connect.
74
+ transport_factory (Optional[Callable[[str | BLEDevice, Callable[[], None]], Transport]]): Creates the
75
+ `Transport` for an address (or a `BLEDevice`, see `set_device`). It gets a callback that has to be called when
76
+ the connection was lost. By default, a `BleakTransport` is used. Use it to connect in a different way, f.e. with
77
+ the client that Home Assistant provides, or to test code against a fake device.
78
+ install_signal_handlers (bool): Whether to close the connection on SIGINT and SIGTERM, which replaces the
79
+ handlers of these signals of the event loop. Turn it off if the application handles them itself.
80
+ """
81
+ self._max_ble_packet_size_override = max_ble_packet_size
82
+ self.address: Optional[str] = None
83
+ self._transport_factory = transport_factory or BleakTransport
84
+ self._transport: Optional[Transport] = None
85
+ self._transport_target: str | BLEDevice | None = None # what to connect to
86
+ self._transport_created_for: str | BLEDevice | None = None # what the current transport was created for
87
+
88
+ if address:
89
+ self.set_address(address)
90
+
91
+ self._connected = False
92
+ self._lock = asyncio.Lock()
93
+ # commands and uploads must not be mixed, f.e. an acknowledgement belongs to the last command written
94
+ self._io_lock = asyncio.Lock()
95
+
96
+ self._heartbeat_interval: Optional[float] = None
97
+ self._heartbeat_task: Optional[Task] = None
98
+ self._last_activity = time.monotonic()
99
+
100
+ self._auto_reconnect = False
101
+ self._is_auto_reconnect_active = False
102
+ self._reconnect_loop_task: Optional[Task] = None
103
+
104
+ self._ble_packet_size = None
105
+
106
+ self._notifications: asyncio.Queue[bytes] = asyncio.Queue()
107
+ self._notifications_available = False
108
+
109
+ self._connection_listeners: List[ConnectionListener] = []
110
+
111
+ if install_signal_handlers:
112
+ self._setup_signal_handlers()
113
+
114
+ @staticmethod
115
+ async def discover_devices() -> List[str]:
116
+ """
117
+ Discovers iDotMatrix Bluetooth devices.
118
+ Scans for devices with names starting with the defined BLUETOOTH_DEVICE_NAME.
119
+ Returns:
120
+ List[str]: A list of Bluetooth addresses (MAC) of discovered iDotMatrix devices.
121
+ """
122
+ ConnectionManager.logging.info("scanning for iDotMatrix bluetooth devices...")
123
+ devices = await BleakScanner.discover(return_adv=True)
124
+ filtered_devices: List[str] = []
125
+ for key, (device, adv) in devices.items():
126
+ if (
127
+ isinstance(adv, AdvertisementData)
128
+ and adv.local_name
129
+ and str(adv.local_name).startswith(BLUETOOTH_DEVICE_NAME)
130
+ ):
131
+ ConnectionManager.logging.info(f"found device {key} with name {adv.local_name}")
132
+ filtered_devices.append(device.address)
133
+ return filtered_devices
134
+
135
+ def set_address(self, address: str) -> None:
136
+ """
137
+ Sets the Bluetooth address (MAC) of the iDotMatrix device.
138
+ Args:
139
+ address (str): The Bluetooth address (MAC) of the iDotMatrix device, f.e. "00:11:22:33:44:55".
140
+ """
141
+ self.address = address
142
+ self._transport_target = address
143
+ self._create_transport()
144
+
145
+ def set_device(self, device: BLEDevice) -> None:
146
+ """
147
+ Sets the device to connect to as a `BLEDevice`, f.e. one that a scanner of Home Assistant found, which knows
148
+ how to reach the device (f.e. over a Bluetooth proxy). Call it again with the newer `BLEDevice` when the
149
+ scanner found the device again. An established connection is not interrupted, the new device is used for
150
+ the next connection.
151
+ Args:
152
+ device (BLEDevice): The iDotMatrix device.
153
+ """
154
+ same_device = self.address == device.address
155
+ self.address = device.address
156
+ self._transport_target = device
157
+ if not (same_device and self.is_connected()):
158
+ self._create_transport()
159
+
160
+ def _create_transport(self) -> Transport:
161
+ """
162
+ Creates a transport for the address or device that was set, unless the current one already is for it.
163
+ Returns:
164
+ Transport: A transport for the device.
165
+ Raises:
166
+ ValueError: If neither an address nor a device was set.
167
+ """
168
+ target = self._transport_target
169
+ if target is None:
170
+ raise ValueError("No address provided for the transport.")
171
+
172
+ if self._transport and self._transport_created_for == target:
173
+ self.logging.debug(f"reusing existing transport for {self.address}")
174
+ return self._transport
175
+
176
+ if self._transport:
177
+ # a transport is bound to one device, so a different one needs a new transport
178
+ self._connected = False
179
+ self._ble_packet_size = None
180
+
181
+ self._transport = self._transport_factory(target, self._on_disconnected)
182
+ self._transport_created_for = target
183
+ return self._transport
184
+
185
+ async def connect_by_address(self, address: str) -> None:
186
+ """
187
+ Connects to the iDotMatrix device using the provided address.
188
+ Args:
189
+ address (str): The Bluetooth address (MAC) of the iDotMatrix device, f.e. "00:11:22:33:44:55".
190
+ """
191
+ self.set_address(address)
192
+ await self.connect()
193
+
194
+ async def connect_by_discovery(self) -> str:
195
+ """
196
+ Connects to the first discovered iDotMatrix device.
197
+ If no devices are found, an error message is logged.
198
+ Returns:
199
+ str: The address of the connected device
200
+ Raises:
201
+ AssertionError: If no iDotMatrix devices are found during discovery.
202
+ """
203
+ devices = await self.discover_devices()
204
+ if devices:
205
+ device = devices[0]
206
+ # connect to first device
207
+ self.set_address(device)
208
+ await self.connect()
209
+ return device
210
+ raise AssertionError(
211
+ "No iDotMatrix devices found. Please ensure the device is powered on, in range, and not connected to another device.")
212
+
213
+ async def connect(self) -> None:
214
+ """
215
+ Connects to the device using the address set in the ConnectionManager.
216
+ If the client is already connected, it does nothing.
217
+ Raises:
218
+ ValueError: If the device address is not set.
219
+ """
220
+ if not self.address:
221
+ # discovery calls connect() again, so it must run before the (non-reentrant) lock is taken
222
+ self.logging.warning("device address is not set, trying to connect by discovery...")
223
+ await self.connect_by_discovery()
224
+ return
225
+
226
+ newly_connected = False
227
+ async with self._lock:
228
+ if self._auto_reconnect:
229
+ self._is_auto_reconnect_active = True
230
+
231
+ if not self.is_connected():
232
+ self.logging.info(f"connecting to {self.address}...")
233
+ self._create_transport() # a newer device may have been set while connected
234
+ await self._transport.connect()
235
+ self._connected = True
236
+ newly_connected = True
237
+ # the negotiated MTU can differ between connections, so it has to be detected again
238
+ self._ble_packet_size = None
239
+ self.logging.info(f"connected to {self.address}")
240
+ self._last_activity = time.monotonic()
241
+ await self._subscribe_to_notifications()
242
+ self._update_heartbeat()
243
+ else:
244
+ self.logging.info(f"already connected to {self.address}")
245
+
246
+ if newly_connected:
247
+ self._notify_connection_listeners_connected()
248
+
249
+ async def disconnect(self) -> None:
250
+ """
251
+ Disconnects from the device if connected.
252
+ If the client is not connected, this method does nothing.
253
+ """
254
+ # Disable auto-reconnect during active disconnection, it will be re-enabled on active connection attempt
255
+ self._is_auto_reconnect_active = False
256
+ self._stop_heartbeat()
257
+ async with self._lock:
258
+ if self._reconnect_loop_task:
259
+ self._reconnect_loop_task.cancel()
260
+ self._reconnect_loop_task = None
261
+ if self.is_connected():
262
+ await self._transport.disconnect()
263
+ self._connected = False
264
+
265
+ def is_connected(self) -> bool:
266
+ """
267
+ Checks if the client is connected to the device.
268
+ Returns:
269
+ bool: True if connected, False otherwise.
270
+ """
271
+ if not self._transport:
272
+ return False
273
+ return self._transport.is_connected or self._connected
274
+
275
+ async def send_bytes(
276
+ self,
277
+ data: bytearray | bytes,
278
+ response=False,
279
+ wait_for_ack: bool | None = None,
280
+ ) -> bool:
281
+ """
282
+ Sends raw data to the device.
283
+
284
+ Args:
285
+ data (bytearray | bytes): The data to send to the device.
286
+ response (bool): If True, a write-with-response operation will be used, otherwise a write-without-response operation will be used.
287
+ wait_for_ack (bool | None): Whether to wait for the acknowledgement of the device (`05 00 <command> <subcommand> <status>`)
288
+ and raise a `CommandRejectedError` if the device rejected the arguments of the command. By default (None) it is
289
+ waited for commands the device is known to acknowledge (see `util/command_ack.py`). A missing acknowledgement
290
+ is logged, but not an error.
291
+ Returns:
292
+ bool: True if the device acknowledged the command, so it is done with it.
293
+ Raises:
294
+ CommandRejectedError: If the device rejects the command.
295
+ """
296
+ async with self._io_lock:
297
+ if not self.is_connected():
298
+ await self.connect()
299
+
300
+ if wait_for_ack is None:
301
+ wait_for_ack = is_acknowledged_command(data)
302
+ wait_for_ack = wait_for_ack and self._notifications_available
303
+ if wait_for_ack:
304
+ # leftovers of earlier commands must not be taken for the acknowledgement of this one
305
+ self._notifications = asyncio.Queue()
306
+
307
+ await self._write_chunks(data, response)
308
+
309
+ return wait_for_ack and await self._wait_for_command_ack(bytes(data))
310
+
311
+ async def _write_chunks(self, data: bytearray | bytes, response: bool) -> None:
312
+ self.logging.debug("sending raw data to device")
313
+ ble_packet_size = await self.get_max_bytes_per_chunk(response)
314
+ chunk_count = -(-len(data) // ble_packet_size)
315
+ for packet in range(0, len(data), ble_packet_size):
316
+ self.logging.debug(f"sending chunk {packet // ble_packet_size + 1} of {chunk_count}")
317
+ await self._transport.write(data[packet:packet + ble_packet_size], response=response)
318
+
319
+ async def request(
320
+ self,
321
+ data: bytearray | bytes,
322
+ response: bool = True,
323
+ timeout: float = COMMAND_ACK_TIMEOUT_SECONDS,
324
+ ) -> Optional[bytes]:
325
+ """
326
+ Sends a command and returns the notification that the device answers it with, for commands that are
327
+ answered with data instead of a status (f.e. `CommonModule.get_device_info`). The answer starts with the
328
+ length, then the command and subcommand byte of the request.
329
+
330
+ Args:
331
+ data: The command.
332
+ response: Whether to use a write with response.
333
+ timeout: How long to wait for the answer.
334
+ Returns:
335
+ The notification, or None if the device did not answer in time or notifications are not available.
336
+ """
337
+ async with self._io_lock:
338
+ if not self.is_connected():
339
+ await self.connect()
340
+ if not self._notifications_available:
341
+ await self._write_chunks(data, response)
342
+ return None
343
+ self._notifications = asyncio.Queue()
344
+ await self._write_chunks(data, response)
345
+ try:
346
+ async with asyncio.timeout(timeout):
347
+ while True:
348
+ notification = await self._notifications.get()
349
+ if len(notification) >= 4 and (notification[2], notification[3]) == (data[2], data[3]):
350
+ return notification
351
+ except TimeoutError:
352
+ self.logging.warning(f"the device did not answer the command {bytes(data).hex()} within {timeout} seconds")
353
+ return None
354
+
355
+ async def _wait_for_command_ack(self, command: bytes, timeout: float = None) -> bool:
356
+ """
357
+ Waits for the acknowledgement of a command, which has the form `05 00 <command> <subcommand> <status>`.
358
+ Returns:
359
+ bool: True if the device acknowledged the command, False if it did not answer in time.
360
+ Raises:
361
+ CommandRejectedError: If the device answers with status 0.
362
+ """
363
+ expected = (command[2], command[3])
364
+ try:
365
+ async with asyncio.timeout(timeout or COMMAND_ACK_TIMEOUT_SECONDS):
366
+ while True:
367
+ notification = await self._notifications.get()
368
+ if len(notification) >= 5 and notification[0:2] == b"\x05\x00" and \
369
+ (notification[2], notification[3]) == expected:
370
+ break
371
+ except TimeoutError:
372
+ self.logging.warning(
373
+ f"the device did not acknowledge the command {command.hex()} within {timeout or COMMAND_ACK_TIMEOUT_SECONDS} seconds")
374
+ return False
375
+
376
+ if notification[4] == 0:
377
+ raise CommandRejectedError(
378
+ f"the device rejected the command {command.hex()} (notification {notification.hex()})")
379
+ return True
380
+
381
+ async def _subscribe_to_notifications(self) -> None:
382
+ """
383
+ Subscribes to the notifications of the device, which acknowledge the chunks of an upload.
384
+ """
385
+ self._notifications = asyncio.Queue()
386
+ try:
387
+ await self._transport.start_notify(self._on_notification)
388
+ self._notifications_available = True
389
+ except Exception as e:
390
+ self._notifications_available = False
391
+ self.logging.warning(f"could not subscribe to device notifications, uploads are not flow controlled: {e}")
392
+
393
+ def _on_notification(self, data: bytes) -> None:
394
+ self.logging.debug(f"received notification: {bytes(data).hex()}")
395
+ self._last_activity = time.monotonic()
396
+ self._notifications.put_nowait(bytes(data))
397
+
398
+ async def _wait_for_upload_status(self) -> UploadStatus:
399
+ """
400
+ Waits for the device to acknowledge an upload chunk.
401
+ Raises:
402
+ UploadError: If the device rejects the upload or does not answer in time.
403
+ """
404
+ try:
405
+ async with asyncio.timeout(UPLOAD_ACK_TIMEOUT_SECONDS):
406
+ while True:
407
+ notification = await self._notifications.get()
408
+ status = parse_upload_notification(notification)
409
+ if status is not None:
410
+ break
411
+ except TimeoutError:
412
+ raise UploadError(
413
+ f"the device did not acknowledge the upload within {UPLOAD_ACK_TIMEOUT_SECONDS} seconds") from None
414
+
415
+ if status == UploadStatus.ERROR:
416
+ raise UploadError(f"the device rejected the upload (notification {notification.hex()})")
417
+ return status
418
+
419
+ async def send_packets(
420
+ self,
421
+ packets: List[List[bytearray | bytes]],
422
+ response: bool = False,
423
+ wait_for_ack: bool = False,
424
+ ):
425
+ """
426
+ Sends multiple packets to the device.
427
+ Each packet is a list of bytearrays or bytes, which will be sent sequentially.
428
+ The structure of the packets depends on the command being sent to the device.
429
+ If the data needs to be sent in chunks, the caller needs to ensure that the packets are split accordingly.
430
+ Keep in mind that there are two chunking mechanisms:
431
+ 1. The outer chunking for the data itself, which is defined in the protocol for a command.
432
+ 2. The inner chunking for transmitting over BLE, which is defined by the MTU size of the BLE connection, or the protocol of the command.
433
+ Args:
434
+ packets: A list of packets, where each packet is a list of bytearrays or bytes.
435
+ response: If True, a write-with-response operation will be used, otherwise a write-without-response operation will be used.
436
+ wait_for_ack: If True, the device has to acknowledge each packet before the next one is sent. This is how
437
+ the official app transfers images and GIFs, the device drops or garbles data that is sent too early.
438
+ Raises:
439
+ UploadError: If wait_for_ack is set and the device rejects a packet or does not answer in time.
440
+ """
441
+ async with self._io_lock:
442
+ if len(packets) == 0:
443
+ self.logging.warning("no packets to send, skipping")
444
+ return
445
+ if not self.is_connected():
446
+ await self.connect()
447
+
448
+ total_byte_count = 0
449
+ for packet in packets:
450
+ for ble_packet in packet:
451
+ total_byte_count += len(ble_packet)
452
+
453
+ self.logging.debug(
454
+ 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"
455
+ )
456
+
457
+ # All but the last BLE packet of each packet are sent without response,
458
+ # so every one of them has to fit into a single write-without-response.
459
+ ble_packet_size = await self.get_max_bytes_per_chunk(response=False)
460
+ self.logging.debug(f"ble_packet_size size is {ble_packet_size} bytes")
461
+ packets = self._split_oversized_ble_packets(packets, ble_packet_size)
462
+
463
+ wait_for_ack = wait_for_ack and self._notifications_available
464
+ if wait_for_ack:
465
+ # leftovers of earlier commands must not be taken for the acknowledgement of the first packet
466
+ self._notifications = asyncio.Queue()
467
+
468
+ for i, packet in enumerate(packets):
469
+ for j, ble_paket in enumerate(packet):
470
+ self.logging.debug(f"sending packet {i + 1}.{j + 1} of {len(packets)}.{len(packets[-1])}")
471
+ wait_for_response = response if j == len(packet) - 1 else False
472
+ await self._transport.write(ble_paket, response=wait_for_response)
473
+ if wait_for_ack:
474
+ status = await self._wait_for_upload_status()
475
+ if status == UploadStatus.FINISHED and i < len(packets) - 1:
476
+ # f.e. the device already has the same data stored
477
+ self.logging.debug("the device reports the upload as finished, skipping the remaining packets")
478
+ return
479
+
480
+ @staticmethod
481
+ def _split_oversized_ble_packets(
482
+ packets: List[List[bytearray | bytes]],
483
+ max_size: int,
484
+ ) -> List[List[bytearray | bytes]]:
485
+ """
486
+ Splits BLE packets that are larger than max_size into multiple BLE packets.
487
+ Packets that already fit are passed through unchanged, and packets are never merged,
488
+ so commands that rely on their own packet boundaries are not affected.
489
+ The device reassembles the byte stream, so the BLE packet size is not part of the protocol.
490
+ Args:
491
+ packets: A list of packets, where each packet is a list of bytearrays or bytes.
492
+ max_size: The maximum size of a single BLE packet.
493
+ Returns:
494
+ The packets, with every BLE packet being at most max_size bytes long.
495
+ """
496
+ return [
497
+ [
498
+ ble_packet[offset:offset + max_size]
499
+ for ble_packet in packet
500
+ for offset in range(0, max(len(ble_packet), 1), max_size)
501
+ ]
502
+ for packet in packets
503
+ ]
504
+
505
+ async def get_max_bytes_per_chunk(self, response: bool) -> int:
506
+ if response:
507
+ # Maximum write size with response is limited to 512 bytes
508
+ # see: https://bleak.readthedocs.io/en/latest/api/client.html#bleak.BleakClient.write_gatt_char
509
+ return 512
510
+ else:
511
+ if self._ble_packet_size is None:
512
+ self._ble_packet_size = await self._detect_max_write_without_response_size()
513
+ self.logging.info(f"using a BLE packet size of {self._ble_packet_size} bytes")
514
+
515
+ return self._ble_packet_size
516
+
517
+ async def _detect_max_write_without_response_size(self) -> int:
518
+ """
519
+ Determines the maximum payload of a single write-without-response on the current connection.
520
+ """
521
+ if self._max_ble_packet_size_override:
522
+ return self._max_ble_packet_size_override
523
+ return await self._transport.max_write_without_response_size()
524
+
525
+ async def read(self) -> bytes:
526
+ if not self._transport.is_connected:
527
+ await self.connect()
528
+ data = await self._transport.read()
529
+ self.logging.info("data received")
530
+ return data
531
+
532
+ def add_connection_listener(self, listener: ConnectionListener):
533
+ """
534
+ Adds a connection listener to the ConnectionManager.
535
+ Args:
536
+ listener (ConnectionListener): The listener to be added. It should implement the on_connected and on_disconnected methods.
537
+ """
538
+ self._connection_listeners.append(listener)
539
+
540
+ def _notify_connection_listeners_connected(self):
541
+ """
542
+ Notifies all registered connection listeners that the device has been connected.
543
+ """
544
+ for listener in self._connection_listeners:
545
+ if listener.on_connected:
546
+ asyncio.ensure_future(listener.on_connected())
547
+
548
+ def _on_disconnected(self):
549
+ """
550
+ Callback function that is called when the transport lost the connection.
551
+ It notifies all registered connection listeners about the disconnection.
552
+ """
553
+ if not self.is_connected():
554
+ return
555
+
556
+ self.logging.info(f"disconnected from {self.address}")
557
+ self._handle_disconnect()
558
+
559
+ def _handle_disconnect(self):
560
+ """
561
+ Reacts to a lost connection: informs the listeners and starts to reconnect if that is enabled.
562
+ """
563
+ if not self._connected:
564
+ return
565
+ self._connected = False
566
+ self._stop_heartbeat()
567
+ for listener in self._connection_listeners:
568
+ if listener.on_disconnected:
569
+ asyncio.ensure_future(listener.on_disconnected())
570
+
571
+ if self._auto_reconnect and self._is_auto_reconnect_active:
572
+ self.logging.info("auto-reconnect is enabled, trying to reconnect...")
573
+ # Start the reconnect loop if not already running
574
+ if self._reconnect_loop_task is None or self._reconnect_loop_task.done():
575
+ self._reconnect_loop_task = asyncio.create_task(self._reconnect_loop())
576
+
577
+ def set_heartbeat(self, interval_seconds: Optional[float]) -> None:
578
+ """
579
+ Enables or disables a heartbeat that detects a link that died without the BLE stack noticing, which can
580
+ happen when the device is powered off or goes out of range. While nothing was received from the device for
581
+ the given time, a command is sent that the device answers without changing anything. If the answer is
582
+ missing, the link is closed, the connection listeners are informed and, if enabled, the connection is
583
+ restored (see `set_auto_reconnect`).
584
+ Args:
585
+ interval_seconds (Optional[float]): How long the device may be silent before it is checked, or None to disable.
586
+ Raises:
587
+ ValueError: If the interval is not positive.
588
+ """
589
+ if interval_seconds is not None and interval_seconds <= 0:
590
+ raise ValueError("The heartbeat interval must be greater than 0 seconds.")
591
+ self._heartbeat_interval = interval_seconds
592
+ self._update_heartbeat()
593
+
594
+ def _update_heartbeat(self) -> None:
595
+ """Starts or stops the heartbeat task, depending on the settings and the state of the connection."""
596
+ self._stop_heartbeat()
597
+ if self._heartbeat_interval and self._connected and self._notifications_available:
598
+ self._heartbeat_task = asyncio.create_task(self._heartbeat_loop())
599
+
600
+ def _stop_heartbeat(self) -> None:
601
+ if self._heartbeat_task:
602
+ if self._heartbeat_task is not asyncio.current_task():
603
+ self._heartbeat_task.cancel()
604
+ self._heartbeat_task = None
605
+
606
+ async def _heartbeat_loop(self):
607
+ interval = self._heartbeat_interval
608
+ while True:
609
+ # anything the device sends proves that it is alive, so there is no need to ask
610
+ silent_for = time.monotonic() - self._last_activity
611
+ if silent_for < interval:
612
+ await asyncio.sleep(interval - silent_for)
613
+ continue
614
+
615
+ if not await self._device_answers():
616
+ self.logging.warning(f"the device does not answer, closing the connection to {self.address}")
617
+ await self._close_dead_link()
618
+ return
619
+
620
+ async def _device_answers(self) -> bool:
621
+ try:
622
+ async with self._io_lock:
623
+ self._notifications = asyncio.Queue()
624
+ await self._transport.write(HEARTBEAT_COMMAND, response=True)
625
+ try:
626
+ return await self._wait_for_command_ack(HEARTBEAT_COMMAND, HEARTBEAT_ACK_TIMEOUT_SECONDS)
627
+ except CommandRejectedError:
628
+ return True # rejected on purpose
629
+ except asyncio.CancelledError:
630
+ raise
631
+ except Exception as e:
632
+ self.logging.warning(f"could not reach the device: {e}")
633
+ return False
634
+
635
+ async def _close_dead_link(self):
636
+ """Closes a link that does not work anymore, so that a fresh connection can be made."""
637
+ self._handle_disconnect()
638
+ try:
639
+ async with asyncio.timeout(HEARTBEAT_ACK_TIMEOUT_SECONDS):
640
+ await self._transport.disconnect()
641
+ except Exception as e:
642
+ self.logging.debug(f"error while closing the dead link: {e}")
643
+ # the old transport may still believe that it is connected, so it is not used again
644
+ self._transport = None
645
+ self._create_transport()
646
+
647
+ async def _reconnect_loop(self):
648
+ """
649
+ A loop that attempts to reconnect to the device if the connection is lost.
650
+ It will keep trying to reconnect until it succeeds or the auto-reconnect is disabled.
651
+ """
652
+ delay = RECONNECT_INITIAL_DELAY_SECONDS
653
+ while self._auto_reconnect and self._is_auto_reconnect_active and not self.is_connected():
654
+ try:
655
+ await asyncio.sleep(delay) # Wait before trying to reconnect
656
+ # back off, so a device that is off or out of range is not hammered with attempts
657
+ delay = min(delay * 2, RECONNECT_MAX_DELAY_SECONDS)
658
+ await self.connect()
659
+ except asyncio.CancelledError:
660
+ self.logging.info("Reconnection loop cancelled.")
661
+ break
662
+ except Exception as e:
663
+ self.logging.error(f"Reconnection attempt failed: {e}")
664
+
665
+ def set_auto_reconnect(self, auto_reconnect: bool) -> None:
666
+ """
667
+ Sets whether the client should automatically reconnect to the device if the connection is lost.
668
+ Args:
669
+ auto_reconnect (bool): True to enable auto-reconnect, False to disable.
670
+ """
671
+ self._auto_reconnect = auto_reconnect
672
+ self._is_auto_reconnect_active = True
673
+
674
+ def _setup_signal_handlers(self):
675
+ """
676
+ Sets up signal handlers for graceful shutdown.
677
+ This is useful to ensure that the connection is properly closed when the application is terminated.
678
+ """
679
+ import signal
680
+ async def async_signal_handler():
681
+ """
682
+ Handles the signal to stop the slideshow gracefully.
683
+ """
684
+ await self.disconnect()
685
+
686
+ def signal_handler(signum):
687
+ signame = signal.Signals(signum).name
688
+ logging.info(f'Signal handler called with signal {signame} ({signum})')
689
+ asyncio.ensure_future(async_signal_handler())
690
+
691
+ try:
692
+ loop = asyncio.get_event_loop()
693
+ loop.add_signal_handler(signal.SIGINT, lambda: signal_handler(signal.SIGINT))
694
+ loop.add_signal_handler(signal.SIGTERM, lambda: signal_handler(signal.SIGTERM))
695
+ except (NotImplementedError, RuntimeError) as e:
696
+ # NotImplementedError: add_signal_handler() isn't supported on
697
+ # Windows, by any event loop (Proactor or Selector).
698
+ # RuntimeError: no running event loop yet (e.g. ConnectionManager
699
+ # constructed at plain module import time, before an event loop
700
+ # has started).
701
+ logging.debug(f"signal handlers are not supported in this context, skipping: {e}")
702
+