-
Notifications
You must be signed in to change notification settings - Fork 0
/
serial_utils.py
64 lines (55 loc) · 1.9 KB
/
serial_utils.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
import serial
import time
from threading import Thread, ThreadError
class SerialStream:
def __init__(self, ser, connection_char, encoding="utf-8", terminator="\n"):
self.ser = ser
self.encoding = encoding
self.char = connection_char.encode(self.encoding)
self.thread_cancelled = False
self.thread = Thread(target=self.run)
self.data = []
self.str = ""
self.reading = False
self.terminator = terminator.encode(self.encoding)
def open(self):
if not self.ser.is_open:
self.ser.open()
self.thread.start()
def write(self, str):
self.ser.write(str.encode())
def flush(self):
self.ser.flush()
def run(self):
while not self.thread_cancelled:
try:
if not self.reading:
self.ser.write(self.char)
self.ser.flush()
self.reading = True
return_val = self.ser.read(self.ser.in_waiting)
newline_idx = return_val.find(self.terminator)
if newline_idx != -1:
self.str += return_val[:newline_idx]
self.data.append(self.str.decode(self.encoding))
self.str = return_val[newline_idx+1:]
self.reading = False
elif len(return_val) > 0:
self.str += return_val
except ThreadError:
self.thread_cancelled = True
def get_data(self):
tmp = self.data
self.data = []
return tmp
def is_running(self):
return self.thread.isAlive()
def close(self):
self.thread_cancelled = True
# block while waiting for thread to terminate
while self.thread.isAlive():
time.sleep(1)
self.ser.flush()
if self.ser.is_open:
self.ser.close()
return True