blob: 72ea9b020d19924609574f817df5a1f1e919403b [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 Liechtie13d0f62016-04-25 23:30:44 +02006# (C) 2001-2016 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 Liechtie13d0f62016-04-25 23:30:44 +020015# Collection of port names (was previously used by number_to_device which was
16# removed.
17# - Linux /dev/ttyS%d (confirmed)
18# - cygwin/win32 /dev/com%d (confirmed)
19# - openbsd (OpenBSD) /dev/cua%02d
20# - bsd*, freebsd* /dev/cuad%d
21# - darwin (OS X) /dev/cuad%d
22# - netbsd /dev/dty%02d (NetBSD 1.6 testing by Erk)
23# - irix (IRIX) /dev/ttyf%d (partially tested) names depending on flow control
24# - hp (HP-UX) /dev/tty%dp0 (not tested)
25# - sunos (Solaris/SunOS) /dev/tty%c (letters, 'a'..'z') (confirmed)
26# - aix (AIX) /dev/tty%d
27
28
Chris Liechti9eaa40c2016-02-12 23:32:59 +010029# pylint: disable=abstract-method
Chris Liechti33f0ec52015-08-06 16:37:21 +020030import errno
31import fcntl
Chris Liechti33f0ec52015-08-06 16:37:21 +020032import os
33import select
34import struct
35import sys
36import termios
37import time
Chris Liechti033f17c2015-08-30 21:28:04 +020038
39import serial
40from serial.serialutil import SerialBase, SerialException, to_bytes, portNotOpenError, writeTimeoutError
cliechti89b4af12002-02-12 23:24:41 +000041
cliechti89b4af12002-02-12 23:24:41 +000042
Chris Liechtid6847af2015-08-06 17:54:30 +020043class PlatformSpecificBase(object):
44 BAUDRATE_CONSTANTS = {}
cliechti89b4af12002-02-12 23:24:41 +000045
Chris Liechtid6847af2015-08-06 17:54:30 +020046 def _set_special_baudrate(self, baudrate):
47 raise NotImplementedError('non-standard baudrates are not supported on this platform')
48
49 def _set_rs485_mode(self, rs485_settings):
50 raise NotImplementedError('RS485 not supported on this platform')
51
52# try to detect the OS so that a device can be selected...
53# this code block should supply a device() and set_special_baudrate() function
54# for the platform
55plat = sys.platform.lower()
56
Chris Liechtiba45c522016-02-06 23:53:23 +010057if plat[:5] == 'linux': # Linux (confirmed) # noqa
Chris Liechtid6847af2015-08-06 17:54:30 +020058 import array
59
60 # baudrate ioctls
61 TCGETS2 = 0x802C542A
62 TCSETS2 = 0x402C542B
63 BOTHER = 0o010000
64
65 # RS485 ioctls
66 TIOCGRS485 = 0x542E
67 TIOCSRS485 = 0x542F
Chris Liechti033f17c2015-08-30 21:28:04 +020068 SER_RS485_ENABLED = 0b00000001
69 SER_RS485_RTS_ON_SEND = 0b00000010
Chris Liechtid6847af2015-08-06 17:54:30 +020070 SER_RS485_RTS_AFTER_SEND = 0b00000100
Chris Liechti033f17c2015-08-30 21:28:04 +020071 SER_RS485_RX_DURING_TX = 0b00010000
Chris Liechtid6847af2015-08-06 17:54:30 +020072
73 class PlatformSpecific(PlatformSpecificBase):
74 BAUDRATE_CONSTANTS = {
75 0: 0o000000, # hang up
76 50: 0o000001,
77 75: 0o000002,
78 110: 0o000003,
79 134: 0o000004,
80 150: 0o000005,
81 200: 0o000006,
82 300: 0o000007,
83 600: 0o000010,
84 1200: 0o000011,
85 1800: 0o000012,
86 2400: 0o000013,
87 4800: 0o000014,
88 9600: 0o000015,
89 19200: 0o000016,
90 38400: 0o000017,
91 57600: 0o010001,
92 115200: 0o010002,
93 230400: 0o010003,
94 460800: 0o010004,
95 500000: 0o010005,
96 576000: 0o010006,
97 921600: 0o010007,
98 1000000: 0o010010,
99 1152000: 0o010011,
100 1500000: 0o010012,
101 2000000: 0o010013,
102 2500000: 0o010014,
103 3000000: 0o010015,
104 3500000: 0o010016,
105 4000000: 0o010017
106 }
107
Chris Liechtid6847af2015-08-06 17:54:30 +0200108 def _set_special_baudrate(self, baudrate):
109 # right size is 44 on x86_64, allow for some growth
110 buf = array.array('i', [0] * 64)
111 try:
112 # get serial_struct
113 fcntl.ioctl(self.fd, TCGETS2, buf)
114 # set custom speed
115 buf[2] &= ~termios.CBAUD
116 buf[2] |= BOTHER
117 buf[9] = buf[10] = baudrate
118
119 # set serial_struct
Chris Liechti033f17c2015-08-30 21:28:04 +0200120 fcntl.ioctl(self.fd, TCSETS2, buf)
Chris Liechtid6847af2015-08-06 17:54:30 +0200121 except IOError as e:
Chris Liechti984c5c52016-02-15 23:48:45 +0100122 raise ValueError('Failed to set custom baud rate ({}): {}'.format(baudrate, e))
Chris Liechtid6847af2015-08-06 17:54:30 +0200123
124 def _set_rs485_mode(self, rs485_settings):
Chris Liechti033f17c2015-08-30 21:28:04 +0200125 buf = array.array('i', [0] * 8) # flags, delaytx, delayrx, padding
Chris Liechtid6847af2015-08-06 17:54:30 +0200126 try:
127 fcntl.ioctl(self.fd, TIOCGRS485, buf)
Chris Liechti7a554462016-03-24 21:17:22 +0100128 buf[0] |= SER_RS485_ENABLED
Chris Liechtid6847af2015-08-06 17:54:30 +0200129 if rs485_settings is not None:
130 if rs485_settings.loopback:
131 buf[0] |= SER_RS485_RX_DURING_TX
132 else:
133 buf[0] &= ~SER_RS485_RX_DURING_TX
134 if rs485_settings.rts_level_for_tx:
135 buf[0] |= SER_RS485_RTS_ON_SEND
136 else:
137 buf[0] &= ~SER_RS485_RTS_ON_SEND
138 if rs485_settings.rts_level_for_rx:
139 buf[0] |= SER_RS485_RTS_AFTER_SEND
140 else:
141 buf[0] &= ~SER_RS485_RTS_AFTER_SEND
Chris Liechti01df8892016-03-17 23:01:42 +0100142 buf[1] = int(rs485_settings.delay_before_tx * 1000)
143 buf[2] = int(rs485_settings.delay_before_rx * 1000)
Chris Liechtid6847af2015-08-06 17:54:30 +0200144 else:
145 buf[0] = 0 # clear SER_RS485_ENABLED
Chris Liechti033f17c2015-08-30 21:28:04 +0200146 fcntl.ioctl(self.fd, TIOCSRS485, buf)
Chris Liechtid6847af2015-08-06 17:54:30 +0200147 except IOError as e:
Chris Liechti984c5c52016-02-15 23:48:45 +0100148 raise ValueError('Failed to set RS485 mode: {}'.format(e))
Chris Liechtid6847af2015-08-06 17:54:30 +0200149
150
151elif plat == 'cygwin': # cygwin/win32 (confirmed)
152
153 class PlatformSpecific(PlatformSpecificBase):
154 BAUDRATE_CONSTANTS = {
155 128000: 0x01003,
156 256000: 0x01005,
157 500000: 0x01007,
158 576000: 0x01008,
159 921600: 0x01009,
160 1000000: 0x0100a,
161 1152000: 0x0100b,
162 1500000: 0x0100c,
163 2000000: 0x0100d,
164 2500000: 0x0100e,
165 3000000: 0x0100f
166 }
167
Chris Liechtid6847af2015-08-06 17:54:30 +0200168
169elif plat[:6] == 'darwin': # OS X
170 import array
Chris Liechti033f17c2015-08-30 21:28:04 +0200171 IOSSIOSPEED = 0x80045402 # _IOW('T', 2, speed_t)
Chris Liechtid6847af2015-08-06 17:54:30 +0200172
173 class PlatformSpecific(PlatformSpecificBase):
Chris Liechtid6847af2015-08-06 17:54:30 +0200174 osx_version = os.uname()[2].split('.')
175 # Tiger or above can support arbitrary serial speeds
176 if int(osx_version[0]) >= 8:
177 def _set_special_baudrate(self, baudrate):
178 # use IOKit-specific call to set up high speeds
179 buf = array.array('i', [baudrate])
180 fcntl.ioctl(self.fd, IOSSIOSPEED, buf, 1)
181
Chris Liechtid6847af2015-08-06 17:54:30 +0200182else:
183 class PlatformSpecific(PlatformSpecificBase):
184 pass
cliechti89b4af12002-02-12 23:24:41 +0000185
cliechti89b4af12002-02-12 23:24:41 +0000186
cliechti58b481c2009-02-16 20:42:32 +0000187# load some constants for later use.
Chris Liechti11465c82015-08-04 15:55:22 +0200188# try to use values from termios, use defaults from linux otherwise
Chris Liechti033f17c2015-08-30 21:28:04 +0200189TIOCMGET = getattr(termios, 'TIOCMGET', 0x5415)
190TIOCMBIS = getattr(termios, 'TIOCMBIS', 0x5416)
191TIOCMBIC = getattr(termios, 'TIOCMBIC', 0x5417)
192TIOCMSET = getattr(termios, 'TIOCMSET', 0x5418)
cliechti89b4af12002-02-12 23:24:41 +0000193
Chris Liechti033f17c2015-08-30 21:28:04 +0200194# TIOCM_LE = getattr(termios, 'TIOCM_LE', 0x001)
Chris Liechtid6847af2015-08-06 17:54:30 +0200195TIOCM_DTR = getattr(termios, 'TIOCM_DTR', 0x002)
196TIOCM_RTS = getattr(termios, 'TIOCM_RTS', 0x004)
Chris Liechti033f17c2015-08-30 21:28:04 +0200197# TIOCM_ST = getattr(termios, 'TIOCM_ST', 0x008)
198# TIOCM_SR = getattr(termios, 'TIOCM_SR', 0x010)
cliechti89b4af12002-02-12 23:24:41 +0000199
Chris Liechtid6847af2015-08-06 17:54:30 +0200200TIOCM_CTS = getattr(termios, 'TIOCM_CTS', 0x020)
201TIOCM_CAR = getattr(termios, 'TIOCM_CAR', 0x040)
202TIOCM_RNG = getattr(termios, 'TIOCM_RNG', 0x080)
203TIOCM_DSR = getattr(termios, 'TIOCM_DSR', 0x100)
Chris Liechti033f17c2015-08-30 21:28:04 +0200204TIOCM_CD = getattr(termios, 'TIOCM_CD', TIOCM_CAR)
205TIOCM_RI = getattr(termios, 'TIOCM_RI', TIOCM_RNG)
206# TIOCM_OUT1 = getattr(termios, 'TIOCM_OUT1', 0x2000)
207# TIOCM_OUT2 = getattr(termios, 'TIOCM_OUT2', 0x4000)
Chris Liechti11465c82015-08-04 15:55:22 +0200208if hasattr(termios, 'TIOCINQ'):
209 TIOCINQ = termios.TIOCINQ
cliechti28b8fd02011-12-28 21:39:42 +0000210else:
Chris Liechtid6847af2015-08-06 17:54:30 +0200211 TIOCINQ = getattr(termios, 'FIONREAD', 0x541B)
Chris Liechti033f17c2015-08-30 21:28:04 +0200212TIOCOUTQ = getattr(termios, 'TIOCOUTQ', 0x5411)
cliechti89b4af12002-02-12 23:24:41 +0000213
214TIOCM_zero_str = struct.pack('I', 0)
215TIOCM_RTS_str = struct.pack('I', TIOCM_RTS)
216TIOCM_DTR_str = struct.pack('I', TIOCM_DTR)
217
Chris Liechti033f17c2015-08-30 21:28:04 +0200218TIOCSBRK = getattr(termios, 'TIOCSBRK', 0x5427)
219TIOCCBRK = getattr(termios, 'TIOCCBRK', 0x5428)
cliechti997b63c2008-06-21 00:09:31 +0000220
Chris Liechti033f17c2015-08-30 21:28:04 +0200221CMSPAR = 0o10000000000 # Use "stick" (mark/space) parity
cliechtiaec27ab2014-07-31 22:21:24 +0000222
cliechti89b4af12002-02-12 23:24:41 +0000223
Chris Liechtief6b7b42015-08-06 22:19:26 +0200224class Serial(SerialBase, PlatformSpecific):
cliechti7d448562014-08-03 21:57:45 +0000225 """\
Chris Liechti033f17c2015-08-30 21:28:04 +0200226 Serial port class POSIX implementation. Serial port configuration is
cliechtid6bf52c2003-10-01 02:28:12 +0000227 done with termios and fcntl. Runs on Linux and many other Un*x like
cliechtif0a81d42014-08-04 14:03:53 +0000228 systems.
229 """
cliechtid6bf52c2003-10-01 02:28:12 +0000230
231 def open(self):
cliechti7d448562014-08-03 21:57:45 +0000232 """\
233 Open port with current settings. This may throw a SerialException
234 if the port cannot be opened."""
cliechtid6bf52c2003-10-01 02:28:12 +0000235 if self._port is None:
236 raise SerialException("Port must be configured before it can be used.")
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200237 if self.is_open:
cliechti02ef43a2011-03-24 23:33:12 +0000238 raise SerialException("Port is already open.")
239 self.fd = None
cliechti58b481c2009-02-16 20:42:32 +0000240 # open
cliechti4616bf12002-04-08 23:13:14 +0000241 try:
Chris Liechti033f17c2015-08-30 21:28:04 +0200242 self.fd = os.open(self.portstr, os.O_RDWR | os.O_NOCTTY | os.O_NONBLOCK)
Chris Liechti68340d72015-08-03 14:15:48 +0200243 except OSError as msg:
cliechti4616bf12002-04-08 23:13:14 +0000244 self.fd = None
Chris Liechti984c5c52016-02-15 23:48:45 +0100245 raise SerialException(msg.errno, "could not open port {}: {}".format(self._port, msg))
Chris Liechti11465c82015-08-04 15:55:22 +0200246 #~ fcntl.fcntl(self.fd, fcntl.F_SETFL, 0) # set blocking
cliechti58b481c2009-02-16 20:42:32 +0000247
cliechtib2f5fc82006-10-20 00:09:07 +0000248 try:
Chris Liechti94284702015-11-15 01:21:48 +0100249 self._reconfigure_port(force_update=True)
cliechtib2f5fc82006-10-20 00:09:07 +0000250 except:
cliechti2750b832009-07-28 00:13:52 +0000251 try:
252 os.close(self.fd)
253 except:
254 # ignore any exception when closing the port
255 # also to keep original exception that happened when setting up
256 pass
cliechtib2f5fc82006-10-20 00:09:07 +0000257 self.fd = None
cliechtif0a4f0f2009-07-21 21:12:37 +0000258 raise
cliechtib2f5fc82006-10-20 00:09:07 +0000259 else:
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200260 self.is_open = True
Chris Liechtif2fdeb92016-05-07 23:57:50 +0200261 try:
262 if not self._dsrdtr:
263 self._update_dtr_state()
264 if not self._rtscts:
265 self._update_rts_state()
266 except IOError as e:
267 if e.errno == 22: # ignore Invalid argument
268 pass
269 else:
270 raise
Chris Liechtief1fe252015-08-27 23:25:21 +0200271 self.reset_input_buffer()
cliechti58b481c2009-02-16 20:42:32 +0000272
Chris Liechti94284702015-11-15 01:21:48 +0100273 def _reconfigure_port(self, force_update=False):
cliechtib2f5fc82006-10-20 00:09:07 +0000274 """Set communication parameters on opened port."""
cliechtic6178262004-03-22 22:04:52 +0000275 if self.fd is None:
cliechtia9a093e2010-01-02 03:05:08 +0000276 raise SerialException("Can only operate on a valid file descriptor")
cliechtie8c45422008-06-20 23:23:14 +0000277 custom_baud = None
cliechti58b481c2009-02-16 20:42:32 +0000278
cliechti2750b832009-07-28 00:13:52 +0000279 vmin = vtime = 0 # timeout is done via select
Chris Liechti518b0d32015-08-30 02:20:39 +0200280 if self._inter_byte_timeout is not None:
cliechti679bfa62008-06-20 23:58:15 +0000281 vmin = 1
Chris Liechti518b0d32015-08-30 02:20:39 +0200282 vtime = int(self._inter_byte_timeout * 10)
cliechti6ce7ab12002-11-07 02:15:00 +0000283 try:
cliechti4d0af5e2011-08-05 02:18:16 +0000284 orig_attr = termios.tcgetattr(self.fd)
285 iflag, oflag, cflag, lflag, ispeed, ospeed, cc = orig_attr
Chris Liechti68340d72015-08-03 14:15:48 +0200286 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 +0100287 raise SerialException("Could not configure port: {}".format(msg))
cliechti58b481c2009-02-16 20:42:32 +0000288 # set up raw mode / no echo / binary
Chris Liechti033f17c2015-08-30 21:28:04 +0200289 cflag |= (termios.CLOCAL | termios.CREAD)
290 lflag &= ~(termios.ICANON | termios.ECHO | termios.ECHOE |
291 termios.ECHOK | termios.ECHONL |
292 termios.ISIG | termios.IEXTEN) # |termios.ECHOPRT
293 for flag in ('ECHOCTL', 'ECHOKE'): # netbsd workaround for Erk
Chris Liechti11465c82015-08-04 15:55:22 +0200294 if hasattr(termios, flag):
295 lflag &= ~getattr(termios, flag)
cliechti58b481c2009-02-16 20:42:32 +0000296
Chris Liechti033f17c2015-08-30 21:28:04 +0200297 oflag &= ~(termios.OPOST | termios.ONLCR | termios.OCRNL)
298 iflag &= ~(termios.INLCR | termios.IGNCR | termios.ICRNL | termios.IGNBRK)
Chris Liechti11465c82015-08-04 15:55:22 +0200299 if hasattr(termios, 'IUCLC'):
300 iflag &= ~termios.IUCLC
301 if hasattr(termios, 'PARMRK'):
302 iflag &= ~termios.PARMRK
cliechti58b481c2009-02-16 20:42:32 +0000303
cliechtif0a4f0f2009-07-21 21:12:37 +0000304 # setup baud rate
cliechti89b4af12002-02-12 23:24:41 +0000305 try:
Chris Liechti984c5c52016-02-15 23:48:45 +0100306 ispeed = ospeed = getattr(termios, 'B{}'.format(self._baudrate))
cliechti895e8302004-04-20 02:40:28 +0000307 except AttributeError:
cliechtif1559d02007-11-08 23:43:58 +0000308 try:
Chris Liechtid6847af2015-08-06 17:54:30 +0200309 ispeed = ospeed = self.BAUDRATE_CONSTANTS[self._baudrate]
cliechtif1559d02007-11-08 23:43:58 +0000310 except KeyError:
cliechtie8c45422008-06-20 23:23:14 +0000311 #~ raise ValueError('Invalid baud rate: %r' % self._baudrate)
cliechtif0a4f0f2009-07-21 21:12:37 +0000312 # may need custom baud rate, it isn't in our list.
Chris Liechti11465c82015-08-04 15:55:22 +0200313 ispeed = ospeed = getattr(termios, 'B38400')
cliechtif0a4f0f2009-07-21 21:12:37 +0000314 try:
Chris Liechti033f17c2015-08-30 21:28:04 +0200315 custom_baud = int(self._baudrate) # store for later
cliechtif0a4f0f2009-07-21 21:12:37 +0000316 except ValueError:
Chris Liechti984c5c52016-02-15 23:48:45 +0100317 raise ValueError('Invalid baud rate: {!r}'.format(self._baudrate))
cliechtif0a4f0f2009-07-21 21:12:37 +0000318 else:
319 if custom_baud < 0:
Chris Liechti984c5c52016-02-15 23:48:45 +0100320 raise ValueError('Invalid baud rate: {!r}'.format(self._baudrate))
cliechti58b481c2009-02-16 20:42:32 +0000321
322 # setup char len
Chris Liechti11465c82015-08-04 15:55:22 +0200323 cflag &= ~termios.CSIZE
cliechtid6bf52c2003-10-01 02:28:12 +0000324 if self._bytesize == 8:
Chris Liechti11465c82015-08-04 15:55:22 +0200325 cflag |= termios.CS8
cliechtid6bf52c2003-10-01 02:28:12 +0000326 elif self._bytesize == 7:
Chris Liechti11465c82015-08-04 15:55:22 +0200327 cflag |= termios.CS7
cliechtid6bf52c2003-10-01 02:28:12 +0000328 elif self._bytesize == 6:
Chris Liechti11465c82015-08-04 15:55:22 +0200329 cflag |= termios.CS6
cliechtid6bf52c2003-10-01 02:28:12 +0000330 elif self._bytesize == 5:
Chris Liechti11465c82015-08-04 15:55:22 +0200331 cflag |= termios.CS5
cliechti89b4af12002-02-12 23:24:41 +0000332 else:
Chris Liechti984c5c52016-02-15 23:48:45 +0100333 raise ValueError('Invalid char len: {!r}'.format(self._bytesize))
cliechtif0a81d42014-08-04 14:03:53 +0000334 # setup stop bits
Chris Liechti033f17c2015-08-30 21:28:04 +0200335 if self._stopbits == serial.STOPBITS_ONE:
Chris Liechti11465c82015-08-04 15:55:22 +0200336 cflag &= ~(termios.CSTOPB)
Chris Liechti033f17c2015-08-30 21:28:04 +0200337 elif self._stopbits == serial.STOPBITS_ONE_POINT_FIVE:
338 cflag |= (termios.CSTOPB) # XXX same as TWO.. there is no POSIX support for 1.5
339 elif self._stopbits == serial.STOPBITS_TWO:
340 cflag |= (termios.CSTOPB)
cliechti89b4af12002-02-12 23:24:41 +0000341 else:
Chris Liechti984c5c52016-02-15 23:48:45 +0100342 raise ValueError('Invalid stop bit specification: {!r}'.format(self._stopbits))
cliechti58b481c2009-02-16 20:42:32 +0000343 # setup parity
Chris Liechti033f17c2015-08-30 21:28:04 +0200344 iflag &= ~(termios.INPCK | termios.ISTRIP)
345 if self._parity == serial.PARITY_NONE:
346 cflag &= ~(termios.PARENB | termios.PARODD)
347 elif self._parity == serial.PARITY_EVEN:
Chris Liechti11465c82015-08-04 15:55:22 +0200348 cflag &= ~(termios.PARODD)
Chris Liechti033f17c2015-08-30 21:28:04 +0200349 cflag |= (termios.PARENB)
350 elif self._parity == serial.PARITY_ODD:
351 cflag |= (termios.PARENB | termios.PARODD)
352 elif self._parity == serial.PARITY_MARK and plat[:5] == 'linux':
353 cflag |= (termios.PARENB | CMSPAR | termios.PARODD)
354 elif self._parity == serial.PARITY_SPACE and plat[:5] == 'linux':
355 cflag |= (termios.PARENB | CMSPAR)
Chris Liechti11465c82015-08-04 15:55:22 +0200356 cflag &= ~(termios.PARODD)
cliechti89b4af12002-02-12 23:24:41 +0000357 else:
Chris Liechti984c5c52016-02-15 23:48:45 +0100358 raise ValueError('Invalid parity: {!r}'.format(self._parity))
cliechti58b481c2009-02-16 20:42:32 +0000359 # setup flow control
360 # xonxoff
Chris Liechti11465c82015-08-04 15:55:22 +0200361 if hasattr(termios, 'IXANY'):
cliechtid6bf52c2003-10-01 02:28:12 +0000362 if self._xonxoff:
Chris Liechti033f17c2015-08-30 21:28:04 +0200363 iflag |= (termios.IXON | termios.IXOFF) # |termios.IXANY)
cliechti89b4af12002-02-12 23:24:41 +0000364 else:
Chris Liechti033f17c2015-08-30 21:28:04 +0200365 iflag &= ~(termios.IXON | termios.IXOFF | termios.IXANY)
cliechti89b4af12002-02-12 23:24:41 +0000366 else:
cliechtid6bf52c2003-10-01 02:28:12 +0000367 if self._xonxoff:
Chris Liechti033f17c2015-08-30 21:28:04 +0200368 iflag |= (termios.IXON | termios.IXOFF)
cliechti89b4af12002-02-12 23:24:41 +0000369 else:
Chris Liechti033f17c2015-08-30 21:28:04 +0200370 iflag &= ~(termios.IXON | termios.IXOFF)
cliechti58b481c2009-02-16 20:42:32 +0000371 # rtscts
Chris Liechti11465c82015-08-04 15:55:22 +0200372 if hasattr(termios, 'CRTSCTS'):
cliechtid6bf52c2003-10-01 02:28:12 +0000373 if self._rtscts:
Chris Liechti033f17c2015-08-30 21:28:04 +0200374 cflag |= (termios.CRTSCTS)
cliechti89b4af12002-02-12 23:24:41 +0000375 else:
Chris Liechti11465c82015-08-04 15:55:22 +0200376 cflag &= ~(termios.CRTSCTS)
377 elif hasattr(termios, 'CNEW_RTSCTS'): # try it with alternate constant name
cliechtid6bf52c2003-10-01 02:28:12 +0000378 if self._rtscts:
Chris Liechti033f17c2015-08-30 21:28:04 +0200379 cflag |= (termios.CNEW_RTSCTS)
cliechtid4743692002-04-08 22:39:53 +0000380 else:
Chris Liechti11465c82015-08-04 15:55:22 +0200381 cflag &= ~(termios.CNEW_RTSCTS)
cliechti2750b832009-07-28 00:13:52 +0000382 # XXX should there be a warning if setting up rtscts (and xonxoff etc) fails??
cliechti58b481c2009-02-16 20:42:32 +0000383
384 # buffer
cliechtif0a81d42014-08-04 14:03:53 +0000385 # vmin "minimal number of characters to be read. 0 for non blocking"
cliechtid6bf52c2003-10-01 02:28:12 +0000386 if vmin < 0 or vmin > 255:
Chris Liechti984c5c52016-02-15 23:48:45 +0100387 raise ValueError('Invalid vmin: {!r}'.format(vmin))
Chris Liechti11465c82015-08-04 15:55:22 +0200388 cc[termios.VMIN] = vmin
cliechti58b481c2009-02-16 20:42:32 +0000389 # vtime
cliechtid6bf52c2003-10-01 02:28:12 +0000390 if vtime < 0 or vtime > 255:
Chris Liechti984c5c52016-02-15 23:48:45 +0100391 raise ValueError('Invalid vtime: {!r}'.format(vtime))
Chris Liechti11465c82015-08-04 15:55:22 +0200392 cc[termios.VTIME] = vtime
cliechti58b481c2009-02-16 20:42:32 +0000393 # activate settings
Chris Liechti94284702015-11-15 01:21:48 +0100394 if force_update or [iflag, oflag, cflag, lflag, ispeed, ospeed, cc] != orig_attr:
Chris Liechti033f17c2015-08-30 21:28:04 +0200395 termios.tcsetattr(
Chris Liechti9eaa40c2016-02-12 23:32:59 +0100396 self.fd,
397 termios.TCSANOW,
398 [iflag, oflag, cflag, lflag, ispeed, ospeed, cc])
cliechti58b481c2009-02-16 20:42:32 +0000399
cliechtie8c45422008-06-20 23:23:14 +0000400 # apply custom baud rate, if any
401 if custom_baud is not None:
Chris Liechtid6847af2015-08-06 17:54:30 +0200402 self._set_special_baudrate(custom_baud)
403
404 if self._rs485_mode is not None:
405 self._set_rs485_mode(self._rs485_mode)
cliechti89b4af12002-02-12 23:24:41 +0000406
407 def close(self):
cliechtid6bf52c2003-10-01 02:28:12 +0000408 """Close port"""
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200409 if self.is_open:
cliechtic6178262004-03-22 22:04:52 +0000410 if self.fd is not None:
cliechtid6bf52c2003-10-01 02:28:12 +0000411 os.close(self.fd)
412 self.fd = None
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200413 self.is_open = False
cliechtid6bf52c2003-10-01 02:28:12 +0000414
415 # - - - - - - - - - - - - - - - - - - - - - - - -
cliechti95c62212002-03-04 22:17:53 +0000416
Chris Liechtief1fe252015-08-27 23:25:21 +0200417 @property
418 def in_waiting(self):
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200419 """Return the number of bytes currently in the input buffer."""
Chris Liechti11465c82015-08-04 15:55:22 +0200420 #~ s = fcntl.ioctl(self.fd, termios.FIONREAD, TIOCM_zero_str)
cliechtif5831e02002-12-05 23:15:27 +0000421 s = fcntl.ioctl(self.fd, TIOCINQ, TIOCM_zero_str)
Chris Liechti033f17c2015-08-30 21:28:04 +0200422 return struct.unpack('I', s)[0]
cliechti89b4af12002-02-12 23:24:41 +0000423
cliechtia9a093e2010-01-02 03:05:08 +0000424 # select based implementation, proved to work on many systems
425 def read(self, size=1):
cliechti7d448562014-08-03 21:57:45 +0000426 """\
427 Read size bytes from the serial port. If a timeout is set it may
428 return less characters as requested. With no timeout it will block
429 until the requested number of bytes is read.
430 """
Chris Liechti033f17c2015-08-30 21:28:04 +0200431 if not self.is_open:
432 raise portNotOpenError
cliechtia9a093e2010-01-02 03:05:08 +0000433 read = bytearray()
Cristiano De Altic30622f2015-12-12 11:00:01 +0100434 timeout = self._timeout
cliechtia9a093e2010-01-02 03:05:08 +0000435 while len(read) < size:
cliechti8d744de2013-10-11 14:31:13 +0000436 try:
Cristiano De Altic30622f2015-12-12 11:00:01 +0100437 start_time = time.time()
438 ready, _, _ = select.select([self.fd], [], [], timeout)
cliechti8d744de2013-10-11 14:31:13 +0000439 # If select was used with a timeout, and the timeout occurs, it
440 # returns with empty lists -> thus abort read operation.
Chris Liechti033f17c2015-08-30 21:28:04 +0200441 # For timeout == 0 (non-blocking operation) also abort when
442 # there is nothing to read.
cliechti8d744de2013-10-11 14:31:13 +0000443 if not ready:
444 break # timeout
Chris Liechti033f17c2015-08-30 21:28:04 +0200445 buf = os.read(self.fd, size - len(read))
cliechti8d744de2013-10-11 14:31:13 +0000446 # read should always return some data as select reported it was
447 # ready to read when we get to this point.
448 if not buf:
449 # Disconnected devices, at least on Linux, show the
450 # behavior that they are always ready to read immediately
451 # but reading returns nothing.
Chris Liechti92df95a2016-02-09 23:30:37 +0100452 raise SerialException(
453 'device reports readiness to read but returned no data '
454 '(device disconnected or multiple access on port?)')
cliechti8d744de2013-10-11 14:31:13 +0000455 read.extend(buf)
Cristiano De Altic30622f2015-12-12 11:00:01 +0100456 if timeout is not None:
457 timeout -= time.time() - start_time
458 if timeout <= 0:
459 break
Chris Liechti68340d72015-08-03 14:15:48 +0200460 except OSError as e:
Chris Liechti033f17c2015-08-30 21:28:04 +0200461 # this is for Python 3.x where select.error is a subclass of
462 # OSError ignore EAGAIN errors. all other errors are shown
cliechtic7cd7212014-08-03 21:34:38 +0000463 if e.errno != errno.EAGAIN:
Chris Liechti984c5c52016-02-15 23:48:45 +0100464 raise SerialException('read failed: {}'.format(e))
Chris Liechti68340d72015-08-03 14:15:48 +0200465 except select.error as e:
cliechtic7cd7212014-08-03 21:34:38 +0000466 # this is for Python 2.x
cliechti8d744de2013-10-11 14:31:13 +0000467 # ignore EAGAIN errors. all other errors are shown
468 # see also http://www.python.org/dev/peps/pep-3151/#select
469 if e[0] != errno.EAGAIN:
Chris Liechti984c5c52016-02-15 23:48:45 +0100470 raise SerialException('read failed: {}'.format(e))
cliechtia9a093e2010-01-02 03:05:08 +0000471 return bytes(read)
cliechti89b4af12002-02-12 23:24:41 +0000472
cliechti4a567a02009-07-27 22:09:31 +0000473 def write(self, data):
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200474 """Output the given byte string over the serial port."""
Chris Liechti033f17c2015-08-30 21:28:04 +0200475 if not self.is_open:
476 raise portNotOpenError
cliechti38077122013-10-16 02:57:27 +0000477 d = to_bytes(data)
478 tx_len = len(d)
Robert Smallshire325a7382016-03-25 21:18:38 +0100479 timeout = self._write_timeout
480 if timeout and timeout > 0: # Avoid comparing None with zero
481 timeout += time.time()
cliechti9f7c2352013-10-11 01:13:46 +0000482 while tx_len > 0:
cliechti5d4d0bd2004-11-13 03:27:39 +0000483 try:
cliechti5d4d0bd2004-11-13 03:27:39 +0000484 n = os.write(self.fd, d)
Robert Smallshire325a7382016-03-25 21:18:38 +0100485 if timeout == 0:
486 # Zero timeout indicates non-blocking - simply return the
487 # number of bytes of data actually written
488 return n
489 elif timeout and timeout > 0: # Avoid comparing None with zero
cliechti3cf46d62009-08-07 00:19:57 +0000490 # when timeout is set, use select to wait for being ready
491 # with the time left as timeout
492 timeleft = timeout - time.time()
493 if timeleft < 0:
494 raise writeTimeoutError
495 _, ready, _ = select.select([], [self.fd], [], timeleft)
cliechti5d4d0bd2004-11-13 03:27:39 +0000496 if not ready:
497 raise writeTimeoutError
cliechti88c62442013-10-12 04:03:16 +0000498 else:
Robert Smallshire325a7382016-03-25 21:18:38 +0100499 assert timeout is None
cliechti88c62442013-10-12 04:03:16 +0000500 # wait for write operation
501 _, ready, _ = select.select([], [self.fd], [], None)
502 if not ready:
503 raise SerialException('write failed (select)')
cliechti5d4d0bd2004-11-13 03:27:39 +0000504 d = d[n:]
cliechti9f7c2352013-10-11 01:13:46 +0000505 tx_len -= n
Chris Liechti675f7e12015-08-03 15:48:41 +0200506 except SerialException:
507 raise
Chris Liechti68340d72015-08-03 14:15:48 +0200508 except OSError as v:
cliechti5d4d0bd2004-11-13 03:27:39 +0000509 if v.errno != errno.EAGAIN:
Chris Liechti984c5c52016-02-15 23:48:45 +0100510 raise SerialException('write failed: {}'.format(v))
Chris Liechtic6362db2015-12-13 23:44:35 +0100511 # still calculate and check timeout
512 if timeout and timeout - time.time() < 0:
513 raise writeTimeoutError
cliechtif81362e2009-07-25 03:44:33 +0000514 return len(data)
cliechtid6bf52c2003-10-01 02:28:12 +0000515
cliechtia30a8a02003-10-05 12:28:13 +0000516 def flush(self):
cliechti7d448562014-08-03 21:57:45 +0000517 """\
518 Flush of file like objects. In this case, wait until all data
519 is written.
520 """
Chris Liechti033f17c2015-08-30 21:28:04 +0200521 if not self.is_open:
522 raise portNotOpenError
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200523 termios.tcdrain(self.fd)
cliechtia30a8a02003-10-05 12:28:13 +0000524
Chris Liechtief1fe252015-08-27 23:25:21 +0200525 def reset_input_buffer(self):
cliechtid6bf52c2003-10-01 02:28:12 +0000526 """Clear input buffer, discarding all that is in the buffer."""
Chris Liechti033f17c2015-08-30 21:28:04 +0200527 if not self.is_open:
528 raise portNotOpenError
Chris Liechti11465c82015-08-04 15:55:22 +0200529 termios.tcflush(self.fd, termios.TCIFLUSH)
cliechti89b4af12002-02-12 23:24:41 +0000530
Chris Liechtief1fe252015-08-27 23:25:21 +0200531 def reset_output_buffer(self):
cliechti7d448562014-08-03 21:57:45 +0000532 """\
533 Clear output buffer, aborting the current output and discarding all
534 that is in the buffer.
535 """
Chris Liechti033f17c2015-08-30 21:28:04 +0200536 if not self.is_open:
537 raise portNotOpenError
Chris Liechti11465c82015-08-04 15:55:22 +0200538 termios.tcflush(self.fd, termios.TCOFLUSH)
cliechti89b4af12002-02-12 23:24:41 +0000539
Chris Liechtief1fe252015-08-27 23:25:21 +0200540 def send_break(self, duration=0.25):
cliechti7d448562014-08-03 21:57:45 +0000541 """\
542 Send break condition. Timed, returns to idle state after given
543 duration.
544 """
Chris Liechti033f17c2015-08-30 21:28:04 +0200545 if not self.is_open:
546 raise portNotOpenError
547 termios.tcsendbreak(self.fd, int(duration / 0.25))
cliechti89b4af12002-02-12 23:24:41 +0000548
Chris Liechtief1fe252015-08-27 23:25:21 +0200549 def _update_break_state(self):
cliechti7d448562014-08-03 21:57:45 +0000550 """\
551 Set break: Controls TXD. When active, no transmitting is possible.
552 """
Chris Liechtief1fe252015-08-27 23:25:21 +0200553 if self._break_state:
cliechti997b63c2008-06-21 00:09:31 +0000554 fcntl.ioctl(self.fd, TIOCSBRK)
555 else:
556 fcntl.ioctl(self.fd, TIOCCBRK)
557
Chris Liechtief1fe252015-08-27 23:25:21 +0200558 def _update_rts_state(self):
cliechtid6bf52c2003-10-01 02:28:12 +0000559 """Set terminal status line: Request To Send"""
Chris Liechtif7534c82016-05-07 23:35:54 +0200560 if self._rts_state:
561 fcntl.ioctl(self.fd, TIOCMBIS, TIOCM_RTS_str)
562 else:
563 fcntl.ioctl(self.fd, TIOCMBIC, TIOCM_RTS_str)
cliechtid6bf52c2003-10-01 02:28:12 +0000564
Chris Liechtief1fe252015-08-27 23:25:21 +0200565 def _update_dtr_state(self):
cliechtid6bf52c2003-10-01 02:28:12 +0000566 """Set terminal status line: Data Terminal Ready"""
Chris Liechtif7534c82016-05-07 23:35:54 +0200567 if self._dtr_state:
568 fcntl.ioctl(self.fd, TIOCMBIS, TIOCM_DTR_str)
569 else:
570 fcntl.ioctl(self.fd, TIOCMBIC, TIOCM_DTR_str)
cliechtid6bf52c2003-10-01 02:28:12 +0000571
Chris Liechtief1fe252015-08-27 23:25:21 +0200572 @property
573 def cts(self):
cliechtid6bf52c2003-10-01 02:28:12 +0000574 """Read terminal status line: Clear To Send"""
Chris Liechti033f17c2015-08-30 21:28:04 +0200575 if not self.is_open:
576 raise portNotOpenError
cliechtid6bf52c2003-10-01 02:28:12 +0000577 s = fcntl.ioctl(self.fd, TIOCMGET, TIOCM_zero_str)
Chris Liechti033f17c2015-08-30 21:28:04 +0200578 return struct.unpack('I', s)[0] & TIOCM_CTS != 0
cliechtid6bf52c2003-10-01 02:28:12 +0000579
Chris Liechtief1fe252015-08-27 23:25:21 +0200580 @property
581 def dsr(self):
cliechtid6bf52c2003-10-01 02:28:12 +0000582 """Read terminal status line: Data Set Ready"""
Chris Liechti033f17c2015-08-30 21:28:04 +0200583 if not self.is_open:
584 raise portNotOpenError
cliechtid6bf52c2003-10-01 02:28:12 +0000585 s = fcntl.ioctl(self.fd, TIOCMGET, TIOCM_zero_str)
Chris Liechti033f17c2015-08-30 21:28:04 +0200586 return struct.unpack('I', s)[0] & TIOCM_DSR != 0
cliechtid6bf52c2003-10-01 02:28:12 +0000587
Chris Liechtief1fe252015-08-27 23:25:21 +0200588 @property
589 def ri(self):
cliechtid6bf52c2003-10-01 02:28:12 +0000590 """Read terminal status line: Ring Indicator"""
Chris Liechti033f17c2015-08-30 21:28:04 +0200591 if not self.is_open:
592 raise portNotOpenError
cliechti89b4af12002-02-12 23:24:41 +0000593 s = fcntl.ioctl(self.fd, TIOCMGET, TIOCM_zero_str)
Chris Liechti033f17c2015-08-30 21:28:04 +0200594 return struct.unpack('I', s)[0] & TIOCM_RI != 0
cliechti89b4af12002-02-12 23:24:41 +0000595
Chris Liechtief1fe252015-08-27 23:25:21 +0200596 @property
597 def cd(self):
cliechtid6bf52c2003-10-01 02:28:12 +0000598 """Read terminal status line: Carrier Detect"""
Chris Liechti033f17c2015-08-30 21:28:04 +0200599 if not self.is_open:
600 raise portNotOpenError
cliechti89b4af12002-02-12 23:24:41 +0000601 s = fcntl.ioctl(self.fd, TIOCMGET, TIOCM_zero_str)
Chris Liechti033f17c2015-08-30 21:28:04 +0200602 return struct.unpack('I', s)[0] & TIOCM_CD != 0
cliechti89b4af12002-02-12 23:24:41 +0000603
cliechtia30a8a02003-10-05 12:28:13 +0000604 # - - platform specific - - - -
605
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200606 @property
607 def out_waiting(self):
608 """Return the number of bytes currently in the output buffer."""
Chris Liechti11465c82015-08-04 15:55:22 +0200609 #~ s = fcntl.ioctl(self.fd, termios.FIONREAD, TIOCM_zero_str)
cliechti28b8fd02011-12-28 21:39:42 +0000610 s = fcntl.ioctl(self.fd, TIOCOUTQ, TIOCM_zero_str)
Chris Liechti033f17c2015-08-30 21:28:04 +0200611 return struct.unpack('I', s)[0]
cliechti28b8fd02011-12-28 21:39:42 +0000612
cliechtia30a8a02003-10-05 12:28:13 +0000613 def nonblocking(self):
614 """internal - not portable!"""
Chris Liechti033f17c2015-08-30 21:28:04 +0200615 if not self.is_open:
616 raise portNotOpenError
Chris Liechti11465c82015-08-04 15:55:22 +0200617 fcntl.fcntl(self.fd, fcntl.F_SETFL, os.O_NONBLOCK)
cliechtia30a8a02003-10-05 12:28:13 +0000618
cliechti8753bbc2005-01-15 20:32:51 +0000619 def fileno(self):
cliechti2f0f8a32011-12-28 22:10:00 +0000620 """\
621 For easier use of the serial port instance with select.
622 WARNING: this function is not portable to different platforms!
623 """
Chris Liechti033f17c2015-08-30 21:28:04 +0200624 if not self.is_open:
625 raise portNotOpenError
cliechti8753bbc2005-01-15 20:32:51 +0000626 return self.fd
cliechti89b4af12002-02-12 23:24:41 +0000627
Chris Liechti518b0d32015-08-30 02:20:39 +0200628 def set_input_flow_control(self, enable=True):
cliechti2f0f8a32011-12-28 22:10:00 +0000629 """\
630 Manually control flow - when software flow control is enabled.
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200631 This will send XON (true) or XOFF (false) to the other device.
cliechti2f0f8a32011-12-28 22:10:00 +0000632 WARNING: this function is not portable to different platforms!
633 """
Chris Liechti033f17c2015-08-30 21:28:04 +0200634 if not self.is_open:
635 raise portNotOpenError
cliechti4a601342011-12-29 02:22:17 +0000636 if enable:
Chris Liechti11465c82015-08-04 15:55:22 +0200637 termios.tcflow(self.fd, termios.TCION)
cliechti57e48a62009-08-03 22:29:58 +0000638 else:
Chris Liechti11465c82015-08-04 15:55:22 +0200639 termios.tcflow(self.fd, termios.TCIOFF)
cliechti57e48a62009-08-03 22:29:58 +0000640
Chris Liechti518b0d32015-08-30 02:20:39 +0200641 def set_output_flow_control(self, enable=True):
cliechti2f0f8a32011-12-28 22:10:00 +0000642 """\
643 Manually control flow of outgoing data - when hardware or software flow
644 control is enabled.
645 WARNING: this function is not portable to different platforms!
646 """
Chris Liechti033f17c2015-08-30 21:28:04 +0200647 if not self.is_open:
648 raise portNotOpenError
cliechti2f0f8a32011-12-28 22:10:00 +0000649 if enable:
Chris Liechti11465c82015-08-04 15:55:22 +0200650 termios.tcflow(self.fd, termios.TCOON)
cliechti2f0f8a32011-12-28 22:10:00 +0000651 else:
Chris Liechti11465c82015-08-04 15:55:22 +0200652 termios.tcflow(self.fd, termios.TCOOFF)
cliechti2f0f8a32011-12-28 22:10:00 +0000653
cliechtif81362e2009-07-25 03:44:33 +0000654
cliechtia9a093e2010-01-02 03:05:08 +0000655class PosixPollSerial(Serial):
cliechti7d448562014-08-03 21:57:45 +0000656 """\
cliechtif0a81d42014-08-04 14:03:53 +0000657 Poll based read implementation. Not all systems support poll properly.
658 However this one has better handling of errors, such as a device
cliechti7d448562014-08-03 21:57:45 +0000659 disconnecting while it's in use (e.g. USB-serial unplugged).
660 """
cliechtia9a093e2010-01-02 03:05:08 +0000661
662 def read(self, size=1):
cliechti7d448562014-08-03 21:57:45 +0000663 """\
664 Read size bytes from the serial port. If a timeout is set it may
665 return less characters as requested. With no timeout it will block
666 until the requested number of bytes is read.
667 """
Chris Liechtiacac2362016-03-29 22:37:48 +0200668 if not self.is_open:
Chris Liechti033f17c2015-08-30 21:28:04 +0200669 raise portNotOpenError
cliechtia9a093e2010-01-02 03:05:08 +0000670 read = bytearray()
671 poll = select.poll()
Chris Liechti033f17c2015-08-30 21:28:04 +0200672 poll.register(self.fd, select.POLLIN | select.POLLERR | select.POLLHUP | select.POLLNVAL)
cliechtia9a093e2010-01-02 03:05:08 +0000673 if size > 0:
674 while len(read) < size:
675 # print "\tread(): size",size, "have", len(read) #debug
676 # wait until device becomes ready to read (or something fails)
Chris Liechti033f17c2015-08-30 21:28:04 +0200677 for fd, event in poll.poll(self._timeout * 1000):
678 if event & (select.POLLERR | select.POLLHUP | select.POLLNVAL):
cliechtia9a093e2010-01-02 03:05:08 +0000679 raise SerialException('device reports error (poll)')
680 # we don't care if it is select.POLLIN or timeout, that's
681 # handled below
682 buf = os.read(self.fd, size - len(read))
683 read.extend(buf)
Chris Liechti518b0d32015-08-30 02:20:39 +0200684 if ((self._timeout is not None and self._timeout >= 0) or
Chris Liechti033f17c2015-08-30 21:28:04 +0200685 (self._inter_byte_timeout is not None and self._inter_byte_timeout > 0)) and not buf:
cliechtia9a093e2010-01-02 03:05:08 +0000686 break # early abort on timeout
687 return bytes(read)
688
cliechtif81362e2009-07-25 03:44:33 +0000689
Chris Liechti4cf54702015-10-18 00:21:56 +0200690class VTIMESerial(Serial):
691 """\
692 Implement timeout using vtime of tty device instead of using select.
693 This means that no inter character timeout can be specified and that
694 the error handling is degraded.
695
696 Overall timeout is disabled when inter-character timeout is used.
697 """
698
Chris Liechti94284702015-11-15 01:21:48 +0100699 def _reconfigure_port(self, force_update=True):
Chris Liechti4cf54702015-10-18 00:21:56 +0200700 """Set communication parameters on opened port."""
701 super(VTIMESerial, self)._reconfigure_port()
Chris Liechtid6bcaaf2016-02-01 22:55:26 +0100702 fcntl.fcntl(self.fd, fcntl.F_SETFL, 0) # clear O_NONBLOCK
Chris Liechti4cf54702015-10-18 00:21:56 +0200703
704 if self._inter_byte_timeout is not None:
705 vmin = 1
706 vtime = int(self._inter_byte_timeout * 10)
707 else:
708 vmin = 0
709 vtime = int(self._timeout * 10)
710 try:
711 orig_attr = termios.tcgetattr(self.fd)
712 iflag, oflag, cflag, lflag, ispeed, ospeed, cc = orig_attr
713 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 +0100714 raise serial.SerialException("Could not configure port: {}".format(msg))
Chris Liechti4cf54702015-10-18 00:21:56 +0200715
716 if vtime < 0 or vtime > 255:
Chris Liechti984c5c52016-02-15 23:48:45 +0100717 raise ValueError('Invalid vtime: {!r}'.format(vtime))
Chris Liechti4cf54702015-10-18 00:21:56 +0200718 cc[termios.VTIME] = vtime
719 cc[termios.VMIN] = vmin
720
721 termios.tcsetattr(
722 self.fd,
723 termios.TCSANOW,
724 [iflag, oflag, cflag, lflag, ispeed, ospeed, cc])
725
Chris Liechti4cf54702015-10-18 00:21:56 +0200726 def read(self, size=1):
727 """\
728 Read size bytes from the serial port. If a timeout is set it may
729 return less characters as requested. With no timeout it will block
730 until the requested number of bytes is read.
731 """
732 if not self.is_open:
733 raise portNotOpenError
734 read = bytearray()
735 while len(read) < size:
736 buf = os.read(self.fd, size - len(read))
737 if not buf:
738 break
739 read.extend(buf)
740 return bytes(read)