-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathrun_tasker.py
510 lines (442 loc) · 16.9 KB
/
run_tasker.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
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
import os
import sys
import time
SCARLETT_DEBUG = None
if SCARLETT_DEBUG:
# Setting GST_DEBUG_DUMP_DOT_DIR environment variable enables us to have a
# dotfile generated
os.environ[
"GST_DEBUG_DUMP_DOT_DIR"] = "/home/pi/dev/bossjones-github/scarlett-dbus-poc/_debug"
os.putenv('GST_DEBUG_DUMP_DIR_DIR',
'/home/pi/dev/bossjones-github/scarlett-dbus-poc/_debug')
import argparse
import pprint
pp = pprint.PrettyPrinter(indent=4)
import gi
gi.require_version('Gst', '1.0')
from gi.repository import GObject
from gi.repository import Gst
from gi.repository import GLib
from gi.repository import Gio
import threading
GObject.threads_init()
Gst.init(None)
print '********************************************************'
print 'GObject: '
pp.pprint(GObject.pygobject_version)
print ''
print 'Gst: '
pp.pprint(Gst.version_string())
print '********************************************************'
Gst.debug_set_active(True)
Gst.debug_set_default_threshold(3)
import StringIO
import re
import ConfigParser
from signal import signal, SIGWINCH, SIGKILL, SIGTERM
from IPython.core.debugger import Tracer
from IPython.core import ultratb
sys.excepthook = ultratb.FormattedTB(mode='Verbose',
color_scheme='Linux',
call_pdb=True,
ostream=sys.__stdout__)
from colorlog import ColoredFormatter
import logging
SCARLETT_CANCEL = "pi-cancel"
SCARLETT_LISTENING = "pi-listening"
SCARLETT_RESPONSE = "pi-response"
SCARLETT_FAILED = "pi-response2"
from gettext import gettext as _
gst = Gst
import scarlett_gstutils
import scarlett_config
import traceback
from functools import wraps
import Queue
from random import randint
from pydbus import SessionBus
# scarlett object dependencies for playing sounds and speaking
import test_gdbus_speaker
import test_gdbus_player
def setup_logger():
"""Return a logger with a default ColoredFormatter."""
formatter = ColoredFormatter(
"(%(threadName)-9s) %(log_color)s%(levelname)-8s%(reset)s %(message_log_color)s%(message)s",
datefmt=None,
reset=True,
log_colors={
'DEBUG': 'cyan',
'INFO': 'green',
'WARNING': 'yellow',
'ERROR': 'red',
'CRITICAL': 'red',
},
secondary_log_colors={
'message': {
'ERROR': 'red',
'CRITICAL': 'red',
'DEBUG': 'yellow'
}
},
style='%'
)
logger = logging.getLogger(__name__)
handler = logging.StreamHandler()
handler.setFormatter(formatter)
logger.addHandler(handler)
logger.setLevel(logging.DEBUG)
return logger
# Create a player
PWD = '/home/pi/dev/bossjones-github/scarlett-dbus-poc'
logger = setup_logger()
gst = Gst
# Managing the Gobject main loop thread.
_shared_loop_thread = None
_loop_thread_lock = threading.RLock()
# NOTE: on plane to DC
def get_loop_thread():
"""Get the shared main-loop thread.
"""
global _shared_loop_thread
with _loop_thread_lock:
if not _shared_loop_thread:
# Start a new thread.
_shared_loop_thread = ExcThread()
_shared_loop_thread.start()
return _shared_loop_thread
# source: https://github.com/jcollado/pygtk-webui/blob/master/demo.py
def trace(func):
"""Tracing wrapper to log when function enter/exit happens.
:param func: Function to wrap
:type func: callable
"""
@wraps(func)
def wrapper(*args, **kwargs):
logger.debug('Start {!r}'. format(func.__name__))
result = func(*args, **kwargs)
logger.debug('End {!r}'. format(func.__name__))
return result
return wrapper
NUM_THREADS = 10
class ExcThread(threading.Thread):
"""
Exception Thread Class aka Producer. Acts as the Child thread.
Any errors that happen here will get placed into a Queue and raised for the parent thread to consume.
A thread class that supports raising exception in the thread from another thread.
"""
@trace
def __init__(self, bucket, *args, **kargs):
threading.Thread.__init__(self, *args, **kargs)
self.bucket = bucket
self.running = True
self._stop = threading.Event()
# self.loop = GObject.MainLoop()
self.loop = GLib.MainLoop()
# if loop is None:
# self.loop = GLib.MainLoop()
# # self.loop = GObject.MainLoop()
# else:
# self.loop = loop
# self.daemon = True
@trace
def run(self):
try:
print "Child Thread Started", self
# # NOTE: first iteration # threading.Thread.run(self)
# # NOTE: second iteration # self.loop.run()
self.loop.run()
# raise Exception('An error occured here.')
except Exception:
self.bucket.put(sys.exc_info())
raise
@trace
def stop(self):
self._stop.set()
@trace
def stopped(self):
return self._stop.isSet()
# # NOTE: enumerate req to iterate through tuple and find GVariant
# @trace
# def player_cb(*args, **kwargs):
# if SCARLETT_DEBUG:
# logger.debug("player_cb PrettyPrinter: ")
# pp = pprint.PrettyPrinter(indent=4)
# pp.pprint(args)
# for i, v in enumerate(args):
# if SCARLETT_DEBUG:
# logger.debug("Type v: {}".format(type(v)))
# logger.debug("Type i: {}".format(type(i)))
# if type(v) is gi.overrides.GLib.Variant:
# if SCARLETT_DEBUG:
# logger.debug(
# "THIS SHOULD BE A Tuple now: {}".format(v))
# msg, scarlett_sound = v
# logger.warning(" msg: {}".format(msg))
# logger.warning(
# " scarlett_sound: {}".format(scarlett_sound))
# # NOTE: Create something like test_gdbus_player.ScarlettPlayer('pi-listening')
# # NOTE: test_gdbus_player.ScarlettPlayer
# # NOTE: self.bucket.put()
# # NOTE: ADD self.queue.put(v)
#
#
# # NOTE: enumerate req to iterate through tuple and find GVariant
# @trace
# def command_cb(*args, **kwargs):
# if SCARLETT_DEBUG:
# logger.debug("player_cb PrettyPrinter: ")
# pp = pprint.PrettyPrinter(indent=4)
# pp.pprint(args)
# for i, v in enumerate(args):
# if SCARLETT_DEBUG:
# logger.debug("Type v: {}".format(type(v)))
# logger.debug("Type i: {}".format(type(i)))
# if type(v) is gi.overrides.GLib.Variant:
# if SCARLETT_DEBUG:
# logger.debug(
# "THIS SHOULD BE A Tuple now: {}".format(v))
# msg, scarlett_sound, command = v
# logger.warning(" msg: {}".format(msg))
# logger.warning(
# " scarlett_sound: {}".format(scarlett_sound))
# logger.warning(" command: {}".format(command))
# # NOTE: Create something like test_gdbus_player.ScarlettPlayer('pi-listening')
# # NOTE: test_gdbus_player.ScarlettPlayer
# # NOTE: self.bucket.put()
# # NOTE: ADD self.queue.put(v)
class ScarlettTasker():
@trace
def __init__(self, bucket, loop, *args, **kargs):
self.bucket = bucket
self.loop = loop
self.running = True
self._stop = threading.Event()
self.queue = Queue.Queue(10)
# NOTE: enumerate req to iterate through tuple and find GVariant
@trace
def player_cb(*args, **kwargs):
if SCARLETT_DEBUG:
logger.debug("player_cb PrettyPrinter: ")
pp = pprint.PrettyPrinter(indent=4)
pp.pprint(args)
for i, v in enumerate(args):
if SCARLETT_DEBUG:
logger.debug("Type v: {}".format(type(v)))
logger.debug("Type i: {}".format(type(i)))
if type(v) is gi.overrides.GLib.Variant:
if SCARLETT_DEBUG:
logger.debug(
"THIS SHOULD BE A Tuple now: {}".format(v))
msg, scarlett_sound = v
logger.warning(" msg: {}".format(msg))
logger.warning(
" scarlett_sound: {}".format(scarlett_sound))
# NOTE: Create something like test_gdbus_player.ScarlettPlayer('pi-listening')
# NOTE: test_gdbus_player.ScarlettPlayer
# NOTE: self.bucket.put()
# NOTE: ADD self.queue.put(v)
# NOTE: enumerate req to iterate through tuple and find GVariant
@trace
def command_cb(*args, **kwargs):
if SCARLETT_DEBUG:
logger.debug("player_cb PrettyPrinter: ")
pp = pprint.PrettyPrinter(indent=4)
pp.pprint(args)
for i, v in enumerate(args):
if SCARLETT_DEBUG:
logger.debug("Type v: {}".format(type(v)))
logger.debug("Type i: {}".format(type(i)))
if type(v) is gi.overrides.GLib.Variant:
if SCARLETT_DEBUG:
logger.debug(
"THIS SHOULD BE A Tuple now: {}".format(v))
msg, scarlett_sound, command = v
logger.warning(" msg: {}".format(msg))
logger.warning(
" scarlett_sound: {}".format(scarlett_sound))
logger.warning(" command: {}".format(command))
# NOTE: Create something like test_gdbus_player.ScarlettPlayer('pi-listening')
# NOTE: test_gdbus_player.ScarlettPlayer
# NOTE: self.bucket.put()
# NOTE: ADD self.queue.put(v)
# with SessionBus() as bus:
bus = SessionBus()
ss = bus.get("org.scarlett", object_path='/org/scarlett/Listener')
# SttFailedSignal / player_cb
ss_failed_signal = bus.con.signal_subscribe(None,
"org.scarlett.Listener",
"SttFailedSignal",
'/org/scarlett/Listener',
None,
0,
player_cb)
# ListenerReadySignal / player_cb
ss_rdy_signal = bus.con.signal_subscribe(None,
"org.scarlett.Listener",
"ListenerReadySignal",
'/org/scarlett/Listener',
None,
0,
player_cb)
# KeywordRecognizedSignal / player_cb
ss_kw_rec_signal = bus.con.signal_subscribe(None,
"org.scarlett.Listener",
"KeywordRecognizedSignal",
'/org/scarlett/Listener',
None,
0,
player_cb)
# CommandRecognizedSignal /command_cb
ss_cmd_rec_signal = bus.con.signal_subscribe(None,
"org.scarlett.Listener",
"CommandRecognizedSignal",
'/org/scarlett/Listener',
None,
0,
command_cb)
# ListenerCancelSignal / player_cb
ss_cancel_signal = bus.con.signal_subscribe(None,
"org.scarlett.Listener",
"ListenerCancelSignal",
'/org/scarlett/Listener',
None,
0,
player_cb)
# NOTE: print dir(ss)
# NOTE: # Quit mainloop
# NOTE: self.quit = ss.quit()
# NOTE: # let listener know when we connect to it
# NOTE: self._tasker_connected = ss.emitConnectedToListener("{}".format(
# NOTE:
# self._tasker_connected(ScarlettTasker().__class__.__name__)))
logger.debug("ss PrettyPrinter: ")
pp = pprint.PrettyPrinter(indent=4)
pp.pprint(ss)
# NOTE: WE NEED TO ADD MORE TO THIS. WE NEED TO DO A self.queue.get() then have it join the mainthread
# queue.get should have either a ScarlettPlayer or a ScarlettSpeaker object
@trace
def go(self):
self.loop.run()
@trace
def run(self):
try:
print "ScarlettTasker Thread Started", self
self.loop.run()
except Exception:
self.bucket.put(sys.exc_info())
raise
# @trace
# def main():
# """
# Parent thread and supervisor.
# """
# global player_cb
# global command_cb
#
# bucket = Queue.Queue()
# mainloop = GLib.MainLoop()
#
# # TODO: Try calling child thread like below.
# # TODO: Allow us to pass in a target, and args.
# # TODO: Eg. target=ScarlettPlayer or target=ScarlettSpeaker
# # SOURCE: https://github.com/jhcepas/npr/blob/master/nprlib/interface.py
# # t = ExcThread(bucket=exceptions, target=func, args=[args])
# # Start child thread
# ### thread_obj = ScarlettTasker(bucket, mainloop)
# ### thread_obj.daemon = True
# ### thread_obj.start()
#
# thread_obj = ExcThread(bucket)
# thread_obj.daemon = True
# thread_obj.start()
#
# # st = ScarlettTasker(bucket, mainloop)
# # st_thread = threading.Thread(target=st.go)
# # st_thread.daemon = True
# # st_thread.start()
# # start_mainloop(bucket, mainloop)
# st = ScarlettTasker(bucket, mainloop)
# st.run()
#
# while True:
# try:
# exc = bucket.get(block=False)
# # NOTE: IMPORTANT NOTES
# # check type of exc
# # if exc is a ScarlettPlayer or a ScarlettSpeaker ...
# # s_obj = ScarlettPlayer
# # OR
# # s_obj = ScarlettSpeaker
# # add to the thread supervisor, which will block till finished
# # thread_obj.join(s_obj)
# except Queue.Empty:
# time.sleep(.2)
# logger.info('nothing yet')
# pass
# else:
# exc_type, exc_obj, exc_trace = exc
# # deal with the exception
# # print exc_type, exc_obj
# # print exc_trace
# # deal with the exception
# # print exc_trace, exc_type, exc_obj
# raise exc_obj
#
# thread_obj.join(0.1)
# if thread_obj.isAlive():
# continue
# else:
# break
if __name__ == '__main__':
global player_cb
global command_cb
bucket = Queue.Queue()
mainloop = GLib.MainLoop()
# TODO: Try calling child thread like below.
# TODO: Allow us to pass in a target, and args.
# TODO: Eg. target=ScarlettPlayer or target=ScarlettSpeaker
# SOURCE: https://github.com/jhcepas/npr/blob/master/nprlib/interface.py
# t = ExcThread(bucket=exceptions, target=func, args=[args])
# Start child thread
### thread_obj = ScarlettTasker(bucket, mainloop)
### thread_obj.daemon = True
### thread_obj.start()
thread_obj = ExcThread(bucket)
thread_obj.daemon = True
thread_obj.start()
st = ScarlettTasker(bucket, mainloop)
st_thread = threading.Thread(target=st.go)
# st_thread.daemon = True
st_thread.start()
# start_mainloop(bucket, mainloop)
#st = ScarlettTasker(bucket, mainloop)
#st.run()
while True:
try:
exc = bucket.get(block=False)
# NOTE: IMPORTANT NOTES
# check type of exc
# if exc is a ScarlettPlayer or a ScarlettSpeaker ...
# s_obj = ScarlettPlayer
# OR
# s_obj = ScarlettSpeaker
# add to the thread supervisor, which will block till finished
# thread_obj.join(s_obj)
except Queue.Empty:
time.sleep(.2)
logger.info('nothing yet')
else:
exc_type, exc_obj, exc_trace = exc
# deal with the exception
# print exc_type, exc_obj
# print exc_trace
# deal with the exception
# print exc_trace, exc_type, exc_obj
raise exc_obj
thread_obj.join(0.1)
if thread_obj.isAlive():
continue
else:
break