-
Notifications
You must be signed in to change notification settings - Fork 0
/
frame.py
328 lines (262 loc) · 9.78 KB
/
frame.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
import datetime
import locale
import os
import subprocess
import sys
import threading
import time
import xml.etree.ElementTree as ET
from os import walk
from random import shuffle
from requests import post as http_post, get as http_get
import exifread
import pyglet
import yaml
from tendo import singleton
import random
def is_subset(sub, set):
def recurse_is_subset(sub, set):
if isinstance(set, list) and isinstance(sub, list):
if len(set) < len(sub):
yield False
for v1, v2 in zip(sub, set):
yield is_subset(v1, v2)
elif isinstance(set, dict) and isinstance(sub, dict):
subset = {}
for k, v in set.items():
if k in sub:
subset[k] = v
yield subset == sub
else:
yield sub == set
return all(recurse_is_subset(sub, set))
#bufferedStream = open('frame.log', 'a', buffering=1)
#sys.stdout = bufferedStream
#sys.stderr = bufferedStream
print("")
print("-------------------------------------")
print("Launching new instance of frame.py...")
print(datetime.datetime.now().strftime("%d/%m/%Y %H:%M:%S"))
print("-------------------------------------")
print("")
class Config(yaml.YAMLObject):
yaml_loader = yaml.SafeLoader
yaml_tag = u'!Config'
def __init__(self):
self.restEndpoint = {}
self.startTime = {}
self.stopTime = {}
self.cecEnabled = True
self.basePath = "/mnt/photos"
self.pathSeparator = "/"
self.locale = ""
config = Config()
with open("config.yml") as stream:
try:
config = yaml.safe_load(stream)
except yaml.YAMLError as exc:
print(exc)
cecAvailable = False
displayOn = None # Default indeterminate state
if config.cecEnabled:
try:
import cec
cecAvailable = True
except ImportError:
cecAvailable = False
me = singleton.SingleInstance()
images = []
def images_load():
global images
global config
images.clear()
for (_, _, filenames) in walk(config.basePath):
images.extend(filenames)
break
if len(images) == 0:
print("Error: no images found.")
exit(1)
shuffle(images)
images_load()
print("Found", len(images), "pictures.")
if hasattr(config, "locale") and config.locale != "":
locale.setlocale(locale.LC_ALL, config.locale)
if cecAvailable:
try:
cec.init()
except Exception as ex:
print("Could not initialize CEC: ", ex)
cecAvailable = False
print("CEC is", "available" if cecAvailable else "unavailable.")
window = pyglet.window.Window(fullscreen=True, vsync=True)
window.set_mouse_visible(False)
window_dim = window.get_size()
print("Detected screen resolution:", window_dim[0], "x", window_dim[1])
class pic(object):
def __init__(self, filename):
self.filename = filename
self.drawn = False
fstream = open(self.filename, 'rb')
try:
self.image = pyglet.image.load(self.filename, file=fstream)
except Exception as ex:
print("Could not parse image" + self.filename + ":" + repr(ex))
self.image = None
return
self.image.anchor_x = self.image.width // 2
self.image.anchor_y = self.image.height // 2
fstream.seek(0, 0)
self.tags = exifread.process_file(fstream)
fstream.seek(0, 0)
data = fstream.read().decode('utf-8', 'ignore')
fstream.close()
xmp_start = data.find('<x:xmpmeta')
xmp_end = data.find('</x:xmpmeta')
xmp_str = data[xmp_start:xmp_end + 12]
namesp = {
'x': 'adobe:ns:meta/',
'rdf': 'http://www.w3.org/1999/02/22-rdf-syntax-ns#',
'photoshop': 'http://ns.adobe.com/photoshop/1.0/',
'dc': 'http://purl.org/dc/elements/1.1/'
}
xmp_tree = ET.fromstring(xmp_str)
xmp_desc = xmp_tree.find('rdf:RDF', namesp).find('rdf:Description', namesp)
try:
self.title = xmp_desc.find('dc:title', namesp).find('rdf:Alt', namesp).find('{http://www.w3.org/1999/02/22-rdf-syntax-ns#}li').text.strip()
except Exception:
self.title = None
if self.title is not None:
self.fullname = self.title
else:
self.city = xmp_desc.get('{http://ns.adobe.com/photoshop/1.0/}City')
self.state = xmp_desc.get('{http://ns.adobe.com/photoshop/1.0/}State')
self.country = xmp_desc.get('{http://ns.adobe.com/photoshop/1.0/}Country')
self.fullname = ', '.join(filter(None, [self.city, self.state, self.country]))
if 'EXIF DateTimeOriginal' in self.tags:
t = str(self.tags['EXIF DateTimeOriginal'])
self.shot_time = datetime.datetime.strptime(t, "%Y:%m:%d %H:%M:%S")
else:
self.shot_time = None
if self.shot_time is not None:
self.fullname += self.shot_time.strftime(" (%d %B %Y)")
self.label = pyglet.text.Label(self.fullname,
font_name='Droid Sans Bold',
font_size=36,
x=10, y=10,
anchor_x='left', anchor_y='bottom')
self.back_label = pyglet.text.Label(self.fullname,
font_name='Droid Sans Bold',
font_size=36,
x=12, y=8,
color=(0, 0, 0, 255),
anchor_x='left', anchor_y='bottom')
def draw(self):
if self.image is None:
return
self.image.blit(window_dim[0] // 2, window_dim[1] // 2)
self.back_label.draw()
self.label.draw()
self.drawn = True
def valid(self):
return self.image is not None
image_at = 0
current_picture = None
def call_rest(key):
headers = {}
if "headers" in config.restEndpoint:
headers = config.restEndpoint["headers"]
if "post_data" in config.restEndpoint[key]:
response = http_post(config.restEndpoint[key]["url"],
json=config.restEndpoint[key]["post_data"],
headers=headers,
timeout=10)
else:
response = http_get(config.restEndpoint[key]["url"],
headers=headers,
timeout=10)
response.raise_for_status()
if "return_like" in config.restEndpoint[key]:
return_val = response.json()
return_like = config.restEndpoint[key]["return_like"]
return is_subset(return_like, return_val)
else:
return True
def set_display_state(shouldBeOn: bool):
if not config.startTime or not config.stopTime:
return
global cecAvailable
global displayOn
if cecAvailable:
try:
tv = cec.Device(0)
displayOn = tv.is_on()
if shouldBeOn:
if displayOn is not True:
tv.power_on()
displayOn = True
print("Powering TV on...")
else:
if displayOn is not False:
tv.standby()
displayOn = False
print("Powering TV off...")
except Exception as excec:
print("Exception in CEC TV handling:", excec)
displayOn = None # Keep in indeterminate state, we'll check again on the next refresh
elif config.restEndpoint and "turn_on" in config.restEndpoint and "turn_off" in config.restEndpoint:
try:
# Occasionally retest state if checking is available
if "check" in config.restEndpoint and random.randint(1, 4) == 1:
displayOn = call_rest("check")
if displayOn is None and "check" in config.restEndpoint:
displayOn = call_rest("check")
if shouldBeOn and displayOn is not True:
if call_rest("turn_on"):
displayOn = True
elif not shouldBeOn and displayOn is not False:
if call_rest("turn_off"):
displayOn = False
except Exception as exreq:
print("Exception in REST API TV handling:", exreq)
displayOn = None # Keep in indeterminate state, we'll check again on the next refresh
else:
if shouldBeOn and displayOn is not True:
os.system("xset dpms force on")
displayOn = True
elif not shouldBeOn and displayOn is not False:
os.system("xset dpms force off")
displayOn = False
return displayOn
def picture_update(dt):
global image_at
global current_picture
while image_at < len(images):
current_picture = pic(config.basePath + config.pathSeparator + images[image_at])
if not current_picture.valid():
image_at += 1
else:
break
now = datetime.datetime.now().time()
startt = datetime.time(hour=config.startTime["hour"], minute=config.startTime["minute"])
endt = datetime.time(hour=config.stopTime["hour"], minute=config.stopTime["minute"])
set_display_state(startt <= now and endt >= now)
if displayOn:
image_at += 1
if image_at >= len(images):
images_load()
image_at = 0
@window.event
def on_draw():
if current_picture is not None and current_picture.drawn is False:
window.clear()
current_picture.draw()
@window.event
def on_key_press(symbol, modifiers):
if symbol == pyglet.window.key.ESCAPE:
print("ESC detected, exiting...")
window.clear()
window.flip()
set_display_state(False)
window.close()
pyglet.clock.schedule_interval_soft(picture_update, 5)
pyglet.app.run()