forked from runmyrobot/runmyrobot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
controller.py
1435 lines (1110 loc) · 43 KB
/
controller.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
import platform
import os
import uuid
import urllib2
import json
import traceback
import tempfile
import re
import getpass
#import configparser
import sys
import argparse
import random
import telly
import robot_util
parser = argparse.ArgumentParser(description='start robot control program')
parser.add_argument('robot_id', help='Robot ID')
parser.add_argument('--info-server', help="Server that robot will connect to for information about servers and things", default='letsrobot.tv')
parser.add_argument('--type', help="Serial or motor_hat or gopigo2 or gopigo3 or l298n or motozero or pololu or mdd10", default='motor_hat')
parser.add_argument('--serial-device', help="Serial device", default='/dev/ttyACM0')
parser.add_argument('--male', dest='male', action='store_true')
parser.add_argument('--female', dest='male', action='store_false')
parser.add_argument('--voice-number', type=int, default=1)
parser.add_argument('--led', help="Type of LED for example max7219", default=None)
parser.add_argument('--ledrotate', help="Rotates the LED matrix. Example: 180", default=None)
parser.add_argument('--tts-volume', type=int, default=80)
parser.add_argument('--secret-key', default=None)
parser.add_argument('--turn-delay', type=float, default=0.4)
parser.add_argument('--straight-delay', type=float, default=0.5)
parser.add_argument('--driving-speed', type=int, default=90)
parser.add_argument('--day-speed', type=int, default=255)
parser.add_argument('--night-speed', type=int, default=255)
parser.add_argument('--forward', default='[-1,1,-1,1]')
parser.add_argument('--left', default='[1,1,1,1]')
parser.add_argument('--festival-tts', dest='festival_tts', action='store_true')
parser.set_defaults(festival_tts=False)
parser.add_argument('--auto-wifi', dest='auto_wifi', action='store_true')
parser.set_defaults(auto_wifi=False)
parser.add_argument('--no-anon-tts', dest='anon_tts', action='store_false')
parser.set_defaults(anon_tts=True)
parser.add_argument('--no-chat-server-connection', dest='enable_chat_server_connection', action='store_false')
parser.set_defaults(enable_chat_server_connection=True)
parser.add_argument('--no-secure-cert', dest='secure_cert', action='store_false')
parser.set_defaults(secure_cert=True)
parser.add_argument('--filter-url-tts', dest='filter_url_tts', action='store_true')
parser.set_defaults(filter_url_tts=False)
parser.add_argument('--slow-for-low-battery', dest='slow_for_low_battery', action='store_true')
parser.set_defaults(slow_for_low_battery=False)
parser.add_argument('--reverse-ssh-key-file', default='/home/pi/reverse_ssh_key1.pem')
parser.add_argument('--reverse-ssh-host', default='[email protected]')
parser.add_argument('--charge-hours', type=float, default = 3.0)
parser.add_argument('--discharge-hours', type=float, default = 8.0)
parser.add_argument('--right-wheel-forward-speed', type=int)
parser.add_argument('--right-wheel-backward-speed', type=int)
parser.add_argument('--left-wheel-forward-speed', type=int)
parser.add_argument('--left-wheel-backward-speed', type=int)
parser.add_argument('--led-max-brightness', type=int)
commandArgs = parser.parse_args()
print commandArgs
chargeCheckInterval = 5
chargeValue = 0.0
secondsToCharge = 60.0 * 60.0 * commandArgs.charge_hours
secondsToDischarge = 60.0 * 60.0 * commandArgs.discharge_hours
maxSpeedEnabled = False
# watch dog timer
os.system("sudo modprobe bcm2835_wdt")
os.system("sudo /usr/sbin/service watchdog start")
# set volume level
# tested for 3.5mm audio jack
os.system("amixer set PCM -- 100%d%%" % commandArgs.tts_volume)
#if commandArgs.tts_volume > 50:
#os.system("amixer set PCM -- -100")
# tested for USB audio device
os.system("amixer -c 2 cset numid=3 %d%%" % commandArgs.tts_volume)
infoServer = commandArgs.info_server
#infoServer = "letsrobot.tv"
#infoServer = "runmyrobot.com"
#infoServer = "52.52.213.92"
#infoServer = "letsrobot.tv:3100"
print "info server:", infoServer
tempDir = tempfile.gettempdir()
print "temporary directory:", tempDir
# motor controller specific intializations
if commandArgs.type == 'none':
pass
elif commandArgs.type == 'serial':
import serial
elif commandArgs.type == 'motor_hat':
pass
elif commandArgs.type == 'gopigo2':
import gopigo
elif commandArgs.type == 'gopigo3':
sys.path.append("/home/pi/Dexter/GoPiGo3/Software/Python")
import easygopigo3
easyGoPiGo3 = easygopigo3.EasyGoPiGo3()
elif commandArgs.type == 'l298n':
try:
import configparser
except ImportError:
print "You need to install configparser (sudo python -m pip install configparser)\n Ctrl-C to quit"
while True:
pass # Halt program to avoid error down the line.
elif commandArgs.type == 'motozero':
pass
elif commandArgs.type == 'pololu':
pass
elif commandArgs.type == 'screencap':
pass
elif commandArgs.type == 'adafruit_pwm':
from Adafruit_PWM_Servo_Driver import PWM
elif commandArgs.led == 'max7219':
import spidev
elif commandArgs.type == 'owi_arm':
import owi_arm
elif commandArgs.type == 'mdd10':
pass
else:
print "invalid --type in command line"
exit(0)
serialDevice = commandArgs.serial_device
if commandArgs.type == 'motor_hat':
try:
from Adafruit_MotorHAT import Adafruit_MotorHAT, Adafruit_DCMotor
motorsEnabled = True
except ImportError:
print "You need to install Adafruit_MotorHAT"
print "Please install Adafruit_MotorHAT for python and restart this script."
print "To install: cd /usr/local/src && sudo git clone https://github.com/adafruit/Adafruit-Motor-HAT-Python-Library.git"
print "cd /usr/local/src/Adafruit-Motor-HAT-Python-Library && sudo python setup.py install"
print "Running in test mode."
print "Ctrl-C to quit"
motorsEnabled = False
# todo: specificity is not correct, this is specific to a bot with a claw, not all motor_hat based bots
if commandArgs.type == 'motor_hat':
from Adafruit_PWM_Servo_Driver import PWM
import time
import atexit
import sys
import thread
import subprocess
if (commandArgs.type == 'motor_hat') or (commandArgs.type == 'l298n') or (commandArgs.type == 'motozero'):
import RPi.GPIO as GPIO
import datetime
from socketIO_client import SocketIO, LoggingNamespace
chargeIONumber = 17
robotID = commandArgs.robot_id
if commandArgs.type == 'motor_hat':
GPIO.setmode(GPIO.BCM)
GPIO.setup(chargeIONumber, GPIO.IN)
if commandArgs.type == 'l298n':
mode=GPIO.getmode()
print " mode ="+str(mode)
GPIO.cleanup()
#Change the GPIO Pins to your connected motors in gpio.conf
#visit http://bit.ly/1S5nQ4y for reference
gpio_config = configparser.ConfigParser()
gpio_config.read('gpio.conf')
if str(robotID) in gpio_config.sections():
config_id = str(robotID)
else:
config_id = 'default'
StepPinForward = int(str(gpio_config[config_id]['StepPinForward']).split(',')[0]),int(str(gpio_config[config_id]['StepPinForward']).split(',')[1])
StepPinBackward = int(str(gpio_config[config_id]['StepPinBackward']).split(',')[0]),int(str(gpio_config[config_id]['StepPinBackward']).split(',')[1])
StepPinLeft = int(str(gpio_config[config_id]['StepPinLeft']).split(',')[0]),int(str(gpio_config[config_id]['StepPinLeft']).split(',')[1])
StepPinRight = int(str(gpio_config[config_id]['StepPinRight']).split(',')[0]),int(str(gpio_config[config_id]['StepPinRight']).split(',')[1])
GPIO.setmode(GPIO.BOARD)
GPIO.setup(StepPinForward, GPIO.OUT)
GPIO.setup(StepPinBackward, GPIO.OUT)
GPIO.setup(StepPinLeft, GPIO.OUT)
GPIO.setup(StepPinRight, GPIO.OUT)
#Test if user
if commandArgs.type == "pololu":
try:
from pololu_drv8835_rpi import motors, MAX_SPEED
except ImportError:
print "You need to install drv8835-motor-driver-rpi"
print "Please install drv8835-motor-driver-rpi for python and restart this script."
print "To install: cd /usr/local/src && sudo git clone https://github.com/pololu/drv8835-motor-driver-rpi"
print "cd /usr/local/src/drv8835-motor-driver-rpi && sudo python setup.py install"
print "Running in test mode."
print "Ctrl-C to quit"
if commandArgs.type == 'motozero':
GPIO.cleanup()
GPIO.setmode(GPIO.BCM)
# Motor1 is back left
# Motor1A is reverse
# Motor1B is forward
Motor1A = 24
Motor1B = 27
Motor1Enable = 5
# Motor2 is back right
# Motor2A is reverse
# Motor2B is forward
Motor2A = 6
Motor2B = 22
Motor2Enable = 17
# Motor3 is ?
# Motor3A is reverse
# Motor3B is forward
Motor3A = 23
Motor3B = 16
Motor3Enable = 12
# Motor4 is ?
# Motor4A is reverse
# Motor4B is forward
Motor4A = 13
Motor4B = 18
Motor4Enable = 25
GPIO.setup(Motor1A,GPIO.OUT)
GPIO.setup(Motor1B,GPIO.OUT)
GPIO.setup(Motor1Enable,GPIO.OUT)
GPIO.setup(Motor2A,GPIO.OUT)
GPIO.setup(Motor2B,GPIO.OUT)
GPIO.setup(Motor2Enable,GPIO.OUT)
GPIO.setup(Motor3A,GPIO.OUT)
GPIO.setup(Motor3B,GPIO.OUT)
GPIO.setup(Motor3Enable,GPIO.OUT)
GPIO.setup(Motor4A,GPIO.OUT)
GPIO.setup(Motor4B,GPIO.OUT)
GPIO.setup(Motor4Enable,GPIO.OUT)
#Cytron MDD10 GPIO setup
if commandArgs.type == 'mdd10' :
# pwm.setPWMFreq(60)
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
AN2 = 13
AN1 = 12
DIG2 = 24
DIG1 = 26
GPIO.setup(AN2, GPIO.OUT)
GPIO.setup(AN1, GPIO.OUT)
GPIO.setup(DIG2, GPIO.OUT)
GPIO.setup(DIG1, GPIO.OUT)
time.sleep(1)
p1 = GPIO.PWM(AN1, 100)
p2 = GPIO.PWM(AN2, 100)
#LED controlling
if commandArgs.led == 'max7219':
spi = spidev.SpiDev()
spi.open(0,0)
#VCC -> RPi Pin 2
#GND -> RPi Pin 6
#DIN -> RPi Pin 19
#CLK -> RPi Pin 23
#CS -> RPi Pin 24
# decoding:BCD
spi.writebytes([0x09])
spi.writebytes([0x00])
# Start with low brightness
spi.writebytes([0x0a])
spi.writebytes([0x03])
# scanlimit; 8 LEDs
spi.writebytes([0x0b])
spi.writebytes([0x07])
# Enter normal power-mode
spi.writebytes([0x0c])
spi.writebytes([0x01])
# Activate display
spi.writebytes([0x0f])
spi.writebytes([0x00])
columns = [0x1,0x2,0x3,0x4,0x5,0x6,0x7,0x8]
LEDOn = [0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF]
LEDOff = [0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0]
LEDEmoteSmile = [0x0,0x0,0x24,0x0,0x42,0x3C,0x0,0x0]
LEDEmoteSad = [0x0,0x0,0x24,0x0,0x0,0x3C,0x42,0x0]
LEDEmoteTongue = [0x0,0x0,0x24,0x0,0x42,0x3C,0xC,0x0]
LEDEmoteSuprise = [0x0,0x0,0x24,0x0,0x18,0x24,0x24,0x18]
if commandArgs.ledrotate == '180':
LEDEmoteSmile = LEDEmoteSmile[::-1]
LEDEmoteSad = LEDEmoteSad[::-1]
LEDEmoteTongue = LEDEmoteTongue[::-1]
LEDEmoteSuprise = LEDEmoteSuprise[::-1]
def SetLED_On():
if commandArgs.led == 'max7219':
for i in range(len(columns)):
spi.xfer([columns[i],LEDOn[i]])
def SetLED_Off():
if commandArgs.led == 'max7219':
for i in range(len(columns)):
spi.xfer([columns[i],LEDOff[i]])
def SetLED_E_Smiley():
if commandArgs.led == 'max7219':
for i in range(len(columns)):
spi.xfer([columns[i],LEDEmoteSmile[i]])
def SetLED_E_Sad():
if commandArgs.led == 'max7219':
for i in range(len(columns)):
spi.xfer([columns[i],LEDEmoteSad[i]])
def SetLED_E_Tongue():
if commandArgs.led == 'max7219':
for i in range(len(columns)):
spi.xfer([columns[i],LEDEmoteTongue[i]])
def SetLED_E_Suprised():
if commandArgs.led == 'max7219':
for i in range(len(columns)):
spi.xfer([columns[i],LEDEmoteSuprise[i]])
def SetLED_Low():
if commandArgs.led == 'max7219':
# brightness MIN
spi.writebytes([0x0a])
spi.writebytes([0x00])
def SetLED_Med():
if commandArgs.led == 'max7219':
#brightness MED
spi.writebytes([0x0a])
spi.writebytes([0x06])
def SetLED_Full():
if commandArgs.led == 'max7219':
# brightness MAX
spi.writebytes([0x0a])
spi.writebytes([0x0F])
SetLED_Off()
steeringSpeed = 90
steeringHoldingSpeed = 90
global drivingSpeed
#drivingSpeed = 90
drivingSpeed = commandArgs.driving_speed
handlingCommand = False
# Marvin
turningSpeedActuallyUsed = 250
dayTimeDrivingSpeedActuallyUsed = commandArgs.day_speed
nightTimeDrivingSpeedActuallyUsed = commandArgs.night_speed
# Initialise the PWM device
if commandArgs.type == 'motor_hat':
pwm = PWM(0x42)
elif commandArgs.type == 'adafruit_pwm':
pwm = PWM(0x40)
# Note if you'd like more debug output you can instead run:
#pwm = PWM(0x40, debug=True)
servoMin = [150, 150, 130] # Min pulse length out of 4096
servoMax = [600, 600, 270] # Max pulse length out of 4096
armServo = [300, 300, 300]
#def setMotorsToIdle():
# s = 65
# for i in range(1, 2):
# mh.getMotor(i).setSpeed(s)
# mh.getMotor(i).run(Adafruit_MotorHAT.FORWARD)
#if commandArgs.env == 'dev':
# print 'DEV MODE ***************'
# print "using dev port 8122"
# port = 8122
#elif commandArgs.env == 'prod':
# print 'PROD MODE *************'
# print "using prod port 8022"
# port = 8022
#else:
# print "invalid environment"
# sys.exit(0)
if commandArgs.type == 'serial':
# initialize serial connection
serialBaud = 9600
print "baud:", serialBaud
#ser = serial.Serial('/dev/tty.usbmodem12341', 19200, timeout=1) # open serial
ser = None
try:
ser = serial.Serial(serialDevice, serialBaud, timeout=1) # open serial
except:
print "error: could not open serial port"
try:
ser = serial.Serial('/dev/ttyACM0', serialBaud, timeout=1) # open serial
except:
print "error: could not open serial port /dev/ttyACM0"
try:
ser = serial.Serial('/dev/ttyUSB0', serialBaud, timeout=1) # open serial
except:
print "error: could not open serial port /dev/ttyUSB0"
try:
ser = serial.Serial('/dev/ttyUSB1', serialBaud, timeout=1) # open serial
except:
print "error: could not open serial port /dev/ttyUSB1"
try:
ser = serial.Serial('/dev/ttyUSB2', serialBaud, timeout=1) # open serial
except:
print "error: could not open serial port /dev/ttyUSB2"
if ser is None:
print "error: could not find any valid serial port"
else:
telly.sendSettings(ser, commandArgs)
def getControlHostPort():
url = 'https://%s/get_control_host_port/%s' % (infoServer, commandArgs.robot_id)
response = robot_util.getWithRetry(url, secure=commandArgs.secure_cert)
return json.loads(response)
def getChatHostPort():
url = 'https://%s/get_chat_host_port/%s' % (infoServer, commandArgs.robot_id)
response = robot_util.getWithRetry(url, secure=commandArgs.secure_cert)
return json.loads(response)
controlHostPort = getControlHostPort()
chatHostPort = getChatHostPort()
print "connecting to control socket.io", controlHostPort
controlSocketIO = SocketIO(controlHostPort['host'], controlHostPort['port'], LoggingNamespace)
print "finished using socket io to connect to control host port", controlHostPort
if commandArgs.enable_chat_server_connection:
print "connecting to chat socket.io", chatHostPort
chatSocket = SocketIO(chatHostPort['host'], chatHostPort['port'], LoggingNamespace)
print 'finished using socket io to connect to chat ', chatHostPort
else:
print "chat server connection disabled"
print "connecting to app server socket.io"
appServerSocketIO = SocketIO(infoServer, 8022, LoggingNamespace)
print "finished connecting to app server"
def setServoPulse(channel, pulse):
pulseLength = 1000000 # 1,000,000 us per second
pulseLength /= 60 # 60 Hz
print "%d us per period" % pulseLength
pulseLength /= 4096 # 12 bits of resolution
print "%d us per bit" % pulseLength
pulse *= 1000
pulse /= pulseLength
pwm.setPWM(channel, 0, pulse)
if commandArgs.type == 'motor_hat' or commandArgs.type == 'adafruit_pwm':
pwm.setPWMFreq(60) # Set frequency to 60 Hz
WPA_FILE_TEMPLATE = """ctrl_interface=DIR=/var/run/wpa_supplicant GROUP=netdev
update_config=1
country=GB
network={{
ssid=\"beepx\"
psk=\"yellow123\"
key_mgmt=WPA-PSK
}}
network={{
ssid=\"{name}\"
psk=\"{password}\"
key_mgmt=WPA-PSK
}}
"""
def isInternetConnected():
try:
urllib2.urlopen('https://www.google.com', timeout=1)
return True
except urllib2.URLError as err:
return False
def configWifiLogin(secretKey):
url = 'https://%s/get_wifi_login/%s' % (infoServer, secretKey)
try:
print "GET", url
response = urllib2.urlopen(url).read()
responseJson = json.loads(response)
print "get wifi login response:", response
with open("/etc/wpa_supplicant/wpa_supplicant.conf", 'r') as originalWPAFile:
originalWPAText = originalWPAFile.read()
wpaText = WPA_FILE_TEMPLATE.format(name=responseJson['wifi_name'], password=responseJson['wifi_password'])
print "original(" + originalWPAText + ")"
print "new(" + wpaText + ")"
if originalWPAText != wpaText:
wpaFile = open("/etc/wpa_supplicant/wpa_supplicant.conf", 'w')
print wpaText
print
wpaFile.write(wpaText)
wpaFile.close()
say("Updated wifi settings. I will automatically reset in 10 seconds.")
time.sleep(8)
say("Reseting")
time.sleep(2)
os.system("reboot")
except:
print "exception while configuring setting wifi", url
traceback.print_exc()
def incrementArmServo(channel, amount):
armServo[channel] += amount
print "arm servo positions:", armServo
if armServo[channel] > servoMax[channel]:
armServo[channel] = servoMax[channel]
if armServo[channel] < servoMin[channel]:
armServo[channel] = servoMin[channel]
pwm.setPWM(channel, 0, armServo[channel])
def times(lst, number):
return [x*number for x in lst]
def runMotor(motorIndex, direction):
motor = mh.getMotor(motorIndex+1)
if direction == 1:
motor.setSpeed(drivingSpeed)
motor.run(Adafruit_MotorHAT.FORWARD)
if direction == -1:
motor.setSpeed(drivingSpeed)
motor.run(Adafruit_MotorHAT.BACKWARD)
if direction == 0.5:
motor.setSpeed(128)
motor.run(Adafruit_MotorHAT.FORWARD)
if direction == -0.5:
motor.setSpeed(128)
motor.run(Adafruit_MotorHAT.BACKWARD)
forward = json.loads(commandArgs.forward)
backward = times(forward, -1)
left = json.loads(commandArgs.left)
right = times(left, -1)
straightDelay = commandArgs.straight_delay
turnDelay = commandArgs.turn_delay
#Change sleeptime to adjust driving speed
#Change rotatetimes to adjust the rotation. Will be multiplicated with sleeptime.
l298n_sleeptime=0.2
l298n_rotatetimes=5
def handle_exclusive_control(args):
if 'status' in args and 'robot_id' in args and args['robot_id'] == robotID:
status = args['status']
if status == 'start':
print "start exclusive control"
if status == 'end':
print "end exclusive control"
def say(message):
tempFilePath = os.path.join(tempDir, "text_" + str(uuid.uuid4()))
f = open(tempFilePath, "w")
f.write(message)
f.close()
#os.system('"C:\Program Files\Jampal\ptts.vbs" -u ' + tempFilePath) Whaa?
if commandArgs.festival_tts:
# festival tts
os.system('festival --tts < ' + tempFilePath)
#os.system('espeak < /tmp/speech.txt')
else:
# espeak tts
for hardwareNumber in (2, 0, 3, 1, 4):
print 'plughw:%d,0' % hardwareNumber
if commandArgs.male:
os.system('cat ' + tempFilePath + ' | espeak --stdout | aplay -D plughw:%d,0' % hardwareNumber)
else:
os.system('cat ' + tempFilePath + ' | espeak -ven-us+f%d -s170 --stdout | aplay -D plughw:%d,0' % (commandArgs.voice_number, hardwareNumber))
os.remove(tempFilePath)
def handle_chat_message(args):
print "chat message received:", args
rawMessage = args['message']
withoutName = rawMessage.split(']')[1:]
message = "".join(withoutName)
urlRegExp = "(http|ftp|https)://([\w_-]+(?:(?:\.[\w_-]+)+))([\w.,@?^=%&:/~+#-]*[\w@?^=%&/~+#-])?"
if message[1] == ".":
exit()
elif commandArgs.anon_tts != True and args['anonymous'] == True:
exit()
elif commandArgs.filter_url_tts == True and re.search(urlRegExp, message):
exit()
else:
say(message)
#MDD10 speed and movement controls
def moveMDD10(command, speedPercent):
if command == 'F':
GPIO.output(DIG1, GPIO.LOW)
GPIO.output(DIG2, GPIO.LOW)
p1.start(speedPercent) # set speed for M1
p2.start(speedPercent) # set speed for M2
time.sleep(straightDelay)
if command == 'B':
GPIO.output(DIG1, GPIO.HIGH)
GPIO.output(DIG2, GPIO.HIGH)
p1.start(speedPercent)
p2.start(speedPercent)
time.sleep(straightDelay)
if command == 'L':
GPIO.output(DIG1, GPIO.LOW)
GPIO.output(DIG2, GPIO.HIGH)
p1.start(speedPercent)
p2.start(speedPercent)
time.sleep(turnDelay)
if command == 'R':
GPIO.output(DIG1, GPIO.HIGH)
GPIO.output(DIG2, GPIO.LOW)
p1.start(speedPercent)
p2.start(speedPercent)
time.sleep(turnDelay)
def moveAdafruitPWM(command):
print "move adafruit pwm command", command
if command == 'L':
pwm.setPWM(1, 0, 300) # turn left
pwm.setPWM(0, 0, 445) # drive forward
time.sleep(0.5)
pwm.setPWM(1, 0, 400) # turn neutral
pwm.setPWM(0, 0, 335) # drive neutral
if command == 'R':
pwm.setPWM(1, 0, 500) # turn right
pwm.setPWM(0, 0, 445) # drive forward
time.sleep(0.5)
pwm.setPWM(1, 0, 400) # turn neutral
pwm.setPWM(0, 0, 335) # drive neutral
if command == 'BL':
pwm.setPWM(1, 0, 300) # turn left
pwm.setPWM(0, 0, 270) # drive backward
time.sleep(0.5)
pwm.setPWM(1, 0, 400) # turn neutral
pwm.setPWM(0, 0, 335) # drive neutral
if command == 'BR':
pwm.setPWM(1, 0, 500) # turn right
pwm.setPWM(0, 0, 270) # drive backward
time.sleep(0.5)
pwm.setPWM(1, 0, 400) # turn neurtral
pwm.setPWM(0, 0, 335) # drive neutral
if command == 'F':
pwm.setPWM(0, 0, 445) # drive forward
time.sleep(0.3)
pwm.setPWM(0, 0, 345) # drive slowly forward
time.sleep(0.4)
pwm.setPWM(0, 0, 335) # drive neutral
if command == 'B':
pwm.setPWM(0, 0, 270) # drive backward
time.sleep(0.3)
pwm.setPWM(0, 0, 325) # drive slowly backward
time.sleep(0.4)
pwm.setPWM(0, 0, 335) # drive neutral
if command == 'S2INC': # neutral
pwm.setPWM(2, 0, 300)
if command == 'S2DEC':
pwm.setPWM(2, 0, 400)
if command == 'POS60':
pwm.setPWM(2, 0, 490)
if command == 'NEG60':
pwm.setPWM(2, 0, 100)
def moveGoPiGo2(command):
if command == 'L':
gopigo.left_rot()
time.sleep(0.15)
gopigo.stop()
if command == 'R':
gopigo.right_rot()
time.sleep(0.15)
gopigo.stop()
if command == 'F':
gopigo.forward()
time.sleep(0.35)
gopigo.stop()
if command == 'B':
gopigo.backward()
time.sleep(0.35)
gopigo.stop()
def changeVolumeHighThenNormal(seconds):
os.system("amixer -c 2 cset numid=3 %d%%" % 50)
time.sleep(seconds)
os.system("amixer -c 2 cset numid=3 %d%%" % commandArgs.tts_volume)
def maxSpeedThenNormal():
global maxSpeedEnabled
maxSpeedEnabled = True
print "max speed"
time.sleep(120)
maxSpeedEnabled = False
print "normal speed"
def handleLoudCommand(seconds):
thread.start_new_thread(changeVolumeHighThenNormal, (seconds,))
def handleMaxSpeedCommand():
thread.start_new_thread(maxSpeedThenNormal, ())
def moveGoPiGo3(command):
e = easyGoPiGo3
if command == 'L':
e.set_motor_dps(e.MOTOR_LEFT, -e.get_speed())
e.set_motor_dps(e.MOTOR_RIGHT, e.get_speed())
time.sleep(0.15)
easyGoPiGo3.stop()
if command == 'R':
e.set_motor_dps(e.MOTOR_LEFT, e.get_speed())
e.set_motor_dps(e.MOTOR_RIGHT, -e.get_speed())
time.sleep(0.15)
easyGoPiGo3.stop()
if command == 'F':
easyGoPiGo3.forward()
time.sleep(0.35)
easyGoPiGo3.stop()
if command == 'B':
easyGoPiGo3.backward()
time.sleep(0.35)
easyGoPiGo3.stop()
def handle_command(args):
now = datetime.datetime.now()
now_time = now.time()
# if it's late, make the robot slower
if now_time >= datetime.time(21,30) or now_time <= datetime.time(9,30):
#print "within the late time interval"
drivingSpeedActuallyUsed = nightTimeDrivingSpeedActuallyUsed
else:
drivingSpeedActuallyUsed = dayTimeDrivingSpeedActuallyUsed
global drivingSpeed
global handlingCommand
if 'robot_id' in args and args['robot_id'] == robotID: print "received message:", args
# Note: If you are adding features to your bot,
# you can get direct access to incomming commands right here.
if handlingCommand:
return
#if 'robot_id' in args:
# print "args robot id:", args['robot_id']
#if 'command' in args:
# print "args command:", args['command']
if 'command' in args and 'robot_id' in args and args['robot_id'] == robotID:
print('got command', args)
command = args['command']
# don't turn set handlingCommand true for
# commands that persist for a while and are not exclusive
# so others are allowed to run
if command not in ("SOUND2", "WALL", "LOUD", "MAXSPEED"):
handlingCommand = True
if command == 'LOUD':
handleLoudCommand(25)
if command == 'MAXSPEED':
handleMaxSpeedCommand()
if commandArgs.type == 'mdd10':
if maxSpeedEnabled:
print "AT MAX....................."
print maxSpeedEnabled
moveMDD10(command, 100)
else:
print "NORMAL................."
print maxSpeedEnabled
moveMDD10(command, int(float(drivingSpeedActuallyUsed) / 2.55))
if commandArgs.type == 'adafruit_pwm':
moveAdafruitPWM(command)
if commandArgs.type == 'gopigo2':
moveGoPiGo2(command)
if commandArgs.type == 'gopigo3':
moveGoPiGo3(command)
if commandArgs.type == 'owi_arm':
owi_arm.handleOwiArm(command)
if commandArgs.type == 'serial':
robot_util.sendSerialCommand(ser, command)
if commandArgs.type == 'motor_hat' and motorsEnabled:
motorA.setSpeed(drivingSpeed)
motorB.setSpeed(drivingSpeed)
if command == 'F':
drivingSpeed = drivingSpeedActuallyUsed
for motorIndex in range(4):
runMotor(motorIndex, forward[motorIndex])
time.sleep(straightDelay)
if command == 'B':
drivingSpeed = drivingSpeedActuallyUsed
for motorIndex in range(4):
runMotor(motorIndex, backward[motorIndex])
time.sleep(straightDelay)
if command == 'L':
drivingSpeed = turningSpeedActuallyUsed
for motorIndex in range(4):
runMotor(motorIndex, left[motorIndex])
time.sleep(turnDelay)
if command == 'R':
drivingSpeed = turningSpeedActuallyUsed
for motorIndex in range(4):
runMotor(motorIndex, right[motorIndex])
time.sleep(turnDelay)
if command == 'U':
#mhArm.getMotor(1).setSpeed(127)
#mhArm.getMotor(1).run(Adafruit_MotorHAT.BACKWARD)
incrementArmServo(1, 10)
time.sleep(0.05)
if command == 'D':
#mhArm.getMotor(1).setSpeed(127)
#mhArm.getMotor(1).run(Adafruit_MotorHAT.FORWARD)
incrementArmServo(1, -10)
time.sleep(0.05)
if command == 'O':
#mhArm.getMotor(2).setSpeed(127)
#mhArm.getMotor(2).run(Adafruit_MotorHAT.BACKWARD)
incrementArmServo(2, -10)
time.sleep(0.05)
if command == 'C':
#mhArm.getMotor(2).setSpeed(127)
#mhArm.getMotor(2).run(Adafruit_MotorHAT.FORWARD)
incrementArmServo(2, 10)
time.sleep(0.05)
if commandArgs.type == 'mdd10':
turnOffMotorsMDD10()
if commandArgs.type == 'motor_hat':
turnOffMotors()
if command == 'WALL':
handleLoudCommand(25)
os.system("aplay -D plughw:2,0 /home/pi/wall.wav")
if command == 'SOUND2':
handleLoudCommand(25)
os.system("aplay -D plughw:2,0 /home/pi/sound2.wav")
if commandArgs.type == 'l298n':
runl298n(command)
#setMotorsToIdle()
if commandArgs.type == 'motozero':
runmotozero(command)
if commandArgs.type == 'pololu':
runPololu(command)
if commandArgs.led == 'max7219':
if command == 'LED_OFF':
SetLED_Off()
if command == 'LED_FULL':
SetLED_On()
SetLED_Full()
if command == 'LED_MED':
SetLED_On()
SetLED_Med()
if command == 'LED_LOW':
SetLED_On()
SetLED_Low()
if command == 'LED_E_SMILEY':
SetLED_On()
SetLED_E_Smiley()
if command == 'LED_E_SAD':
SetLED_On()
SetLED_E_Sad()
if command == 'LED_E_TONGUE':
SetLED_On()
SetLED_E_Tongue()
if command == 'LED_E_SUPRISED':
SetLED_On()
SetLED_E_Suprised()
handlingCommand = False
def runl298n(direction):
if direction == 'F':
GPIO.output(StepPinForward, GPIO.HIGH)
time.sleep(l298n_sleeptime * l298n_rotatetimes)
GPIO.output(StepPinForward, GPIO.LOW)
if direction == 'B':
GPIO.output(StepPinBackward, GPIO.HIGH)
time.sleep(l298n_sleeptime * l298n_rotatetimes)
GPIO.output(StepPinBackward, GPIO.LOW)
if direction == 'L':
GPIO.output(StepPinLeft, GPIO.HIGH)
time.sleep(l298n_sleeptime)