-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcom_monitor.py
120 lines (92 loc) · 3.4 KB
/
com_monitor.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
import queue, threading, time, serial
class ComMonitorThread(threading.Thread):
""" A thread for monitoring a COM port. The COM port is
opened when the thread is started.
data_q:
Queue for received data. Items in the queue are
(data, timestamp) pairs, where data is a binary
string representing the received data, and timestamp
is the time elapsed from the thread's start (in
seconds).
error_q:
Queue for error messages. In particular, if the
serial port fails to open for some reason, an error
is placed into this queue.
port:
The COM port to open. Must be recognized by the
system.
port_baud/stopbits/parity:
Serial communication parameters
port_timeout:
The timeout used for reading the COM port. If this
value is low, the thread will return data in finer
grained chunks, with more accurate timestamps, but
it will also consume more CPU.
"""
def __init__(self,
data_q, error_q,
port_num,
port_baud,
port_stopbits=serial.STOPBITS_ONE,
port_parity=serial.PARITY_NONE,
port_timeout=0.01):
threading.Thread.__init__(self)
self.serial_port = None
self.serial_arg = dict(port=port_num,
baudrate=port_baud,
stopbits=port_stopbits,
parity=port_parity,
timeout=port_timeout)
self.data_q = data_q
self.error_q = error_q
self.alive = threading.Event()
self.alive.set()
# ------------------------------------------------------
# ------------------------------------------------------
def run(self):
try:
if self.serial_port:
self.serial_port.close()
self.serial_port = serial.Serial(**self.serial_arg)
except serial.SerialException:
pass
return
# Restart the clock
startTime = time.time()
while self.alive.isSet():
Line = self.serial_port.readline()
bytes = Line.split()
print
bytes
# use map(int) for simulation
data = map(ord, bytes)
qdata = [0, 0, 0]
if len(data) == 6:
timestamp = time.time() - startTime
# data = list(map(ord, list(Line)))
print
"Line", Line
print
"bytes", bytes
print
"data", data
axes = self.getAxes(data)
print
" x = %.3fG" % (axes['x'])
print
" y = %.3fG" % (axes['y'])
print
" z = %.3fG" % (axes['z'])
qdata[0] = axes['x']
qdata[1] = axes['y']
qdata[2] = axes['z']
print
"qdata :", qdata
timestamp = time.clock()
self.data_q.put((qdata, timestamp))
# clean up
if self.serial_port:
self.serial_port.close()
def join(self, timeout=None):
self.alive.clear()
threading.Thread.join(self, timeout)