-
Notifications
You must be signed in to change notification settings - Fork 0
/
baedge.py
265 lines (204 loc) · 9.72 KB
/
baedge.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
""" application """
import importlib
import logging
import os
import platform
import qrcode
from PIL import Image, ImageDraw, ImageFont
import helpers as hlp
import config as cfg
# enable logging at the specified level
logging.basicConfig(level=cfg.app["logging"]["level"])
hlp.log_debug(__name__, 'detected platform: `' + platform.system() + '`')
# Waveshare's EPD library queries the content of `/proc/cpuinfo` for system information for string `Raspberry`
# This makes it cumbersome to develop on non-RPi devices, so we override `epd_library` and skip initialization
if os.path.exists("/proc/cpuinfo"):
# conditionally import the correct library depending on vartiables describing the EPD model and revision
hardware_model = cfg.baedge["hardware"]["model"]
hardware_revision = cfg.baedge["hardware"]["revision"]
hlp.log_debug(__name__, 'load EPD Library for Model `' + hardware_model + '` (Rev: `' + hardware_revision + '`)')
epd_library = importlib.import_module("lib.waveshare_epd.epd" + hardware_model + hardware_revision)
SKIP_INITIALIZE_SCREEN = False
else:
hlp.log_info(__name__, 'skip load of EPD Library on unsupported system')
epd_library = {}
# set flag to skip initialization of screen on unsupported system
SKIP_INITIALIZE_SCREEN = True
def initialize_screen():
"""
Initialize screen for use
Parameters:
n/a
Returns:
object: Object containing EPD library and configuration
"""
hlp.log_debug('initialize_screen', 'init function')
try:
epd = epd_library.EPD()
hlp.log_debug('initialize_screen', 'initialize screen')
epd.init()
hlp.log_debug('initialize_screen', 'clear screen')
epd.Clear()
hlp.log_debug('initialize_screen', 'end function')
return epd
except IOError as e:
hlp.log_exception('initialize_screen', e)
return None
def clear_screen(epd, sleep_screen=False):
"""
Clear contents on screen
Parameters:
epd (object): Object containing EPD library and configuration
sleep_screen (bool): Boolean indicating whether to sleep display or not
Returns:
bool: Boolean True if screen was cleared successfully
"""
hlp.log_debug('clear_screen', 'init function')
try:
hlp.log_debug('clear_screen', 'clear screen')
epd.Clear()
# only sleep if requested
if sleep_screen:
hlp.log_debug('clear_screen', 'sleep screen')
epd.sleep()
hlp.log_debug('clear_screen', 'end function')
return True
except IOError as e:
hlp.log_exception('clear_screen', e)
return None
def write_screen(epd, screen_name, sleep_screen=False):
"""
Write contents to screen
Parameters:
epd (object): Object containing EPD library and configuration
screen_name (string): String indicating which screen to load data from
sleep_screen (bool): Boolean indicating whether to sleep display or not
Returns:
bool: Boolean True if contents were written successfully
"""
hlp.log_debug('write_screen', 'init function')
# load screen data from common object
hlp.log_debug('write_screen', 'load screen data for `' + screen_name + '`')
screen = cfg.screens[screen_name]
hlp.log_debug('write_screen:screen', screen_name)
try:
# assemble font information
# see https://pillow.readthedocs.io/en/latest/reference/ImageFont.html#PIL.ImageFont.truetype
font = ImageFont.truetype(
screen["font"]["face"],
screen["font"]["size"],
)
# create canvas for downstream population with relevant data
# see https://pillow.readthedocs.io/en/latesmt/reference/Image.html#PIL.Image.new
canvas = Image.new(
mode=cfg.baedge["image_mode"],
size=(epd.height, epd.width),
color=255,
)
# draw initial image to canvas
draw = ImageDraw.Draw(canvas)
# iterate over shape items for screen
if "shapes" in screen:
for item in screen["shapes"]:
hlp.log_debug('write_screen:shape', item)
if "coordinates" in item and "fill" in item and "type" in item:
hlp.log_debug('write_screen:shape', "Complete data to write a shape, trying to write it")
if item["type"] == "rectangle":
hlp.log_debug('write_screen:shape', "Creating a rectangle")
draw.rectangle(item["coordinates"], fill=item["fill"])
else:
hlp.log_debug('write_screen:shape', "Unknown shape type: " + item["type"] + ", skipping")
else:
hlp.log_debug('write_screen:shape', 'incomplete data, skip write shape')
# iterate over image items for screen
if "images" in screen:
for item in screen["images"]:
hlp.log_debug('write_screen:image', item)
if "content" in item and "coordinates" in item:
content = item["content"]
coordinates = item["coordinates"]
hlp.log_debug('write_screen:image', 'write image')
image = Image.open(item["content"])
canvas.paste(image, item["coordinates"])
else:
hlp.log_debug('write_screen:image', 'incomplete data, skip write image')
# iterate over text items for screen
if "texts" in screen:
for item in screen["texts"]:
hlp.log_debug('write_screen:text', item)
if "content" in item and "coordinates" in item and "fill" in item:
text_font = font
if "font" in item and "size" in item["font"] and "face" in item["font"]:
hlp.log_debug("write_scree:text", "Overriding font with per-text specified one")
text_font = ImageFont.truetype(
item["font"]["face"],
item["font"]["size"],
)
font_size = item["font"]["size"]
else:
font_size = screen["font"]["size"]
# while the longest single line of text (based on splitting by \n, getting the longest one, and comparing its length)
# used to make the text small enough to fit on the screen
while text_font.getlength(max(item["content"].split("\n"), key=len)) > max(epd.width, epd.height):
hlp.log_debug("write_scree:text", "Overriding font size to fit on screen")
font_size -= 1
text_font = ImageFont.truetype(
screen["font"]["face"],
font_size,
)
hlp.log_debug("write_screen:text", "Final font size, adjusted for tthe screen size:" + str(font_size))
content = item["content"]
coordinates = item["coordinates"]
fill = item["fill"]
hlp.log_debug('write_screen:text', 'write text')
# assemble text object
# see https://pillow.readthedocs.io/en/latest/reference/ImageDraw.html#PIL.ImageDraw.Draw
draw.text(
coordinates,
content.lstrip(),
font=text_font,
fill=fill
)
else:
hlp.log_debug('write_screen:text', 'incomplete data, skip write text')
# check if QR Code configuration is present and prep QR code image
if "qrcode" not in screen:
hlp.log_debug('write_screen:qrcode', 'incomplete data, skip write QR code')
else:
if screen["qrcode"]["content"] and screen["qrcode"]["offset"]:
try:
content = screen["qrcode"]["content"]
# the (21,21) refers to the QR code image size, which matches the "version" 1 of the QR Code generation lib
hlp.log_debug('write_screen:qrcode', 'prep QR code image')
# see https://pypi.org/project/qrcode/#advanced-usage
qrc_image = qrcode.QRCode(
box_size=cfg.baedge["qrcode"]["box_size"],
version=cfg.baedge["qrcode"]["version"],
)
# add data to image and make it fit the bounding box
qrc_image.add_data(content)
qrc_image.make(cfg.baedge["qrcode"]["fit"])
hlp.log_debug('write_screen:qrcode', qrc_image)
qrc_canvas = qrc_image.make_image()
coordinates = hlp.generate_relative_coordinates(
epd.height,
epd.width,
screen["qrcode"]["offset"],
qrc_canvas.size
)
hlp.log_debug('write_screen:qrcode', 'place QR code image at coordinates: ' + str(coordinates))
canvas.paste(qrc_canvas, coordinates)
except ValueError as e:
hlp.log_exception('write_screen:qrcode', e)
return None
# get buffered canvas data and update display
epd.display(epd.getbuffer(canvas))
# only sleep if requested
if sleep_screen:
hlp.log_debug('write_screen', 'sleep screen')
epd.sleep()
hlp.log_debug('write_screen', 'end function')
return True
except IOError as e:
hlp.log_exception('write_screen', e)
return False