blob: 70fb241e23c7e37c7fefe2f8fbe7046ab39e28d3 [file] [log] [blame]
cliechti89b4af12002-02-12 23:24:41 +00001#!/usr/bin/env python
cliechti58b481c2009-02-16 20:42:32 +00002#
Chris Liechti3e02f702015-12-16 23:06:04 +01003# backend for serial IO for POSIX compatible systems, like Linux, OSX
cliechti89b4af12002-02-12 23:24:41 +00004#
Chris Liechti3e02f702015-12-16 23:06:04 +01005# This file is part of pySerial. https://github.com/pyserial/pyserial
Chris Liechti68340d72015-08-03 14:15:48 +02006# (C) 2001-2015 Chris Liechti <cliechti@gmx.net>
Chris Liechtifbdd8a02015-08-09 02:37:45 +02007#
8# SPDX-License-Identifier: BSD-3-Clause
cliechti89b4af12002-02-12 23:24:41 +00009#
cliechtic54b2c82008-06-21 01:59:08 +000010# parts based on code from Grant B. Edwards <grante@visi.com>:
cliechti89b4af12002-02-12 23:24:41 +000011# ftp://ftp.visi.com/users/grante/python/PosixSerial.py
cliechti53c9fd42009-07-23 23:51:51 +000012#
cliechti89b4af12002-02-12 23:24:41 +000013# references: http://www.easysw.com/~mike/serial/serial.html
14
Chris Liechti9eaa40c2016-02-12 23:32:59 +010015# pylint: disable=abstract-method
Chris Liechti33f0ec52015-08-06 16:37:21 +020016import errno
17import fcntl
Chris Liechti33f0ec52015-08-06 16:37:21 +020018import os
19import select
20import struct
21import sys
22import termios
23import time
Chris Liechti033f17c2015-08-30 21:28:04 +020024
25import serial
26from serial.serialutil import SerialBase, SerialException, to_bytes, portNotOpenError, writeTimeoutError
cliechti89b4af12002-02-12 23:24:41 +000027
cliechti89b4af12002-02-12 23:24:41 +000028
Chris Liechtid6847af2015-08-06 17:54:30 +020029class PlatformSpecificBase(object):
30 BAUDRATE_CONSTANTS = {}
cliechti89b4af12002-02-12 23:24:41 +000031
Chris Liechtid6847af2015-08-06 17:54:30 +020032 def number_to_device(self, port_number):
33 sys.stderr.write("""\
cliechti7aaead32009-07-23 14:02:41 +000034don't know how to number ttys on this system.
cliechti895e8302004-04-20 02:40:28 +000035! Use an explicit path (eg /dev/ttyS1) or send this information to
36! the author of this module:
cliechti89b4af12002-02-12 23:24:41 +000037
Chris Liechti984c5c52016-02-15 23:48:45 +010038sys.platform = {!r}
39os.name = {!r}
40serialposix.py version = {}
cliechti89b4af12002-02-12 23:24:41 +000041
42also add the device name of the serial port and where the
43counting starts for the first serial port.
44e.g. 'first serial port: /dev/ttyS0'
45and with a bit luck you can get this module running...
Chris Liechti984c5c52016-02-15 23:48:45 +010046""".format(sys.platform, os.name, serial.VERSION))
Chris Liechtid6847af2015-08-06 17:54:30 +020047 raise NotImplementedError('no number-to-device mapping defined on this platform')
48
49 def _set_special_baudrate(self, baudrate):
50 raise NotImplementedError('non-standard baudrates are not supported on this platform')
51
52 def _set_rs485_mode(self, rs485_settings):
53 raise NotImplementedError('RS485 not supported on this platform')
54
55# try to detect the OS so that a device can be selected...
56# this code block should supply a device() and set_special_baudrate() function
57# for the platform
58plat = sys.platform.lower()
59
Chris Liechtiba45c522016-02-06 23:53:23 +010060if plat[:5] == 'linux': # Linux (confirmed) # noqa
Chris Liechtid6847af2015-08-06 17:54:30 +020061 import array
62
63 # baudrate ioctls
64 TCGETS2 = 0x802C542A
65 TCSETS2 = 0x402C542B
66 BOTHER = 0o010000
67
68 # RS485 ioctls
69 TIOCGRS485 = 0x542E
70 TIOCSRS485 = 0x542F
Chris Liechti033f17c2015-08-30 21:28:04 +020071 SER_RS485_ENABLED = 0b00000001
72 SER_RS485_RTS_ON_SEND = 0b00000010
Chris Liechtid6847af2015-08-06 17:54:30 +020073 SER_RS485_RTS_AFTER_SEND = 0b00000100
Chris Liechti033f17c2015-08-30 21:28:04 +020074 SER_RS485_RX_DURING_TX = 0b00010000
Chris Liechtid6847af2015-08-06 17:54:30 +020075
76 class PlatformSpecific(PlatformSpecificBase):
77 BAUDRATE_CONSTANTS = {
78 0: 0o000000, # hang up
79 50: 0o000001,
80 75: 0o000002,
81 110: 0o000003,
82 134: 0o000004,
83 150: 0o000005,
84 200: 0o000006,
85 300: 0o000007,
86 600: 0o000010,
87 1200: 0o000011,
88 1800: 0o000012,
89 2400: 0o000013,
90 4800: 0o000014,
91 9600: 0o000015,
92 19200: 0o000016,
93 38400: 0o000017,
94 57600: 0o010001,
95 115200: 0o010002,
96 230400: 0o010003,
97 460800: 0o010004,
98 500000: 0o010005,
99 576000: 0o010006,
100 921600: 0o010007,
101 1000000: 0o010010,
102 1152000: 0o010011,
103 1500000: 0o010012,
104 2000000: 0o010013,
105 2500000: 0o010014,
106 3000000: 0o010015,
107 3500000: 0o010016,
108 4000000: 0o010017
109 }
110
111 def number_to_device(self, port_number):
112 return '/dev/ttyS%d' % (port_number,)
113
114 def _set_special_baudrate(self, baudrate):
115 # right size is 44 on x86_64, allow for some growth
116 buf = array.array('i', [0] * 64)
117 try:
118 # get serial_struct
119 fcntl.ioctl(self.fd, TCGETS2, buf)
120 # set custom speed
121 buf[2] &= ~termios.CBAUD
122 buf[2] |= BOTHER
123 buf[9] = buf[10] = baudrate
124
125 # set serial_struct
Chris Liechti033f17c2015-08-30 21:28:04 +0200126 fcntl.ioctl(self.fd, TCSETS2, buf)
Chris Liechtid6847af2015-08-06 17:54:30 +0200127 except IOError as e:
Chris Liechti984c5c52016-02-15 23:48:45 +0100128 raise ValueError('Failed to set custom baud rate ({}): {}'.format(baudrate, e))
Chris Liechtid6847af2015-08-06 17:54:30 +0200129
130 def _set_rs485_mode(self, rs485_settings):
Chris Liechti033f17c2015-08-30 21:28:04 +0200131 buf = array.array('i', [0] * 8) # flags, delaytx, delayrx, padding
Chris Liechtid6847af2015-08-06 17:54:30 +0200132 try:
133 fcntl.ioctl(self.fd, TIOCGRS485, buf)
Chris Liechti7a554462016-03-24 21:17:22 +0100134 buf[0] |= SER_RS485_ENABLED
Chris Liechtid6847af2015-08-06 17:54:30 +0200135 if rs485_settings is not None:
136 if rs485_settings.loopback:
137 buf[0] |= SER_RS485_RX_DURING_TX
138 else:
139 buf[0] &= ~SER_RS485_RX_DURING_TX
140 if rs485_settings.rts_level_for_tx:
141 buf[0] |= SER_RS485_RTS_ON_SEND
142 else:
143 buf[0] &= ~SER_RS485_RTS_ON_SEND
144 if rs485_settings.rts_level_for_rx:
145 buf[0] |= SER_RS485_RTS_AFTER_SEND
146 else:
147 buf[0] &= ~SER_RS485_RTS_AFTER_SEND
Chris Liechti01df8892016-03-17 23:01:42 +0100148 buf[1] = int(rs485_settings.delay_before_tx * 1000)
149 buf[2] = int(rs485_settings.delay_before_rx * 1000)
Chris Liechtid6847af2015-08-06 17:54:30 +0200150 else:
151 buf[0] = 0 # clear SER_RS485_ENABLED
Chris Liechti033f17c2015-08-30 21:28:04 +0200152 fcntl.ioctl(self.fd, TIOCSRS485, buf)
Chris Liechtid6847af2015-08-06 17:54:30 +0200153 except IOError as e:
Chris Liechti984c5c52016-02-15 23:48:45 +0100154 raise ValueError('Failed to set RS485 mode: {}'.format(e))
Chris Liechtid6847af2015-08-06 17:54:30 +0200155
156
157elif plat == 'cygwin': # cygwin/win32 (confirmed)
158
159 class PlatformSpecific(PlatformSpecificBase):
160 BAUDRATE_CONSTANTS = {
161 128000: 0x01003,
162 256000: 0x01005,
163 500000: 0x01007,
164 576000: 0x01008,
165 921600: 0x01009,
166 1000000: 0x0100a,
167 1152000: 0x0100b,
168 1500000: 0x0100c,
169 2000000: 0x0100d,
170 2500000: 0x0100e,
171 3000000: 0x0100f
172 }
173
174 def number_to_device(self, port_number):
175 return '/dev/com%d' % (port_number + 1,)
176
177
178elif plat[:7] == 'openbsd': # OpenBSD
179 class PlatformSpecific(PlatformSpecificBase):
180 def number_to_device(self, port_number):
181 return '/dev/cua%02d' % (port_number,)
182
183elif plat[:3] == 'bsd' or plat[:7] == 'freebsd':
184 class PlatformSpecific(PlatformSpecificBase):
185 def number_to_device(self, port_number):
186 return '/dev/cuad%d' % (port_number,)
187
188elif plat[:6] == 'darwin': # OS X
189 import array
Chris Liechti033f17c2015-08-30 21:28:04 +0200190 IOSSIOSPEED = 0x80045402 # _IOW('T', 2, speed_t)
Chris Liechtid6847af2015-08-06 17:54:30 +0200191
192 class PlatformSpecific(PlatformSpecificBase):
193 def number_to_device(self, port_number):
194 return '/dev/cuad%d' % (port_number,)
195
196 osx_version = os.uname()[2].split('.')
197 # Tiger or above can support arbitrary serial speeds
198 if int(osx_version[0]) >= 8:
199 def _set_special_baudrate(self, baudrate):
200 # use IOKit-specific call to set up high speeds
201 buf = array.array('i', [baudrate])
202 fcntl.ioctl(self.fd, IOSSIOSPEED, buf, 1)
203
204
205elif plat[:6] == 'netbsd': # NetBSD 1.6 testing by Erk
206 class PlatformSpecific(PlatformSpecificBase):
207 def number_to_device(self, port_number):
208 return '/dev/dty%02d' % (port_number,)
209
210elif plat[:4] == 'irix': # IRIX (partially tested)
211 class PlatformSpecific(PlatformSpecificBase):
212 def number_to_device(self, port_number):
Chris Liechti033f17c2015-08-30 21:28:04 +0200213 return '/dev/ttyf%d' % (port_number + 1,) # XXX different device names depending on flow control
Chris Liechtid6847af2015-08-06 17:54:30 +0200214
215elif plat[:2] == 'hp': # HP-UX (not tested)
216 class PlatformSpecific(PlatformSpecificBase):
217 def number_to_device(self, port_number):
218 return '/dev/tty%dp0' % (port_number + 1,)
219
220elif plat[:5] == 'sunos': # Solaris/SunOS (confirmed)
221 class PlatformSpecific(PlatformSpecificBase):
222 def number_to_device(self, port_number):
223 return '/dev/tty%c' % (ord('a') + port_number,)
224
225elif plat[:3] == 'aix': # AIX
226 class PlatformSpecific(PlatformSpecificBase):
227 def number_to_device(self, port_number):
228 return '/dev/tty%d' % (port_number,)
229
230else:
231 class PlatformSpecific(PlatformSpecificBase):
232 pass
cliechti89b4af12002-02-12 23:24:41 +0000233
cliechti58b481c2009-02-16 20:42:32 +0000234# whats up with "aix", "beos", ....
235# they should work, just need to know the device names.
cliechti89b4af12002-02-12 23:24:41 +0000236
237
cliechti58b481c2009-02-16 20:42:32 +0000238# load some constants for later use.
Chris Liechti11465c82015-08-04 15:55:22 +0200239# try to use values from termios, use defaults from linux otherwise
Chris Liechti033f17c2015-08-30 21:28:04 +0200240TIOCMGET = getattr(termios, 'TIOCMGET', 0x5415)
241TIOCMBIS = getattr(termios, 'TIOCMBIS', 0x5416)
242TIOCMBIC = getattr(termios, 'TIOCMBIC', 0x5417)
243TIOCMSET = getattr(termios, 'TIOCMSET', 0x5418)
cliechti89b4af12002-02-12 23:24:41 +0000244
Chris Liechti033f17c2015-08-30 21:28:04 +0200245# TIOCM_LE = getattr(termios, 'TIOCM_LE', 0x001)
Chris Liechtid6847af2015-08-06 17:54:30 +0200246TIOCM_DTR = getattr(termios, 'TIOCM_DTR', 0x002)
247TIOCM_RTS = getattr(termios, 'TIOCM_RTS', 0x004)
Chris Liechti033f17c2015-08-30 21:28:04 +0200248# TIOCM_ST = getattr(termios, 'TIOCM_ST', 0x008)
249# TIOCM_SR = getattr(termios, 'TIOCM_SR', 0x010)
cliechti89b4af12002-02-12 23:24:41 +0000250
Chris Liechtid6847af2015-08-06 17:54:30 +0200251TIOCM_CTS = getattr(termios, 'TIOCM_CTS', 0x020)
252TIOCM_CAR = getattr(termios, 'TIOCM_CAR', 0x040)
253TIOCM_RNG = getattr(termios, 'TIOCM_RNG', 0x080)
254TIOCM_DSR = getattr(termios, 'TIOCM_DSR', 0x100)
Chris Liechti033f17c2015-08-30 21:28:04 +0200255TIOCM_CD = getattr(termios, 'TIOCM_CD', TIOCM_CAR)
256TIOCM_RI = getattr(termios, 'TIOCM_RI', TIOCM_RNG)
257# TIOCM_OUT1 = getattr(termios, 'TIOCM_OUT1', 0x2000)
258# TIOCM_OUT2 = getattr(termios, 'TIOCM_OUT2', 0x4000)
Chris Liechti11465c82015-08-04 15:55:22 +0200259if hasattr(termios, 'TIOCINQ'):
260 TIOCINQ = termios.TIOCINQ
cliechti28b8fd02011-12-28 21:39:42 +0000261else:
Chris Liechtid6847af2015-08-06 17:54:30 +0200262 TIOCINQ = getattr(termios, 'FIONREAD', 0x541B)
Chris Liechti033f17c2015-08-30 21:28:04 +0200263TIOCOUTQ = getattr(termios, 'TIOCOUTQ', 0x5411)
cliechti89b4af12002-02-12 23:24:41 +0000264
265TIOCM_zero_str = struct.pack('I', 0)
266TIOCM_RTS_str = struct.pack('I', TIOCM_RTS)
267TIOCM_DTR_str = struct.pack('I', TIOCM_DTR)
268
Chris Liechti033f17c2015-08-30 21:28:04 +0200269TIOCSBRK = getattr(termios, 'TIOCSBRK', 0x5427)
270TIOCCBRK = getattr(termios, 'TIOCCBRK', 0x5428)
cliechti997b63c2008-06-21 00:09:31 +0000271
Chris Liechti033f17c2015-08-30 21:28:04 +0200272CMSPAR = 0o10000000000 # Use "stick" (mark/space) parity
cliechtiaec27ab2014-07-31 22:21:24 +0000273
cliechti89b4af12002-02-12 23:24:41 +0000274
Chris Liechtief6b7b42015-08-06 22:19:26 +0200275class Serial(SerialBase, PlatformSpecific):
cliechti7d448562014-08-03 21:57:45 +0000276 """\
Chris Liechti033f17c2015-08-30 21:28:04 +0200277 Serial port class POSIX implementation. Serial port configuration is
cliechtid6bf52c2003-10-01 02:28:12 +0000278 done with termios and fcntl. Runs on Linux and many other Un*x like
cliechtif0a81d42014-08-04 14:03:53 +0000279 systems.
280 """
cliechtid6bf52c2003-10-01 02:28:12 +0000281
282 def open(self):
cliechti7d448562014-08-03 21:57:45 +0000283 """\
284 Open port with current settings. This may throw a SerialException
285 if the port cannot be opened."""
cliechtid6bf52c2003-10-01 02:28:12 +0000286 if self._port is None:
287 raise SerialException("Port must be configured before it can be used.")
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200288 if self.is_open:
cliechti02ef43a2011-03-24 23:33:12 +0000289 raise SerialException("Port is already open.")
290 self.fd = None
cliechti58b481c2009-02-16 20:42:32 +0000291 # open
cliechti4616bf12002-04-08 23:13:14 +0000292 try:
Chris Liechti033f17c2015-08-30 21:28:04 +0200293 self.fd = os.open(self.portstr, os.O_RDWR | os.O_NOCTTY | os.O_NONBLOCK)
Chris Liechti68340d72015-08-03 14:15:48 +0200294 except OSError as msg:
cliechti4616bf12002-04-08 23:13:14 +0000295 self.fd = None
Chris Liechti984c5c52016-02-15 23:48:45 +0100296 raise SerialException(msg.errno, "could not open port {}: {}".format(self._port, msg))
Chris Liechti11465c82015-08-04 15:55:22 +0200297 #~ fcntl.fcntl(self.fd, fcntl.F_SETFL, 0) # set blocking
cliechti58b481c2009-02-16 20:42:32 +0000298
cliechtib2f5fc82006-10-20 00:09:07 +0000299 try:
Chris Liechti94284702015-11-15 01:21:48 +0100300 self._reconfigure_port(force_update=True)
cliechtib2f5fc82006-10-20 00:09:07 +0000301 except:
cliechti2750b832009-07-28 00:13:52 +0000302 try:
303 os.close(self.fd)
304 except:
305 # ignore any exception when closing the port
306 # also to keep original exception that happened when setting up
307 pass
cliechtib2f5fc82006-10-20 00:09:07 +0000308 self.fd = None
cliechtif0a4f0f2009-07-21 21:12:37 +0000309 raise
cliechtib2f5fc82006-10-20 00:09:07 +0000310 else:
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200311 self.is_open = True
312 if not self._dsrdtr:
Chris Liechtief1fe252015-08-27 23:25:21 +0200313 self._update_dtr_state()
Chris Liechtidc2beec2015-09-18 21:25:28 +0200314 if not self._rtscts:
Chris Liechtief1fe252015-08-27 23:25:21 +0200315 self._update_rts_state()
316 self.reset_input_buffer()
cliechti58b481c2009-02-16 20:42:32 +0000317
Chris Liechti94284702015-11-15 01:21:48 +0100318 def _reconfigure_port(self, force_update=False):
cliechtib2f5fc82006-10-20 00:09:07 +0000319 """Set communication parameters on opened port."""
cliechtic6178262004-03-22 22:04:52 +0000320 if self.fd is None:
cliechtia9a093e2010-01-02 03:05:08 +0000321 raise SerialException("Can only operate on a valid file descriptor")
cliechtie8c45422008-06-20 23:23:14 +0000322 custom_baud = None
cliechti58b481c2009-02-16 20:42:32 +0000323
cliechti2750b832009-07-28 00:13:52 +0000324 vmin = vtime = 0 # timeout is done via select
Chris Liechti518b0d32015-08-30 02:20:39 +0200325 if self._inter_byte_timeout is not None:
cliechti679bfa62008-06-20 23:58:15 +0000326 vmin = 1
Chris Liechti518b0d32015-08-30 02:20:39 +0200327 vtime = int(self._inter_byte_timeout * 10)
cliechti6ce7ab12002-11-07 02:15:00 +0000328 try:
cliechti4d0af5e2011-08-05 02:18:16 +0000329 orig_attr = termios.tcgetattr(self.fd)
330 iflag, oflag, cflag, lflag, ispeed, ospeed, cc = orig_attr
Chris Liechti68340d72015-08-03 14:15:48 +0200331 except termios.error as msg: # if a port is nonexistent but has a /dev file, it'll fail here
Chris Liechti984c5c52016-02-15 23:48:45 +0100332 raise SerialException("Could not configure port: {}".format(msg))
cliechti58b481c2009-02-16 20:42:32 +0000333 # set up raw mode / no echo / binary
Chris Liechti033f17c2015-08-30 21:28:04 +0200334 cflag |= (termios.CLOCAL | termios.CREAD)
335 lflag &= ~(termios.ICANON | termios.ECHO | termios.ECHOE |
336 termios.ECHOK | termios.ECHONL |
337 termios.ISIG | termios.IEXTEN) # |termios.ECHOPRT
338 for flag in ('ECHOCTL', 'ECHOKE'): # netbsd workaround for Erk
Chris Liechti11465c82015-08-04 15:55:22 +0200339 if hasattr(termios, flag):
340 lflag &= ~getattr(termios, flag)
cliechti58b481c2009-02-16 20:42:32 +0000341
Chris Liechti033f17c2015-08-30 21:28:04 +0200342 oflag &= ~(termios.OPOST | termios.ONLCR | termios.OCRNL)
343 iflag &= ~(termios.INLCR | termios.IGNCR | termios.ICRNL | termios.IGNBRK)
Chris Liechti11465c82015-08-04 15:55:22 +0200344 if hasattr(termios, 'IUCLC'):
345 iflag &= ~termios.IUCLC
346 if hasattr(termios, 'PARMRK'):
347 iflag &= ~termios.PARMRK
cliechti58b481c2009-02-16 20:42:32 +0000348
cliechtif0a4f0f2009-07-21 21:12:37 +0000349 # setup baud rate
cliechti89b4af12002-02-12 23:24:41 +0000350 try:
Chris Liechti984c5c52016-02-15 23:48:45 +0100351 ispeed = ospeed = getattr(termios, 'B{}'.format(self._baudrate))
cliechti895e8302004-04-20 02:40:28 +0000352 except AttributeError:
cliechtif1559d02007-11-08 23:43:58 +0000353 try:
Chris Liechtid6847af2015-08-06 17:54:30 +0200354 ispeed = ospeed = self.BAUDRATE_CONSTANTS[self._baudrate]
cliechtif1559d02007-11-08 23:43:58 +0000355 except KeyError:
cliechtie8c45422008-06-20 23:23:14 +0000356 #~ raise ValueError('Invalid baud rate: %r' % self._baudrate)
cliechtif0a4f0f2009-07-21 21:12:37 +0000357 # may need custom baud rate, it isn't in our list.
Chris Liechti11465c82015-08-04 15:55:22 +0200358 ispeed = ospeed = getattr(termios, 'B38400')
cliechtif0a4f0f2009-07-21 21:12:37 +0000359 try:
Chris Liechti033f17c2015-08-30 21:28:04 +0200360 custom_baud = int(self._baudrate) # store for later
cliechtif0a4f0f2009-07-21 21:12:37 +0000361 except ValueError:
Chris Liechti984c5c52016-02-15 23:48:45 +0100362 raise ValueError('Invalid baud rate: {!r}'.format(self._baudrate))
cliechtif0a4f0f2009-07-21 21:12:37 +0000363 else:
364 if custom_baud < 0:
Chris Liechti984c5c52016-02-15 23:48:45 +0100365 raise ValueError('Invalid baud rate: {!r}'.format(self._baudrate))
cliechti58b481c2009-02-16 20:42:32 +0000366
367 # setup char len
Chris Liechti11465c82015-08-04 15:55:22 +0200368 cflag &= ~termios.CSIZE
cliechtid6bf52c2003-10-01 02:28:12 +0000369 if self._bytesize == 8:
Chris Liechti11465c82015-08-04 15:55:22 +0200370 cflag |= termios.CS8
cliechtid6bf52c2003-10-01 02:28:12 +0000371 elif self._bytesize == 7:
Chris Liechti11465c82015-08-04 15:55:22 +0200372 cflag |= termios.CS7
cliechtid6bf52c2003-10-01 02:28:12 +0000373 elif self._bytesize == 6:
Chris Liechti11465c82015-08-04 15:55:22 +0200374 cflag |= termios.CS6
cliechtid6bf52c2003-10-01 02:28:12 +0000375 elif self._bytesize == 5:
Chris Liechti11465c82015-08-04 15:55:22 +0200376 cflag |= termios.CS5
cliechti89b4af12002-02-12 23:24:41 +0000377 else:
Chris Liechti984c5c52016-02-15 23:48:45 +0100378 raise ValueError('Invalid char len: {!r}'.format(self._bytesize))
cliechtif0a81d42014-08-04 14:03:53 +0000379 # setup stop bits
Chris Liechti033f17c2015-08-30 21:28:04 +0200380 if self._stopbits == serial.STOPBITS_ONE:
Chris Liechti11465c82015-08-04 15:55:22 +0200381 cflag &= ~(termios.CSTOPB)
Chris Liechti033f17c2015-08-30 21:28:04 +0200382 elif self._stopbits == serial.STOPBITS_ONE_POINT_FIVE:
383 cflag |= (termios.CSTOPB) # XXX same as TWO.. there is no POSIX support for 1.5
384 elif self._stopbits == serial.STOPBITS_TWO:
385 cflag |= (termios.CSTOPB)
cliechti89b4af12002-02-12 23:24:41 +0000386 else:
Chris Liechti984c5c52016-02-15 23:48:45 +0100387 raise ValueError('Invalid stop bit specification: {!r}'.format(self._stopbits))
cliechti58b481c2009-02-16 20:42:32 +0000388 # setup parity
Chris Liechti033f17c2015-08-30 21:28:04 +0200389 iflag &= ~(termios.INPCK | termios.ISTRIP)
390 if self._parity == serial.PARITY_NONE:
391 cflag &= ~(termios.PARENB | termios.PARODD)
392 elif self._parity == serial.PARITY_EVEN:
Chris Liechti11465c82015-08-04 15:55:22 +0200393 cflag &= ~(termios.PARODD)
Chris Liechti033f17c2015-08-30 21:28:04 +0200394 cflag |= (termios.PARENB)
395 elif self._parity == serial.PARITY_ODD:
396 cflag |= (termios.PARENB | termios.PARODD)
397 elif self._parity == serial.PARITY_MARK and plat[:5] == 'linux':
398 cflag |= (termios.PARENB | CMSPAR | termios.PARODD)
399 elif self._parity == serial.PARITY_SPACE and plat[:5] == 'linux':
400 cflag |= (termios.PARENB | CMSPAR)
Chris Liechti11465c82015-08-04 15:55:22 +0200401 cflag &= ~(termios.PARODD)
cliechti89b4af12002-02-12 23:24:41 +0000402 else:
Chris Liechti984c5c52016-02-15 23:48:45 +0100403 raise ValueError('Invalid parity: {!r}'.format(self._parity))
cliechti58b481c2009-02-16 20:42:32 +0000404 # setup flow control
405 # xonxoff
Chris Liechti11465c82015-08-04 15:55:22 +0200406 if hasattr(termios, 'IXANY'):
cliechtid6bf52c2003-10-01 02:28:12 +0000407 if self._xonxoff:
Chris Liechti033f17c2015-08-30 21:28:04 +0200408 iflag |= (termios.IXON | termios.IXOFF) # |termios.IXANY)
cliechti89b4af12002-02-12 23:24:41 +0000409 else:
Chris Liechti033f17c2015-08-30 21:28:04 +0200410 iflag &= ~(termios.IXON | termios.IXOFF | termios.IXANY)
cliechti89b4af12002-02-12 23:24:41 +0000411 else:
cliechtid6bf52c2003-10-01 02:28:12 +0000412 if self._xonxoff:
Chris Liechti033f17c2015-08-30 21:28:04 +0200413 iflag |= (termios.IXON | termios.IXOFF)
cliechti89b4af12002-02-12 23:24:41 +0000414 else:
Chris Liechti033f17c2015-08-30 21:28:04 +0200415 iflag &= ~(termios.IXON | termios.IXOFF)
cliechti58b481c2009-02-16 20:42:32 +0000416 # rtscts
Chris Liechti11465c82015-08-04 15:55:22 +0200417 if hasattr(termios, 'CRTSCTS'):
cliechtid6bf52c2003-10-01 02:28:12 +0000418 if self._rtscts:
Chris Liechti033f17c2015-08-30 21:28:04 +0200419 cflag |= (termios.CRTSCTS)
cliechti89b4af12002-02-12 23:24:41 +0000420 else:
Chris Liechti11465c82015-08-04 15:55:22 +0200421 cflag &= ~(termios.CRTSCTS)
422 elif hasattr(termios, 'CNEW_RTSCTS'): # try it with alternate constant name
cliechtid6bf52c2003-10-01 02:28:12 +0000423 if self._rtscts:
Chris Liechti033f17c2015-08-30 21:28:04 +0200424 cflag |= (termios.CNEW_RTSCTS)
cliechtid4743692002-04-08 22:39:53 +0000425 else:
Chris Liechti11465c82015-08-04 15:55:22 +0200426 cflag &= ~(termios.CNEW_RTSCTS)
cliechti2750b832009-07-28 00:13:52 +0000427 # XXX should there be a warning if setting up rtscts (and xonxoff etc) fails??
cliechti58b481c2009-02-16 20:42:32 +0000428
429 # buffer
cliechtif0a81d42014-08-04 14:03:53 +0000430 # vmin "minimal number of characters to be read. 0 for non blocking"
cliechtid6bf52c2003-10-01 02:28:12 +0000431 if vmin < 0 or vmin > 255:
Chris Liechti984c5c52016-02-15 23:48:45 +0100432 raise ValueError('Invalid vmin: {!r}'.format(vmin))
Chris Liechti11465c82015-08-04 15:55:22 +0200433 cc[termios.VMIN] = vmin
cliechti58b481c2009-02-16 20:42:32 +0000434 # vtime
cliechtid6bf52c2003-10-01 02:28:12 +0000435 if vtime < 0 or vtime > 255:
Chris Liechti984c5c52016-02-15 23:48:45 +0100436 raise ValueError('Invalid vtime: {!r}'.format(vtime))
Chris Liechti11465c82015-08-04 15:55:22 +0200437 cc[termios.VTIME] = vtime
cliechti58b481c2009-02-16 20:42:32 +0000438 # activate settings
Chris Liechti94284702015-11-15 01:21:48 +0100439 if force_update or [iflag, oflag, cflag, lflag, ispeed, ospeed, cc] != orig_attr:
Chris Liechti033f17c2015-08-30 21:28:04 +0200440 termios.tcsetattr(
Chris Liechti9eaa40c2016-02-12 23:32:59 +0100441 self.fd,
442 termios.TCSANOW,
443 [iflag, oflag, cflag, lflag, ispeed, ospeed, cc])
cliechti58b481c2009-02-16 20:42:32 +0000444
cliechtie8c45422008-06-20 23:23:14 +0000445 # apply custom baud rate, if any
446 if custom_baud is not None:
Chris Liechtid6847af2015-08-06 17:54:30 +0200447 self._set_special_baudrate(custom_baud)
448
449 if self._rs485_mode is not None:
450 self._set_rs485_mode(self._rs485_mode)
cliechti89b4af12002-02-12 23:24:41 +0000451
452 def close(self):
cliechtid6bf52c2003-10-01 02:28:12 +0000453 """Close port"""
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200454 if self.is_open:
cliechtic6178262004-03-22 22:04:52 +0000455 if self.fd is not None:
cliechtid6bf52c2003-10-01 02:28:12 +0000456 os.close(self.fd)
457 self.fd = None
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200458 self.is_open = False
cliechtid6bf52c2003-10-01 02:28:12 +0000459
460 # - - - - - - - - - - - - - - - - - - - - - - - -
cliechti95c62212002-03-04 22:17:53 +0000461
Chris Liechtief1fe252015-08-27 23:25:21 +0200462 @property
463 def in_waiting(self):
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200464 """Return the number of bytes currently in the input buffer."""
Chris Liechti11465c82015-08-04 15:55:22 +0200465 #~ s = fcntl.ioctl(self.fd, termios.FIONREAD, TIOCM_zero_str)
cliechtif5831e02002-12-05 23:15:27 +0000466 s = fcntl.ioctl(self.fd, TIOCINQ, TIOCM_zero_str)
Chris Liechti033f17c2015-08-30 21:28:04 +0200467 return struct.unpack('I', s)[0]
cliechti89b4af12002-02-12 23:24:41 +0000468
cliechtia9a093e2010-01-02 03:05:08 +0000469 # select based implementation, proved to work on many systems
470 def read(self, size=1):
cliechti7d448562014-08-03 21:57:45 +0000471 """\
472 Read size bytes from the serial port. If a timeout is set it may
473 return less characters as requested. With no timeout it will block
474 until the requested number of bytes is read.
475 """
Chris Liechti033f17c2015-08-30 21:28:04 +0200476 if not self.is_open:
477 raise portNotOpenError
cliechtia9a093e2010-01-02 03:05:08 +0000478 read = bytearray()
Cristiano De Altic30622f2015-12-12 11:00:01 +0100479 timeout = self._timeout
cliechtia9a093e2010-01-02 03:05:08 +0000480 while len(read) < size:
cliechti8d744de2013-10-11 14:31:13 +0000481 try:
Cristiano De Altic30622f2015-12-12 11:00:01 +0100482 start_time = time.time()
483 ready, _, _ = select.select([self.fd], [], [], timeout)
cliechti8d744de2013-10-11 14:31:13 +0000484 # If select was used with a timeout, and the timeout occurs, it
485 # returns with empty lists -> thus abort read operation.
Chris Liechti033f17c2015-08-30 21:28:04 +0200486 # For timeout == 0 (non-blocking operation) also abort when
487 # there is nothing to read.
cliechti8d744de2013-10-11 14:31:13 +0000488 if not ready:
489 break # timeout
Chris Liechti033f17c2015-08-30 21:28:04 +0200490 buf = os.read(self.fd, size - len(read))
cliechti8d744de2013-10-11 14:31:13 +0000491 # read should always return some data as select reported it was
492 # ready to read when we get to this point.
493 if not buf:
494 # Disconnected devices, at least on Linux, show the
495 # behavior that they are always ready to read immediately
496 # but reading returns nothing.
Chris Liechti92df95a2016-02-09 23:30:37 +0100497 raise SerialException(
498 'device reports readiness to read but returned no data '
499 '(device disconnected or multiple access on port?)')
cliechti8d744de2013-10-11 14:31:13 +0000500 read.extend(buf)
Cristiano De Altic30622f2015-12-12 11:00:01 +0100501 if timeout is not None:
502 timeout -= time.time() - start_time
503 if timeout <= 0:
504 break
Chris Liechti68340d72015-08-03 14:15:48 +0200505 except OSError as e:
Chris Liechti033f17c2015-08-30 21:28:04 +0200506 # this is for Python 3.x where select.error is a subclass of
507 # OSError ignore EAGAIN errors. all other errors are shown
cliechtic7cd7212014-08-03 21:34:38 +0000508 if e.errno != errno.EAGAIN:
Chris Liechti984c5c52016-02-15 23:48:45 +0100509 raise SerialException('read failed: {}'.format(e))
Chris Liechti68340d72015-08-03 14:15:48 +0200510 except select.error as e:
cliechtic7cd7212014-08-03 21:34:38 +0000511 # this is for Python 2.x
cliechti8d744de2013-10-11 14:31:13 +0000512 # ignore EAGAIN errors. all other errors are shown
513 # see also http://www.python.org/dev/peps/pep-3151/#select
514 if e[0] != errno.EAGAIN:
Chris Liechti984c5c52016-02-15 23:48:45 +0100515 raise SerialException('read failed: {}'.format(e))
cliechtia9a093e2010-01-02 03:05:08 +0000516 return bytes(read)
cliechti89b4af12002-02-12 23:24:41 +0000517
cliechti4a567a02009-07-27 22:09:31 +0000518 def write(self, data):
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200519 """Output the given byte string over the serial port."""
Chris Liechti033f17c2015-08-30 21:28:04 +0200520 if not self.is_open:
521 raise portNotOpenError
cliechti38077122013-10-16 02:57:27 +0000522 d = to_bytes(data)
523 tx_len = len(d)
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200524 if self._write_timeout is not None and self._write_timeout > 0:
525 timeout = time.time() + self._write_timeout
cliechti3cf46d62009-08-07 00:19:57 +0000526 else:
527 timeout = None
cliechti9f7c2352013-10-11 01:13:46 +0000528 while tx_len > 0:
cliechti5d4d0bd2004-11-13 03:27:39 +0000529 try:
cliechti5d4d0bd2004-11-13 03:27:39 +0000530 n = os.write(self.fd, d)
cliechti3cf46d62009-08-07 00:19:57 +0000531 if timeout:
532 # when timeout is set, use select to wait for being ready
533 # with the time left as timeout
534 timeleft = timeout - time.time()
535 if timeleft < 0:
536 raise writeTimeoutError
537 _, ready, _ = select.select([], [self.fd], [], timeleft)
cliechti5d4d0bd2004-11-13 03:27:39 +0000538 if not ready:
539 raise writeTimeoutError
cliechti88c62442013-10-12 04:03:16 +0000540 else:
541 # wait for write operation
542 _, ready, _ = select.select([], [self.fd], [], None)
543 if not ready:
544 raise SerialException('write failed (select)')
cliechti5d4d0bd2004-11-13 03:27:39 +0000545 d = d[n:]
cliechti9f7c2352013-10-11 01:13:46 +0000546 tx_len -= n
Chris Liechti675f7e12015-08-03 15:48:41 +0200547 except SerialException:
548 raise
Chris Liechti68340d72015-08-03 14:15:48 +0200549 except OSError as v:
cliechti5d4d0bd2004-11-13 03:27:39 +0000550 if v.errno != errno.EAGAIN:
Chris Liechti984c5c52016-02-15 23:48:45 +0100551 raise SerialException('write failed: {}'.format(v))
Chris Liechtic6362db2015-12-13 23:44:35 +0100552 # still calculate and check timeout
553 if timeout and timeout - time.time() < 0:
554 raise writeTimeoutError
cliechtif81362e2009-07-25 03:44:33 +0000555 return len(data)
cliechtid6bf52c2003-10-01 02:28:12 +0000556
cliechtia30a8a02003-10-05 12:28:13 +0000557 def flush(self):
cliechti7d448562014-08-03 21:57:45 +0000558 """\
559 Flush of file like objects. In this case, wait until all data
560 is written.
561 """
Chris Liechti033f17c2015-08-30 21:28:04 +0200562 if not self.is_open:
563 raise portNotOpenError
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200564 termios.tcdrain(self.fd)
cliechtia30a8a02003-10-05 12:28:13 +0000565
Chris Liechtief1fe252015-08-27 23:25:21 +0200566 def reset_input_buffer(self):
cliechtid6bf52c2003-10-01 02:28:12 +0000567 """Clear input buffer, discarding all that is in the buffer."""
Chris Liechti033f17c2015-08-30 21:28:04 +0200568 if not self.is_open:
569 raise portNotOpenError
Chris Liechti11465c82015-08-04 15:55:22 +0200570 termios.tcflush(self.fd, termios.TCIFLUSH)
cliechti89b4af12002-02-12 23:24:41 +0000571
Chris Liechtief1fe252015-08-27 23:25:21 +0200572 def reset_output_buffer(self):
cliechti7d448562014-08-03 21:57:45 +0000573 """\
574 Clear output buffer, aborting the current output and discarding all
575 that is in the buffer.
576 """
Chris Liechti033f17c2015-08-30 21:28:04 +0200577 if not self.is_open:
578 raise portNotOpenError
Chris Liechti11465c82015-08-04 15:55:22 +0200579 termios.tcflush(self.fd, termios.TCOFLUSH)
cliechti89b4af12002-02-12 23:24:41 +0000580
Chris Liechtief1fe252015-08-27 23:25:21 +0200581 def send_break(self, duration=0.25):
cliechti7d448562014-08-03 21:57:45 +0000582 """\
583 Send break condition. Timed, returns to idle state after given
584 duration.
585 """
Chris Liechti033f17c2015-08-30 21:28:04 +0200586 if not self.is_open:
587 raise portNotOpenError
588 termios.tcsendbreak(self.fd, int(duration / 0.25))
cliechti89b4af12002-02-12 23:24:41 +0000589
Chris Liechtief1fe252015-08-27 23:25:21 +0200590 def _update_break_state(self):
cliechti7d448562014-08-03 21:57:45 +0000591 """\
592 Set break: Controls TXD. When active, no transmitting is possible.
593 """
Chris Liechtief1fe252015-08-27 23:25:21 +0200594 if self._break_state:
cliechti997b63c2008-06-21 00:09:31 +0000595 fcntl.ioctl(self.fd, TIOCSBRK)
596 else:
597 fcntl.ioctl(self.fd, TIOCCBRK)
598
Chris Liechtief1fe252015-08-27 23:25:21 +0200599 def _update_rts_state(self):
cliechtid6bf52c2003-10-01 02:28:12 +0000600 """Set terminal status line: Request To Send"""
Chris Liechti4cf65392016-01-21 23:57:02 +0100601 if self._rts_state is not None:
602 if self._rts_state:
603 fcntl.ioctl(self.fd, TIOCMBIS, TIOCM_RTS_str)
604 else:
605 fcntl.ioctl(self.fd, TIOCMBIC, TIOCM_RTS_str)
cliechtid6bf52c2003-10-01 02:28:12 +0000606
Chris Liechtief1fe252015-08-27 23:25:21 +0200607 def _update_dtr_state(self):
cliechtid6bf52c2003-10-01 02:28:12 +0000608 """Set terminal status line: Data Terminal Ready"""
Chris Liechti4cf65392016-01-21 23:57:02 +0100609 if self._dtr_state is not None:
610 if self._dtr_state:
611 fcntl.ioctl(self.fd, TIOCMBIS, TIOCM_DTR_str)
612 else:
613 fcntl.ioctl(self.fd, TIOCMBIC, TIOCM_DTR_str)
cliechtid6bf52c2003-10-01 02:28:12 +0000614
Chris Liechtief1fe252015-08-27 23:25:21 +0200615 @property
616 def cts(self):
cliechtid6bf52c2003-10-01 02:28:12 +0000617 """Read terminal status line: Clear To Send"""
Chris Liechti033f17c2015-08-30 21:28:04 +0200618 if not self.is_open:
619 raise portNotOpenError
cliechtid6bf52c2003-10-01 02:28:12 +0000620 s = fcntl.ioctl(self.fd, TIOCMGET, TIOCM_zero_str)
Chris Liechti033f17c2015-08-30 21:28:04 +0200621 return struct.unpack('I', s)[0] & TIOCM_CTS != 0
cliechtid6bf52c2003-10-01 02:28:12 +0000622
Chris Liechtief1fe252015-08-27 23:25:21 +0200623 @property
624 def dsr(self):
cliechtid6bf52c2003-10-01 02:28:12 +0000625 """Read terminal status line: Data Set Ready"""
Chris Liechti033f17c2015-08-30 21:28:04 +0200626 if not self.is_open:
627 raise portNotOpenError
cliechtid6bf52c2003-10-01 02:28:12 +0000628 s = fcntl.ioctl(self.fd, TIOCMGET, TIOCM_zero_str)
Chris Liechti033f17c2015-08-30 21:28:04 +0200629 return struct.unpack('I', s)[0] & TIOCM_DSR != 0
cliechtid6bf52c2003-10-01 02:28:12 +0000630
Chris Liechtief1fe252015-08-27 23:25:21 +0200631 @property
632 def ri(self):
cliechtid6bf52c2003-10-01 02:28:12 +0000633 """Read terminal status line: Ring Indicator"""
Chris Liechti033f17c2015-08-30 21:28:04 +0200634 if not self.is_open:
635 raise portNotOpenError
cliechti89b4af12002-02-12 23:24:41 +0000636 s = fcntl.ioctl(self.fd, TIOCMGET, TIOCM_zero_str)
Chris Liechti033f17c2015-08-30 21:28:04 +0200637 return struct.unpack('I', s)[0] & TIOCM_RI != 0
cliechti89b4af12002-02-12 23:24:41 +0000638
Chris Liechtief1fe252015-08-27 23:25:21 +0200639 @property
640 def cd(self):
cliechtid6bf52c2003-10-01 02:28:12 +0000641 """Read terminal status line: Carrier Detect"""
Chris Liechti033f17c2015-08-30 21:28:04 +0200642 if not self.is_open:
643 raise portNotOpenError
cliechti89b4af12002-02-12 23:24:41 +0000644 s = fcntl.ioctl(self.fd, TIOCMGET, TIOCM_zero_str)
Chris Liechti033f17c2015-08-30 21:28:04 +0200645 return struct.unpack('I', s)[0] & TIOCM_CD != 0
cliechti89b4af12002-02-12 23:24:41 +0000646
cliechtia30a8a02003-10-05 12:28:13 +0000647 # - - platform specific - - - -
648
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200649 @property
650 def out_waiting(self):
651 """Return the number of bytes currently in the output buffer."""
Chris Liechti11465c82015-08-04 15:55:22 +0200652 #~ s = fcntl.ioctl(self.fd, termios.FIONREAD, TIOCM_zero_str)
cliechti28b8fd02011-12-28 21:39:42 +0000653 s = fcntl.ioctl(self.fd, TIOCOUTQ, TIOCM_zero_str)
Chris Liechti033f17c2015-08-30 21:28:04 +0200654 return struct.unpack('I', s)[0]
cliechti28b8fd02011-12-28 21:39:42 +0000655
cliechtia30a8a02003-10-05 12:28:13 +0000656 def nonblocking(self):
657 """internal - not portable!"""
Chris Liechti033f17c2015-08-30 21:28:04 +0200658 if not self.is_open:
659 raise portNotOpenError
Chris Liechti11465c82015-08-04 15:55:22 +0200660 fcntl.fcntl(self.fd, fcntl.F_SETFL, os.O_NONBLOCK)
cliechtia30a8a02003-10-05 12:28:13 +0000661
cliechti8753bbc2005-01-15 20:32:51 +0000662 def fileno(self):
cliechti2f0f8a32011-12-28 22:10:00 +0000663 """\
664 For easier use of the serial port instance with select.
665 WARNING: this function is not portable to different platforms!
666 """
Chris Liechti033f17c2015-08-30 21:28:04 +0200667 if not self.is_open:
668 raise portNotOpenError
cliechti8753bbc2005-01-15 20:32:51 +0000669 return self.fd
cliechti89b4af12002-02-12 23:24:41 +0000670
Chris Liechti518b0d32015-08-30 02:20:39 +0200671 def set_input_flow_control(self, enable=True):
cliechti2f0f8a32011-12-28 22:10:00 +0000672 """\
673 Manually control flow - when software flow control is enabled.
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200674 This will send XON (true) or XOFF (false) to the other device.
cliechti2f0f8a32011-12-28 22:10:00 +0000675 WARNING: this function is not portable to different platforms!
676 """
Chris Liechti033f17c2015-08-30 21:28:04 +0200677 if not self.is_open:
678 raise portNotOpenError
cliechti4a601342011-12-29 02:22:17 +0000679 if enable:
Chris Liechti11465c82015-08-04 15:55:22 +0200680 termios.tcflow(self.fd, termios.TCION)
cliechti57e48a62009-08-03 22:29:58 +0000681 else:
Chris Liechti11465c82015-08-04 15:55:22 +0200682 termios.tcflow(self.fd, termios.TCIOFF)
cliechti57e48a62009-08-03 22:29:58 +0000683
Chris Liechti518b0d32015-08-30 02:20:39 +0200684 def set_output_flow_control(self, enable=True):
cliechti2f0f8a32011-12-28 22:10:00 +0000685 """\
686 Manually control flow of outgoing data - when hardware or software flow
687 control is enabled.
688 WARNING: this function is not portable to different platforms!
689 """
Chris Liechti033f17c2015-08-30 21:28:04 +0200690 if not self.is_open:
691 raise portNotOpenError
cliechti2f0f8a32011-12-28 22:10:00 +0000692 if enable:
Chris Liechti11465c82015-08-04 15:55:22 +0200693 termios.tcflow(self.fd, termios.TCOON)
cliechti2f0f8a32011-12-28 22:10:00 +0000694 else:
Chris Liechti11465c82015-08-04 15:55:22 +0200695 termios.tcflow(self.fd, termios.TCOOFF)
cliechti2f0f8a32011-12-28 22:10:00 +0000696
cliechtif81362e2009-07-25 03:44:33 +0000697
cliechtia9a093e2010-01-02 03:05:08 +0000698class PosixPollSerial(Serial):
cliechti7d448562014-08-03 21:57:45 +0000699 """\
cliechtif0a81d42014-08-04 14:03:53 +0000700 Poll based read implementation. Not all systems support poll properly.
701 However this one has better handling of errors, such as a device
cliechti7d448562014-08-03 21:57:45 +0000702 disconnecting while it's in use (e.g. USB-serial unplugged).
703 """
cliechtia9a093e2010-01-02 03:05:08 +0000704
705 def read(self, size=1):
cliechti7d448562014-08-03 21:57:45 +0000706 """\
707 Read size bytes from the serial port. If a timeout is set it may
708 return less characters as requested. With no timeout it will block
709 until the requested number of bytes is read.
710 """
Chris Liechti033f17c2015-08-30 21:28:04 +0200711 if self.fd is None:
712 raise portNotOpenError
cliechtia9a093e2010-01-02 03:05:08 +0000713 read = bytearray()
714 poll = select.poll()
Chris Liechti033f17c2015-08-30 21:28:04 +0200715 poll.register(self.fd, select.POLLIN | select.POLLERR | select.POLLHUP | select.POLLNVAL)
cliechtia9a093e2010-01-02 03:05:08 +0000716 if size > 0:
717 while len(read) < size:
718 # print "\tread(): size",size, "have", len(read) #debug
719 # wait until device becomes ready to read (or something fails)
Chris Liechti033f17c2015-08-30 21:28:04 +0200720 for fd, event in poll.poll(self._timeout * 1000):
721 if event & (select.POLLERR | select.POLLHUP | select.POLLNVAL):
cliechtia9a093e2010-01-02 03:05:08 +0000722 raise SerialException('device reports error (poll)')
723 # we don't care if it is select.POLLIN or timeout, that's
724 # handled below
725 buf = os.read(self.fd, size - len(read))
726 read.extend(buf)
Chris Liechti518b0d32015-08-30 02:20:39 +0200727 if ((self._timeout is not None and self._timeout >= 0) or
Chris Liechti033f17c2015-08-30 21:28:04 +0200728 (self._inter_byte_timeout is not None and self._inter_byte_timeout > 0)) and not buf:
cliechtia9a093e2010-01-02 03:05:08 +0000729 break # early abort on timeout
730 return bytes(read)
731
cliechtif81362e2009-07-25 03:44:33 +0000732
Chris Liechti4cf54702015-10-18 00:21:56 +0200733class VTIMESerial(Serial):
734 """\
735 Implement timeout using vtime of tty device instead of using select.
736 This means that no inter character timeout can be specified and that
737 the error handling is degraded.
738
739 Overall timeout is disabled when inter-character timeout is used.
740 """
741
Chris Liechti94284702015-11-15 01:21:48 +0100742 def _reconfigure_port(self, force_update=True):
Chris Liechti4cf54702015-10-18 00:21:56 +0200743 """Set communication parameters on opened port."""
744 super(VTIMESerial, self)._reconfigure_port()
Chris Liechtid6bcaaf2016-02-01 22:55:26 +0100745 fcntl.fcntl(self.fd, fcntl.F_SETFL, 0) # clear O_NONBLOCK
Chris Liechti4cf54702015-10-18 00:21:56 +0200746
747 if self._inter_byte_timeout is not None:
748 vmin = 1
749 vtime = int(self._inter_byte_timeout * 10)
750 else:
751 vmin = 0
752 vtime = int(self._timeout * 10)
753 try:
754 orig_attr = termios.tcgetattr(self.fd)
755 iflag, oflag, cflag, lflag, ispeed, ospeed, cc = orig_attr
756 except termios.error as msg: # if a port is nonexistent but has a /dev file, it'll fail here
Chris Liechti984c5c52016-02-15 23:48:45 +0100757 raise serial.SerialException("Could not configure port: {}".format(msg))
Chris Liechti4cf54702015-10-18 00:21:56 +0200758
759 if vtime < 0 or vtime > 255:
Chris Liechti984c5c52016-02-15 23:48:45 +0100760 raise ValueError('Invalid vtime: {!r}'.format(vtime))
Chris Liechti4cf54702015-10-18 00:21:56 +0200761 cc[termios.VTIME] = vtime
762 cc[termios.VMIN] = vmin
763
764 termios.tcsetattr(
765 self.fd,
766 termios.TCSANOW,
767 [iflag, oflag, cflag, lflag, ispeed, ospeed, cc])
768
Chris Liechti4cf54702015-10-18 00:21:56 +0200769 def read(self, size=1):
770 """\
771 Read size bytes from the serial port. If a timeout is set it may
772 return less characters as requested. With no timeout it will block
773 until the requested number of bytes is read.
774 """
775 if not self.is_open:
776 raise portNotOpenError
777 read = bytearray()
778 while len(read) < size:
779 buf = os.read(self.fd, size - len(read))
780 if not buf:
781 break
782 read.extend(buf)
783 return bytes(read)