-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathserialinterface.py
114 lines (104 loc) · 3.23 KB
/
serialinterface.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
import serial
import string
import sys
import time
class SerialInterface:
def __init__ ( self, path2device, baudrate, timeout=0):
self.portopen = False
self.dummy = False
if path2device == '/dev/null':
self.dummy = True
self.portopen = True
while not self.portopen:
try:
self.ser = serial.Serial(path2device, baudrate)
self.path2device = path2device
self.baudrate = baudrate
self.timeout = timeout+1
self.ser.flushInput()
self.ser.flushOutput()
if timeout:
self.ser.setTimeout(timeout+1)
self.portopen = True
break
except serial.SerialException:
#print "Exception while opening", path2device
pass
time.sleep(1)
print "Opened", path2device
def close(self):
try:
self.portopen = False
self.ser.close()
except serial.SerialException:
pass
def reinit(self):
self.close()
#print "reopening"
while not self.portopen:
self.__init__(self.path2device, self.baudrate, self.timeout)
time.sleep(1)
#print "done"
def writeMessage(self,message):
enc = "\\1" + message.replace('\\','\\\\') + "\\2";
#print 'writing %s' % list(enc)
try:
self.ser.write(enc)
except :
pass
#self.reinit()
def write(self,message):
#print 'writing', list(message)
if self.dummy:
return
try:
self.ser.write(message)
except :
self.reinit()
def readMessage(self):
data = ""
escaped = False
stop = False
start = False
inframe = False
while True:
starttime = time.time()
c = self.ser.read(1)
endtime = time.time()
if len(c) == 0: #A timout occured
if endtime-starttime < self.timeout - 1:
print "port broken"
self.reinit()
raise Exception()
else:
#print 'TIMEOUT'
return False
if escaped:
if c == '1':
start = True
inframe = True
elif c == '9':
stop = True
inframe = False
elif c == '\\':
d = '\\'
escaped = False
elif c == '\\':
escaped = 1
else:
d = c
if start and inframe:
start = False
elif stop:
if data[0] == 'D':
message = '%f %s'%(time.time(), data[2:])
print 'serial debug message:',data
#print message
data = ""
stop = False
else:
#print 'received message: len=%d data=%s'%(len(data),data)
#print 'received message:',list(data)
return data
elif escaped == False and inframe:
data += str(d)