-
Notifications
You must be signed in to change notification settings - Fork 23
/
xscratchgpio_handler4.py
executable file
·2289 lines (1917 loc) · 109 KB
/
xscratchgpio_handler4.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
#!/usr/bin/env python
# ScratchGPIO - control Raspberry Pi GPIO ports using Scratch.
#Copyright (C) 2013 by Simon Walters based on original code for PiFace by Thomas Preston
#This program is free software; you can redistribute it and/or
#modify it under the terms of the GNU General Public License
#as published by the Free Software Foundation; either version 2
#of the License, or (at your option) any later version.
#This program is distributed in the hope that it will be useful,
#but WITHOUT ANY WARRANTY; without even the implied warranty of
#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
#GNU General Public License for more details.
#You should have received a copy of the GNU General Public License
#along with this program; if not, write to the Free Software
#Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
# This code now hosted on Github thanks to Ben Nuttall
Version = 'v4.1.07' # 30Dec13
import threading
import socket
import time
import sys
import struct
import datetime as dt
import shlex
import os
import math
import re
import sgh_GPIOController
import sgh_PiGlow
import sgh_Stepper
import logging
import subprocess
try:
from Adafruit_PWM_Servo_Driver import PWM
from sgh_PCF8591P import sgh_PCF8591P
from sgh_Adafruit_8x8 import sgh_EightByEight
except:
pass
#try and inport smbus but don't worry if not installed
#try:
# from smbus import SMBus
#except:
# pass
#import RPi.GPIO as GPIO
class Compass:
__scales = {
0.88: [0, 0.73],
1.30: [1, 0.92],
1.90: [2, 1.22],
2.50: [3, 1.52],
4.00: [4, 2.27],
4.70: [5, 2.56],
5.60: [6, 3.03],
8.10: [7, 4.35],
}
def __init__(self, port=0, address=0x1E, gauss=1.3, declination=(0,0)):
self.bus = SMBus(port)
self.address = address
(degrees, minutes) = declination
self.__declDegrees = degrees
self.__declMinutes = minutes
self.__declination = (degrees + minutes / 60) * math.pi / 180
(reg, self.__scale) = self.__scales[gauss]
self.bus.write_byte_data(self.address, 0x00, 0x70) # 8 Average, 15 Hz, normal measurement
self.bus.write_byte_data(self.address, 0x01, reg << 5) # Scale
self.bus.write_byte_data(self.address, 0x02, 0x00) # Continuous measurement
def declination(self):
return (self.__declDegrees, self.__declMinutes)
def twos_complement(self, val, len):
# Convert twos compliment to integer
if (val & (1 << len - 1)):
val = val - (1<<len)
return val
def __convert(self, data, offset):
val = self.twos_complement(data[offset] << 8 | data[offset+1], 16)
if val == -4096: return None
return round(val * self.__scale, 4)
def axes(self):
data = self.bus.read_i2c_block_data(self.address, 0x00)
#print map(hex, data)
x = self.__convert(data, 3)
y = self.__convert(data, 7)
z = self.__convert(data, 5)
return (x,y,z)
def heading(self):
(x, y, z) = self.axes()
headingRad = float(math.atan2(y, x))
headingRad += self.__declination
# Correct for reversed heading
if headingRad < 0:
headingRad += 2 * math.pi
# Check for wrap and compensate
elif headingRad > 2 * math.pi:
headingRad -= 2 * math.pi
# Convert to degrees from radians
headingDeg = headingRad * 180 / math.pi
degrees = math.floor(headingDeg)
minutes = round((headingDeg - degrees) * 60)
return headingDeg
def degrees(self, (degrees, minutes)):
return str(degrees) + "*" + str(minutes) + "'"
def degreesdecimal(self, (degrees, minutes)):
return str(degrees + (minutes /60.0) ) if (degrees >=0) else str(degrees - (minutes /60.0) )
def __str__(self):
(x, y, z) = self.axes()
return "Axis X: " + str(x) + "\n" \
"Axis Y: " + str(y) + "\n" \
"Axis Z: " + str(z) + "\n" \
"dec deg: " + str(self.__declDegrees) + "\n" \
"dec min: " + str(self.__declMinutes) + "\n" \
"Declination: " + self.degreesdecimal(self.declination()) + "\n" \
"Heading: " + str(self.heading()) + "\n"
### End Compasss ###################################################################################################
def isNumeric(s):
try:
float(s)
return True
except ValueError:
return False
def removeNonAscii(s): return "".join(i for i in s if ord(i)<128)
def xgetValue(searchString, dataString):
outputall_pos = dataString.find((searchString + ' '))
sensor_value = dataString[(outputall_pos+1+len(searchString)):].split()
return sensor_value[0]
def sign(number):return cmp(number,0)
def parse_data(dataraw, search_string):
outputall_pos = dataraw.find(search_string)
return dataraw[(outputall_pos + 1 + search_string.length):].split()
class MyError(Exception):
def __init__(self, value):
self.value = value
def __str__(self):
return repr(self.value)
class ScratchSender(threading.Thread):
def __init__(self, socket):
threading.Thread.__init__(self)
self.scratch_socket = socket
self._stop = threading.Event()
self.time_last_ping = 0.0
self.time_last_compass = 0.0
self.distlist = [0.0,0.0,0.0]
def stop(self):
self._stop.set()
def stopped(self):
return self._stop.isSet()
def broadcast_changed_pins(self, changed_pin_map, pin_value_map):
for pin in sghGC.validPins:
#print pin
# if we care about this pin's value
if (changed_pin_map >> pin) & 0b1:
#print "changed"
pin_value = (pin_value_map >> pin) & 0b1
if (sghGC.pinUse[pin] == sghGC.PINPUT):
#print pin , pin_value
#print "broadcast changed pin"
self.broadcast_pin_update(pin, pin_value)
def broadcast_pin_update(self, pin, value):
#print ADDON
#sensor_name = "gpio" + str(GPIO_NUM[pin_index])
#bcast_str = 'sensor-update "%s" %d' % (sensor_name, value)
#print 'sending: %s' % bcast_str
#self.send_scratch_command(bcast_str)
#Normal action is to just send updates to pin values but this can be modified if known addon in use
if "ladder" in ADDON:
#do ladderboard stuff
sensor_name = "switch" + str([0,21,19,24,26].index(pin))
elif "motorpitx" in ADDON:
#do MotorPiTx stuff
if pin == 13:
sensor_name = "input1"
if pin == 7:
sensor_name = "input2"
elif "berry" in ADDON:
#do berryclip stuff
if pin == 26:
sensor_name = "switch"
elif "piringo" in ADDON:
#do PiRingo stuff
sensor_name = "switch" + str(1 + [19,21].index(pin))
elif "pibrella" in ADDON:
#print pin
#sensor_name = "in" + str([0,19,21,24,26,23].index(pin))
try:
sensor_name = "In" + ["NA","A","B","C","D","E"][([0,21,26,24,19,23].index(pin))]
if sensor_name == "InE":
sensor_name = "switch"
except:
print "pibrella input out of range"
sensor_name = "pin" + str(pin)
pass
elif "pidie" in ADDON:
#print pin
#sensor_name = "in" + str([0,19,21,24,26,23].index(pin))
try:
sensor_name = ["blue","red","white","yellow"][([19,21,26,24].index(pin))]
except:
print "pidie input out of range"
sensor_name = "pin" + str(pin)
pass
else:
sensor_name = "pin" + str(pin)
#
#
#
#
bcast_str = 'sensor-update "%s" %d' % (sensor_name, value)
if ("piringo" in ADDON) or ("pidie" in ADDON):
bcast_str = 'sensor-update "%s" %s' % (sensor_name,("Down","Up")[value == 1])
if ("fishdish" in ADDON):
bcast_str = 'sensor-update "switch" %s' % (("Up","Down")[value == 1])
#print 'sending: %s' % bcast_str
self.send_scratch_command(bcast_str)
if "motorpitx" in ADDON:
bcast_str = 'broadcast "%s%s"' % (sensor_name,("Off","On")[value == 1])
#print 'sending: %s' % bcast_str
self.send_scratch_command(bcast_str)
def send_scratch_command(self, cmd):
n = len(cmd)
b = (chr((n >> 24) & 0xFF)) + (chr((n >> 16) & 0xFF)) + (chr((n >> 8) & 0xFF)) + (chr(n & 0xFF))
self.scratch_socket.send(b + cmd)
def run(self):
global firstRun,ADDON,compass
# while firstRun:
# print "first run running"
#time.sleep(5)
last_bit_pattern=0L
self.send_scratch_command('broadcast "SetPins"')
#print sghGC.pinUse
with lock:
for pin in sghGC.validPins:
if (sghGC.pinUse[pin] == sghGC.PINPUT):
#self.broadcast_pin_update(pin, sghGC.pinRead(pin))
last_bit_pattern += sghGC.pinRead(pin) << pin
else:
last_bit_pattern += 1 << pin
#print 'lbp %s' % bin(last_bit_pattern)
last_bit_pattern = last_bit_pattern ^ -1
lastPinUpdateTime = 0
while not self.stopped():
time.sleep(0.01) # be kind to cpu :)
#print "sender running"
pin_bit_pattern = 0
with lock:
#print "lOCKED"
for pin in sghGC.validPins:
#print pin
if (sghGC.pinUse[pin] == sghGC.PINPUT):
#print 'trying to read pin' , pin
pin_bit_pattern += sghGC.pinRead(pin) << pin
else:
pin_bit_pattern += 1 << pin
#print "unlocked"
#print bin(pin_bit_pattern) , pin_bit_pattern
#print bin(pin_bit_pattern) , pin_bit_pattern
# if there is a change in the input pins
changed_pins = pin_bit_pattern ^ last_bit_pattern
#print "changed pins" , bin(changed_pins)
if changed_pins:
#print 'pin bit pattern' , bin(pin_bit_pattern)
try:
self.broadcast_changed_pins(changed_pins, pin_bit_pattern)
except Exception as e:
print e
break
last_bit_pattern = pin_bit_pattern
if (time.time() - lastPinUpdateTime) > 2:
#print int(time.time())
lastPinUpdateTime = time.time()
for pin in sghGC.validPins:
if (sghGC.pinUse[pin] == sghGC.PINPUT):
self.broadcast_pin_update(pin, sghGC.pinRead(pin))
if (time.time() - self.time_last_ping) > 1: # Check if time to do another ultra ping
for pin in sghGC.validPins:
if sghGC.pinUse[pin] == sghGC.PULTRA:
distance = sghGC.pinSonar(pin) # do a ping
sghGC.pinUse[pin] = sghGC.PULTRA # reset pin use back from sonar to ultra
sensor_name = 'ultra' + str(pin)
if "motorpitx" in ADDON:
if pin == 13:
sensor_name = "ultra1"
if pin == 7:
sensor_name = "ultra2"
bcast_str = 'sensor-update "%s" %d' % (sensor_name, distance)
#print 'sending: %s' % bcast_str
self.send_scratch_command(bcast_str)
self.time_last_ping = time.time()
if (time.time() - self.time_last_compass) > 0.25:
#print "time up"
#print compass
#If Compass board truely present
if (compass != None):
#print "compass code"
heading = compass.heading()
sensor_name = 'heading'
bcast_str = 'sensor-update "%s" %d' % (sensor_name, heading)
#print 'sending: %s' % bcast_str
self.send_scratch_command(bcast_str)
self.time_last_compass = time.time()
#time.sleep(1)
class ScratchListener(threading.Thread):
def __init__(self, socket):
threading.Thread.__init__(self)
self.scratch_socket = socket
self._stop = threading.Event()
self.dataraw = ''
self.value = None
self.valueNumeric = None
self.valueIsNumeric = None
self.OnOrOff = None
self.encoderDiff = 0
self.turnSpeed = 100
def send_scratch_command(self, cmd):
n = len(cmd)
b = (chr((n >> 24) & 0xFF)) + (chr((n >> 16) & 0xFF)) + (chr((n >> 8) & 0xFF)) + (chr(n & 0xFF))
self.scratch_socket.send(b + cmd)
def getValue(self,searchString):
outputall_pos = self.dataraw.find((searchString + ' '))
sensor_value = self.dataraw[(outputall_pos+1+len(searchString)):].split()
return sensor_value[0]
def bFind(self,searchStr):
return (searchStr in self.dataraw)
def bFindOn(self,searchStr):
return (self.bFind(searchStr + 'on') or self.bFind(searchStr + 'high'))
def bFindOff(self,searchStr):
return (self.bFind(searchStr + 'off') or self.bFind(searchStr + 'low'))
def bFindOnOff(self,searchStr):
self.OnOrOff = None
if (self.bFind(searchStr + 'on') or self.bFind(searchStr + 'high')):
self.OnOrOff = 1
return True
elif (self.bFind(searchStr + 'off') or self.bFind(searchStr + 'low')):
self.OnOrOff = 0
return True
else:
return False
# def dRtnOnOff(self,searchStr):
# if self.bFindOn(searchStr):
# return 1
# else:
# return 0
def bCheckAll(self):
if self.bFindOnOff('all'):
for pin in sghGC.validPins:
#print pin
if sghGC.pinUse[pin] in [sghGC.POUTPUT,sghGC.PPWM]:
#print pin
sghGC.pinUpdate(pin,self.OnOrOff)
def bPinCheck(self):
for pin in sghGC.validPins:
if self.bFindOnOff('pin' + str(pin)):
sghGC.pinUpdate(pin,self.OnOrOff)
if self.bFindOnOff('gpio' + str(sghGC.gpioLookup[pin])):
sghGC.pinUpdate(pin,self.OnOrOff)
#print pin
def bLEDCheck(self,ledList):
for led in range(1,(1+ len(ledList))): # loop thru led numbers
if self.bFindOnOff('led' + str(led)):
sghGC.pinUpdate(ledList[led - 1],self.OnOrOff)
def bFindValue(self,searchStr):
#print "searching for ", searchStr
self.value = None
self.valueNumeric = None
self.valueIsNumeric = False
if self.bFind(searchStr):
self.findPos = self.dataraw.find((searchStr))
logging.debug("1st chars of value:%s",(self.dataraw[self.findPos + len(searchStr):]) )
try:
if (self.dataraw[self.findPos + len(searchStr):][0]) == " ":
logging.debug("space found in bfindvalue")
self.value = ""
return True
except IndexError:
self.value = ""
return True
sensor_value = self.dataraw[(self.dataraw.find((searchStr)) + 0 + len(searchStr)):].split()
try:
self.value = sensor_value[0]
except IndexError:
self.value = ""
pass
#print self.value
if isNumeric(self.value):
self.valueNumeric = float(self.value)
self.valueIsNumeric = True
#print "numeric" , self.valueNumeric
return True
else:
return False
def bLEDPowerCheck(self,ledList):
for led in range(1,(1+ len(ledList))): # loop thru led numbers
#print "power" +str(led) + ","
if self.bFindValue('power' + str(led) +","):
if self.valueIsNumeric:
sghGC.pinUpdate(ledList[led - 1],self.valueNumeric,type="pwm")
else:
sghGC.pinUpdate(ledList[led - 1],0,type="pwm")
def vFind(self,searchStr):
return ((searchStr + ' ') in self.dataraw)
def vFindOn(self,searchStr):
return (self.vFind(searchStr + 'on') or self.vFind(searchStr + 'high')or self.vFind(searchStr + '1'))
def vFindOff(self,searchStr):
return (self.vFind(searchStr + 'off') or self.vFind(searchStr + 'low') or self.vFind(searchStr + '0'))
def vFindOnOff(self,searchStr):
self.value = None
self.valueNumeric = None
self.valueIsNumeric = False
if self.vFind(searchStr):
self.value = self.getValue(searchStr)
if str(self.value) in ["high","on","1"]:
self.valueNumeric = 1
else:
self.valueNumeric = 0
return True
else:
return False
def vFindValue(self,searchStr):
#print "searching for ", searchStr
self.value = None
self.valueNumeric = None
self.valueIsNumeric = False
if self.vFind(searchStr):
#print "found"
self.value = self.getValue(searchStr)
#print self.value
if isNumeric(self.value):
self.valueNumeric = float(self.value)
self.valueIsNumeric = True
#print "numeric" , self.valueNumeric
return True
else:
return False
def vAllCheck(self,searchStr):
if self.vFindOnOff(searchStr):
for pin in sghGC.validPins:
if sghGC.pinUse[pin] in [sghGC.POUTPUT,sghGC.PPWM]:
sghGC.pinUpdate(pin,self.valueNumeric)
def vPinCheck(self):
for pin in sghGC.validPins:
#print "checking pin" ,pin
if self.vFindValue('pin' + str(pin)):
if self.valueIsNumeric:
sghGC.pinUpdate(pin,self.valueNumeric)
else:
sghGC.pinUpdate(pin,0)
if self.vFindValue('power' + str(pin)):
#print pin , "found"
if self.valueIsNumeric:
sghGC.pinUpdate(pin,self.valueNumeric,type="pwm")
else:
sghGC.pinUpdate(pin,0,type="pwm")
if self.vFindValue('motor' + str(pin)):
if self.valueIsNumeric:
sghGC.pinUpdate(pin,self.valueNumeric,type="pwm")
else:
sghGC.pinUpdate(pin,0,type="pwm")
if self.vFindValue('gpio' + str(sghGC.gpioLookup[pin])):
if self.valueIsNumeric:
sghGC.pinUpdate(pin,self.valueNumeric)
else:
sghGC.pinUpdate(pin,0)
if self.vFindValue('gpiopower' + str(sghGC.gpioLookup[pin])):
#print pin , "found"
if self.valueIsNumeric:
sghGC.pinUpdate(pin,self.valueNumeric,type="pwm")
else:
sghGC.pinUpdate(pin,0,type="pwm")
def vLEDCheck(self,ledList):
for led in range(1,(1+ len(ledList))): # loop thru led numbers
if self.vFindValue('led' + str(led)):
if self.valueIsNumeric:
sghGC.pinUpdate(ledList[led - 1],self.valueNumeric)
else:
sghGC.pinUpdate(ledList[led - 1],0)
if self.vFindValue('power' + str(led)):
if self.valueIsNumeric:
sghGC.pinUpdate(ledList[led - 1],self.valueNumeric,type="pwm")
else:
sghGC.pinUpdate(ledList[led - 1],0,type="pwm")
def stop(self):
self._stop.set()
def stopped(self):
return self._stop.isSet()
def stepperUpdate(self, pins, value,steps=2123456789,stepDelay = 0.003):
print "pin" , pins , "value" , value
print "Stepper type", sgh_Stepper.sghStepper, "this one", type(sghGC.pinRef[pins[0]])
try:
sghGC.pinRef[pins[0]].changeSpeed(max(-100,min(100,value)),steps) # just update Stepper value
print "stepper updated"
print ("pin",pins, "set to", value)
except:
try:
print ("Stopping PWM")
sghGC.pinRef[pins[0]].stop()
except:
pass
sghGC.pinRef[pins[0]] = None
#time.sleep(5)
print ("New Stepper instance started", pins)
sghGC.pinRef[pins[0]] = sgh_Stepper.sghStepper(sghGC,pins,stepDelay) # create new Stepper instance
sghGC.pinRef[pins[0]].changeSpeed(max(-100,min(100,value)),steps) # update Stepper value
sghGC.pinRef[pins[0]].start() # update Stepper value
print 'pin' , pins , ' changed to Stepper'
print ("pins",pins, "set to", value)
sghGC.pinUse[pins[0]] = sghGC.POUTPUT
def stopTurning(self,motorList,count,startCount):
self.send_scratch_command('sensor-update "encoder" "turning"') #set turning sensor to turning
countingPin = motorList[0][3] # use 1st motor counting pin only
print "EncoderDiffMove:",self.encoderDiff
countwanted = startCount + count + self.encoderDiff # modifiy count based on previous result
countattempted = startCount + count + int(1 * self.encoderDiff) # allow for modified behaviour
countingPin = motorList[0][3] # use 1st motor counting pin only
print countwanted,countattempted
turningStartTime = time.time() # used to timeout if necessary
if count >= 0:
while (sghGC.pinCount[countingPin] < int(countattempted * 1) and ((time.time()-turningStartTime) < 2)):
#Just block until count acheived or timeout occurs
time.sleep(0.01)
else:
while (sghGC.pinCount[countingPin] > int(countattempted * 1) and ((time.time()-turningStartTime) < 2)):
#Just block until count acheived or timeout occurs
time.sleep(0.01)
for listLoop in range(0,2): # switch off both motors
sghGC.pinUpdate(motorList[listLoop][1],0)
sghGC.pinUpdate(motorList[listLoop][2],0)
time.sleep(0.5) #wait until motors have actually stopped
print ("Move Stopped",countingPin,(sghGC.pinCount[countingPin] - startCount))
if self.encoderDiff == 0:
self.encoderDiff = 1 * (countwanted - (sghGC.pinCount[countingPin])) #work out new error in position
else:
self.encoderDiff = 1 * (countwanted - (sghGC.pinCount[countingPin])) #work out new error in position
print "Diff:" , self.encoderDiff
self.send_scratch_command('sensor-update "encoder" "stopped"') # inform Scratch that turning is finished
def beep(self,pin,freq,duration):
print freq
if sghGC.pinUse != sghGC.PPWM: # Checks use of pin if not PWM mode then
sghGC.pinUpdate(pin,0,"pwm") #Set pin to PWM mode
startCount = time.time() #Get current time
sghGC.pinFreq(pin,freq) # Set freq used for PWM cycle
sghGC.pinUpdate(pin,50,"pwm") # Set duty cycle to 50% to produce square wave
while (time.time() - startCount) < (duration * 1.0): # Wait until duration has passed
time.sleep(0.01)
sghGC.pinUpdate(pin,0,"pwm") #Turn pin off
print ("Beep Stopped")
def run(self):
global firstRun,cycle_trace,step_delay,stepType,INVERT, \
Ultra,ultraTotalInUse,piglow,PiGlow_Brightness,compass,ADDON
#firstRun = True #Used for testing in overcoming Scratch "bug/feature"
firstRunData = ''
anyAddOns = False
ADDON = ""
#semi global variables used for servos in PiRoCon
panoffset = 0
tiltoffset = 0
pan = 0
tilt = 0
steppersInUse = None
beepDuration = 0.5
beepNote = 60
if GPIOPlus == False:
with lock:
print "set pins standard"
for pin in sghGC.validPins:
sghGC.pinUse[pin] = sghGC.PINPUTDOWN
sghGC.pinUse[11] = sghGC.POUTPUT
sghGC.pinUse[12] = sghGC.POUTPUT
sghGC.pinUse[13] = sghGC.POUTPUT
sghGC.pinUse[15] = sghGC.POUTPUT
sghGC.pinUse[16] = sghGC.POUTPUT
sghGC.pinUse[18] = sghGC.POUTPUT
sghGC.setPinMode()
#This is main listening routine
lcount = 0
dataPrevious = ""
#This is the main loop that listens for messages from Scratch and sends appropriate commands off to various routines
while not self.stopped():
#lcount += 1
#print lcount
try:
#print "try reading socket"
BUFFER_SIZE = 512 # This size will accomdate normal Scratch Control 'droid app sensor updates
data = dataPrevious + self.scratch_socket.recv(BUFFER_SIZE) # get the data from the socket plus any data not yet processed
logging.debug(len(data))
logging.debug("RAW: %s", data)
if "send-vars" in data:
#Reset if New project detected from Scratch
#tell outer loop that Scratch has disconnected
if cycle_trace == 'running':
cycle_trace = 'disconnected'
print "cycle_trace has changed to" ,cycle_trace
break
if len(data) > 0: # Connection still valid so process the data received
dataIn = data
#dataOut = ""
dataList = [] # used to hold series of broadcasts or sensor updates
dataPrefix = "" # data to be re-added onto front of incoming data
while len(dataIn) > 0: # loop thru data
if len(dataIn) < 4: #If whole length not received then break out of loop
#print "<4 chrs received"
dataPrevious = dataIn # store data and tag it onto next data read
break
sizeInfo = dataIn[0:4]
size = struct.unpack(">L", sizeInfo)[0] # get size of Scratch msg
#print "size:", size
if size > 0:
#print dataIn[4:size + 4]
#dataOut = dataOut + dataIn[4:size + 4].lower() + " "
dataMsg = dataIn[4:size + 4].lower() # turn msg into lower case
#print "msg:",dataMsg
if len(dataMsg) < size: # if msg recieved is too small
#print "half msg found"
#print size, len(dataMsg)
dataPrevious = dataIn # store data and tag it onto next data read
break
if len(dataMsg) == size: # if msg recieved is correct
if "alloff" in dataMsg:
allSplit = dataMsg.find("alloff")
logging.debug("Whole message:%s", dataIn)
#dataPrevious = dataIn # store data and tag it onto next data read
#break
#print "half msg found"
#print size, len(dataMsg)
dataPrevious = dataIn # store data and tag it onto next data read
#break
dataPrevious = "" # no data needs tagging to next read
if ("alloff" in dataMsg) or ("allon" in dataMsg):
dataList.append(dataMsg)
else:
if dataMsg[0:2] == "br": # removed redundant "broadcast" and "sensor-update" txt
if dataPrefix == "br":
dataList[-1] = dataList[-1] + " "+ dataMsg[10:]
else:
dataList.append(dataMsg)
dataPrefix = "br"
else:
if dataPrefix == "se":
dataList[-1] = dataList[-1] + dataMsg[10:]
else:
dataList.append(dataMsg)
dataPrefix = "se"
dataIn = dataIn[size+4:] # cut data down that's been processed
#print "previous:", dataPrevious
#print 'Cycle trace' , cycle_trace
if len(data) == 0:
#This is due to client disconnecting or user loading new Scratch program so temp disconnect
#I'd like the program to retry connecting to the client
#tell outer loop that Scratch has disconnected
if cycle_trace == 'running':
cycle_trace = 'disconnected'
print "cycle_trace has changed to" ,cycle_trace
break
except (KeyboardInterrupt, SystemExit):
print "reraise error"
raise
except socket.timeout:
#print "No data received: socket timeout"
continue
except:
print "Unknown error occured with receiving data"
#raise
continue
#At this point dataList[] contains a series of strings either broadcast or sensor-updates
#print "data being processed:" , dataraw
#This section is only enabled if flag set - I am in 2 minds as to whether to use it or not!
#if (firstRun == True) or (anyAddOns == False):
#print
logging.debug("dataList: %s",dataList)
#print "GPIOPLus" , GPIOPlus
for dataItem in dataList:
dataraw = dataraw = ' '.join([item.replace(' ','') for item in shlex.split(dataItem)])
self.dataraw = dataraw
#print "Loop processing"
#print self.dataraw
#print
if 'sensor-update' in self.dataraw:
#print "this data ignored" , dataraw
firstRunData = self.dataraw
#dataraw = ''
#firstRun = False
if self.vFindValue("autostart"):
if self.value == "true":
self.send_scratch_command("broadcast Scratch-StartClicked")
if self.vFindValue("leddim"):
sghGC.ledDim = int(self.valueNumeric) if self.valueIsNumeric else 100
print sghGC.ledDim
pinsoraddon = None
if self.vFindValue("setpins"):
setupValue = self.value
pinsoraddon = "pins"
if self.vFindValue("addon"):
setupValue = self.value
pinsoraddon = "addon"
if pinsoraddon != None:
ADDON = setupValue
print (ADDON, " declared")
if "low" in ADDON:
with lock:
print "set pins to input with pulldown low"
for pin in sghGC.validPins:
sghGC.pinUse[pin] = sghGC.PINPUTDOWN
#sghGC.pinUse[3] = sghGC.PUNUSED
#sghGC.pinUse[5] = sghGC.PUNUSED
sghGC.setPinMode()
anyAddOns = True
if "high" in ADDON:
with lock:
print "set pins to input"
for pin in sghGC.validPins:
sghGC.pinUse[pin] = sghGC.PINPUT
#sghGC.pinUse[3] = sghGC.PUNUSED
#sghGC.pinUse[5] = sghGC.PUNUSED
sghGC.setPinMode()
anyAddOns = True
if "none" in ADDON:
with lock:
print "set pins to input"
for pin in sghGC.validPins:
sghGC.pinUse[pin] = sghGC.PINPUTNONE
#sghGC.pinUse[3] = sghGC.PUNUSED
#sghGC.pinUse[5] = sghGC.PUNUSED
sghGC.setPinMode()
anyAddOns = True
if "normal" in ADDON:
with lock:
sghGC.pinUse[11] = sghGC.POUTPUT
sghGC.pinUse[12] = sghGC.POUTPUT
sghGC.pinUse[13] = sghGC.POUTPUT
sghGC.pinUse[15] = sghGC.POUTPUT
sghGC.pinUse[16] = sghGC.POUTPUT
sghGC.pinUse[18] = sghGC.POUTPUT
sghGC.pinUse[22] = sghGC.PINPUT
sghGC.pinUse[7] = sghGC.PINPUT
sghGC.setPinMode()
anyAddOns = True
if "ladder" in ADDON:
with lock:
sghGC.resetPinMode()
ladderOutputs = [11,12,13,15,16,18,22, 7, 5, 3]
for pin in ladderOutputs:
sghGC.pinUse[pin] = sghGC.POUTPUT
for pin in [24,26,19,21]:
sghGC.pinUse[pin] = sghGC.PINPUT
sghGC.setPinMode()
anyAddOns = True
if "motorpitx" in ADDON:
with lock:
sghGC.resetPinMode()
sghGC.pinUse[11] = sghGC.POUTPUT #Out2
sghGC.pinUse[15] = sghGC.POUTPUT #Out1
sghGC.pinUse[16] = sghGC.POUTPUT #Motor2 B
sghGC.pinUse[18] = sghGC.POUTPUT #Motor2 A
sghGC.pinUse[19] = sghGC.POUTPUT #Motor1
sghGC.pinUse[21] = sghGC.POUTPUT #Motor1
sghGC.pinUse[22] = sghGC.POUTPUT #Motr 2 Enable
sghGC.pinUse[23] = sghGC.POUTPUT #Motor1 Enable
sghGC.pinUse[13] = sghGC.PINPUT #Motor1 Enable
sghGC.pinUse[7] = sghGC.PINPUT #Motor1 Enable
sghGC.setPinMode()
sghGC.startServod([12,10]) # servos
print "MotorPiTx setup"
anyAddOns = True
if "piglow" in ADDON:
with lock:
sghGC.resetPinMode()
PiGlow_Values = [0] * 18
PiGlow_Lookup = [0,1,2,3,14,12,17,16,15,13,11,10,6,7,8,5,4,9]
PiGlow_Brightness = 255
anyAddOns = True
if "gpio" in ADDON:
with lock:
print sghGC.pinUse
sghGC.resetPinMode()
print sghGC.pinUse
sghGC.pinUse[11] = sghGC.POUTPUT
sghGC.pinUse[12] = sghGC.POUTPUT
sghGC.pinUse[13] = sghGC.POUTPUT
sghGC.pinUse[15] = sghGC.POUTPUT
sghGC.pinUse[16] = sghGC.POUTPUT
sghGC.pinUse[18] = sghGC.POUTPUT
sghGC.pinUse[7] = sghGC.PINPUT
sghGC.pinUse[8] = sghGC.PINPUT
sghGC.pinUse[10] = sghGC.PINPUT
sghGC.pinUse[22] = sghGC.PINPUT
sghGC.setPinMode()
print "gPiO setup"
print sghGC.pinUse
anyAddOns = True
if "berry" in ADDON:
with lock:
sghGC.resetPinMode()
berryOutputs = [7,11,15,19,21,23,24]
for pin in berryOutputs:
sghGC.pinUse[pin] = sghGC.POUTPUT
sghGC.pinUse[26] = sghGC.PINPUT
sghGC.setPinMode()
anyAddOns = True
if "pirocon" in ADDON:
with lock:
sghGC.resetPinMode()
sghGC.pinUse[19] = sghGC.POUTPUT #MotorA
sghGC.pinUse[21] = sghGC.POUTPUT #MotorB (MotorA in v1.2)
sghGC.pinUse[26] = sghGC.POUTPUT #MotorA (MotorB in V1.2)
sghGC.pinUse[24] = sghGC.POUTPUT #MotorB
sghGC.pinUse[7] = sghGC.PINPUT #ObsLeft
sghGC.pinUse[11] = sghGC.PINPUT #ObsRight
sghGC.pinUse[12] = sghGC.PINPUT #LFLeft
sghGC.pinUse[13] = sghGC.PINPUT #LFRight
if "encoders" in ADDON:
logging.debug("Encoders Found:%s", ADDON)
sghGC.pinUse[7] = sghGC.PCOUNT
sghGC.pinUse[11] = sghGC.PCOUNT
self.send_scratch_command('sensor-update "encoder" "stopped"')
self.send_scratch_command('sensor-update "count7" "0"')
sghGC.setPinMode()
sghGC.startServod([18,22]) # servos
print "pirocon setup"
anyAddOns = True
if "piringo" in ADDON:
with lock:
sghGC.resetPinMode()
print "piringo detected"
sghGC.INVERT = True # GPIO pull down each led so need to invert 0 to 1 and vice versa
piringoOutputs = [7,11,12,13,15,16,18,22, 24, 26, 8,10] # these are pins used for LEDS for PiRingo
piringoInputs = [19,21] # These are the pins connected to the switches
for pin in piringoOutputs:
sghGC.pinUse[pin] = sghGC.POUTPUT # set leds as outputs
for pin in piringoInputs:
sghGC.pinUse[pin] = sghGC.PINPUT # set switches as inputs
sghGC.setPinMode() # execute pin assignment
anyAddOns = True # add on declared
if "pibrella" in ADDON:
with lock:
sghGC.resetPinMode()
pibrellaOutputs = [7,11,13,15,16,18,22,12]
for pin in pibrellaOutputs:
sghGC.pinUse[pin] = sghGC.POUTPUT
pibrellaInputs = [21,26,24,19,23]
for pin in pibrellaInputs:
sghGC.pinUse[pin] = sghGC.PINPUTDOWN
sghGC.setPinMode()
anyAddOns = True
if "rgbled" in ADDON:
with lock:
sghGC.resetPinMode()
rgbOutputs = [12,16,18,22,7,11,13,15]
for pin in rgbOutputs:
sghGC.pinUse[pin] = sghGC.POUTPUT
sghGC.setPinMode()
anyAddOns = True
if "rtkmotorcon" in ADDON:
with lock:
sghGC.resetPinMode()