-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpyMultiwii.py
357 lines (329 loc) · 13 KB
/
pyMultiwii.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
#!/usr/bin/env python
"""multiwii.py: Handles Multiwii Serial Protocol."""
__author__ = "Aldo Vargas"
__copyright__ = "Copyright 2014 Altax.net"
__license__ = "GPL"
__version__ = "1.5"
__maintainer__ = "Aldo Vargas"
__email__ = "[email protected]"
__status__ = "Development"
import serial, time, struct
class MultiWii:
"""Multiwii Serial Protocol message ID"""
""" notice: just attitude, rc channels and raw imu, set raw rc are implemented at the moment """
IDENT = 100
STATUS = 101
RAW_IMU = 102
SERVO = 103
MOTOR = 104
RC = 105
RAW_GPS = 106
COMP_GPS = 107
ATTITUDE = 108
ALTITUDE = 109
ANALOG = 110
RC_TUNING = 111
PID = 112
BOX = 113
MISC = 114
MOTOR_PINS = 115
BOXNAMES = 116
PIDNAMES = 117
WP = 118
BOXIDS = 119
RC_RAW_IMU = 121
SET_RAW_RC = 200
SET_RAW_GPS = 201
SET_PID = 202
SET_BOX = 203
SET_RC_TUNING = 204
ACC_CALIBRATION = 205
MAG_CALIBRATION = 206
SET_MISC = 207
RESET_CONF = 208
SET_WP = 209
SWITCH_RC_SERIAL = 210
IS_SERIAL = 211
DEBUG = 254
"""Class initialization"""
def __init__(self, serPort):
"""Global variables of data"""
self.rcChannels = {'roll':0,'pitch':0,'yaw':0,'throttle':0,'elapsed':0,'timestamp':0}
self.rawIMU = {'ax':0,'ay':0,'az':0,'gx':0,'gy':0,'gz':0,'elapsed':0,'timestamp':0}
self.motor = {'m1':0,'m2':0,'m3':0,'m4':0,'elapsed':0,'timestamp':0}
self.attitude = {'angx':0,'angy':0,'heading':0,'elapsed':0,'timestamp':0}
self.message = {'angx':0,'angy':0,'heading':0,'roll':0,'pitch':0,'yaw':0,'throttle':0,'elapsed':0,'timestamp':0}
self.temp = ();
self.temp2 = ();
self.elapsed = 0
self.PRINT = 1
self.ser = serial.Serial()
self.ser.port = serPort
self.ser.baudrate = 115200
self.ser.bytesize = serial.EIGHTBITS
self.ser.parity = serial.PARITY_NONE
self.ser.stopbits = serial.STOPBITS_ONE
self.ser.timeout = 3
self.ser.xonxoff = False
self.ser.rtscts = False
self.ser.dsrdtr = False
self.ser.writeTimeout = 2
"""Time to wait until the board becomes operational"""
wakeup = 2
try:
self.ser.open()
if self.PRINT:
print "Waking up board on "+self.ser.port+"..."
time.sleep(2)
# for i in range(1,wakeup):
# if self.PRINT:
# print wakeup-i
# time.sleep(1)
# else:
# time.sleep(1)
except Exception, error:
print "\n\nError opening "+self.ser.port+" port.\n"+str(error)+"\n\n"
def disconnect(self):
print "disconnecting from " +self.ser.port+ "..."
self.ser.flushInput()
self.ser.flushOutput()
self.ser.read(self.ser.inWaiting())
self.ser.close()
"""Function for sending a command to the board"""
def sendCMD(self, data_length, code, data):
checksum = 0
total_data = ['$', 'M', '<', data_length, code] + data
for i in struct.pack('<2B%dh' % len(data), *total_data[3:len(total_data)]):
checksum = checksum ^ ord(i)
total_data.append(checksum)
try:
b = None
b = self.ser.write(struct.pack('<3c2B%dhB' % len(data), *total_data))
except Exception, error:
#print "\n\nError in sendCMD."
#print "("+str(error)+")\n\n"
pass
"""Function for sending a command to the board and receive attitude"""
"""
Modification required on Multiwii firmware to Protocol.cpp in evaluateCommand:
case MSP_SET_RAW_RC:
s_struct_w((uint8_t*)&rcSerial,16);
rcSerialCount = 50; // 1s transition
s_struct((uint8_t*)&att,6);
break;
"""
def sendCMDreceiveATT(self, data_length, code, data):
checksum = 0
total_data = ['$', 'M', '<', data_length, code] + data
for i in struct.pack('<2B%dh' % len(data), *total_data[3:len(total_data)]):
checksum = checksum ^ ord(i)
total_data.append(checksum)
try:
start = time.time()
b = None
b = self.ser.write(struct.pack('<3c2B%dhB' % len(data), *total_data))
while True:
header = self.ser.read()
if header == '$':
header = header+self.ser.read(2)
break
datalength = struct.unpack('<b', self.ser.read())[0]
code = struct.unpack('<b', self.ser.read())
data = self.ser.read(datalength)
temp = struct.unpack('<'+'h'*(datalength/2),data)
self.ser.flushInput()
self.ser.flushOutput()
elapsed = time.time() - start
self.attitude['angx']=float(temp[0]/10.0)
self.attitude['angy']=float(temp[1]/10.0)
self.attitude['heading']=float(temp[2])
self.attitude['elapsed']=round(elapsed,3)
self.attitude['timestamp']="%0.2f" % (time.time(),)
return self.attitude
except Exception, error:
#print "\n\nError in sendCMDreceiveATT."
#print "("+str(error)+")\n\n"
pass
"""Function to arm / disarm """
"""
Modification required on Multiwii firmware to Protocol.cpp in evaluateCommand:
case MSP_SET_RAW_RC:
s_struct_w((uint8_t*)&rcSerial,16);
rcSerialCount = 50; // 1s transition
s_struct((uint8_t*)&att,6);
break;
"""
def arm(self):
timer = 0
start = time.time()
while timer < 0.5:
data = [1500,1500,2000,1000]
self.sendCMD(8,MultiWii.SET_RAW_RC,data)
time.sleep(0.05)
timer = timer + (time.time() - start)
start = time.time()
def disarm(self):
timer = 0
start = time.time()
while timer < 0.5:
data = [1500,1500,1000,1000]
self.sendCMD(8,MultiWii.SET_RAW_RC,data)
time.sleep(0.05)
timer = timer + (time.time() - start)
start = time.time()
def readWithTimeout(self, numBytes):
val = self.ser.read(numBytes)
if len(val) < numBytes:
raise serial.SerialTimeoutException("timeout")
#print val
return val
"""Function to receive a data packet from the board"""
def getData(self, cmd):
#try:
start = time.time()
self.sendCMD(0,cmd,[])
while True:
header = self.readWithTimeout(1)
if header == '$':
header = header+self.readWithTimeout(2)
break
datalength = struct.unpack('<b', self.readWithTimeout(1))[0]
#print datalength
code = struct.unpack('<b', self.readWithTimeout(1))
#print code
data = self.readWithTimeout(datalength)
temp = struct.unpack('<'+'h'*(datalength/2),data)
self.ser.flushInput()
self.ser.flushOutput()
elapsed = time.time() - start
if cmd == MultiWii.ATTITUDE:
self.attitude['angx']=float(temp[0]/10.0)
self.attitude['angy']=float(temp[1]/10.0)
self.attitude['heading']=float(temp[2])
self.attitude['elapsed']=round(elapsed,3)
self.attitude['timestamp']="%0.2f" % (time.time(),)
return self.attitude
elif cmd == MultiWii.RC:
self.rcChannels['roll']=temp[0]
self.rcChannels['pitch']=temp[1]
self.rcChannels['yaw']=temp[2]
self.rcChannels['throttle']=temp[3]
self.rcChannels['elapsed']=elapsed
self.rcChannels['timestamp']="%0.2f" % (time.time(),)
return self.rcChannels
elif cmd == MultiWii.RAW_IMU:
self.rawIMU['ax']=float(temp[0])
self.rawIMU['ay']=float(temp[1])
self.rawIMU['az']=float(temp[2])
self.rawIMU['gx']=float(temp[3])
self.rawIMU['gy']=float(temp[4])
self.rawIMU['gz']=float(temp[5])
self.rawIMU['elapsed']=round(elapsed,3)
self.rawIMU['timestamp']="%0.2f" % (time.time(),)
return self.rawIMU
elif cmd == MultiWii.MOTOR:
self.motor['m1']=float(temp[0])
self.motor['m2']=float(temp[1])
self.motor['m3']=float(temp[2])
self.motor['m4']=float(temp[3])
self.motor['elapsed']="%0.3f" % (elapsed,)
self.motor['timestamp']="%0.2f" % (time.time(),)
return self.motor
else:
return "No return error!"
#except Exception, error:
# #print error
# pass
"""Function to receive a data packet from the board. Note: easier to use on threads"""
def getDataInf(self, cmd):
while True:
try:
start = time.clock()
self.sendCMD(0,cmd,[])
while True:
header = self.ser.read()
if header == '$':
header = header+self.ser.read(2)
break
datalength = struct.unpack('<b', self.ser.read())[0]
code = struct.unpack('<b', self.ser.read())
data = self.ser.read(datalength)
temp = struct.unpack('<'+'h'*(datalength/2),data)
elapsed = time.clock() - start
self.ser.flushInput()
self.ser.flushOutput()
if cmd == MultiWii.ATTITUDE:
self.attitude['angx']=float(temp[0]/10.0)
self.attitude['angy']=float(temp[1]/10.0)
self.attitude['heading']=float(temp[2])
self.attitude['elapsed']="%0.3f" % (elapsed,)
self.attitude['timestamp']="%0.2f" % (time.time(),)
elif cmd == MultiWii.RC:
self.rcChannels['roll']=temp[0]
self.rcChannels['pitch']=temp[1]
self.rcChannels['yaw']=temp[2]
self.rcChannels['throttle']=temp[3]
self.rcChannels['elapsed']="%0.3f" % (elapsed,)
self.rcChannels['timestamp']="%0.2f" % (time.time(),)
elif cmd == MultiWii.RAW_IMU:
self.rawIMU['ax']=float(temp[0])
self.rawIMU['ay']=float(temp[1])
self.rawIMU['az']=float(temp[2])
self.rawIMU['gx']=float(temp[3])
self.rawIMU['gy']=float(temp[4])
self.rawIMU['gz']=float(temp[5])
self.rawIMU['elapsed']="%0.3f" % (elapsed,)
self.rawIMU['timestamp']="%0.2f" % (time.time(),)
elif cmd == MultiWii.MOTOR:
self.motor['m1']=float(temp[0])
self.motor['m2']=float(temp[1])
self.motor['m3']=float(temp[2])
self.motor['m4']=float(temp[3])
self.motor['elapsed']="%0.3f" % (elapsed,)
self.motor['timestamp']="%0.2f" % (time.time(),)
except Exception, error:
pass
"""Function to ask for 2 fixed cmds, attitude and rc channels, and receive them. Note: is a bit slower than others"""
def getData2cmd(self, cmd):
try:
start = time.time()
self.sendCMD(0,self.ATTITUDE,[])
while True:
header = self.ser.read()
if header == '$':
header = header+self.ser.read(2)
break
datalength = struct.unpack('<b', self.ser.read())[0]
code = struct.unpack('<b', self.ser.read())
data = self.ser.read(datalength)
temp = struct.unpack('<'+'h'*(datalength/2),data)
self.ser.flushInput()
self.ser.flushOutput()
self.sendCMD(0,self.RC,[])
while True:
header = self.ser.read()
if header == '$':
header = header+self.ser.read(2)
break
datalength = struct.unpack('<b', self.ser.read())[0]
code = struct.unpack('<b', self.ser.read())
data = self.ser.read(datalength)
temp2 = struct.unpack('<'+'h'*(datalength/2),data)
elapsed = time.time() - start
self.ser.flushInput()
self.ser.flushOutput()
if cmd == MultiWii.ATTITUDE:
self.message['angx']=float(temp[0]/10.0)
self.message['angy']=float(temp[1]/10.0)
self.message['heading']=float(temp[2])
self.message['roll']=temp2[0]
self.message['pitch']=temp2[1]
self.message['yaw']=temp2[2]
self.message['throttle']=temp2[3]
self.message['elapsed']=round(elapsed,3)
self.message['timestamp']="%0.2f" % (time.time(),)
return self.message
else:
return "No return error!"
except Exception, error:
print error