-
Notifications
You must be signed in to change notification settings - Fork 11
/
adafruit_slideshow.py
executable file
·510 lines (411 loc) · 17.5 KB
/
adafruit_slideshow.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
# SPDX-FileCopyrightText: 2018 Kattni Rembor for Adafruit Industries
#
# SPDX-License-Identifier: MIT
"""
`adafruit_slideshow`
====================================================
CircuitPython helper library for displaying a slideshow of images on a display.
* Author(s): Kattni Rembor, Carter Nelson, Rose Hooper, Melissa LeBlanc-Williams
Implementation Notes
--------------------
**Hardware:**
* `Adafruit Hallowing M0 Express <https://www.adafruit.com/product/3900>`_
**Software and Dependencies:**
* Adafruit CircuitPython firmware for the supported boards:
https://github.com/adafruit/circuitpython/releases
"""
import time
import os
import random
import displayio
try:
# text slides are an optional feature and require adafruit_display_text
from adafruit_display_text import bitmap_label
import terminalio
import json
TEXT_SLIDES_ENABLED = True
except ImportError:
print("Warning: adafruit_display_text not found. No support for text slides.")
TEXT_SLIDES_ENABLED = False
try:
# custom fonts are an optional feature and require adafruit_bitmap_font
from adafruit_bitmap_font import bitmap_font
CUSTOM_FONTS = True
except ImportError:
print("Warning: adafruit_bitmap_font not found. No support for custom fonts.")
CUSTOM_FONTS = False
try:
from typing import Optional
from pwmio import PWMOut
except ImportError:
pass
__version__ = "0.0.0+auto.0"
__repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_Slideshow.git"
class HorizontalAlignment:
"""Defines possible horizontal alignment orders."""
# pylint: disable=too-few-public-methods
LEFT = 1
CENTER = 2
RIGHT = 3
# pylint: enable=too-few-public-methods
class VerticalAlignment:
"""Defines possible vertical alignment orders."""
# pylint: disable=too-few-public-methods
TOP = 1
CENTER = 2
BOTTOM = 3
# pylint: enable=too-few-public-methods
class PlayBackOrder:
"""Defines possible slideshow playback orders."""
# pylint: disable=too-few-public-methods
ALPHABETICAL = 0
"""Orders by alphabetical sort of filenames"""
RANDOM = 1
"""Randomly shuffles the images"""
# pylint: enable=too-few-public-methods
class PlayBackDirection:
"""Defines possible slideshow playback directions."""
# pylint: disable=too-few-public-methods
BACKWARD = -1
"""The next image is before the current image. When alphabetically sorted, this is towards A."""
FORWARD = 1
"""The next image is after the current image. When alphabetically sorted, this is towards Z."""
# pylint: enable=too-few-public-methods
class SlideShow:
# pylint: disable=too-many-instance-attributes
"""
Class for displaying a slideshow of .bmp images on displays.
:param displayio.Display display: The display to use
:param PWMOut backlight_pwm: The PWMOut object used for the backlight
:param str folder: Specify the folder containing the image files, in quotes. Default is
the root directory, ``"/"``.
:param PlayBackOrder order: The order in which the images display. You can choose random
(``RANDOM``) or alphabetical (``ALPHABETICAL``). Default is
``ALPHABETICAL``.
:param bool loop: Specify whether to loop the images or play through the list once. `True`
if slideshow will continue to loop, ``False`` if it will play only once.
Default is ``True``.
:param int dwell: The number of seconds each image displays, in seconds. Default is 3.
:param bool fade_effect: Specify whether to include the fade effect between images. ``True``
tells the code to fade the backlight up and down between image display
transitions. ``False`` maintains max brightness on the backlight between
image transitions. Default is ``True``.
:param bool auto_advance: Specify whether to automatically advance after dwell seconds. ``True``
if slideshow should auto play, ``False`` if you want to control advancement
manually. Default is ``True``.
:param PlayBackDirection direction: The playback direction.
:param HorizonalAlignment h_align: The Horizontal alignment of smaller/larger images
:param VerticalAlignment v_align: The Vertical alignment of smaller/larger images
Example code for Hallowing Express. With this example, the slideshow will play through once
in alphabetical order:
.. code-block:: python
from adafruit_slideshow import PlayBackOrder, SlideShow
import board
import pwmio
slideshow = SlideShow(board.DISPLAY, pwmio.PWMOut(board.TFT_BACKLIGHT), folder="/",
loop=False, order=PlayBackOrder.ALPHABETICAL)
while slideshow.update():
pass
Example code for Hallowing Express. Sets ``dwell`` to 0 seconds, turns ``auto_advance`` off,
and uses capacitive touch to advance backwards and forwards through the images and to control
the brightness level of the backlight:
.. code-block:: python
from adafruit_slideshow import PlayBackOrder, SlideShow, PlayBackDirection
import touchio
import board
import pwmio
forward_button = touchio.TouchIn(board.TOUCH4)
back_button = touchio.TouchIn(board.TOUCH1)
brightness_up = touchio.TouchIn(board.TOUCH3)
brightness_down = touchio.TouchIn(board.TOUCH2)
slideshow = SlideShow(board.DISPLAY, pwmio.PWMOut(board.TFT_BACKLIGHT), folder="/",
auto_advance=False, dwell=0)
while True:
if forward_button.value:
slideshow.direction = PlayBackDirection.FORWARD
slideshow.advance()
if back_button.value:
slideshow.direction = PlayBackDirection.BACKWARD
slideshow.advance()
if brightness_up.value:
slideshow.brightness += 0.001
elif brightness_down.value:
slideshow.brightness -= 0.001
"""
def __init__(
self,
display: displayio.Display,
backlight_pwm: Optional[PWMOut] = None,
*,
folder: str = "/",
order: int = PlayBackOrder.ALPHABETICAL,
loop: bool = True,
dwell: int = 3,
fade_effect: bool = True,
auto_advance: bool = True,
direction: int = PlayBackDirection.FORWARD,
h_align: int = HorizontalAlignment.LEFT,
v_align: int = VerticalAlignment.TOP,
) -> None:
def _check_json_file(file: str) -> bool:
if TEXT_SLIDES_ENABLED:
if file.endswith(".json"):
with open(file) as _file_obj:
try:
json_data = json.loads(_file_obj.read())
if "text" in json_data:
return True
except ValueError:
return False
return False
self.loop = loop
"""Specifies whether to loop through the slides continuously or play through the list once.
``True`` will continue to loop, ``False`` will play only once."""
self.dwell = dwell
"""The number of seconds each slide displays, in seconds."""
self.direction = direction
"""Specify the playback direction. Default is ``PlayBackDirection.FORWARD``. Can also be
``PlayBackDirection.BACKWARD``."""
self.auto_advance = auto_advance
"""Enable auto-advance based on dwell time. Set to ``False`` to manually control."""
self.fade_effect = fade_effect
"""Whether to include the fade effect between slides. ``True`` tells the code to fade the
backlight up and down between slide display transitions. ``False`` maintains max
brightness on the backlight between slide transitions."""
# Load the image names before setting order so they can be reordered.
self._img_start = None
self._file_list = [
folder + "/" + f
for f in os.listdir(folder)
if (
not f.startswith(".")
and (f.endswith(".bmp") or _check_json_file(folder + "/" + f))
)
]
self._order = None
self.order = order
"""The order in which the images display. You can choose random (``RANDOM``) or
alphabetical (``ALPHA``)."""
# Default positioning
self._h_align = h_align
self._v_align = v_align
self._current_slide_index = -1
self._file_name = None
self._brightness = 0.5
# Setup the display
self._group = displayio.Group()
self._display = display
display.root_group = self._group
self._backlight_pwm = backlight_pwm
if (
not backlight_pwm
and fade_effect
and hasattr(self._display, "auto_brightness")
):
self._display.auto_brightness = False
# Show the first image
self.advance()
@property
def current_slide_name(self) -> str:
"""Returns the current image name."""
return self._file_list[self._current_slide_index]
@property
def order(self) -> int:
"""Specifies the order in which the images are displayed. Options are random (``RANDOM``) or
alphabetical (``ALPHABETICAL``). Default is ``RANDOM``."""
return self._order
@order.setter
def order(self, order: int) -> None:
if order not in [PlayBackOrder.ALPHABETICAL, PlayBackOrder.RANDOM]:
raise ValueError("Order must be either 'RANDOM' or 'ALPHABETICAL'")
self._order = order
self._reorder_slides()
def _reorder_slides(self) -> None:
if self.order == PlayBackOrder.ALPHABETICAL:
self._file_list = sorted(self._file_list)
elif self.order == PlayBackOrder.RANDOM:
self._file_list = sorted(self._file_list, key=lambda x: random.random())
def _set_backlight(self, brightness: float) -> None:
if self._backlight_pwm:
full_brightness = 2**16 - 1
self._backlight_pwm.duty_cycle = int(full_brightness * brightness)
else:
try:
self._display.brightness = brightness
except (RuntimeError, AttributeError):
pass
@property
def brightness(self) -> float:
"""Brightness of the backlight when an image is displaying. Clamps to 0 to 1.0"""
return self._brightness
@brightness.setter
def brightness(self, brightness: float) -> None:
if brightness < 0:
brightness = 0
elif brightness > 1.0:
brightness = 1.0
self._brightness = brightness
self._set_backlight(brightness)
def _fade_up(self) -> None:
if not self.fade_effect:
self._set_backlight(self.brightness)
return
steps = 100
for i in range(steps):
self._set_backlight(self.brightness * i / steps)
time.sleep(0.01)
def _fade_down(self) -> None:
if not self.fade_effect:
self._set_backlight(self.brightness)
return
steps = 100
for i in range(steps, -1, -1):
self._set_backlight(self.brightness * i / steps)
time.sleep(0.01)
def _create_label(self, file_name: str) -> bitmap_label.Label:
# pylint: disable=too-many-branches
"""Creates and returns a label from a file object that contains
valid valid json describing the text to use.
See: examples/sample_text_slide.json
"""
with open(file_name, "rb") as file:
json_data = json.loads(file.read())
_scale = 1
if "scale" in json_data:
_scale = int(json_data["scale"])
if CUSTOM_FONTS:
if "font" in json_data:
_font = bitmap_font.load_font(json_data["font"])
else:
_font = terminalio.FONT
else:
_font = terminalio.FONT
label = bitmap_label.Label(_font, text=json_data["text"], scale=_scale)
if "h_align" not in json_data or json_data["h_align"] == "LEFT":
x_anchor_point = 0.0
x_anchored_position = 0
elif json_data["h_align"] == "CENTER":
x_anchor_point = 0.5
x_anchored_position = self._display.width // 2
elif json_data["h_align"] == "RIGHT":
x_anchor_point = 1.0
x_anchored_position = self._display.width - 1
else:
# wrong value for align
x_anchor_point = 0.0
x_anchored_position = 0
if "v_align" not in json_data or json_data["v_align"] == "TOP":
y_anchor_point = 0.0
y_anchored_position = 0
elif json_data["v_align"] == "CENTER":
y_anchor_point = 0.5
y_anchored_position = self._display.height // 2
elif json_data["v_align"] == "BOTTOM":
y_anchor_point = 1.0
y_anchored_position = self._display.height - 1
else:
# wrong value for align
y_anchor_point = 0.0
y_anchored_position = 0
if "background_color" in json_data:
label.background_color = int(json_data["background_color"], 16)
if "color" in json_data:
label.color = int(json_data["color"], 16)
label.anchor_point = (x_anchor_point, y_anchor_point)
label.anchored_position = (x_anchored_position, y_anchored_position)
return label
def update(self) -> bool:
"""Updates the slideshow to the next image."""
now = time.monotonic()
if not self.auto_advance or now - self._img_start < self.dwell:
return True
return self.advance()
# pylint: disable=too-many-branches, too-many-statements
def advance(self) -> bool:
"""Displays the next image. Returns True when a new image was displayed, False otherwise."""
if self._file_name:
self._fade_down()
self._group.pop()
self._file_name = None
self._current_slide_index += self.direction
# Try to load slides until a valid file is found or we run out of options. This
# loop stops because we either set odb or reduce the length of _file_list.
odb = None
lbl = None
while not odb and not lbl and self._file_list:
if 0 <= self._current_slide_index < len(self._file_list):
pass
elif not self.loop:
return False
else:
slide_count = len(self._file_list)
if self._current_slide_index < 0:
self._current_slide_index += slide_count
elif self._current_slide_index >= slide_count:
self._current_slide_index -= slide_count
self._reorder_slides()
self._file_name = self._file_list[self._current_slide_index]
if self._file_name.endswith(".bmp"):
try:
odb = displayio.OnDiskBitmap(self._file_name)
except ValueError:
del self._file_list[self._current_slide_index]
self._file_name = None
elif self._file_name.endswith(".json"):
lbl = self._create_label(self._file_name)
if not odb and not lbl:
raise RuntimeError("No valid images or text json files")
if odb:
if self._h_align == HorizontalAlignment.RIGHT:
self._group.x = self._display.width - odb.width
elif self._h_align == HorizontalAlignment.CENTER:
self._group.x = round(self._display.width / 2 - odb.width / 2)
else:
self._group.x = 0
if self._v_align == VerticalAlignment.BOTTOM:
self._group.y = self._display.height - odb.height
elif self._v_align == VerticalAlignment.CENTER:
self._group.y = round(self._display.height / 2 - odb.height / 2)
else:
self._group.y = 0
image_tilegrid = displayio.TileGrid(
odb,
pixel_shader=getattr(odb, "pixel_shader", displayio.ColorConverter()),
# TODO: Once CP6 is no longer supported, replace the above line with below
# pixel_shader=odb.pixel_shader,
)
self._group.append(image_tilegrid)
if lbl:
self._group.append(lbl)
self._fade_up()
if hasattr(self._display, "refresh"):
self._display.refresh()
self._img_start = time.monotonic()
return True
# pylint: enable=too-many-branches
@property
def h_align(self) -> int:
"""Get or Set the Horizontal Alignment"""
return self._h_align
@h_align.setter
def h_align(self, val: int) -> None:
if val not in (
HorizontalAlignment.LEFT,
HorizontalAlignment.CENTER,
HorizontalAlignment.RIGHT,
):
raise ValueError("Alignment must be LEFT, RIGHT, or CENTER")
self._h_align = val
@property
def v_align(self) -> int:
"""Get or Set the Vertical Alignment"""
return self._v_align
@v_align.setter
def v_align(self, val: int) -> None:
if val not in (
VerticalAlignment.TOP,
VerticalAlignment.CENTER,
VerticalAlignment.BOTTOM,
):
raise ValueError("Alignment must be TOP, BOTTOM, or CENTER")
self._v_align = val