-
Notifications
You must be signed in to change notification settings - Fork 0
/
lrpi_play.py
executable file
·336 lines (297 loc) · 11.3 KB
/
lrpi_play.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
#!/usr/bin/env python3
#
# LushRoom sound and light player
# Standalone player
#
from phue import Bridge
from random import random
from time import sleep, time, perf_counter
from pysrt import SubRipFile, SubRipItem, SubRipTime
from pysrt import open as srtopen
from datetime import datetime, timedelta
from pynput import keyboard
from pytz import utc
from apscheduler.schedulers.background import BackgroundScheduler
import vlc
import argparse
from tinkerforge.ip_connection import IPConnection
from tinkerforge.bricklet_dmx import BrickletDMX
from tf_device_ids import deviceIdentifiersList
from numpy import array, ones
DEBUG = False
VERBOSE = True
MAX_BRIGHTNESS = 254
SRT_FILENAME = "Surround_Test_Audio.srt"
AUDIO_FILENAME = "Surround_Test_Audio.m4a"
# HUE_IP_ADDRESS = "10.0.0.2"
HUE_IP_ADDRESS = "192.168.0.51"
TICK_TIME = 0.05 # seconds
PLAY_HUE = True
PLAY_AUDIO = True
PLAY_DMX = True
# SLEEP_TIME = 0.1 # seconds
# TRANSITION_TIME = 10 # milliseconds
subs = []
player = None
bridge = None
HOST = "127.0.0.1"
PORT = 4223
dmx = None
scheduler = None
last_played = 0
tfIDs = []
tfConnect = True
ipcon = IPConnection()
deviceIDs = [i[0] for i in deviceIdentifiersList]
def getIdentifier(ID):
deviceType = ""
for t in range(len(deviceIDs)):
if ID[1]==deviceIdentifiersList[t][0]:
deviceType = deviceIdentifiersList[t][1]
return(deviceType)
# Tinkerforge sensors enumeration
def cb_enumerate(uid, connected_uid, position, hardware_version, firmware_version,
device_identifier, enumeration_type):
tfIDs.append([uid, device_identifier])
# def find_subtitle(subtitle, from_t, to_t, lo=0):
# i = lo
# # print(subtitle)
# while (i < len(subtitle)):
# # if DEBUG:
# # print("\n---\n",i, subtitle[i].start, from_t, subtitle[i].end, to_t)
# # print(subtitle[i], from_t, to_t)
# if (subtitle[i].start >= to_t):
# break
# # if (subtitle[i].start <= from_t) & (to_t <= subtitle[i].end):
# if (subtitle[i].start >= from_t) & (subtitle[i].end <= to_t):
# # print(subtitle[i], subtitle[i].start, from_t, to_t)
# return subtitle[i].text, i
# i += 1
# return "", i
def find_subtitle(subtitle, from_t, to_t, lo=0):
i = lo
while (i < len(subtitle)):
# print(subtitle[i])
if (subtitle[i].start >= to_t):
break
# if (subtitle[i].start >= from_t) & (to_t >= subtitle[i].start):
if (from_t >= subtitle[i].start) & (from_t <= subtitle[i].end):
# print(subtitle[i].start, from_t, to_t)
return subtitle[i].text, i
i += 1
return "", i
def find_subtitles(subtitle, from_t, to_t, lo=0):
i = lo
# print(subtitle)
subtitles_output = []
while (i < len(subtitle)):
# if DEBUG:
# print("\n---\n",i, subtitle[i].start, from_t, subtitle[i].end, to_t)
# print(subtitle[i], from_t, to_t)
# if (subtitle[i].start >= to_t):
# break
# if (subtitle[i].start <= from_t) & (to_t <= subtitle[i].end):
if (subtitle[i].start >= from_t) & (subtitle[i].end <= to_t):
# print(subtitle[i], subtitle[i].start, from_t, to_t)
subtitles_output.append((subtitle[i].text, i))
i += 1
return subtitles_output
def end_callback(event):
print('End of media stream (event %s)' % event.type)
exit(0)
def trigger_light(subs):
# print(perf_counter(), subs)
commands = str(subs).split(";")
global bridge, dmx, MAX_BRIGHTNESS, DEBUG
for command in commands:
# try:
if True:
# print(command)
scope,items = command[0:len(command)-1].split("(")
# print(scope,items)
if scope[0:3] == "HUE":
l = int(scope[3:])
hue, sat, bri, TRANSITION_TIME = items.split(',')
TRANSITION_TIME = int(float(TRANSITION_TIME))
print(perf_counter(), l, items, hue, sat, bri, TRANSITION_TIME)
bri = int((float(bri)/255.0)*int(MAX_BRIGHTNESS))
# print(bri)
cmd = {'transitiontime' : int(TRANSITION_TIME), 'on' : True, 'bri' : int(bri), 'sat' : int(sat), 'hue' : int(hue)}
if DEBUG:
print("Trigger HUE",l,cmd)
if PLAY_HUE:
bridge.set_light(l, cmd)
# sleep(.1)
if scope[0:3] == "DMX":
l = int(scope[3:])
# channels = int(int(MAX_BRIGHTNESS)/255.0*(array(items.split(",")).astype(int)))
channels = array(items.split(",")).astype(int)
# channels = array(map(lambda i: int(MAX_BRIGHTNESS)*i, channels))
if DEBUG:
print("Trigger DMX:", l, channels)
if PLAY_DMX:
dmx.write_frame(channels)
# except:
# pass
print(30*'-')
def tick():
global subs
global player
global last_played
global TICK_TIME, DEBUG
# print(subs[0])
t = perf_counter()
# ts = str(timedelta(seconds=t)).replace('.',',')
# tsd = str(timedelta(seconds=t+10*TICK_TIME)).replace('.',',')
ts = SubRipTime(seconds = t)
tsd = SubRipTime(seconds = t+1*TICK_TIME)
#print(dir(player))
pp = player.get_position()
ptms = player.get_time()/1000.0
pt = SubRipTime(seconds=(player.get_time()/1000.0))
ptd = SubRipTime(seconds=(player.get_time()/1000.0+1*TICK_TIME))
if DEBUG:
print('Time: %s | %s | %s - %s | %s - %s | %s | %s' % (datetime.now(),t,ts,tsd,pt,ptd,pp,ptms))
print('Finding subtitle starting at %s and ending at %s' % (pt, ptd))
# sub, i = find_subtitle(subs, ts, tsd)
sub, i = find_subtitle(subs, pt, ptd, lo=last_played)
# sub, i = find_subtitle(subs, pt, ptd)
# sub_list = find_subtitles(subs, pt, ptd, lo=last_played)
if DEBUG:
print('Result of find_subtitle: ', i)
# print('Result of find_subtitles: ', len(sub_list))
# hours, minutes, seconds, milliseconds = time_convert(sub.start)
# t = seconds + minutes*60 + hours*60*60 + milliseconds/1000.0
if sub!="": # and i > last_played:
print("Light event:", i, sub)
# print("Trigger light event %s" % i)
trigger_light(sub)
# sleep(.1)
last_played=i
# for sub in sub_list:
# # print(sub)
# print("Light event:", sub[1], sub[0])
# trigger_light(sub[0])
# last_played=sub[1]
def time_convert(t):
block, milliseconds = str(t).split(",")
hours, minutes, seconds = block.split(":")
return(int(hours),int(minutes),int(seconds), int(milliseconds))
class ExitException(Exception):
def __init__(self, key):
global scheduler, player, ipcon
scheduler.shutdown()
player.stop()
if tfConnect:
ipcon.disconnect()
exit(0)
def on_release(key):
# print(key.char)
global scheduler, player
print('{0} released'.format(
key))
if key == keyboard.Key.esc:
raise ExitException(key)
elif key == keyboard.KeyCode.from_char('p'):
print("Pausing ...")
scheduler.pause()
player.pause()
elif key == keyboard.KeyCode.from_char('r'):
print("Resuming ...")
scheduler.resume()
player.play()
def main():
global subs, player, bridge, scheduler, ipcon, dmx
global SRT_FILENAME, AUDIO_FILENAME, MAX_BRIGHTNESS, TICK_TIME, HUE_IP_ADDRESS, DEBUG, VERBOSE
parser = argparse.ArgumentParser(description="LushRoom sound and light command-line player. \
Press Esc to exit, P to pause and R to resume.")
group = parser.add_mutually_exclusive_group()
group.add_argument("-v", "--verbose", action="store_true")
group.add_argument("-q", "--quiet", action="store_true")
parser.add_argument("-d", "--debug", action="store_true")
parser.add_argument("-s","--srt", default=SRT_FILENAME, help=".srt file name for lighting events")
parser.add_argument("-a","--audio", default=AUDIO_FILENAME, help="audio file for sound stream")
parser.add_argument("-b","--brightness", default=MAX_BRIGHTNESS, help="maximum brightness")
parser.add_argument("-t","--time", default=TICK_TIME, help="time between events")
parser.add_argument("--hue", default=HUE_IP_ADDRESS, help="Philips Hue bridge IP address")
args = parser.parse_args()
MAX_BRIGHTNESS = int(args.brightness)
SRT_FILENAME = args.srt
AUDIO_FILENAME = args.audio
TICK_TIME = float(args.time)
HUE_IP_ADDRESS = args.hue
VERBOSE = args.verbose
DEBUG = args.debug
if DEBUG:
print(args)
ipcon.connect(HOST, PORT)
# Register Enumerate Callback
ipcon.register_callback(IPConnection.CALLBACK_ENUMERATE, cb_enumerate)
# Trigger Enumerate
ipcon.enumerate()
sleep(2)
if DEBUG:
print(tfIDs)
dmxcount = 0
for tf in tfIDs:
# try:
if True:
# print(len(tf[0]))
if len(tf[0])<=3: # if the device UID is 3 characters it is a bricklet
if tf[1] in deviceIDs:
if VERBOSE:
print(tf[0],tf[1], getIdentifier(tf))
if tf[1] == 285: # DMX Bricklet
if dmxcount == 0:
print("Registering %s as slave DMX device for capturing DMX frames" % tf[0])
dmx = BrickletDMX(tf[0], ipcon)
dmx.set_dmx_mode(dmx.DMX_MODE_MASTER)
# channels = int((int(MAX_BRIGHTNESS)/255.0)*ones(512,)*255)
# dmx.write_frame([255,255])
sleep(1)
# channels = int((int(MAX_BRIGHTNESS)/255.0)*zeros(512,)*255)
# dmx.write_frame(channels)
dmxcount += 1
if PLAY_AUDIO:
player = vlc.MediaPlayer(AUDIO_FILENAME)
event_manager = player.event_manager()
event_manager.event_attach(vlc.EventType.MediaPlayerEndReached, end_callback)
if PLAY_HUE:
# b = Bridge('lushroom-hue.local')
bridge = Bridge(HUE_IP_ADDRESS)
# If the app is not registered and the button is not pressed, press the button and call connect() (this only needs to be run a single time)
bridge.connect()
# Get the bridge state (This returns the full dictionary that you can explore)
bridge.get_api()
lights = bridge.lights
# Print light names
for l in lights:
print(l.name)
#print(dir(l))
for l in lights:
# print(dir(l))
l.on = False
sleep(1)
for l in lights:
l.on = True
l.brightness = MAX_BRIGHTNESS
# Get a dictionary with the light name as the key
light_names = bridge.get_light_objects('name')
print("Light names:", light_names)
subs = srtopen(SRT_FILENAME)
print("Number of lighting events",len(subs))
# print("PLAY_HUE", PLAY_HUE)
scheduler = BackgroundScheduler()
scheduler.add_job(tick, 'interval', seconds=TICK_TIME, misfire_grace_time=10, max_instances=4096, coalesce=True)
if PLAY_AUDIO:
player.play()
scheduler.start(paused=False)
with keyboard.Listener(
# on_press=on_press,
on_release=on_release, suppress=False) as listener:
try:
listener.join()
except ExitException as e:
print("Exiting ...")
if __name__ == "__main__":
main()