forked from info-beamer/package-scheduled-player
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathservice
executable file
·278 lines (242 loc) · 8.26 KB
/
service
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
#!/usr/bin/python
import os
import re
import traceback
import threading
import time
import json
import sys
import pytz
from calendar import timegm
from datetime import datetime, timedelta
from select import select
from evdev import ecodes, InputDevice, list_devices
from evdev.events import KeyEvent
from hosted import config, node, device
from ibquery import InfoBeamerQuery
from websocket import create_connection #added
config.restart_on_update()
if config.timezone == 'device':
schedule_tz = config.metadata_timezone
else:
schedule_tz = pytz.timezone(config.timezone)
def iter_tiles(types=None):
for schedule in config.schedules:
for page in schedule['pages']:
for tile in page['tiles']:
if not types or tile['type'] in types:
yield tile
for layout in config.layouts:
for tile in layout['tiles']:
if not types or tile['type'] in types:
yield tile
all_timezones = {
schedule_tz.zone: schedule_tz,
}
for tile in iter_tiles('time'):
tile_tz = tile['config'].get('timezone')
if tile_tz:
all_timezones[tile_tz] = pytz.timezone(tile_tz)
print >>sys.stderr, all_timezones
countdowns = set()
for tile in iter_tiles('countdown'):
countdowns.add(tile['config'].get('target', ''))
print >>sys.stderr, countdowns
try:
sim_date, sim_time = config.time.strip().split()
d, m, y = sim_date.split('.')
ho, mi = sim_time.split(':')
utc_now = datetime.now(pytz.utc)
local_now = utc_now.astimezone(schedule_tz)
simulated = schedule_tz.localize(datetime(int(y), int(m), int(d), int(ho), int(mi), 00))
diff = local_now.utcoffset()
except:
diff = timedelta()
print >>sys.stderr, "timedelta for simulation: %r" % (diff,)
devices = {}
def update_devices():
new = set(list_devices("/dev/input/"))
old = set(devices.keys())
for device_name in new - old:
devices[device_name] = InputDevice(device_name)
for device_name in old - new:
del devices[device_name]
def send_clock(tz):
utc_now = datetime.now(pytz.utc)
# print >>sys.stderr, 'utc_now', utc_now
unix = timegm(utc_now.timetuple()) + utc_now.microsecond / 1000000.
local_now = utc_now.astimezone(tz)
# print >>sys.stderr, 'local now', local_now
since_midnight = (
local_now -
local_now.replace(hour=0, minute=0, second=0, microsecond=0)
)
since_midnight = since_midnight.seconds + since_midnight.microseconds / 1000000.
monday = (local_now - timedelta(days = local_now.weekday())).replace(hour=0, minute=0, second=0, microsecond=0)
since_monday = local_now - monday
since_monday = since_monday.days * 86400 + since_monday.seconds + since_monday.microseconds / 1000000.
node['/clock/%s' % tz.zone](json.dumps(dict(
year = local_now.year,
month = local_now.month,
day = local_now.day,
unix = unix,
dow = local_now.weekday(),
since_midnight = since_midnight,
since_monday = int(since_monday),
week_hour = int(since_monday / 3600),
diff = diff.total_seconds(),
)))
def send_countdown(countdown_target):
try:
target = datetime.strptime(countdown_target, "%Y-%m-%d %H:%M:%S")
except ValueError as err:
traceback.print_exc()
return
target = schedule_tz.localize(target)
target = target.astimezone(pytz.UTC)
unix = timegm(target.timetuple())
node['/countdown'](json.dumps(dict(
target = countdown_target,
unix = unix,
)))
def device_event(event):
print >>sys.stderr, event
if event.code in ecodes.BTN:
btn = ecodes.BTN[event.code]
if not isinstance(btn, list):
btn = [btn]
for name in btn:
node.send('/event/pad:%s' % json.dumps(dict(
key = name.replace("BTN_", "pad_").lower(),
action = {
KeyEvent.key_up: "up",
KeyEvent.key_down: "down",
}[event.value],
)))
if event.type == ecodes.EV_KEY and event.code in ecodes.KEY:
node.send('/event/keyboard:%s' % json.dumps(dict(
key = ecodes.KEY[event.code].replace("KEY_", "").lower(),
action = {
KeyEvent.key_up: "up",
KeyEvent.key_down: "down",
KeyEvent.key_hold: "hold",
}[event.value],
)))
def monitor_input():
update_devices()
r, w, e = select(devices.values(), [], [], 1)
for event in r:
try:
for ev in event.read():
device_event(ev)
except IOError:
# device disconnected
pass
screen_on_time = 0
def send_time():
print >>sys.stderr, "LOOOK: screen_on_time %s" % screen_on_time
if time.time() < 10000000:
print >>sys.stderr, "too soon"
time.sleep(1)
return
for name, tz in all_timezones.iteritems():
send_clock(tz)
for target in countdowns:
send_countdown(target)
time.sleep(0.5)
def monitor_gpio():
pins = set()
for schedule in config.schedules:
for page in schedule['pages']:
key = page.get('interaction', {}).get('key', '')
m = re.match('gpio_(.*)', key)
if m:
pins.add(int(m.group(1)))
if not pins:
time.sleep(120)
return
print >>sys.stderr, "gpios active: %s" % (pins,)
for pin in pins:
device.gpio.monitor(pin)
for pin, high in device.gpio.poll_forever():
if high:
node.send('/event/gpio:%s' % json.dumps(dict(
pin = pin,
)))
screen_state = True
def screen_toggle():
global screen_state
global screen_on_time
utc_now = datetime.now(pytz.utc)
unix = timegm(utc_now.timetuple()) + utc_now.microsecond / 1000000.
local_now = utc_now.astimezone(schedule_tz)
diff = local_now.utcoffset()
print >>sys.stderr, "LOOOK: UNIX %s" % unix
print >>sys.stderr, "LOOOK: screen_on_time %s" % screen_on_time
print >>sys.stderr, "LOOOK: local_now %s" % local_now
print >>sys.stderr, "LOOOK: diff %s" % diff
if screen_on_time == 0:
ib = InfoBeamerQuery("127.0.0.1")
con = ib.node('root/__fallback__').io(raw=True)
for line in con:
print >>sys.stderr, "LOOOK LINE ORIGINAL: %s" % line
line = int(float(line.strip())) - diff.seconds
print >>sys.stderr, "LOOOK LINE: %s" % line
print >>sys.stderr, "LOOOK: %s" % screen_state
if line > -1 and screen_state:
device.screen(on = False)
screen_state = False
screen_on_time = line
break
else:
if unix >= screen_on_time:
device.screen(on = True)
screen_state = True
screen_on_time = 0
time.sleep(4)
time.sleep(1)
def run_in_thread(fn):
def wrap():
try:
while 1:
fn()
except Exception:
traceback.print_exc()
os._exit(1)
thread = threading.Thread(target=wrap)
thread.daemon = True
thread.start()
def send_to_lua(text):
print(text)
bufSize = 1000
length = len(text)
chunksNumber = length // bufSize
lastChunkSize = length % bufSize
for i in xrange(chunksNumber):
node.send('/socket/ticker:%s' % text[i*bufSize:(i+1)*bufSize])
node.send('/socket/end:%s' % text[chunksNumber*bufSize:chunksNumber*bufSize + lastChunkSize])
def init_websocket():
while True:
try:
url = "wss://rsstickeragent.kimerucore.net/ws/" + config['playeruid']
ws = create_connection(url)
try:
while True:
result = ws.recv()
send_to_lua(result)
except Exception as ex:
print(ex)
ws.close()
except Exception as ex1:
print(ex1)
if __name__ == "__main__":
print >>sys.stderr, "MAIN"
device.screen(on = True)
thr = threading.Thread(target=init_websocket, args=(), kwargs={})
thr.start() # Will run "foo"
thr.is_alive() # Will return whether foo is running currently
run_in_thread(send_time)
run_in_thread(screen_toggle)
run_in_thread(monitor_input)
run_in_thread(monitor_gpio)
while 1: time.sleep(1000)