-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpySerialComm.py
More file actions
341 lines (270 loc) · 11.5 KB
/
pySerialComm.py
File metadata and controls
341 lines (270 loc) · 11.5 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
import serial
import struct
import sys
import time
import threading
import traceback
START = b'\x61'
END = b'\x62'
ESC = b'\x63'
TSTART = b'\x64'
TEND = b'\x65'
TESC = b'\x66'
MESSAGE_LENGTH = 20
ACK_TIMEOUT = 6000
class SerialComm():
def __init__(self, device, baudrate=9600):
self.serial = serial.Serial(device, timeout=1, baudrate=baudrate)
time.sleep(2)
self.serial.flushInput()
self.receptionstarted = False
self.receptiondata = bytearray()
self.esc = False
self.id = set(range(1,20))
self.__idlock = threading.Lock()
self.__seriallock = threading.Lock()
self.__actions = {}
self.__stoprequested = False
self.__threadstarted = False
self.__ackwaited = {}
self.__ackdata = {}
def stop(self):
self.__stoprequested = True
def listenner(self):
self.__threadstarted = True
while not self.__stoprequested:
msg = self.__read()
if msg == None:
continue
action, messageid, data = msg
print("msg received : ");
#print(msg)
if action == 0: # ACK received
if messageid in self.__ackwaited:
self.__ackdata[messageid] = data
self.__ackwaited[messageid].set()
continue
else:
print("ack inconnu")
if action in self.__actions:
self.__actions[action](messageid, data)
self.__threadstarted = False
def checkincomingmessages(self):
while True:
msg = self.__read(timeout=100)
if msg == None:
print("checkincomingmessages - No incoming message")
return
print("checkincomingmessages - An incoming message")
action, messageid, data = msg
if action in self.__actions:
self.__actions[action](messageid, data)
def __read(self, timeout=None, expectedid = None):
messagereceived = False
start_time = self.__getMillis()
while True:
if timeout:
if ((self.__getMillis() - start_time) > timeout):
return None
if self.__stoprequested:
return None
byte = self.serial.read(1)
#print(byte)
if byte == START:
print("__read - START")
self.receptionstarted = True
self.receptiondata = bytearray()
elif self.receptionstarted :
if byte == END:
print("__read - END")
self.receptionstarted = False
#print("Data received :")
#print(self.receptiondata)
message_id = self.receptiondata[1] # ID , action inverses , a verifier
action = self.receptiondata[2]
data = None
if len(self.receptiondata) > 3:
data = self.receptiondata[3:-1]
print("__read - %s, %s" % (action, message_id))
return action, message_id, data
elif byte == ESC:
self.esc = True
else:
if self.esc:
if byte == TSTART:
self.receptiondata += START
elif byte == TEND:
self.receptiondata += END
elif byte == TESC:
self.receptiondata += ESC
else:
raise ValueError("Unknow escaped character : %s" % byte)
self.esc = False
else:
self.receptiondata += byte
def getAck(self, expected_id):
i = 0
"""while True:
byte = self.serial.read(1)
print(byte)
"""
while True:
result = self.__read(ACK_TIMEOUT, expected_id)
action, messageid, data = result
if result == None:
raise TimeoutError("Ack timeout expired...")
return result
def __get_id(self):
with self.__idlock:
if len(self.id) == 0:
raise RuntimeError("No more message ids available")
return self.id.pop()
def __release_id(self, message_id):
self.id.add(message_id)
def __getMillis(self):
return int(round(time.time() * 1000))
def __sendmessage(self, action, messageid, values):
payload = bytearray()
payload = bytes((messageid, ))
payload = payload + bytes([action])
if values:
for value in values:
if isinstance(value, int):
if not(-32768 <= value <= 32767):
raise ValueError('Arduino integer must be in range(-32,768, 32,767)')
lowbyte, highbyte = struct.pack('h', value)
payload = payload + bytes([highbyte]) # First byte
payload = payload + bytes([lowbyte]) # Second byte
if isinstance(value, str):
payload = payload + bytearray(value, "utf-8")
payload = payload + bytearray([0])
#print(self.payload)
#print("lock acquired for :")
#print(action, messageid, values)
self.__seriallock.acquire()
self.serial.write(START) # The START flag
#print(START, end="")
self.__writetoserial(payload) # The payload
self.__writetoserial(self.__checksum(payload)) # The checksum
self.serial.write(END) # The END flag
#print(END)
def sendmessage(self, action, values=None, ack=False):
self.action = action
self.ack = ack
# Prepare the payload
if ack:
messageid = self.__get_id()
else:
messageid = 0
if ack and self.__threadstarted: # thread mode, need a lock
evt = threading.Event()
self.__ackwaited[messageid] = evt
if not self.__threadstarted:
print("sendmessage - Checking incoming message" )
self.checkincomingmessages()
self.__sendmessage(action, messageid, values)
if ack:
if self.__threadstarted: #Mode thread
self.__seriallock.release()
result = evt.wait(ACK_TIMEOUT / 1000)
del self.__ackwaited[messageid]
del evt
self.__release_id(messageid)
if not result:
raise TimeoutError("Ack timeout expired...")
data = self.__ackdata[messageid]
del self.__ackdata[messageid]
return data
else: #Mode sans thread
start_time = self.__getMillis()
while ((self.__getMillis() - start_time) < ACK_TIMEOUT): # Traitement des messages entrants
result = self.__read(ACK_TIMEOUT) # Attente de l accuse
if not result:
self.__seriallock.release()
self.__release_id(messageid)
raise TimeoutError("Ack timeout expired...")
action, incoming_messageid, data = result # Un message recu
if ( action==0 ) and ( messageid == incoming_messageid): # Si accuse attendu
self.__seriallock.release()
self.__release_id(messageid)
return data
self.__seriallock.release()
self.__release_id(messageid)
raise TimeoutError("Ack timeout expired...")
self.__seriallock.release()
def sendack(self, messageid, data=None):
self.__sendmessage(0, messageid, data)
self.__seriallock.release()
def __writetoserial(self, data):
data = data.replace(ESC, ESC + TESC)
data = data.replace(START, ESC + TSTART)
data = data.replace(END, ESC + TEND)
self.serial.write(data)
def __checksum(self, data):
checksum = 0
for c in data:
checksum = checksum ^ c
return bytes((checksum, ))
def parsedata(self, dataformat = None, data = None):
if data == None:
return None
values = []
index = 0
for f in dataformat:
if f == 'i':
if len(data) < (index + 2): # A verifier....
raise IndexError("Too much values excepted (%s) for %s" % (dataformat, data))
value = (data[index]<<8)+data[index+1]
index += 2
values.append(value)
elif f == 's':
i = 0
mystring = ""
while True:
byte = data[index]
index += 1
if byte == 0:
break
elif index > len(data):
raise IndexError("Too much values excepted (%s) for %s" % (dataformat, data))
mystring += chr(byte)
values.append(mystring)
return values
def attach(self, action, function):
self.__actions[action] = function
if __name__ == '__main__':
pccnt = 0
def test(messageid, data):
global pccnt
values = ard.parsedata("is", data)
print("<- Request received from arduino : %s, %s" % (values[0], values[1]))
print("-> Sending the python counter to arduino : %s" % pccnt)
ard.sendack(messageid, (pccnt, ))
pccnt = pccnt + 3
if pccnt > 32767:
pccnt = 0
def test3(messageid, data):
print("action 3 received !!")
values = ard.parsedata("si", data)
print(values)
ard = SerialComm('/dev/ttyUSB2', baudrate=9600)
ard.attach(2, test)
ard.attach(3, test3)
thread = threading.Thread(target=ard.listenner, args=())
thread.daemon = True # Daemonize thread
thread.start() # Start the execution
"""resp = ard.sendmessage(2, (5, "This is a string"), ack=True)
values = ard.parsedata("is", resp)
print(values)"""
for i in range(0, 5):
try:
print("-> Sending an integer and a string to arduino")
resp = ard.sendmessage(2, (i,"This is a string"), ack=True)
values = ard.parsedata("is", resp)
print("<- Ack contains two values (arduino counter, a string) : %s, %s" % (values[0], values[1]))
except TimeoutError:
print("No ack received")
time.sleep(10)
ard.stop()
thread.join()
print("---End of script")