-
Notifications
You must be signed in to change notification settings - Fork 0
/
opensong_monitor.py
349 lines (280 loc) · 12.2 KB
/
opensong_monitor.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
#!/usr/bin/env python2
import os
import time
import websocket
import threading
import argparse
import xml.etree.ElementTree as Et
import Queue
import tempfile
import logging
# Suppress pygame welcome message
os.environ["PYGAME_HIDE_SUPPORT_PROMPT"] = "1"
import pygame
class OpenSongConfig:
default_host = 'localhost'
default_port = 8082
def __init__(self):
self.host = os.getenv("OPENSONG_HOST", self.default_host)
self.port = os.getenv("OPENSONG_PORT", self.default_port)
self.fullscreen = True
class OpenSongMonitor:
def __init__(self):
self.config = OpenSongConfig()
self.screen_size = (0, 0) # Placeholder to store screen size
self.screen_surface = None # Placeholder to store display framebuffer image
self.websocket = None # Placeholder for OpenSong websocket connection
self.shutdown = False
self.slides = Queue.Queue()
self.current_slide = None
self.ws_was_connected = False
def init_screen(self):
# Display drivers, first empty entry will attempt autodetection
drivers = ('', 'directfb', 'fbcon', 'svgalib', 'windib')
initialized = False
for driver in drivers:
if not os.getenv('SDL_VIDEODRIVER'):
if driver:
os.putenv('SDL_VIDEODRIVER', driver)
try:
pygame.display.init()
pygame.font.init()
print("Using video driver %s%s" % (pygame.display.get_driver(), " (autodetected)" if not driver else ""))
initialized = True
except pygame.error:
pass
if initialized:
break
if initialized:
if self.config.fullscreen:
self.screen_size = (pygame.display.Info().current_w, pygame.display.Info().current_h)
self.screen_surface = pygame.display.set_mode(self.screen_size, pygame.FULLSCREEN)
else:
self.screen_size = (pygame.display.Info().current_w/2, pygame.display.Info().current_h/2)
self.screen_surface = pygame.display.set_mode(self.screen_size)
pygame.display.set_caption('OpenSong Monitor')
pygame.mouse.set_visible(False)
else:
raise Exception('No suitable framebuffer video driver found.')
def osws_on_data(self, _ws, data, data_type, complete):
if complete:
if data_type == websocket.ABNF.OPCODE_TEXT:
print(data)
if data[:5] == '<?xml':
try:
xml = Et.fromstring(data)
if xml.tag == 'response' and xml.get('resource') == 'presentation':
pres = xml.find("presentation")
# for child in pres:
# print("**", child.tag, child.attrib)
if pres.get('running') == '1':
itemnumber = int(pres.find("slide").attrib["itemnumber"])
self.load_slide(itemnumber)
# Queue item number for retrieval by update_slides thread
# slides.put(itemnumber)
else:
self.status("No running presentation", clear_slide=True)
# else:
# print("** skip", xml, xml.get('resource'))
except:
print("Failed to parse message from OpenSong:", data)
else:
if not data == "OK":
print("Not parsing: {}".format(data))
elif data_type == websocket.ABNF.OPCODE_BINARY:
print("Received image")
self.slides.put(data)
def osws_on_error(self, _ws, error):
if self.ws_was_connected:
print("Websocket: Connection error: %s" % error)
def osws_on_close(self, _ws):
if self.ws_was_connected:
print("Websocket: Connection to OpenSong closed")
def osws_on_open(self, ws):
self.ws_was_connected = True
print("Websocket: Connected to OpenSong")
# Perform OpenSong subscription delayed
threading.Timer(1.0, osws_subscribe).start()
def opensong_subscribe(self):
self.websocket.send("/ws/subscribe/presentation")
def opensong_connect(self):
# websocket.enableTrace(True)
websocket.setdefaulttimeout(10.0)
url = "ws://%s:%d/ws" % (self.config.host, self.config.port)
self.websocket = websocket.WebSocketApp(url,
on_open=osws_on_open,
on_data=osws_on_data,
on_error=osws_on_error,
on_close=osws_on_close)
def run_os_websocket(self, *args):
first_attempt = True
while not self.shutdown:
try:
# Reset keep_running flag for compatibility with old
# websocket-client package versions
self.websocket.keep_running = True
# Syntax once ping/pong is supported by OpenSong
# self.websocket.run_forever(ping_interval=7, ping_timeout=3)
self.websocket.run_forever()
except Exception as e:
if isinstance(e, SystemExit):
self.shutdown = True
else:
if self.ws_was_connected or first_attempt:
print("Websocket: Connection caused a failure: %s" % str(e), e)
finally:
if self.websocket:
self.websocket.close()
if not self.shutdown:
if self.ws_was_connected or first_attempt:
self.status("Waiting to (re)connect to OpenSong", "at %s ..." % self.websocket.url, clear_slide=True)
first_attempt = False
self.ws_was_connected = False
time.sleep(5)
def status(self, text, details="", clear_slide=False):
font = pygame.font.Font(pygame.font.get_default_font(), 40)
surface = font.render(text, True, (255, 255, 255))
rect = surface.get_rect()
rect.center = ((self.screen_size[0]/2), (self.screen_size[1]/2))
self.show_current_slide(clear=clear_slide)
# background = pygame.Rect((0, 0), self.screen_size)
# background.center = ((self.screen_size[0]/2), (self.screen_size[1]/2))
# pygame.draw.rect(self.screen_surface, (90, 90, 90, 128), background)
self.screen_surface.blit(surface, rect)
pygame.display.update()
print("Status: %s (%s)" % (text, details))
def load_slide(self, slide_number):
if slide_number:
print("Loading slide number %d" % slide_number)
# (w, h) = self.screen_size
url = "/presentation/slide/%d/image" % slide_number
# url = "/presentation/slide/%d/image/width:%d/height:%d" % (slide_number, w, h)
# url = "/presentation/slide/%d/preview" % (slide_number)
self.websocket.send(url)
def update_slides(self, *args):
while not self.shutdown:
try:
slide = self.slides.get(block=True, timeout=1.0)
except Queue.Empty:
slide = None
if slide and self.slides.empty() and not self.shutdown:
if slide:
fd, filename = tempfile.mkstemp()
try:
os.write(fd, slide)
os.close(fd)
img = pygame.image.load(filename).convert()
self.show_current_slide(img)
finally:
os.remove(filename)
def show_current_slide(self, img=None, clear=False):
if img:
self.current_slide = img
elif clear:
self.current_slide = None
if self.current_slide:
print("update new slide")
# img_rect = img.get_rect()
pygame.transform.scale(self.current_slide, self.screen_size, self.screen_surface)
# screen.blit(img, img_rect)
pygame.display.flip()
else:
self.screen_surface.fill((0, 0, 0))
def show_sample_images(self):
img = pygame.image.load('fixtures/color_bars_1121.jpg').convert()
self.show_current_slide(img)
time.sleep(3)
img = pygame.image.load('fixtures/6291.png').convert()
self.show_current_slide(img)
time.sleep(3)
img = pygame.image.load('fixtures/resolution.jpg').convert()
self.show_current_slide(img)
time.sleep(3)
def close(self):
self.shutdown = True
# Insert dummy slide to let the update_slides thread finish
self.slides.put(None)
if self.websocket:
self.websocket.close()
def run_monitor(self):
try:
self.init_screen()
self.opensong_connect()
except Exception as e:
print("Aborting, initialisation failed: %s" % str(e))
exit(1)
self._apply_websocket_logging_workaround()
self.status("OpenSong Monitor")
# Slide retrieval and drawing thread
slide_thread = threading.Thread(name="update_slides", target=self.update_slides)
slide_thread.start()
# OpenSong connection thread
ws_thread = threading.Thread(name="run_os_websocket", target=self.run_os_websocket)
ws_thread.start()
while not self.shutdown:
for event in pygame.event.get():
if event.type == pygame.QUIT:
self.close()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
self.close()
if event.mod == pygame.KMOD_LCTRL and event.key == pygame.K_c:
self.close()
if not self.shutdown:
pygame.display.update()
time.sleep(0.1)
ws_thread.join()
slide_thread.join()
pygame.quit()
@staticmethod
def _apply_websocket_logging_workaround():
# Workaround for Websocket issue #400 Fix #342 Fix #341
_logger = logging.getLogger('websocket')
try:
from logging import NullHandler
except ImportError:
class NullHandler(logging.Handler):
def emit(self, record):
pass
_logger.addHandler(NullHandler())
monitor = None
def osws_on_data(ws, data, data_type, complete):
global monitor
monitor.osws_on_data(ws, data, data_type, complete)
def osws_on_error(ws, error):
global monitor
monitor.osws_on_error(ws, error)
def osws_on_close(ws):
global monitor
monitor.osws_on_close(ws)
def osws_on_open(ws):
global monitor
monitor.osws_on_open(ws)
def osws_subscribe():
global monitor
monitor.opensong_subscribe()
def main():
global monitor
def str2bool(v):
if v.lower() in ('yes', 'true', 't', 'y', '1'):
return True
elif v.lower() in ('no', 'false', 'f', 'n', '0'):
return False
else:
raise argparse.ArgumentTypeError('Boolean value expected.')
arg_parser = argparse.ArgumentParser(description='OpenSong networked monitor.',
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
arg_parser.add_argument("--host", default=OpenSongConfig.default_host, help='Address of the OpenSong application')
arg_parser.add_argument("--port", default=OpenSongConfig.default_port, type=int,
help='Port of the OpenSong API server')
arg_parser.add_argument("--fullscreen", default=True, type=str2bool, nargs='?', help='Run in fullscreen mode')
args = arg_parser.parse_args()
monitor = OpenSongMonitor()
if args.host and args.host is not OpenSongConfig.default_host:
monitor.config.host = args.host
if args.port and args.port is not OpenSongConfig.default_port:
monitor.config.port = args.port
monitor.config.fullscreen = args.fullscreen is True
monitor.run_monitor()
if __name__ == '__main__':
main()