-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcom_monitor.py
109 lines (91 loc) · 3.6 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
import Queue
import threading
import time
import 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.05):
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.invert = False
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, e:
self.error_q.put(e.message)
return
# Restart the clock
# no anda en linux
#time.clock()
# sacar basura que pueda quedar en el buffer
for x in range(10):
self.serial_port.readline()
t0 = time.time()
while self.alive.isSet():
# Reading 1 byte, followed by whatever is left in the
# read buffer, as suggested by the developer of
# PySerial.
#
# data = self.serial_port.read(1)
# data += self.serial_port.read(self.serial_port.inWaiting())
#
# if len(data) > 0:
# timestamp = time.clock()
# self.data_q.put((data, timestamp))
#
data = self.serial_port.readline().strip()
if len(data) > 0:
try:
if self.invert:
data = [1024 - int(x) for x in data.split()]
else:
data = [int(x) for x in data.split()]
timestamp = time.time() - t0
self.data_q.put((timestamp, data))
except:
print 'com_err XXX data: ', data
# clean up
if self.serial_port:
self.serial_port.close()
def join(self, timeout=None):
self.alive.clear()
threading.Thread.join(self, timeout)