-
Notifications
You must be signed in to change notification settings - Fork 11
/
adafruit_slideshow.py
executable file
·342 lines (272 loc) · 12 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
# The MIT License (MIT)
#
# Copyright (c) 2018 Kattni Rembor for Adafruit Industries
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
"""
`adafruit_slideshow`
====================================================
CircuitPython helper library for displaying a slideshow of images on a display.
* Author(s): Kattni Rembor, Carter Nelson, Roy Hooper
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
__version__ = "0.0.0-auto.0"
__repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_Slideshow.git"
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 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.
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 pulseio
slideshow = SlideShow(board.DISPLAY, pulseio.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 pulseio
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, pulseio.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,
backlight_pwm=None,
*,
folder="/",
order=PlayBackOrder.ALPHABETICAL,
loop=True,
dwell=3,
fade_effect=True,
auto_advance=True,
direction=PlayBackDirection.FORWARD
):
self.loop = loop
"""Specifies whether to loop through the images 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 image 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 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."""
# 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 (f.endswith(".bmp") and not f.startswith("."))
]
self._order = None
self.order = order
"""The order in which the images display. You can choose random (``RANDOM``) or
alphabetical (``ALPHA``)."""
self._current_image = -1
self._image_file = None
self._brightness = 0.5
# 4.0.0 Beta 2 replaces Sprite with TileGrid so use either.
self._sprite_class = getattr(displayio, "Sprite", displayio.TileGrid)
# Setup the display
self._group = displayio.Group()
self._display = display
display.show(self._group)
self._backlight_pwm = backlight_pwm
if not backlight_pwm and fade_effect:
self._display.auto_brightness = False
# Show the first image
self.advance()
@property
def current_image_name(self):
"""Returns the current image name."""
return self._file_list[self._current_image]
@property
def order(self):
"""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):
if order not in [PlayBackOrder.ALPHABETICAL, PlayBackOrder.RANDOM]:
raise ValueError("Order must be either 'RANDOM' or 'ALPHABETICAL'")
self._order = order
self._reorder_images()
def _reorder_images(self):
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):
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:
pass
@property
def brightness(self):
"""Brightness of the backlight when an image is displaying. Clamps to 0 to 1.0"""
return self._brightness
@brightness.setter
def brightness(self, brightness):
if brightness < 0:
brightness = 0
elif brightness > 1.0:
brightness = 1.0
self._brightness = brightness
self._set_backlight(brightness)
def _fade_up(self):
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):
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 update(self):
"""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()
def advance(self):
"""Displays the next image. Returns True when a new image was displayed, False otherwise.
"""
if self._image_file:
self._fade_down()
self._group.pop()
self._image_file.close()
self._image_file = None
self._current_image += self.direction
# Try and load an OnDiskBitmap 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
while not odb and self._file_list:
if 0 <= self._current_image < len(self._file_list):
pass
elif not self.loop:
return False
else:
image_count = len(self._file_list)
if self._current_image < 0:
self._current_image += image_count
elif self._current_image >= image_count:
self._current_image -= image_count
self._reorder_images()
image_name = self._file_list[self._current_image]
self._image_file = open(image_name, "rb")
try:
odb = displayio.OnDiskBitmap(self._image_file)
except ValueError:
self._image_file.close()
self._image_file = None
del self._file_list[self._current_image]
if not odb:
raise RuntimeError("No valid images")
try:
sprite = self._sprite_class(odb, pixel_shader=displayio.ColorConverter())
except TypeError:
sprite = self._sprite_class(
odb, pixel_shader=displayio.ColorConverter(), position=(0, 0)
)
self._group.append(sprite)
self._fade_up()
self._img_start = time.monotonic()
return True