forked from cymplecy/scratch_gpio
-
Notifications
You must be signed in to change notification settings - Fork 0
/
scratchgpio_handler5.py
executable file
·3162 lines (2668 loc) · 154 KB
/
scratchgpio_handler5.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 = 'v5.2.13' # 03Aug14 - Hotfix PiRoCon/MicRoCon motors
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_PiMatrix
import sgh_Stepper
import sgh_Minecraft
import logging
import subprocess
import sgh_RasPiCamera
import pygame
try:
from Adafruit_PWM_Servo_Driver import PWM
print "PWM/Servo imported OK"
except:
print "PWM/Servo NOT imported OK"
pass
try:
from sgh_PCF8591P import sgh_PCF8591P
print "ADC/DAC imported OK"
except:
print "ADC/DAC NOT imported OK"
pass
# try:
# from sgh_Adafruit_8x8 import sgh_EightByEight
# print "8x8 imported OK"
# except:
# print "8x8 NOT imported OK"
# pass
try:
import mcpi.minecraft as minecraft
print "Minecraft imported OK"
except:
print "Minecraft NOT imported OK"
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 rtnNumeric(value,default):
try:
return float(value)
except ValueError:
return default
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 ultra(threading.Thread):
def __init__(self, pinTrig,pinEcho,socket):
threading.Thread.__init__(self)
self.scratch_socket = socket
self._stop = threading.Event()
self.pinTrig = pinTrig
self.pinEcho = pinEcho
def stop(self):
self._stop.set()
print "Sender Stop Set"
def stopped(self):
return self._stop.isSet()
def run(self):
while not self.stopped():
startTime = time.time()
if self.pinEcho == 0:
distance = sghGC.pinSonar(self.pinTrig) # do a ping
sensor_name = 'ultra' + str(self.pinTrig)
else:
distance = sghGC.pinSonar2(self.pinTrig,self.pinEcho)
sensor_name = 'ultra' + str(self.pinEcho)
bcast_str = 'sensor-update "%s" %s' % (sensor_name, str(distance))
#print 'sending: %s' % bcast_str
#self.send_scratch_command(bcast_str)
n = len(bcast_str)
b = (chr((n >> 24) & 0xFF)) + (chr((n >> 16) & 0xFF)) + (chr((n >> 8) & 0xFF)) + (chr(n & 0xFF))
self.scratch_socket.send(b + bcast_str)
timeTaken = time.time()-startTime
#print "time taken:",timeTaken
if timeTaken < sghGC.ultraFreq:
time.sleep(sghGC.ultraFreq - timeTaken)
print "ultra run ended for pin:",self.pinTrig
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]
self.sleepTime = 0.1
print "Sender Init"
self.loopCmd = ""
def stop(self):
self._stop.set()
print "Sender Stop Set"
def stopped(self):
return self._stop.isSet()
def broadcast_pin_update(self, pin, value):
#print ADDON
#print "sending",pin,value
#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
sensor_name = "pin" + str(pin)
sensorValue = str(value)
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"
sensorValue = ("off","on")[value == 1]
elif "berry" in ADDON:
#do berryclip stuff
if pin == 26:
sensor_name = "switch"
if pin == 22:
sensor_name = "switch2"
elif "piringo" in ADDON:
#do PiRingo stuff
sensor_name = "switch" + str(1 + [19,21].index(pin))
sensorValue = ("on","off")[value == 1]
elif "pibrella" in ADDON:
#print pin
#sensor_name = "in" + str([0,19,21,24,26,23].index(pin))
try:
sensor_name = "Input" + ["NA","A","B","C","D","E"][([0,21,26,24,19,23].index(pin))]
if sensor_name == "InputE":
sensor_name = "switch"
except:
print "pibrella input out of range"
sensor_name = "pin" + str(pin)
pass
sensorValue = ("off","on")[value == 1]
elif "pidie" in ADDON:
#print pin
#sensor_name = "in" + str([0,19,21,24,26,23].index(pin))
try:
sensor_name = ["green","red","blue","yellow"][([19,21,26,24].index(pin))]
except:
print "pidie input out of range"
sensor_name = "pin" + str(pin)
pass
sensorValue = ("on","off")[value == 1]
elif "pi2go" in ADDON:
#print pin
try:
sensor_name = ["left","front","right","lineleft","lineright","switch1","switch2","switch3"][([7,15,11,12,13,16,18,22].index(pin))]
except:
print "pi2go input out of range"
sensor_name = "pin" + str(pin)
pass
sensorValue = ("on","off")[value == 1]
elif "pizazz" in ADDON:
#print pin
try:
sensor_name = ["left","right",][([13,12].index(pin))]
except:
print "pi2go input out of range"
sensor_name = "pin" + str(pin)
pass
sensorValue = ("on","off")[value == 1]
elif "raspibot2" in ADDON:
sensor_name = ["switch1","switch2"][([23,21].index(pin))]
sensorValue = ("closed","open")[value == 1]
elif "simpie" in ADDON:
sensor_name = ["red","amber","green"][([11,13,15].index(pin))]
sensorValue = ("on","off")[value == 1]
if ("fishdish" in ADDON):
sensorValue = ("on","off")[value == 1]
bcast_str = '"' + sensor_name + '" ' + sensorValue
self.addtosend_scratch_command(bcast_str)
def addtosend_scratch_command(self, cmd):
self.loopCmd += " "+ cmd
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)
#print 'sent: %s' %cmd
#time.sleep(2)
def setsleepTime(self, sleepTime):
self.sleepTime = sleepTime
#print("sleeptime:%s", self.sleepTime )
def run(self):
global firstRun,ADDON,compass
print lock
# while firstRun:
# print "first run running"
#time.sleep(5)
# set last pin pattern to inverse of current state
pin_bit_pattern = [0] * len(sghGC.validPins)
last_bit_pattern = [1] * len(sghGC.validPins)
lastPinUpdateTime = time.time()
lastTimeSinceLastSleep = time.time()
self.sleepTime = 0.1
lastADC = [256,256,256,256]
while not self.stopped():
loopTime = time.time() - lastTimeSinceLastSleep
#print loopTime * 1000
if loopTime < self.sleepTime:
time.sleep(self.sleepTime-(time.time() - lastTimeSinceLastSleep)) # be kind to cpu :)
lastTimeSinceLastSleep = time.time()
#print "before lock"
with lock:
for listIndex in range(len(sghGC.validPins)):
pin = sghGC.validPins[listIndex]
pin_bit_pattern[listIndex] = 0
if (sghGC.pinUse[pin] in [sghGC.PINPUT,sghGC.PINPUTNONE,sghGC.PINPUTDOWN]):
pinEvent = sghGC.pinEvent(pin)
pinValue = sghGC.pinRead(pin)
pin_bit_pattern[listIndex] = pinValue
if pinEvent:
logging.debug(" ")
logging.debug("pinEvent Detected on pin:%s", pin )
#logging.debug("before updating pin patterm,last pattern :",pin_bit_pattern[listIndex],last_bit_pattern[listIndex] )
#logging.debug("afte uipdating pin patterm:",pin_bit_pattern[listIndex] )
if pin_bit_pattern[listIndex] == last_bit_pattern[listIndex]:
logging.debug("pinEvent but pin state the same as before...")
pin_bit_pattern[listIndex] = 1 - pin_bit_pattern[listIndex]
#logging.debug("after checking states pin patterm,last pattern:",pin_bit_pattern[listIndex],last_bit_pattern[listIndex])
time.sleep(0)
if pcfSensor != None: #if PCF ADC found
for channel in range(0,4): #loop thru all 4 inputs
adc = pcfSensor.readADC(channel) # get each value
adc = int((adc + lastADC[channel]) / 2.0)
if adc <> lastADC[channel]:
#print "channel,adc:",(channel+1),adc
sensor_name = 'adc'+str(channel+1)
bcast_str = '"' + sensor_name + '" ' + str(adc)
self.addtosend_scratch_command(bcast_str)
lastADC[channel] = adc
# if there is a change in the input pins
for listIndex in range(len(sghGC.validPins)):
pin = sghGC.validPins[listIndex]
if pin_bit_pattern[listIndex] != last_bit_pattern[listIndex]:
logging.debug("Final change sent value for pin %s is %s", pin,pin_bit_pattern[listIndex])
if (sghGC.pinUse[pin] in [sghGC.PINPUT,sghGC.PINPUTNONE,sghGC.PINPUTDOWN]):
#print pin , pin_value
self.broadcast_pin_update(pin, pin_bit_pattern[listIndex])
time.sleep(0.05) # just to give Scratch a better chance to react to event
last_bit_pattern = list(pin_bit_pattern)
#print ("last:%s",last_bit_pattern)
#print ("this:%s",pin_bit_pattern)
if (time.time() - lastPinUpdateTime) > 2: #This is to force the pin names to be read out even if they don't change
#print int(time.time())
lastPinUpdateTime = time.time()
for listIndex in range(len(sghGC.validPins)):
pin = sghGC.validPins[listIndex]
if (sghGC.pinUse[pin] in [sghGC.PINPUT,sghGC.PINPUTNONE,sghGC.PINPUTDOWN]):
pin_bit_pattern[listIndex] = sghGC.pinRead(pin)
self.broadcast_pin_update(pin,pin_bit_pattern[listIndex])
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)
if self.loopCmd <> "":
#print "loop:",self.loopCmd
self.send_scratch_command("sensor-update " + self.loopCmd)
self.loopCmd = ""
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 ') or self.bFind(searchStr + '1 '))
def bFindOff(self,searchStr):
return (self.bFind(searchStr + 'off ') or self.bFind(searchStr + 'low ') or self.bFind(searchStr + '0 '))
def bFindOnOff(self,searchStr):
self.OnOrOff = None
if (self.bFind(searchStr + 'on ') or self.bFind(searchStr + 'high ') or self.bFind(searchStr + '1 ')):
self.OnOrOff = 1
return True
elif (self.bFind(searchStr + 'off ') or self.bFind(searchStr + 'low ') or self.bFind(searchStr + '0 ')):
self.OnOrOff = 0
return True
else:
return False
def bCheckAll(self):
if self.bFindOnOff('all'):
for pin in sghGC.validPins:
#print pin
if sghGC.pinUse[pin] in [sghGC.POUTPUT,sghGC.PPWM,sghGC.PPWMMOTOR]:
#print pin
sghGC.pinUpdate(pin,self.OnOrOff)
def bPinCheck(self):
for pin in sghGC.validPins:
logging.debug("bPinCheck:%s",pin )
if self.bFindOnOff('pin' + str(pin)):
sghGC.pinUpdate(pin,self.OnOrOff)
if self.bFindOnOff('gpio' + str(sghGC.gpioLookup[pin])):
sghGC.pinUpdate(pin,self.OnOrOff)
if self.bFindValue('power' + str(pin)):
print pin,self.value
if self.valueIsNumeric:
sghGC.pinUpdate(pin,self.valueNumeric,type="pwm")
else:
sghGC.pinUpdate(pin,0,type="pwm")
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 bListCheck(self,pinList,nameList):
for loop in range(0,len(pinList)): # loop thru list
if self.bFindOnOff(str(nameList[loop])):
sghGC.pinUpdate(pinList[loop],self.OnOrOff)
if self.bFindValue('power' + str(nameList[loop])+","):
if self.valueIsNumeric:
sghGC.pinUpdate(pinList[loop],self.valueNumeric,type="pwm")
else:
sghGC.pinUpdate(pinList[loop],0,type="pwm")
def bListCheckPowerOnly(self,pinList,nameList):
for loop in range(0,len(pinList)): # loop thru list
if self.bFindValue('power' + str(nameList[loop])+","):
if self.valueIsNumeric:
sghGC.pinUpdate(pinList[loop],self.valueNumeric,type="pwm")
else:
sghGC.pinUpdate(pinList[loop],0,type="pwm")
def bFindValue(self,searchStr):
#logging.debug("Searching for:%s",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
self.OnOrOff = None
if self.vFind(searchStr):
self.value = self.getValue(searchStr)
if str(self.value) in ["high","on","1"]:
self.valueNumeric = 1
self.OnOrOff = 1
else:
self.valueNumeric = 0
self.OnOrOff = 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.PPWMMOTOR]:
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="pwmmotor")
else:
sghGC.pinUpdate(pin,0,type="pwmmotor")
if self.vFindValue('gpio' + str(sghGC.gpioLookup[pin])):
logging.debug("gpio lookup %s",str(sghGC.gpioLookup[pin]))
if self.valueIsNumeric:
sghGC.pinUpdate(pin,self.valueNumeric)
else:
sghGC.pinUpdate(pin,0)
#time.sleep(1)
if self.vFindValue('powergpio' + str(sghGC.gpioLookup[pin])):
logging.debug("pin %s",pin )
logging.debug("gpiopower lookup %s",str(sghGC.gpioLookup[pin]))
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.vFindOnOff('led' + str(led)):
sghGC.pinUpdate(ledList[led - 1],self.OnOrOff)
#logging.debug("pin %s %s",ledList[led - 1],self.OnOrOff )
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 vListCheck(self,pinList,nameList):
for loop in range(0,len(pinList)): # loop thru pinlist numbers
if self.vFindOnOff(str(nameList[loop])):
sghGC.pinUpdate(pinList[loop],self.OnOrOff)
if self.vFindValue('power' + str(nameList[loop])):
if self.valueIsNumeric:
sghGC.pinUpdate(pinList[loop],self.valueNumeric,type="pwm")
else:
sghGC.pinUpdate(pinList[loop],0,type="pwm")
if self.vFindValue('motor' + str(nameList[loop])):
if self.valueIsNumeric:
sghGC.pinUpdate(pinList[loop],self.valueNumeric,type="pwmmotor")
else:
sghGC.pinUpdate(pinList[loop],0,type="pwmmotor")
def vListCheckPowerOnly(self,pinList,nameList):
for loop in range(0,len(pinList)): # loop thru pinlist numbers
if self.vFindValue('power' + str(nameList[loop])):
if self.valueIsNumeric:
sghGC.pinUpdate(pinList[loop],self.valueNumeric,type="pwm")
else:
sghGC.pinUpdate(pinList[loop],0,type="pwm")
def vListCheckMotorOnly(self,pinList,nameList):
for loop in range(0,len(pinList)): # loop thru pinlist numbers
if self.vFindValue('motor' + str(nameList[loop])):
if self.valueIsNumeric:
sghGC.pinUpdate(pinList[loop],self.valueNumeric,type="pwmmotor")
else:
sghGC.pinUpdate(pinList[loop],0,type="pwmmotor")
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):
logging.debug("Freq:%s", 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
def vListHBridge2(self,motorlist):
for loop in motorlist:
if self.vFindValue(loop[0]):
svalue = min(100,max(-100,int(self.valueNumeric))) if self.valueIsNumeric else 0
logging.debug("motor:%s valuee:%s", loop[0],svalue)
sghGC.motorUpdate(loop[1],loop[2],0,svalue)
def startUltra(self,pinTrig,pinEcho,OnOrOff):
if OnOrOff == 0:
try:
sghGC.pinUltraRef[pinTrig].stop()
sghGC.pinUse[pinTrig] = sghGC.PUNUSED
sghGC.pinUltraRef[pinTrig] = None
print "ultra stopped"
except:
pass
else:
print "Attemping to start ultra on pin:",pinTrig
if sghGC.pinUltraRef[pinTrig] is None:
sghGC.pinUse[pinTrig] = sghGC.PSONAR
sghGC.pinUltraRef[pinTrig] = ultra(pinTrig,pinEcho,self.scratch_socket)
sghGC.pinUltraRef[pinTrig].start()
print 'Ultra started pinging on', str(pinTrig)
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 = ""
#ultraThread = None
#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.PINPUT
sghGC.pinUse[3] = sghGC.PUNUSED
sghGC.pinUse[5] = sghGC.PUNUSED
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 = ""
debugLogging = False
listenLoopTime = time.time() + 10000
#This is the main loop that listens for messages from Scratch and sends appropriate commands off to various routines
while not self.stopped():
#print "ListenLoopTime",listenLoopTime-time.time()
listenLoopTime = time.time()
#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("datalen: %s",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 = ' '.join([item.replace(' ','') for item in shlex.split(dataItem)])
dataraw = " "+dataraw + " "
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("sghdebug"):
if (self.value == "1") and (debugLogging == False):
logging.getLogger().setLevel(logging.DEBUG)
debugLogging = True
if (self.value == "0") and (debugLogging == True):
logging.getLogger().setLevel(logging.INFO)
debugLogging = False
if (debugLogging == False):
logging.getLogger().setLevel(logging.INFO)