-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathOmstTTY.py
267 lines (248 loc) · 8.66 KB
/
OmstTTY.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
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
##Copyright (c) 2018 Douglas E. Moore
##
##Permission is hereby granted, free of charge, to any person obtaining a copy
##of this software and associated documentation files (the "Software"), to deal
##in the Software without restriction, including without limitation the rights
##to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
##copies of the Software, and to permit persons to whom the Software is
##furnished to do so, subject to the following conditions:
##
##The above copyright notice and this permission notice shall be included in all
##copies or substantial portions of the Software.
##
##THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
##IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
##FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
##AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
##LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
##OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
##SOFTWARE.
import termios # configuring the serialport
import struct # reading output from ioctls
import re # parsing directories to find ttys
import fcntl # getting awaiting byte count for os.read
import os # open, read, write, close
from functools import cmp_to_key # sorting tty names
import OmstUTL as utl # various utilities like logging
class OmstTTY:
def __init__(self):
self.tty = None
self.fd = None
self.baud = None
"""
A lookup table of parity values
"""
parity_table = tuple(1 & sum([1 for i in range(8) if (j & (1 << i))])\
for j in range(256))
"""
field indices in termios structure
"""
offset_termios_flags = [
'iflag',
'oflag',
'cflag',
'lflag',
'ispeed',
'ospeed',
'cc'
]
"""
field indices of cc values in termios structure
"""
offset_termios_cc = [
'VINTR',
'VQUIT',
'VERASE',
'VKILL',
'VEOF',
'VTIME',
'VMIN',
'VSWTC',
'VSTART',
'VSTOP',
'VSUSP',
'VEOL',
'VREPRINT',
'VDISCARD',
'VWERASE',
'VLNEXT',
'VEOL2'
]
"""
baudrates
"""
baudrates = (
'300',
'600',
'1200',
'2400',
'4800',
'9600',
'19200',
'38400',
'57600',
'76800',
'115200'
)
@staticmethod
def compare_ttys(tty1,tty2):
"""
callback that sorts ttys first by name prefix, then by numeric suffix
['ttyS0', 'ttyUSB0', 'ttyUSB1']
"""
p = re.compile("^(tty(S|USB))(\d+)$")
m1 = p.match(tty1)
m2 = p.match(tty2)
if m1.group(1) == m2.group(1):
return int(m1.group(3)) - int(m2.group(3))
else:
if m1.group(1) < m2.group(1):
return -1
else:
if m1.group(1) > m2.group(1):
return 1
return 0
@staticmethod
def list_ttys():
"""
list ttys that were found on PCI bus at system boot
and also by PNP such as FTDI USB devices which may
come and go
"""
ttys = []
base = "/sys/devices"
rx = "^.*(pnp|pci).*/tty/(tty(S|USB)\d+)$"
p1 = re.compile(rx)
for root, dirs, files in os.walk(base):
m = p1.match(root)
if m:
ttys.append(m.group(2))
ttys = sorted(ttys,key=cmp_to_key(OmstTTY().compare_ttys))
return {key: '/dev/'+ttys[key] for key in range(len(ttys))}
@staticmethod
def list_baudrates():
return {key:OmstTTY.baudrates[key] for key in range(len(OmstTTY.baudrates))}
@utl.logger
def cfsetspeed(self,tios,speed):
"""
put the baudrate in the termios speed members
"""
tios[self.offset_termios_flags.index('ispeed')] = speed
tios[self.offset_termios_flags.index('ospeed')] = speed
self.baud = speed
return tios
@utl.logger
def open(self,tty,baud=38400):
"""
open the specified tty at the specified baudrate
"""
if self.tty != None:
raise ValueError('tty is allready open on {:s}'.format(self.tty))
try:
fd = os.open(tty,os.O_RDWR | os.O_NOCTTY | os.O_NONBLOCK)
if fd:
tios = termios.tcgetattr(fd)
tios[self.offset_termios_flags.index('iflag')] = 0
tios[self.offset_termios_flags.index('oflag')] = 0
tios[self.offset_termios_flags.index('lflag')] = 0
tios[self.offset_termios_flags.index('cflag')] = \
getattr(termios,'B{:d}'.format(baud)) \
| termios.CLOCAL \
| termios.CREAD \
| termios.CS8
## tios[self.offset_termios_flags.index('cc')][self.offset_termios_cc.index('VMIN')] = 1
tios[self.offset_termios_flags.index('cc')][self.offset_termios_cc.index('VMIN')] = 0
tios[self.offset_termios_flags.index('cc')][self.offset_termios_cc.index('VTIME')] = 0
self.cfsetspeed(tios,getattr(termios,'B{:d}'.format(baud)))
termios.tcsetattr(fd,termios.TCSAFLUSH,tios)
self.tty = tty
self.fd = fd
self.baud = baud
except:
if os.isatty(fd):
os.close(fd)
return False
finally:
print('opened \'{:s}:{:d},N,8,1\''.format(self.tty,self.baud))
return True
@utl.logger
def close(self):
"""
Close the posr
"""
if self.fd != None \
and os.isatty(self.fd):
os.close(self.fd)
print('closed \'{:s}\''.format(self.tty))
self.tty = None
self.fd = None
@utl.logger
def write(self,pkt,mode=False):
"""
write data to port
"""
if mode:
tios = termios.tcgetattr(self.fd)
c_cflag = tios[self.offset_termios_flags.index('cflag')]
c_cflag |= termios.PARENB
# send the address
if self.parity_table[pkt[0]]:
c_cflag &= ~termios.PARODD
else:
c_cflag |= termios.PARODD
tios[self.offset_termios_flags.index('cflag')] = c_cflag
termios.tcsetattr(self.fd,termios.TCSANOW,tios)
n = os.write(self.fd,(pkt[0]).to_bytes(1,byteorder='big'))
# send the data
for i in range(1,len(pkt)):
if self.parity_table[pkt[i]]:
c_cflag |= termios.PARODD
else:
c_cflag &= ~termios.PARODD
tios[self.offset_termios_flags.index('cflag')] = c_cflag
termios.tcsetattr(self.fd,termios.TCSADRAIN,tios)
n += os.write(self.fd,(pkt[i]).to_bytes(1,byteorder='big'))
return n
else:
tios = termios.tcgetattr(self.fd)
c_cflag = tios[self.offset_termios_flags.index('cflag')]
if c_cflag | termios.PARENB:
c_cflag &= ~termios.PARENB
termios.tcsetattr(self.fd,termios.TCSANOW,tios)
# send the bytes
return os.write(self.fd,pkt.encode())
@utl.logger
def read(self,n,mode=False):
"""
read data from port
"""
if mode:
return os.read(self.fd,n)
else:
return os.read(self.fd,n).decode()
@utl.logger
def rx_bytes_available(self):
"""
only safe way to prevent read blocking is to make sure
there is something to be read
"""
#unlikely to get here if nothing to read, but just in case
s = fcntl.ioctl(self.fd, termios.TIOCINQ,struct.pack('I',0))
#how many bytes available?
n = struct.unpack('I', s)[0]
return n
@utl.logger
def flush_input_buffer(self,mode=False):
"""
optomux responses do not maintain any type of message number
so the only way to make sure to tie a command to a response
is to make sure the input buffer is empty before sending a
command.
"""
while True:
n = self.rx_bytes_available()
if n != 0:
self.read(n,mode)
else:
break