forked from Makeblock-official/PythonForMegaPi
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmegapi_python3.py
More file actions
373 lines (301 loc) · 13.3 KB
/
Copy pathmegapi_python3.py
File metadata and controls
373 lines (301 loc) · 13.3 KB
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
import serial
import sys,time,math,random
import signal
from time import ctime,sleep
import glob,struct
from multiprocessing import Process,Manager,Array
import threading
class mSerial():
ser = None
def __init__(self):
print(self)
def start(self, port='/dev/ttyAMA0'):
self.ser = serial.Serial(port,115200,timeout=10)
def device(self):
return self.ser
def serialPorts(self):
if sys.platform.startswith('win'):
ports = ['COM%s' % (i + 1) for i in range(256)]
elif sys.platform.startswith('linux') or sys.platform.startswith('cygwin'):
ports = glob.glob('/dev/tty[A-Za-z]*')
elif sys.platform.startswith('darwin'):
ports = glob.glob('/dev/tty.*')
else:
raise EnvironmentError('Unsupported platform')
result = []
for port in ports:
s = serial.Serial()
s.port = port
s.close()
result.append(port)
return result
def writePackage(self,package):
self.ser.write(package)
sleep(0.01)
def read(self):
return self.ser.read()
def isOpen(self):
return self.ser.isOpen()
def inWaiting(self):
return self.ser.inWaiting()
def close(self):
self.ser.close()
M1 = 9
M2 = 10
A0 = 14
A1 = 15
A2 = 16
A3 = 17
A4 = 18
A6 = 19
A7 = 20
A8 = 21
A9 = 22
A10 = 23
A11 = 24
class MegaPi():
def __init__(self):
print("init MegaPi")
signal.signal(signal.SIGINT, self.exit)
self.manager = Manager()
self.__selectors = self.manager.dict()
self.buffer = []
self.bufferIndex = 0
self.isParseStart = False
self.exiting = False
self.isParseStartIndex = 0
def __del__(self):
self.exiting = True
def start(self,port='/dev/ttyAMA0'):
self.device = mSerial()
self.device.start(port)
sys.excepthook = self.excepthook
th = threading.Thread(target=self.__onRead,args=(self.onParse,))
th.start()
def excepthook(self, exctype, value, traceback):
self.close()
def close(self):
self.device.close()
def exit(self, signal, frame):
self.exiting = True
sys.exit(0)
def __onRead(self,callback):
while True:
if(self.exiting==True):
break
try:
if self.device.isOpen()==True:
n = self.device.inWaiting()
for i in range(n):
r = ord(self.device.read())
callback(r)
sleep(0.01)
else:
sleep(0.5)
except Exception as ex:
print(str(ex))
self.close()
sleep(1)
def __writePackage(self,pack):
self.device.writePackage(pack)
def __writeRequestPackage(self,deviceId,port,callback):
extId = ((port<<4)+deviceId)&0xff
self.__doCallback(extId,callback)
self.__writePackage(bytearray([0xff,0x55,0x4,extId,0x1,deviceId,port]))
def digitalRead(self,pin,callback):
self.__writeRequestPackage(0x1e,pin,callback)
def analogRead(self,pin,callback):
self.__writeRequestPackage(0x1f,pin,callback)
def lightSensorRead(self,port,callback):
self.__writeRequestPackage(4,port,callback)
def ultrasonicSensorRead(self,port,callback):
self.__writeRequestPackage(1,port,callback)
def lineFollowerRead(self,port,callback):
self.__writeRequestPackage(17,port,callback)
def soundSensorRead(self,port,callback):
self.__writeRequestPackage(7,port,callback)
def pirMotionSensorRead(self,port,callback):
self.__writeRequestPackage(15,port,callback)
def potentiometerRead(self,port,callback):
self.__writeRequestPackage(4,port,callback)
def limitSwitchRead(self,port,callback):
self.__writeRequestPackage(21,port,callback)
def temperatureRead(self,port,callback):
self.__writeRequestPackage(2,port,callback)
def touchSensorRead(self,port,callback):
self.__writeRequestPackage(15,port,callback)
def humitureSensorRead(self,port,type,callback):
deviceId = 23;
extId = ((port<<4)+deviceId)&0xff
self.__doCallback(extId,callback)
self.__writePackage(bytearray([0xff,0x55,0x5,extId,0x1,deviceId,port,type]))
def joystickRead(self,port,axis,callback):
deviceId = 5;
extId = (((port+axis)<<4)+deviceId)&0xff
self.__doCallback(extId,callback)
self.__writePackage(bytearray([0xff,0x55,0x5,extId,0x1,deviceId,port,axis]))
def gasSensorRead(self,port,callback):
self.__writeRequestPackage(25,port,callback)
def flameSensorRead(self,port,callback):
self.__writeRequestPackage(24,port,callback)
def compassRead(self,port,callback):
self.__writeRequestPackage(26,port,callback)
def angularSensorRead(self,port,slot,callback):
self.__writeRequestPackage(28,port,callback)
def buttonRead(self,port,callback):
self.__writeRequestPackage(22,port,callback)
def gyroRead(self,port,axis,callback):
deviceId = 6;
extId = (((port+axis)<<4)+deviceId)&0xff
self.__doCallback(extId,callback)
self.__writePackage(bytearray([0xff,0x55,0x5,extId,0x1,deviceId,port,axis]))
def pressureSensorBegin(self):
self.__writePackage(bytearray([0xff,0x55,0x3,0x0,0x2,29]))
def pressureSensorRead(self,type,callback):
self.__writeRequestPackage(29,type,callback)
def digitalWrite(self,pin,level):
self.__writePackage(bytearray([0xff,0x55,0x5,0x0,0x2,0x1e,pin,level]))
def pwmWrite(self,pin,pwm):
self.__writePackage(bytearray([0xff,0x55,0x5,0x0,0x2,0x20,pin,pwm]))
def motorRun(self,port,speed):
self.__writePackage(bytearray([0xff,0x55,0x6,0x0,0x2,0xa,port]+self.short2bytes(speed)))
def motorMove(self,leftSpeed,rightSpeed):
self.__writePackage(bytearray([0xff,0x55,0x7,0x0,0x2,0x5]+self.short2bytes(-leftSpeed)+self.short2bytes(rightSpeed)))
def servoRun(self,port,slot,angle):
self.__writePackage(bytearray([0xff,0x55,0x6,0x0,0x2,0xb,port,slot,angle]))
def encoderMotorRun(self,slot,speed):
deviceId = 62;
self.__writePackage(bytearray([0xff,0x55,0x07,0x00,0x02,deviceId,0x02,slot]+self.short2bytes(speed)))
def encoderMotorMove(self,slot,speed,distance,callback):
deviceId = 62;
extId = ((slot<<4)+deviceId)&0xff
self.__doCallback(extId,callback)
self.__writePackage(bytearray([0xff,0x55,0x0b,extId,0x02,deviceId,0x01,slot]+self.long2bytes(distance)+self.short2bytes(speed)))
def encoderMotorMoveTo(self,slot,speed,distance,callback):
deviceId = 62;
extId = ((slot<<4)+deviceId)&0xff
self.__doCallback(extId,callback)
self.__writePackage(bytearray([0xff,0x55,0x0b,extId,0x02,deviceId,0x06,slot]+self.long2bytes(distance)+self.short2bytes(speed)))
def encoderMotorSetCurPosZero(self,slot):
deviceId = 62;
self.__writePackage(bytearray([0xff,0x55,0x05,0x00,0x02,deviceId,0x04,slot]))
def encoderMotorPosition(self,slot,callback):
deviceId = 61;
extId = ((slot<<4)+deviceId)&0xff
self.__doCallback(extId,callback)
self.__writePackage(bytearray([0xff,0x55,0x06,extId,0x01,deviceId,0x00,slot,0x01]))
def encoderMotorSpeed(self,slot,callback):
deviceId = 61;
extId = ((slot<<4)+deviceId)&0xff
self.__doCallback(extId,callback)
self.__writePackage(bytearray([0xff,0x55,0x06,extId,0x01,deviceId,0x00,slot,0x02]))
def stepperMotorRun(self,slot,speed):
deviceId = 76;
self.__writePackage(bytearray([0xff,0x55,0x07,0x00,0x02,deviceId,0x02,slot]+self.short2bytes(speed)))
def stepperMotorMove(self,port,speed,distance,callback):
deviceId = 76;
extId = ((port<<4)+deviceId)&0xff
self.__doCallback(extId,callback)
self.__writePackage(bytearray([0xff,0x55,0x0b,extId,0x02,deviceId,0x01,port]+self.long2bytes(distance)+self.short2bytes(speed)))
def stepperMotorMoveTo(self,port,speed,distance,callback):
deviceId = 76;
extId = ((port<<4)+deviceId)&0xff
self.__doCallback(extId,callback)
self.__writePackage(bytearray([0xff,0x55,0x0b,extId,0x02,deviceId,0x06,port]+self.long2bytes(distance)+self.short2bytes(speed)))
def stepperMotorSetCurPosZero(self,port):
deviceId = 76;
self.__writePackage(bytearray([0xff,0x55,0x05,0x00,0x02,deviceId,0x04,port]))
def rgbledDisplay(self,port,slot,index,red,green,blue):
self.__writePackage(bytearray([0xff,0x55,0x9,0x0,0x2,0x8,port,slot,index,int(red),int(green),int(blue)]))
def rgbledShow(self,port,slot):
self.__writePackage(bytearray([0xff,0x55,0x5,0x0,0x2,19,port,slot]))
def sevenSegmentDisplay(self,port,value):
self.__writePackage(bytearray([0xff,0x55,0x8,0x0,0x2,9,port]+self.float2bytes(value)))
def ledMatrixMessage(self,port,x,y,message):
arr = list(message);
for i in range(len(arr)):
arr[i] = ord(arr[i]);
self.__writePackage(bytearray([0xff,0x55,8+len(arr),0,0x2,41,port,1,self.char2byte(x),self.char2byte(7-y),len(arr)]+arr))
def ledMatrixDisplay(self,port,x,y,buffer):
self.__writePackage(bytearray([0xff,0x55,7+len(buffer),0,0x2,41,port,2,x,7-y]+buffer))
def shutterOn(self,port):
self.__writePackage(bytearray([0xff,0x55,0x5,0,0x3,20,port,1]))
def shutterOff(self,port):
self.__writePackage(bytearray([0xff,0x55,0x5,0,0x3,20,port,2]))
def focusOn(self,port):
self.__writePackage(bytearray([0xff,0x55,0x5,0,0x3,20,port,3]))
def focusOff(self,port):
self.__writePackage(bytearray([0xff,0x55,0x5,0,0x3,20,port,4]))
def onParse(self, byte):
position = 0
value = 0
self.buffer+=[byte]
bufferLength = len(self.buffer)
if bufferLength >= 2:
if (self.buffer[bufferLength-1]==0x55 and self.buffer[bufferLength-2]==0xff):
self.isParseStart = True
self.isParseStartIndex = bufferLength-2
if (self.buffer[bufferLength-1]==0xa and self.buffer[bufferLength-2]==0xd and self.isParseStart==True):
self.isParseStart = False
position = self.isParseStartIndex+2
extID = self.buffer[position]
position+=1
type = self.buffer[position]
position+=1
# 1 byte 2 float 3 short 4 len+string 5 double
if type == 1:
value = self.buffer[position]
if type == 2:
value = self.readFloat(position)
if(value<-512 or value>1023):
value = 0
if type == 3:
value = self.readShort(position)
if type == 4:
value = self.readString(position)
if type == 5:
value = self.readDouble(position)
if type == 6:
value = self.readLong(position)
if(type<=6):
self.responseValue(extID,value)
self.buffer = []
def readFloat(self, position):
v = [self.buffer[position], self.buffer[position+1],self.buffer[position+2],self.buffer[position+3]]
return struct.unpack('<f', struct.pack('4B', *v))[0]
def readShort(self, position):
v = [self.buffer[position], self.buffer[position+1]]
return struct.unpack('<h', struct.pack('2B', *v))[0]
def readString(self, position):
l = self.buffer[position]
position+=1
s = ""
for i in range(l):
s += self.buffer[position+i].charAt(0)
return s
def readDouble(self, position):
v = [self.buffer[position], self.buffer[position+1],self.buffer[position+2],self.buffer[position+3]]
return struct.unpack('<f', struct.pack('4B', *v))[0]
def readLong(self, position):
v = [self.buffer[position], self.buffer[position+1],self.buffer[position+2],self.buffer[position+3]]
return struct.unpack('<l', struct.pack('4B', *v))[0]
def responseValue(self, extID, value):
self.__selectors["callback_"+str(extID)](value)
def __doCallback(self, extID, callback):
self.__selectors["callback_"+str(extID)] = callback
def float2bytes(self,fval):
val = struct.pack("f",fval)
#return [ord(val[0]),ord(val[1]),ord(val[2]),ord(val[3])]
return [val[0],val[1],val[2],val[3]]
def long2bytes(self,lval):
val = struct.pack("=l",lval)
#return [ord(val[0]),ord(val[1]),ord(val[2]),ord(val[3])]
return [val[0],val[1],val[2],val[3]]
def short2bytes(self,sval):
val = struct.pack("h",sval)
#return [ord(val[0]),ord(val[1])]
return [val[0],val[1]]
def char2byte(self,cval):
val = struct.pack("b",cval)
#return ord(val[0])
return val[0]