-
Notifications
You must be signed in to change notification settings - Fork 0
/
trumpy.py
executable file
·1420 lines (1310 loc) · 45.7 KB
/
trumpy.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
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# trumpy.py TrumpyBear.
'''
Trumpybear is multi-threaded. MQTT message handlers will run code in
different threads. The siren/alarm/tts are also rentrant since
they can be stopped by another thread (mqtt message)
JSON is usually sent and received from the mqtt broker topics.
The front panel is a separate GUI program that uses MQTT to manage trumpybear
manual control and tests. It is not synchronously coupled but does rely the
state machines. There are state machines for 'normal', 'register', and 'mean'
modes. Hubitat (and Alexa via Hubitat) is also listening to the mqtt topics and
sending some messages. We don't know and cant know who sent the message.
Use mosquitto_pub cli and MQTT Explorer for debugging.
Mycroft interactions are also through MQTT (and a proxy program too)
Remember - it's trumpybear. It doesn't need to be perfect - no one is
going to look at the code. Right?
'''
import paho.mqtt.client as mqtt
import sys
import json
import argparse
import warnings
from datetime import datetime
import time, threading, sched
from threading import Lock, Thread
import socket
import os
import shutil
import traceback
from subprocess import Popen
from lib.Settings import Settings
from lib.Homie_MQTT import Homie_MQTT
from lib.Audio import AudioDev
from lib.Constants import State, Event, Role
from lib.TrumpyBear import TrumpyBear
import urllib.request
import logging
import logging.handlers
import numpy as np
import cv2
import imutils
from imutils.video import VideoStream
# Face Recognition uses
import websocket # websocket-client
import base64
from PIL import Image
import io
# Tracking uses:
from lib.ImageZMQ import imagezmq
import zmq
# globals
settings = None
hmqtt = None
debug_level = 1
applog = None
trumpy_state = None
trumpy_bear = None # object of class TrumpyBear
sm_lock = Lock() # state machine lock - only one thread at a time
waitcnt = 0
timerl_thread = None
registering = False
state_machine = None
video_dev = None
active_timer = None
startupTime = None
play_mp3 = False
player_obj = None
zmqsender = None
class NuclearOption(Exception):
pass
'''
def mp3_player(fp):
global player_obj, applog, audiodev
cmd = f'{audiodev.play_mp3_cmd} {fp}'
player_obj = Popen('exec ' + cmd, shell=True)
player_obj.wait()
# Restore volume if it was changed
def player_reset():
global settings, applog, audiodev
if settings.player_vol != settings.player_vol_default and not audiodev.broken:
applog.info(f'reset player vol to {settings.player_vol_default}')
settings.player_vol = settings.player_vol_default
audiodev.set_volume(settings.player_vol_default)
def playUrl(url):
global hmqtt, audiodev, applog, settings, player_mp3, player_obj
applog.info(f'playUrl: {url}')
if url == 'off':
if player_mp3 != True:
return
player_mp3 = False
applog.info("killing tts")
player_obj.terminate()
player_reset()
hmqtt.set_status("ready")
else:
try:
urllib.request.urlretrieve(url, settings.tmpf)
except:
applog.warn(f"Failed download of {url}")
hmqtt.set_status("busy")
# change the volume?
if settings.player_vol != settings.player_vol_default and not audiodev.broken:
applog.info(f'set player vol to {settings.player_vol}')
audiodev.set_volume(settings.player_vol)
player_mp3 = True
mp3_player(settings.tmpf)
player_reset()
hmqtt.set_status("ready")
applog.info('tts finished')
# in order to kill a subprocess running mpg123 (in this case)
# we need a Popen object. I want the Shell too.
playSiren = False
siren_obj = None
def siren_loop(fn):
global playSiren, isDarwin, hmqtt, applog, siren_obj
cmd = f'{audiodev.play_mp3_cmd} sirens/{fn}'
while True:
if playSiren == False:
break
siren_obj = Popen('exec ' + cmd, shell=True)
siren_obj.wait()
# Restore volume if it was changed
def siren_reset():
global settings, applog, audiodev
if settings.siren_vol != settings.siren_vol_default and not audiodev.broken:
applog.info(f'reset siren vol to {settings.siren_vol_default}')
settings.siren_vol = settings.siren_vol_default
audiodev.set_volume(settings.siren_vol_default)
def sirenCb(msg):
global applog, hmqtt, playSiren, siren_obj, audiodev
if msg == 'off':
if playSiren == False:
return
playSiren = False
hmqtt.set_status("ready")
applog.info("killing siren")
siren_obj.terminate()
siren_reset()
else:
if settings.siren_vol != settings.siren_vol_default and not audiodev.broken:
applog.info(f'set siren vol to {settings.siren_vol}')
audiodev.set_volume(settings.siren_vol)
if msg == 'on':
fn = 'Siren.mp3'
else:
fn = msg
applog.info(f'play siren: {fn}')
hmqtt.set_status("busy")
playSiren = True
siren_loop(fn)
siren_reset()
applog.info('siren finished')
hmqtt.set_status("ready")
play_chime = False
chime_obj = None
def chime_mp3(fp):
global chime_obj, applog, audiodev
cmd = f'{audiodev.play_mp3_cmd} {fp}'
chime_obj = Popen('exec ' + cmd, shell=True)
chime_obj.wait()
# Restore volume if it was changed
def chime_reset():
global settings, applog, audiodev
if settings.chime_vol != settings.chime_vol_default and not audiodev.broken:
applog.info(f'reset chime vol to {settings.chime_vol_default}')
settings.chime_vol = settings.chime_vol_default
audiodev.set_volume(settings.chime_vol_default)
def chimeCb(msg):
global applog, chime_obj, play_chime, settings, audiodev
if msg == 'off':
if play_chime != True:
return
play_chime = False
applog.info("killing chime")
chime_obj.terminate()
chime_reset()
hmqtt.set_status("ready")
else:
# if volume != volume_default, set new volume, temporary
if settings.chime_vol != settings.chime_vol_default and not audiodev.broken:
applog.info(f'set chime vol to {settings.chime_vol}')
audiodev.set_volume(settings.chime_vol)
flds = msg.split('-')
num = int(flds[0].strip())
nm = flds[1].strip()
fn = 'chimes/' + nm + '.mp3'
applog.info(f'play chime: {fn}')
hmqtt.set_status("busy")
play_chime = True
chime_mp3(fn)
chime_reset()
hmqtt.set_status("ready")
applog.info('chime finished')
# TODO: order Lasers with pan/tilt motors. Like the turrets? ;-)
def strobeCb(msg):
global applog, hmqtt
applog.info(f'missing lasers for strobe {msg}, Cheapskate!')
'''
def start_muted():
global applog, hmqtt
applog.info(f'startup muting')
hmqtt.display_cmd('off')
hmqtt.tts_mute()
def main():
global settings, hmqtt, applog, audiodev, trumpy_state
global state_machine, video_dev, ml_dict, startupTime
# process cmdline arguments
loglevels = ('DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL')
ap = argparse.ArgumentParser()
ap.add_argument("-c", "--conf", required=True, type=str,
help="path and name of the json configuration file")
ap.add_argument("-s", "--syslog", action = 'store_true',
default=False, help="use syslog")
ap.add_argument("-q", "--quiet", action = 'store_true',
default=False, help="disable TTS")
ap.add_argument("-d", "--debug", action='store', type=int, default='3',
nargs='?', help="debug level, default is 3")
ap.add_argument("-e", "--espeak", action = 'store_true',
default=False, help="use espeak TTS")
args = vars(ap.parse_args())
# logging setup
applog = logging.getLogger('trumpybear')
#applog.setLevel(args['log'])
if args['syslog']:
applog.setLevel(logging.DEBUG)
handler = logging.handlers.SysLogHandler(address = '/dev/log')
# formatter for syslog (no date/time or appname. Just msg, lux, luxavg
formatter = logging.Formatter('%(name)s-%(levelname)-5s: %(message)-30s')
handler.setFormatter(formatter)
applog.addHandler(handler)
else:
logging.basicConfig(level=logging.DEBUG,datefmt="%H:%M:%S",format='%(asctime)s %(levelname)-5s %(message)-40s')
audiodev = AudioDev()
isDarwin = audiodev.isDarwin
state_machine = tame_machine
startupTime = time.time()
settings = Settings(args["conf"],
audiodev,
applog)
hmqtt = Homie_MQTT(settings,
None,
None,
None,
None,
state_machine)
settings.print()
# TODO: minus style points here
# set another callback function in the Mqtt Object for the TB state machine
hmqtt.controller = trumpy_recieve
# Setup video capture if not using a mqttcamera
if settings.local_cam is not None:
applog.info(f'Using local camera: {settings.local_cam}')
video_dev = cv2.VideoCapture(settings.local_cam)
video_dev.release()
# Turn off display, mute mycroft
th = threading.Timer(2 * 60, start_muted)
th.start()
state_machine(Event.start)
# All we do now is loop over a 5 minute delay
# and let the threads do the work.
while True:
time.sleep(5*60)
def new_sm(ns):
global state_machine, trumpy_state, hmqtt
state_machine = ns
hmqtt.state_machine = ns
trumpy_state = State.initialized
# Tame Mode state machine - deprecation begins. It was not a
# well thought out idea
def tame_machine(evt, arg=None):
global applog, settings, hmqtt, trumpy_state, trumpy_bear
global sm_lock
cur_state = trumpy_state
next_state = cur_state
applog.debug("Tm entry {} {}".format(trumpy_state, evt))
sm_lock.acquire()
if evt == Event.start:
next_state = State.starting
elif evt == Event.motion:
# ignore motion - stay in same state
next_state = cur_state
elif evt == Event.abort:
next_state = State.starting
elif evt == Event.reply or evt == Event.pict:
next_state = State.starting
else:
applog.info(f'unknown {evt} for tame mode')
next_state = State.starting
trumpy_state = next_state
applog.debug("Tm exit {} {} => {}".format(cur_state, evt, trumpy_state))
# unlock machine - now we can call long running things
sm_lock.release()
if trumpy_state == State.role_dispatch:
# should not happen?
applog.info('tame: mic on')
hmqtt.tts_unmute()
tame_mycroft()
# The state machine controls the interaction with mycroft(replys),
# mqttcamera and other events.
# BE WATCHFUL about threading
# mqtt calls into state_machine() on it's thread(s).
# You can block it with a sleep(). That's OK in most situations.
# Most of the sleeps are ad hoc timing to keep mycroft
# queue from building since it is LIFO
def mean_machine(evt, arg=None):
global applog, settings, hmqtt, trumpy_state, trumpy_bear
global sm_lock, waitcnt, playSiren, registering
applog.debug("Sm entry {} {}".format(trumpy_state, evt))
cur_state = trumpy_state
# lock machine
sm_lock.acquire()
next_state = None
if evt == Event.motion:
# ignore motion
next_state = cur_state
elif evt == Event.start:
trumpy_state = State.starting
next_state = State.waitrange
waitcnt = 0
hmqtt.set_status('running')
hmqtt.tts_unmute()
hmqtt.display_text('Trumpy Bear is awake')
# not used in trumpybear v2:
# hmqtt.ask('awaken the hooligans')
#TODO: what is this: hmqtt.name()
if settings.ranger_type is not None:
#hmqtt.ranger_mode(settings.ranger_mode)
#hmqtt.start_ranger(75)
# V2 uses a range
start_ranger(settings.ranger_upper, settings.ranger_lower, State.waitrange)
elif evt == Event.reply:
if arg != None:
flds = arg.split('=')
ans_typ = flds[0]
if len(flds) == 2: arg = flds[1]
else:
applog.warn("null arg")
if trumpy_state == State.aborting or trumpy_state == State.initialized:
# This can happen when the switch is turned off and mycroft is
# interacting (publishing to reply/set)
applog.info('swallowing Event.reply in State.aborting')
next_state = State.aborting
#pass
elif trumpy_state == State.waitname:
# have a name. Maybe.
if arg == None or arg == '':
if waitcnt < 2:
next_state = State.waitname # do over
hmqtt.speak("I didn't catch that. Wait for the tone, Kay?")
time.sleep(1)
waitcnt += 1
# not used in trumpybear v2:
#hmqtt.ask('awaken the hooligans')
hmqtt.ask_name()
else:
next_state = State.role_dispatch
trumpy_bear.role = Role.unknown
else:
trumpy_bear = TrumpyBear(settings, arg)
role = trumpy_bear.check_user(arg)
# For Testing, force role.unknown
# role = Role.unknown
if role == Role.owner:
hmqtt.speak(f"Verifying {trumpy_bear.name}")
hmqtt.display_text(f"Verifying {trumpy_bear.name}")
else:
hmqtt.speak("I'm going to take your picture. Face the bear and stand up straight")
hmqtt.display_text("Face the Bear")
time.sleep(2)
next_state = State.waitface
request_picture('face')
elif trumpy_state == State.four_qs:
next_state = State.four_qs
if ans_typ == 'ans1':
trumpy_bear.ans1 = arg
hmqtt.display_text('dialing..')
time.sleep(2.0)
hmqtt.display_text('connected..')
time.sleep(3.0)
hmqtt.display_text('On Their way')
elif ans_typ == 'ans2':
trumpy_bear.ans2 = arg
time.sleep(2)
hmqtt.display_text("Arming Defenses")
elif ans_typ == 'ans3':
trumpy_bear.ans3 = arg
time.sleep(2)
hmqtt.display_text('Music or Talk?')
elif ans_typ == 'ans4':
applog.debug(f"answered {arg}")
trumpy_bear.ans4 = arg
if arg == 'talk':
# TODO: start mycroft
next_state = State.role_dispatch
elif arg == 'music' or arg == None:
# leave the state_machine cycle
next_state = State.role_dispatch
else:
next_state = State.role_dispatch
else:
applog.warn(f'unknown ans {ans_typ} {arg}')
else:
applog.debug('no handler in {} for {}'.format(trumpy_state, evt))
elif evt == Event.pict:
if trumpy_state == State.aborting or trumpy_state == State.initialized:
# This can happen when the picture is canceled by user action
# interacting (publishing to reply/set)
applog.info('swallowing Event.reply in State.aborting')
next_state = State.aborting
if trumpy_state == State.waitface:
# V1 hmqtt.start_ranger(0);
# TODO v2: do we need start_ranger(0, 0, );
trumpy_bear.face_path = "/var/www/camera/face.jpg"
aud_name = trumpy_bear.name
# recognition is synchronous, not an event
vis_name = do_recog(trumpy_bear)
applog.debug(f'recognized {vis_name} using {aud_name}')
if vis_name != None:
vis_role = trumpy_bear.check_user(vis_name)
if vis_role == Role.owner:
trumpy_bear.name = aud_name
trumpy_bear.check_user(aud_name)
else:
# camera overrides lying talkers.
trumpy_bear.name = vis_name
else:
trumpy_bear.role = Role.unknown
trumpy_bear.save_user()
hmqtt.speak('Got it')
if trumpy_bear.role == Role.unknown:
time.sleep(1)
next_state = State.four_qs
hmqtt.display_text('You are Unknown')
hmqtt.ask_music_or_talk()
#hmqtt.ask('send in the terrapin')
else:
next_state = State.role_dispatch
hmqtt.speak('Your access permissions are being checked, {}'.format(trumpy_bear.name))
hmqtt.display_text('Hi {}'.format(trumpy_bear.name))
else:
applog.debug('no handler in {} for {}'.format(trumpy_state, evt))
elif evt == Event.ranger:
applog.info(f'in mean machine arg is {arg}')
rng = arg
next_state = trumpy_state
print(f'ranger stop at {rng}')
if rng == 0:
# timed out. Disappered from view. The perp can't follow instructions
next_state = State.role_dispatch
trumpy_bear = TrumpyBear(settings, 'perp')
hmqtt.speak('I asked nicely. Oh Well. You should have made a better choice.');
if trumpy_state == State.waitrange:
# we ask for their name, which generates a Event.reply
next_state = State.waitname
hmqtt.ask_name()
elif evt == Event.abort:
next_state = State.aborting
elif evt == Event.watchdog:
# TODO: implement. maybe.
applog.debug('no handler in {} for {}'.format(trumpy_state, evt))
else:
applog.warn("Unhandled event: %s" % evt)
# end the pass through the state machine
trumpy_state = next_state
applog.debug("Sm exit {} {} => {}".format(cur_state, evt, trumpy_state))
# unlock machine
sm_lock.release()
if trumpy_state == State.aborting:
trumpy_state = State.initialized
interaction_canceled()
if trumpy_state == State.role_dispatch:
trumpy_state = State.initialized
role_dispatch(trumpy_bear)
# Yes there is a lot of duplication. It's better than weird args and globals
# - we have enough of those.
def login_machine(evt, arg=None):
global applog, settings, hmqtt, trumpy_state, trumpy_bear
global sm_lock, waitcnt
applog.debug("lm entry {} {}".format(trumpy_state, evt))
cur_state = trumpy_state
# lock machine
sm_lock.acquire()
next_state = None
if evt == Event.abort:
next_state = State.aborting
elif evt == Event.motion:
# ignore motion events
next_state = cur_state
elif evt == Event.start:
next_state = State.waitrecog
time.sleep(1)
trumpy_bear = TrumpyBear(settings, None)
trumpy_bear.face_path = "/var/www/camera/face.jpg"
if os.path.isfile(trumpy_bear.face_path):
applog.info(f'removing old pict {trumpy_bear.face_path}')
os.remove(trumpy_bear.face_path)
else:
applog.info(f'no file to delete {trumpy_bear.face_path}')
request_picture('face')
elif evt == Event.reply:
# no voice replys
next_state = cur_state
elif evt == Event.pict:
if trumpy_state == State.waitrecog:
# doing a login
# recognition is synchronous, not an event
applog.debug(f'lm calling recog for {trumpy_bear}')
vis_name = do_recog(trumpy_bear)
applog.debug(f'recognized {vis_name}')
if vis_name != None and vis_name != 'None':
vis_role = trumpy_bear.check_user(vis_name)
hmqtt.display_text(f'Hello {vis_name}. Unlocking')
hmqtt.tts_unmute()
trumpy_bear.save_user()
hmqtt.speak("Oh, it's you.")
time.sleep(0.25)
hmqtt.speak("It's been a long time.")
time.sleep(1.5)
hmqtt.speak("How have you been?")
dt = {"cmd": "user", "user": vis_name, "role": vis_role}
hmqtt.login(json.dumps(dt))
logout_timer()
next_state = State.starting
else:
# not a registered person - ignore
hmqtt.display_text("I don't recognize you. It is about to get Very not good.")
applog.info(f'unknown person ({vis_name}) attempting login')
next_state = State.starting
else:
applog.debug(f'no handler in {trumpy_state} for {evt}')
elif evt == Event.ranger:
next_state = cur_state
else:
applog.warn(f"Unhandled event: {evt} in login_machine")
trumpy_state = next_state
applog.debug("lm exit {} {} => {}".format(cur_state, evt, trumpy_state))
# unlock machine
sm_lock.release()
# nothing else to do for a panel login.
if trumpy_state == State.aborting:
trumpy_state = State.initialized
trumpy_bear = None
if trumpy_state == State.role_dispatch:
trumpy_state = State.initialized
trumpy_bear = None
# role_dispatch(trumpy_bear)
def register_machine(evt, arg=None):
global applog, settings, hmqtt, trumpy_state, trumpy_bear
global sm_lock, waitcnt
applog.debug("rm entry {} {}".format(trumpy_state, evt))
cur_state = trumpy_state
# lock machine
sm_lock.acquire()
next_state = None
if evt == Event.abort:
next_state = State.aborting
elif evt == Event.motion:
# ignore motion events
next_state = cur_state
elif evt == Event.start:
trumpy_state = State.starting
next_state = State.waitrange
waitcnt = 0
hmqtt.set_status('running')
hmqtt.tts_unmute()
hmqtt.display_text('Trumpy Bear is waiting')
hmqtt.speak("Don't be shy. Come over here, a meter away would be nice. Thats a yard, you know")
if settings.ranger_type is not None:
#hmqtt.ranger_mode(settings.ranger_mode)
#hmqtt.start_ranger(75)
start_ranger(settings.ranger_upper, settings.ranger_lower, State.waitrange)
elif evt == Event.reply:
if arg != None:
flds = arg.split('=')
ans_typ = flds[0]
if len(flds) == 2: arg = flds[1]
else:
applog.warn("null arg")
if trumpy_state == State.aborting:
# This can happen when the switch is turned off and mycroft is
# interacting (publishing to reply/set)
next_state = State.aborting
elif trumpy_state == State.waitname:
# have a name. Maybe.
if arg == None or arg == '':
if waitcnt < 2:
next_state = State.waitname # do over
hmqtt.speak("I didn't catch that. Wait for the tone, Kay?")
time.sleep(1)
waitcnt += 1
hmqtt.T('awaken the hooligans')
else:
hmqtt.speak("Too many failures to continue")
hmqtt.display_text('Please retry from beginning')
next_state = State.starting
else:
# Register
trumpy_bear = TrumpyBear(settings, arg)
role = trumpy_bear.check_user(arg)
hmqtt.speak("I'm going to take your picture. Face the bear and please try to stand up straight.")
hmqtt.display_text("Face the Bear")
time.sleep(2)
next_state = State.waitface
request_picture('face')
elif evt == Event.pict:
if trumpy_state == State.waitface:
name1 = trumpy_bear.name
hmqtt.speak("Thank you, I suppose.")
hmqtt.tts_mute()
hmqtt.display_text(f"Saving {name1}'s picture")
# finish registration - have face and picture.
# send them to fc server
trumpy_bear.face_path = "/var/www/camera/face.jpg"
# save_recog(trumpy_bear) This should not be needed. TODO: delete.
trumpy_bear.save_user()
do_recog(trumpy_bear)
if trumpy_bear.name == name1:
hmqtt.display_text(f'Registered {trumpy_bear.name}')
hmqtt.speak("I guess you'll push the login button before I change my mind")
else:
hmqtt.speak("Your name doesn't match the picture. Talk to Cecil, maybe he will care.")
hmqtt.display_text("Please restart")
next_state = State.starting
else:
applog.debug('no handler in {} for {}'.format(trumpy_state, evt))
elif evt == Event.ranger:
rng = int(arg)
print(f'ranger stop at {rng}')
if rng == 0:
# ranger timed out. They didn't follow instructions
next_state = State.aborting
hmqtt.speak('Try Again');
elif trumpy_state == State.waitrange:
next_state = State.waitname
hmqtt.ask_name()
# not used in trumpybear v2:
# hmqtt.ask('awaken the hooligans')
elif evt == Event.abort:
next_state = State.aborting
elif evt == Event.watchdog:
# TODO: implement. maybe.
applog.debug('no handler in {} for {}'.format(trumpy_state, evt))
else:
applog.warn("Unhandled event: %s" % evt)
trumpy_state = next_state
applog.debug("rm exit {} {} => {}".format(cur_state, evt, trumpy_state))
# unlock machine
sm_lock.release()
if trumpy_state == State.aborting:
trumpy_state = State.initialized
trumpy_bear = None
if trumpy_state == State.role_dispatch:
trumpy_state = State.initialized
trumpy_bear = None
def role_dispatch(trumpy_bear):
global applog
role = trumpy_bear.role
applog.info(f'Dispatch: {trumpy_bear.name} is {role}')
if role == Role.player:
begin_rasa(trumpy_bear)
elif role == Role.friend or role == Role.aquaintance or role == Role.relative:
#begin_mycroft()
begin_glados()
elif role == Role.owner:
hmqtt.speak("You are very annoying, {}. Are you with the failing New York Times?".format(trumpy_bear.name))
interaction_finished()
elif role == Role.unknown:
if trumpy_bear.ans4 == 'talk':
#begin_mycroft()
begin_glados()
else:
begin_intruder()
else:
interaction_finished()
def logout_timer_fired():
global hmqtt, applog, active_timer
hmqtt.login('{"cmd": "logout"}')
hmqtt.display_cmd("off")
hmqtt.tts_mute()
applog.info('logging off')
def logout_timer(min=5):
global active_timer
print('creating logout timer')
active_timer = threading.Timer(min * 60, logout_timer_fired)
active_timer.start()
def extend_logout(min=3):
global active_timer
# cancel current timer
if active_timer:
print('reset logout timer')
active_timer.cancel()
active_timer = None
logout_timer(min)
def long_timer_fired():
print('timer_long fired')
interaction_finished()
def long_timer(min=5):
global timerl_thread
print('creating long timer')
timerl_thread = threading.Timer(min * 60, long_timer_fired)
timerl_thread.start()
# called directly or via long_timer()
def interaction_finished():
global hmqtt, warning_level, state_machine
applog.info('closing interaction')
hmqtt.tts_mute()
hmqtt.display_cmd('off')
hmqtt.set_status('ready')
if state_machine == mean_machine:
hmqtt.cops_arrive()
new_sm(tame_machine)
def interaction_canceled():
global hmqtt, warning_level, state_machine
applog.info('canceled interaction')
hmqtt.tts_mute()
hmqtt.display_cmd('off')
hmqtt.set_status('ready')
new_sm(tame_machine)
def begin_mycroft():
global hmqtt, applog
applog.info('starting mean mycroft')
hmqtt.tts_unmute()
long_timer(2)
hmqtt.speak('You have to say "Hey Mycroft", wait for the beep and then ask your question. \
Try "hey mycroft", what about the lasers')
hmqtt.display_text("say 'Hey Mycroft'")
def begin_glados():
global hmqtt, applog
applog.info('starting GLaDOS')
hmqtt.tts_unmute()
long_timer(5)
# tell the bridge to do the chat stuff.
hmqtt.begin_chat()
hmqtt.display_text("You may regret that choice")
def tame_mycroft():
global hmqtt, applog
applog.info('tame mycroft running')
hmqtt.tts_unmute()
long_timer(4)
hmqtt.display_text("Mycroft Active")
def begin_rasa(tb):
global hmqtt, applog
applog.info('starting rasa')
hmqtt.display_text(f"{tb.name} to see Mr. Sanders")
#hmqtt.speak("Mister Sanders is not available {}. Try later.".format(tb.name))
# not used in trumpybear v2:
# hmqtt.ask('Mister Sanders, {} is here'.format(tb.name))
long_timer(1)
def begin_intruder():
global applog, hmqtt
applog.info('begin intruder')
hmqtt.start_music_alarm() # sets mqtt switch to wake up a HE rule
hmqtt.display_text("Lasers are Tracking")
begin_tracking(0.5, False, False);
print('exiting intruder')
long_timer(2)
# return name string or None for the picture (path) in
# TrumpyBear object.
def do_recog(tb):
global applog, settings
applog.debug(f'get_face_name {tb.face_path}')
bfr = open(tb.face_path, 'rb').read()
# Use websocket-client, find one that is up and running.
ws = websocket.WebSocket()
for ip in settings.face_server_ip:
try:
uri = f'ws://{ip}:{settings.face_port}'
applog.debug(f'do_recog() trying {ip}')
ws.connect(uri, timeout=1)
break
except ConnectionRefusedError:
applog.warning(f'Fail {ip} Switching to next backup')
ws.send(base64.b64encode(bfr))
reply = ws.recv()
ws.close()
js = json.loads(reply)
details = js['details']
mats = details['matrices']
names = []
for i in range(len(mats)):
names.append(mats[i]['tag'])
if len(names) == 0:
names = [None]
return names[0]
def request_picture(typ):
global settings, hmqtt, applog, video_dev
# get a picture from the camera
topic = "homie/%s/control/cmd/set" % settings.homie_device
path = f"/var/www/camera/{typ}.jpg"
payload = {"reply": topic,
"path": path}
applog.debug(f"capture ask {settings.camera_topic} {json.dumps(payload)}")
if settings.local_cam is None:
hmqtt.client.publish(settings.camera_topic, 'capture='+json.dumps(payload))
else:
#th = Thread(target=capture_camera_capture_to_file, args=(json.dumps(payload),))
#th.start()
capture_camera_capture_to_file(json.dumps(payload))
def capture_read_cam(dim):
global video_dev
cnt = 0
ret = False
frame = None
frame_n = None
while cnt < 120:
ret, frame = video_dev.read()
if ret == True and np.shape(frame) != ():
frame_n = cv2.resize(frame, dim)
break
cnt += 1
if cnt >= 120:
print("Crashing soon")
return frame_n
def capture_camera_capture_to_file(jsonstr):
global video_dev, applog, state_machine, hmqtt, settings
args = json.loads(jsonstr)
applog.debug("begin capture on demand")
video_dev = cv2.VideoCapture(settings.local_cam)
fr = capture_read_cam((640,480))
cv2.imwrite(args['path'], fr)
video_dev.release()
applog.debug("local Capture to %s reply %s" % (args['path'], args['reply']))
#state_machine(Event.pict)
hmqtt.client.publish(args['reply'], json.dumps({"cmd": "capture_done"}))
def wakeup_mean():
global settings, hmqtt, applog
global pict_count
global state_machine
pict_count = 0
new_sm(mean_machine)
applog.info("Trumpy Bear awakens")
hmqtt.tts_unmute()
hmqtt.speak("Trumpy Bear sees you. Approach and face the Bear!")
state_machine(Event.start)
hmqtt.client.publish(settings.status_topic, 'awakens')
# if w/o ranger
#if settings.ranger_type == None:
# time.sleep(0.25)
# state_machine(Event.ranger, )
def wakeup_register():
global settings, hmqtt, applog
global pict_count
global state_machine
pict_count = 0
time.sleep(1)
new_sm(register_machine)
applog.info("Trumpy Bear awakens")
hmqtt.tts_unmute()
state_machine(Event.start)
hmqtt.client.publish(settings.status_topic, 'registering')
def wakeup_login():
global settings, hmqtt, applog
global pict_count
global state_machine
pict_count = 0
time.sleep(1)
new_sm(login_machine)
applog.info("Trumpy Bear login attempt")
state_machine(Event.start, 'login')
hmqtt.client.publish(settings.status_topic, 'login')
def begin_logout():
global settings, hmqtt, applog, tracking_stop_flag, tame_machine
global state_machine
hmqtt.display_cmd(self, 'off')
tracking_stop_flag = True
new_sm(tame_machine)
# the command channel controls the device from hubitat via mqtt
# AND from the Touch Screen (login) app
def trumpy_recieve(jsonstr):
global settings, hmqtt, applog, trumpy_bear, trumpy_state
global state_machine, startupTime
if time.time() < (startupTime + 30):
# hack. ignore mqtt messages for 30 seconds.
applog.info(f'ignoring {jsonstr}')
return
rargs = json.loads(jsonstr)
cmd = rargs['cmd']
if cmd == 'init':
'''
# hubitat can send an init, which can override camera motion sensor choice in json
topic = rargs['reply']
settings.camera_topic = 'homie/'+topic+'/motionsensor/control/set'
settings.status_topic = 'homie/'+settings.homie_device+'/control/cmd'
hmqtt.client.publish(settings.status_topic,'initialized')
'''
trumpy_state = State.initialized
elif cmd == 'begin':
# this came from hubitat (mqtt switchy alarmy driver thingy) OR debug with
# mosquitto_pub -h pi4 -t homie/trumpy_bear/control/cmd/set -m '{"cmd": "begin"}'
# wake up TrumpyBear (mean mode)
wakeup_mean()
elif cmd == 'login':
wakeup_login()
elif cmd == 'register':
wakeup_register()
elif cmd == 'end':
# abort and reset. Hubitat can do this in a number of ways.
state_machine(Event.abort)
elif cmd == 'capture_done':
if state_machine is None:
applog.warning('Cecil, init the state_machine')
state_machine(Event.pict)
elif cmd == 'keepalive':
s = rargs.get('minutes', 2)
extend_logout(s)
elif cmd == 'mycroft':
#begin_mycroft()
begin_glados()
elif cmd == 'glados':
begin_glados()
elif cmd == 'track':
try:
dbg = rargs.get('debug',False)
test = rargs.get('test',False)
applog.info('calling begin_tracking')
begin_tracking(0.1, dbg, test)
except:
traceback.print_exc()
elif cmd == 'ranger_test':
begin_ranger_calibrate(rargs['distance'],rargs['delay'])
elif cmd == 'calib':
begin_calibrate(rargs['distance'],rargs['time'])
elif cmd == 'closing':
# Front panel logoff - probably manual.
begin_logout
elif cmd == 'get_turrets':
dt = {'cmd': 'set_turrets', 'turrets': settings.turrets}
hmqtt.login(json.dumps(dt))