blob: e7bbc13c15b79c9f7d889c3113752d6fcf883e01 [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
Chris Liechti6dc58e82016-08-29 23:02:13 +020052
53# some systems support an extra flag to enable the two in POSIX unsupported
54# partiy settings for MARK and SPACE
55CMSPAR = 0 # default, for unsupported platforms, override below
56
Chris Liechtid6847af2015-08-06 17:54:30 +020057# try to detect the OS so that a device can be selected...
58# this code block should supply a device() and set_special_baudrate() function
59# for the platform
60plat = sys.platform.lower()
61
Chris Liechtiba45c522016-02-06 23:53:23 +010062if plat[:5] == 'linux': # Linux (confirmed) # noqa
Chris Liechtid6847af2015-08-06 17:54:30 +020063 import array
64
Chris Liechti6dc58e82016-08-29 23:02:13 +020065 # extra termios flags
66 CMSPAR = 0o10000000000 # Use "stick" (mark/space) parity
67
Chris Liechtid6847af2015-08-06 17:54:30 +020068 # baudrate ioctls
69 TCGETS2 = 0x802C542A
70 TCSETS2 = 0x402C542B
71 BOTHER = 0o010000
72
73 # RS485 ioctls
74 TIOCGRS485 = 0x542E
75 TIOCSRS485 = 0x542F
Chris Liechti033f17c2015-08-30 21:28:04 +020076 SER_RS485_ENABLED = 0b00000001
77 SER_RS485_RTS_ON_SEND = 0b00000010
Chris Liechtid6847af2015-08-06 17:54:30 +020078 SER_RS485_RTS_AFTER_SEND = 0b00000100
Chris Liechti033f17c2015-08-30 21:28:04 +020079 SER_RS485_RX_DURING_TX = 0b00010000
Chris Liechtid6847af2015-08-06 17:54:30 +020080
81 class PlatformSpecific(PlatformSpecificBase):
82 BAUDRATE_CONSTANTS = {
83 0: 0o000000, # hang up
84 50: 0o000001,
85 75: 0o000002,
86 110: 0o000003,
87 134: 0o000004,
88 150: 0o000005,
89 200: 0o000006,
90 300: 0o000007,
91 600: 0o000010,
92 1200: 0o000011,
93 1800: 0o000012,
94 2400: 0o000013,
95 4800: 0o000014,
96 9600: 0o000015,
97 19200: 0o000016,
98 38400: 0o000017,
99 57600: 0o010001,
100 115200: 0o010002,
101 230400: 0o010003,
102 460800: 0o010004,
103 500000: 0o010005,
104 576000: 0o010006,
105 921600: 0o010007,
106 1000000: 0o010010,
107 1152000: 0o010011,
108 1500000: 0o010012,
109 2000000: 0o010013,
110 2500000: 0o010014,
111 3000000: 0o010015,
112 3500000: 0o010016,
113 4000000: 0o010017
114 }
115
Chris Liechtid6847af2015-08-06 17:54:30 +0200116 def _set_special_baudrate(self, baudrate):
117 # right size is 44 on x86_64, allow for some growth
118 buf = array.array('i', [0] * 64)
119 try:
120 # get serial_struct
121 fcntl.ioctl(self.fd, TCGETS2, buf)
122 # set custom speed
123 buf[2] &= ~termios.CBAUD
124 buf[2] |= BOTHER
125 buf[9] = buf[10] = baudrate
126
127 # set serial_struct
Chris Liechti033f17c2015-08-30 21:28:04 +0200128 fcntl.ioctl(self.fd, TCSETS2, buf)
Chris Liechtid6847af2015-08-06 17:54:30 +0200129 except IOError as e:
Chris Liechti984c5c52016-02-15 23:48:45 +0100130 raise ValueError('Failed to set custom baud rate ({}): {}'.format(baudrate, e))
Chris Liechtid6847af2015-08-06 17:54:30 +0200131
132 def _set_rs485_mode(self, rs485_settings):
Chris Liechti033f17c2015-08-30 21:28:04 +0200133 buf = array.array('i', [0] * 8) # flags, delaytx, delayrx, padding
Chris Liechtid6847af2015-08-06 17:54:30 +0200134 try:
135 fcntl.ioctl(self.fd, TIOCGRS485, buf)
Chris Liechti7a554462016-03-24 21:17:22 +0100136 buf[0] |= SER_RS485_ENABLED
Chris Liechtid6847af2015-08-06 17:54:30 +0200137 if rs485_settings is not None:
138 if rs485_settings.loopback:
139 buf[0] |= SER_RS485_RX_DURING_TX
140 else:
141 buf[0] &= ~SER_RS485_RX_DURING_TX
142 if rs485_settings.rts_level_for_tx:
143 buf[0] |= SER_RS485_RTS_ON_SEND
144 else:
145 buf[0] &= ~SER_RS485_RTS_ON_SEND
146 if rs485_settings.rts_level_for_rx:
147 buf[0] |= SER_RS485_RTS_AFTER_SEND
148 else:
149 buf[0] &= ~SER_RS485_RTS_AFTER_SEND
Chris Liechti279201b2016-06-09 20:27:05 +0200150 if rs485_settings.delay_before_tx is not None:
151 buf[1] = int(rs485_settings.delay_before_tx * 1000)
152 if rs485_settings.delay_before_rx is not None:
153 buf[2] = int(rs485_settings.delay_before_rx * 1000)
Chris Liechtid6847af2015-08-06 17:54:30 +0200154 else:
155 buf[0] = 0 # clear SER_RS485_ENABLED
Chris Liechti033f17c2015-08-30 21:28:04 +0200156 fcntl.ioctl(self.fd, TIOCSRS485, buf)
Chris Liechtid6847af2015-08-06 17:54:30 +0200157 except IOError as e:
Chris Liechti984c5c52016-02-15 23:48:45 +0100158 raise ValueError('Failed to set RS485 mode: {}'.format(e))
Chris Liechtid6847af2015-08-06 17:54:30 +0200159
160
161elif plat == 'cygwin': # cygwin/win32 (confirmed)
162
163 class PlatformSpecific(PlatformSpecificBase):
164 BAUDRATE_CONSTANTS = {
165 128000: 0x01003,
166 256000: 0x01005,
167 500000: 0x01007,
168 576000: 0x01008,
169 921600: 0x01009,
170 1000000: 0x0100a,
171 1152000: 0x0100b,
172 1500000: 0x0100c,
173 2000000: 0x0100d,
174 2500000: 0x0100e,
175 3000000: 0x0100f
176 }
177
Chris Liechtid6847af2015-08-06 17:54:30 +0200178
179elif plat[:6] == 'darwin': # OS X
180 import array
Chris Liechti033f17c2015-08-30 21:28:04 +0200181 IOSSIOSPEED = 0x80045402 # _IOW('T', 2, speed_t)
Chris Liechtid6847af2015-08-06 17:54:30 +0200182
183 class PlatformSpecific(PlatformSpecificBase):
Chris Liechtid6847af2015-08-06 17:54:30 +0200184 osx_version = os.uname()[2].split('.')
185 # Tiger or above can support arbitrary serial speeds
186 if int(osx_version[0]) >= 8:
187 def _set_special_baudrate(self, baudrate):
188 # use IOKit-specific call to set up high speeds
189 buf = array.array('i', [baudrate])
190 fcntl.ioctl(self.fd, IOSSIOSPEED, buf, 1)
191
Chris Liechtid6847af2015-08-06 17:54:30 +0200192else:
193 class PlatformSpecific(PlatformSpecificBase):
194 pass
cliechti89b4af12002-02-12 23:24:41 +0000195
cliechti89b4af12002-02-12 23:24:41 +0000196
cliechti58b481c2009-02-16 20:42:32 +0000197# load some constants for later use.
Chris Liechti11465c82015-08-04 15:55:22 +0200198# try to use values from termios, use defaults from linux otherwise
Chris Liechti033f17c2015-08-30 21:28:04 +0200199TIOCMGET = getattr(termios, 'TIOCMGET', 0x5415)
200TIOCMBIS = getattr(termios, 'TIOCMBIS', 0x5416)
201TIOCMBIC = getattr(termios, 'TIOCMBIC', 0x5417)
202TIOCMSET = getattr(termios, 'TIOCMSET', 0x5418)
cliechti89b4af12002-02-12 23:24:41 +0000203
Chris Liechti033f17c2015-08-30 21:28:04 +0200204# TIOCM_LE = getattr(termios, 'TIOCM_LE', 0x001)
Chris Liechtid6847af2015-08-06 17:54:30 +0200205TIOCM_DTR = getattr(termios, 'TIOCM_DTR', 0x002)
206TIOCM_RTS = getattr(termios, 'TIOCM_RTS', 0x004)
Chris Liechti033f17c2015-08-30 21:28:04 +0200207# TIOCM_ST = getattr(termios, 'TIOCM_ST', 0x008)
208# TIOCM_SR = getattr(termios, 'TIOCM_SR', 0x010)
cliechti89b4af12002-02-12 23:24:41 +0000209
Chris Liechtid6847af2015-08-06 17:54:30 +0200210TIOCM_CTS = getattr(termios, 'TIOCM_CTS', 0x020)
211TIOCM_CAR = getattr(termios, 'TIOCM_CAR', 0x040)
212TIOCM_RNG = getattr(termios, 'TIOCM_RNG', 0x080)
213TIOCM_DSR = getattr(termios, 'TIOCM_DSR', 0x100)
Chris Liechti033f17c2015-08-30 21:28:04 +0200214TIOCM_CD = getattr(termios, 'TIOCM_CD', TIOCM_CAR)
215TIOCM_RI = getattr(termios, 'TIOCM_RI', TIOCM_RNG)
216# TIOCM_OUT1 = getattr(termios, 'TIOCM_OUT1', 0x2000)
217# TIOCM_OUT2 = getattr(termios, 'TIOCM_OUT2', 0x4000)
Chris Liechti11465c82015-08-04 15:55:22 +0200218if hasattr(termios, 'TIOCINQ'):
219 TIOCINQ = termios.TIOCINQ
cliechti28b8fd02011-12-28 21:39:42 +0000220else:
Chris Liechtid6847af2015-08-06 17:54:30 +0200221 TIOCINQ = getattr(termios, 'FIONREAD', 0x541B)
Chris Liechti033f17c2015-08-30 21:28:04 +0200222TIOCOUTQ = getattr(termios, 'TIOCOUTQ', 0x5411)
cliechti89b4af12002-02-12 23:24:41 +0000223
224TIOCM_zero_str = struct.pack('I', 0)
225TIOCM_RTS_str = struct.pack('I', TIOCM_RTS)
226TIOCM_DTR_str = struct.pack('I', TIOCM_DTR)
227
Chris Liechti033f17c2015-08-30 21:28:04 +0200228TIOCSBRK = getattr(termios, 'TIOCSBRK', 0x5427)
229TIOCCBRK = getattr(termios, 'TIOCCBRK', 0x5428)
cliechti997b63c2008-06-21 00:09:31 +0000230
cliechti89b4af12002-02-12 23:24:41 +0000231
Chris Liechtief6b7b42015-08-06 22:19:26 +0200232class Serial(SerialBase, PlatformSpecific):
cliechti7d448562014-08-03 21:57:45 +0000233 """\
Chris Liechti033f17c2015-08-30 21:28:04 +0200234 Serial port class POSIX implementation. Serial port configuration is
cliechtid6bf52c2003-10-01 02:28:12 +0000235 done with termios and fcntl. Runs on Linux and many other Un*x like
cliechtif0a81d42014-08-04 14:03:53 +0000236 systems.
237 """
cliechtid6bf52c2003-10-01 02:28:12 +0000238
239 def open(self):
cliechti7d448562014-08-03 21:57:45 +0000240 """\
241 Open port with current settings. This may throw a SerialException
242 if the port cannot be opened."""
cliechtid6bf52c2003-10-01 02:28:12 +0000243 if self._port is None:
244 raise SerialException("Port must be configured before it can be used.")
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200245 if self.is_open:
cliechti02ef43a2011-03-24 23:33:12 +0000246 raise SerialException("Port is already open.")
247 self.fd = None
cliechti58b481c2009-02-16 20:42:32 +0000248 # open
cliechti4616bf12002-04-08 23:13:14 +0000249 try:
Chris Liechti033f17c2015-08-30 21:28:04 +0200250 self.fd = os.open(self.portstr, os.O_RDWR | os.O_NOCTTY | os.O_NONBLOCK)
Chris Liechti68340d72015-08-03 14:15:48 +0200251 except OSError as msg:
cliechti4616bf12002-04-08 23:13:14 +0000252 self.fd = None
Chris Liechti984c5c52016-02-15 23:48:45 +0100253 raise SerialException(msg.errno, "could not open port {}: {}".format(self._port, msg))
Chris Liechti11465c82015-08-04 15:55:22 +0200254 #~ fcntl.fcntl(self.fd, fcntl.F_SETFL, 0) # set blocking
cliechti58b481c2009-02-16 20:42:32 +0000255
cliechtib2f5fc82006-10-20 00:09:07 +0000256 try:
Chris Liechti94284702015-11-15 01:21:48 +0100257 self._reconfigure_port(force_update=True)
cliechtib2f5fc82006-10-20 00:09:07 +0000258 except:
cliechti2750b832009-07-28 00:13:52 +0000259 try:
260 os.close(self.fd)
261 except:
262 # ignore any exception when closing the port
263 # also to keep original exception that happened when setting up
264 pass
cliechtib2f5fc82006-10-20 00:09:07 +0000265 self.fd = None
cliechtif0a4f0f2009-07-21 21:12:37 +0000266 raise
cliechtib2f5fc82006-10-20 00:09:07 +0000267 else:
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200268 self.is_open = True
Chris Liechtif2fdeb92016-05-07 23:57:50 +0200269 try:
270 if not self._dsrdtr:
271 self._update_dtr_state()
272 if not self._rtscts:
273 self._update_rts_state()
274 except IOError as e:
Chris Liechti68239372016-06-13 21:22:42 +0200275 if e.errno in (22, 25): # ignore Invalid argument and Inappropriate ioctl
Chris Liechtif2fdeb92016-05-07 23:57:50 +0200276 pass
277 else:
278 raise
Chris Liechtief1fe252015-08-27 23:25:21 +0200279 self.reset_input_buffer()
Chris Liechti42ab2b42016-05-15 23:35:05 +0200280 self.pipe_abort_read_r, self.pipe_abort_read_w = os.pipe()
Chris Liechti13949c62016-05-16 22:45:38 +0200281 self.pipe_abort_write_r, self.pipe_abort_write_w = os.pipe()
Chris Liechti68cecce2016-06-03 23:52:34 +0200282 fcntl.fcntl(self.pipe_abort_read_r, fcntl.F_SETFL, os.O_NONBLOCK)
283 fcntl.fcntl(self.pipe_abort_write_r, fcntl.F_SETFL, os.O_NONBLOCK)
cliechti58b481c2009-02-16 20:42:32 +0000284
Chris Liechti94284702015-11-15 01:21:48 +0100285 def _reconfigure_port(self, force_update=False):
cliechtib2f5fc82006-10-20 00:09:07 +0000286 """Set communication parameters on opened port."""
cliechtic6178262004-03-22 22:04:52 +0000287 if self.fd is None:
cliechtia9a093e2010-01-02 03:05:08 +0000288 raise SerialException("Can only operate on a valid file descriptor")
cliechtie8c45422008-06-20 23:23:14 +0000289 custom_baud = None
cliechti58b481c2009-02-16 20:42:32 +0000290
cliechti2750b832009-07-28 00:13:52 +0000291 vmin = vtime = 0 # timeout is done via select
Chris Liechti518b0d32015-08-30 02:20:39 +0200292 if self._inter_byte_timeout is not None:
cliechti679bfa62008-06-20 23:58:15 +0000293 vmin = 1
Chris Liechti518b0d32015-08-30 02:20:39 +0200294 vtime = int(self._inter_byte_timeout * 10)
cliechti6ce7ab12002-11-07 02:15:00 +0000295 try:
cliechti4d0af5e2011-08-05 02:18:16 +0000296 orig_attr = termios.tcgetattr(self.fd)
297 iflag, oflag, cflag, lflag, ispeed, ospeed, cc = orig_attr
Chris Liechti68340d72015-08-03 14:15:48 +0200298 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 +0100299 raise SerialException("Could not configure port: {}".format(msg))
cliechti58b481c2009-02-16 20:42:32 +0000300 # set up raw mode / no echo / binary
Chris Liechti033f17c2015-08-30 21:28:04 +0200301 cflag |= (termios.CLOCAL | termios.CREAD)
302 lflag &= ~(termios.ICANON | termios.ECHO | termios.ECHOE |
303 termios.ECHOK | termios.ECHONL |
304 termios.ISIG | termios.IEXTEN) # |termios.ECHOPRT
305 for flag in ('ECHOCTL', 'ECHOKE'): # netbsd workaround for Erk
Chris Liechti11465c82015-08-04 15:55:22 +0200306 if hasattr(termios, flag):
307 lflag &= ~getattr(termios, flag)
cliechti58b481c2009-02-16 20:42:32 +0000308
Chris Liechti033f17c2015-08-30 21:28:04 +0200309 oflag &= ~(termios.OPOST | termios.ONLCR | termios.OCRNL)
310 iflag &= ~(termios.INLCR | termios.IGNCR | termios.ICRNL | termios.IGNBRK)
Chris Liechti11465c82015-08-04 15:55:22 +0200311 if hasattr(termios, 'IUCLC'):
312 iflag &= ~termios.IUCLC
313 if hasattr(termios, 'PARMRK'):
314 iflag &= ~termios.PARMRK
cliechti58b481c2009-02-16 20:42:32 +0000315
cliechtif0a4f0f2009-07-21 21:12:37 +0000316 # setup baud rate
cliechti89b4af12002-02-12 23:24:41 +0000317 try:
Chris Liechti984c5c52016-02-15 23:48:45 +0100318 ispeed = ospeed = getattr(termios, 'B{}'.format(self._baudrate))
cliechti895e8302004-04-20 02:40:28 +0000319 except AttributeError:
cliechtif1559d02007-11-08 23:43:58 +0000320 try:
Chris Liechtid6847af2015-08-06 17:54:30 +0200321 ispeed = ospeed = self.BAUDRATE_CONSTANTS[self._baudrate]
cliechtif1559d02007-11-08 23:43:58 +0000322 except KeyError:
cliechtie8c45422008-06-20 23:23:14 +0000323 #~ raise ValueError('Invalid baud rate: %r' % self._baudrate)
cliechtif0a4f0f2009-07-21 21:12:37 +0000324 # may need custom baud rate, it isn't in our list.
Chris Liechti11465c82015-08-04 15:55:22 +0200325 ispeed = ospeed = getattr(termios, 'B38400')
cliechtif0a4f0f2009-07-21 21:12:37 +0000326 try:
Chris Liechti033f17c2015-08-30 21:28:04 +0200327 custom_baud = int(self._baudrate) # store for later
cliechtif0a4f0f2009-07-21 21:12:37 +0000328 except ValueError:
Chris Liechti984c5c52016-02-15 23:48:45 +0100329 raise ValueError('Invalid baud rate: {!r}'.format(self._baudrate))
cliechtif0a4f0f2009-07-21 21:12:37 +0000330 else:
331 if custom_baud < 0:
Chris Liechti984c5c52016-02-15 23:48:45 +0100332 raise ValueError('Invalid baud rate: {!r}'.format(self._baudrate))
cliechti58b481c2009-02-16 20:42:32 +0000333
334 # setup char len
Chris Liechti11465c82015-08-04 15:55:22 +0200335 cflag &= ~termios.CSIZE
cliechtid6bf52c2003-10-01 02:28:12 +0000336 if self._bytesize == 8:
Chris Liechti11465c82015-08-04 15:55:22 +0200337 cflag |= termios.CS8
cliechtid6bf52c2003-10-01 02:28:12 +0000338 elif self._bytesize == 7:
Chris Liechti11465c82015-08-04 15:55:22 +0200339 cflag |= termios.CS7
cliechtid6bf52c2003-10-01 02:28:12 +0000340 elif self._bytesize == 6:
Chris Liechti11465c82015-08-04 15:55:22 +0200341 cflag |= termios.CS6
cliechtid6bf52c2003-10-01 02:28:12 +0000342 elif self._bytesize == 5:
Chris Liechti11465c82015-08-04 15:55:22 +0200343 cflag |= termios.CS5
cliechti89b4af12002-02-12 23:24:41 +0000344 else:
Chris Liechti984c5c52016-02-15 23:48:45 +0100345 raise ValueError('Invalid char len: {!r}'.format(self._bytesize))
cliechtif0a81d42014-08-04 14:03:53 +0000346 # setup stop bits
Chris Liechti033f17c2015-08-30 21:28:04 +0200347 if self._stopbits == serial.STOPBITS_ONE:
Chris Liechti11465c82015-08-04 15:55:22 +0200348 cflag &= ~(termios.CSTOPB)
Chris Liechti033f17c2015-08-30 21:28:04 +0200349 elif self._stopbits == serial.STOPBITS_ONE_POINT_FIVE:
350 cflag |= (termios.CSTOPB) # XXX same as TWO.. there is no POSIX support for 1.5
351 elif self._stopbits == serial.STOPBITS_TWO:
352 cflag |= (termios.CSTOPB)
cliechti89b4af12002-02-12 23:24:41 +0000353 else:
Chris Liechti984c5c52016-02-15 23:48:45 +0100354 raise ValueError('Invalid stop bit specification: {!r}'.format(self._stopbits))
cliechti58b481c2009-02-16 20:42:32 +0000355 # setup parity
Chris Liechti033f17c2015-08-30 21:28:04 +0200356 iflag &= ~(termios.INPCK | termios.ISTRIP)
357 if self._parity == serial.PARITY_NONE:
Chris Liechti6dc58e82016-08-29 23:02:13 +0200358 cflag &= ~(termios.PARENB | termios.PARODD | CMSPAR)
Chris Liechti033f17c2015-08-30 21:28:04 +0200359 elif self._parity == serial.PARITY_EVEN:
Chris Liechti6dc58e82016-08-29 23:02:13 +0200360 cflag &= ~(termios.PARODD | CMSPAR)
Chris Liechti033f17c2015-08-30 21:28:04 +0200361 cflag |= (termios.PARENB)
362 elif self._parity == serial.PARITY_ODD:
Chris Liechti6dc58e82016-08-29 23:02:13 +0200363 cflag &= ~CMSPAR
Chris Liechti033f17c2015-08-30 21:28:04 +0200364 cflag |= (termios.PARENB | termios.PARODD)
Chris Liechti6dc58e82016-08-29 23:02:13 +0200365 elif self._parity == serial.PARITY_MARK and CMSPAR:
Chris Liechti033f17c2015-08-30 21:28:04 +0200366 cflag |= (termios.PARENB | CMSPAR | termios.PARODD)
Chris Liechti6dc58e82016-08-29 23:02:13 +0200367 elif self._parity == serial.PARITY_SPACE and CMSPAR:
Chris Liechti033f17c2015-08-30 21:28:04 +0200368 cflag |= (termios.PARENB | CMSPAR)
Chris Liechti11465c82015-08-04 15:55:22 +0200369 cflag &= ~(termios.PARODD)
cliechti89b4af12002-02-12 23:24:41 +0000370 else:
Chris Liechti984c5c52016-02-15 23:48:45 +0100371 raise ValueError('Invalid parity: {!r}'.format(self._parity))
cliechti58b481c2009-02-16 20:42:32 +0000372 # setup flow control
373 # xonxoff
Chris Liechti11465c82015-08-04 15:55:22 +0200374 if hasattr(termios, 'IXANY'):
cliechtid6bf52c2003-10-01 02:28:12 +0000375 if self._xonxoff:
Chris Liechti033f17c2015-08-30 21:28:04 +0200376 iflag |= (termios.IXON | termios.IXOFF) # |termios.IXANY)
cliechti89b4af12002-02-12 23:24:41 +0000377 else:
Chris Liechti033f17c2015-08-30 21:28:04 +0200378 iflag &= ~(termios.IXON | termios.IXOFF | termios.IXANY)
cliechti89b4af12002-02-12 23:24:41 +0000379 else:
cliechtid6bf52c2003-10-01 02:28:12 +0000380 if self._xonxoff:
Chris Liechti033f17c2015-08-30 21:28:04 +0200381 iflag |= (termios.IXON | termios.IXOFF)
cliechti89b4af12002-02-12 23:24:41 +0000382 else:
Chris Liechti033f17c2015-08-30 21:28:04 +0200383 iflag &= ~(termios.IXON | termios.IXOFF)
cliechti58b481c2009-02-16 20:42:32 +0000384 # rtscts
Chris Liechti11465c82015-08-04 15:55:22 +0200385 if hasattr(termios, 'CRTSCTS'):
cliechtid6bf52c2003-10-01 02:28:12 +0000386 if self._rtscts:
Chris Liechti033f17c2015-08-30 21:28:04 +0200387 cflag |= (termios.CRTSCTS)
cliechti89b4af12002-02-12 23:24:41 +0000388 else:
Chris Liechti11465c82015-08-04 15:55:22 +0200389 cflag &= ~(termios.CRTSCTS)
390 elif hasattr(termios, 'CNEW_RTSCTS'): # try it with alternate constant name
cliechtid6bf52c2003-10-01 02:28:12 +0000391 if self._rtscts:
Chris Liechti033f17c2015-08-30 21:28:04 +0200392 cflag |= (termios.CNEW_RTSCTS)
cliechtid4743692002-04-08 22:39:53 +0000393 else:
Chris Liechti11465c82015-08-04 15:55:22 +0200394 cflag &= ~(termios.CNEW_RTSCTS)
cliechti2750b832009-07-28 00:13:52 +0000395 # XXX should there be a warning if setting up rtscts (and xonxoff etc) fails??
cliechti58b481c2009-02-16 20:42:32 +0000396
397 # buffer
cliechtif0a81d42014-08-04 14:03:53 +0000398 # vmin "minimal number of characters to be read. 0 for non blocking"
cliechtid6bf52c2003-10-01 02:28:12 +0000399 if vmin < 0 or vmin > 255:
Chris Liechti984c5c52016-02-15 23:48:45 +0100400 raise ValueError('Invalid vmin: {!r}'.format(vmin))
Chris Liechti11465c82015-08-04 15:55:22 +0200401 cc[termios.VMIN] = vmin
cliechti58b481c2009-02-16 20:42:32 +0000402 # vtime
cliechtid6bf52c2003-10-01 02:28:12 +0000403 if vtime < 0 or vtime > 255:
Chris Liechti984c5c52016-02-15 23:48:45 +0100404 raise ValueError('Invalid vtime: {!r}'.format(vtime))
Chris Liechti11465c82015-08-04 15:55:22 +0200405 cc[termios.VTIME] = vtime
cliechti58b481c2009-02-16 20:42:32 +0000406 # activate settings
Chris Liechti94284702015-11-15 01:21:48 +0100407 if force_update or [iflag, oflag, cflag, lflag, ispeed, ospeed, cc] != orig_attr:
Chris Liechti033f17c2015-08-30 21:28:04 +0200408 termios.tcsetattr(
Chris Liechti9eaa40c2016-02-12 23:32:59 +0100409 self.fd,
410 termios.TCSANOW,
411 [iflag, oflag, cflag, lflag, ispeed, ospeed, cc])
cliechti58b481c2009-02-16 20:42:32 +0000412
cliechtie8c45422008-06-20 23:23:14 +0000413 # apply custom baud rate, if any
414 if custom_baud is not None:
Chris Liechtid6847af2015-08-06 17:54:30 +0200415 self._set_special_baudrate(custom_baud)
416
417 if self._rs485_mode is not None:
418 self._set_rs485_mode(self._rs485_mode)
cliechti89b4af12002-02-12 23:24:41 +0000419
420 def close(self):
cliechtid6bf52c2003-10-01 02:28:12 +0000421 """Close port"""
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200422 if self.is_open:
cliechtic6178262004-03-22 22:04:52 +0000423 if self.fd is not None:
cliechtid6bf52c2003-10-01 02:28:12 +0000424 os.close(self.fd)
425 self.fd = None
Chris Liechtib658eac2016-05-22 20:51:44 +0200426 os.close(self.pipe_abort_read_w)
427 os.close(self.pipe_abort_read_r)
428 os.close(self.pipe_abort_write_w)
429 os.close(self.pipe_abort_write_r)
430 self.pipe_abort_read_r, self.pipe_abort_read_w = None, None
431 self.pipe_abort_write_r, self.pipe_abort_write_w = None, None
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200432 self.is_open = False
cliechtid6bf52c2003-10-01 02:28:12 +0000433
434 # - - - - - - - - - - - - - - - - - - - - - - - -
cliechti95c62212002-03-04 22:17:53 +0000435
Chris Liechtief1fe252015-08-27 23:25:21 +0200436 @property
437 def in_waiting(self):
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200438 """Return the number of bytes currently in the input buffer."""
Chris Liechti11465c82015-08-04 15:55:22 +0200439 #~ s = fcntl.ioctl(self.fd, termios.FIONREAD, TIOCM_zero_str)
cliechtif5831e02002-12-05 23:15:27 +0000440 s = fcntl.ioctl(self.fd, TIOCINQ, TIOCM_zero_str)
Chris Liechti033f17c2015-08-30 21:28:04 +0200441 return struct.unpack('I', s)[0]
cliechti89b4af12002-02-12 23:24:41 +0000442
cliechtia9a093e2010-01-02 03:05:08 +0000443 # select based implementation, proved to work on many systems
444 def read(self, size=1):
cliechti7d448562014-08-03 21:57:45 +0000445 """\
446 Read size bytes from the serial port. If a timeout is set it may
447 return less characters as requested. With no timeout it will block
448 until the requested number of bytes is read.
449 """
Chris Liechti033f17c2015-08-30 21:28:04 +0200450 if not self.is_open:
451 raise portNotOpenError
cliechtia9a093e2010-01-02 03:05:08 +0000452 read = bytearray()
Cristiano De Altic30622f2015-12-12 11:00:01 +0100453 timeout = self._timeout
cliechtia9a093e2010-01-02 03:05:08 +0000454 while len(read) < size:
cliechti8d744de2013-10-11 14:31:13 +0000455 try:
Cristiano De Altic30622f2015-12-12 11:00:01 +0100456 start_time = time.time()
Chris Liechti42ab2b42016-05-15 23:35:05 +0200457 ready, _, _ = select.select([self.fd, self.pipe_abort_read_r], [], [], timeout)
458 if self.pipe_abort_read_r in ready:
Chris Liechti68cecce2016-06-03 23:52:34 +0200459 os.read(self.pipe_abort_read_r, 1000)
Chris Liechti42ab2b42016-05-15 23:35:05 +0200460 break
cliechti8d744de2013-10-11 14:31:13 +0000461 # If select was used with a timeout, and the timeout occurs, it
462 # returns with empty lists -> thus abort read operation.
Chris Liechti033f17c2015-08-30 21:28:04 +0200463 # For timeout == 0 (non-blocking operation) also abort when
464 # there is nothing to read.
cliechti8d744de2013-10-11 14:31:13 +0000465 if not ready:
466 break # timeout
Chris Liechti033f17c2015-08-30 21:28:04 +0200467 buf = os.read(self.fd, size - len(read))
cliechti8d744de2013-10-11 14:31:13 +0000468 # read should always return some data as select reported it was
469 # ready to read when we get to this point.
470 if not buf:
471 # Disconnected devices, at least on Linux, show the
472 # behavior that they are always ready to read immediately
473 # but reading returns nothing.
Chris Liechti92df95a2016-02-09 23:30:37 +0100474 raise SerialException(
475 'device reports readiness to read but returned no data '
476 '(device disconnected or multiple access on port?)')
cliechti8d744de2013-10-11 14:31:13 +0000477 read.extend(buf)
Chris Liechti68340d72015-08-03 14:15:48 +0200478 except OSError as e:
Chris Liechti033f17c2015-08-30 21:28:04 +0200479 # this is for Python 3.x where select.error is a subclass of
480 # OSError ignore EAGAIN errors. all other errors are shown
nexcvon50ec2232016-05-24 15:48:46 +0800481 if e.errno != errno.EAGAIN and e.errno != errno.EINTR:
Chris Liechti984c5c52016-02-15 23:48:45 +0100482 raise SerialException('read failed: {}'.format(e))
Chris Liechti68340d72015-08-03 14:15:48 +0200483 except select.error as e:
cliechtic7cd7212014-08-03 21:34:38 +0000484 # this is for Python 2.x
cliechti8d744de2013-10-11 14:31:13 +0000485 # ignore EAGAIN errors. all other errors are shown
486 # see also http://www.python.org/dev/peps/pep-3151/#select
487 if e[0] != errno.EAGAIN:
Chris Liechti984c5c52016-02-15 23:48:45 +0100488 raise SerialException('read failed: {}'.format(e))
nexcvon50ec2232016-05-24 15:48:46 +0800489 if timeout is not None:
490 timeout -= time.time() - start_time
491 if timeout <= 0:
492 break
cliechtia9a093e2010-01-02 03:05:08 +0000493 return bytes(read)
cliechti89b4af12002-02-12 23:24:41 +0000494
Chris Liechti42ab2b42016-05-15 23:35:05 +0200495 def cancel_read(self):
496 os.write(self.pipe_abort_read_w, b"x")
497
Chris Liechti13949c62016-05-16 22:45:38 +0200498 def cancel_write(self):
499 os.write(self.pipe_abort_write_w, b"x")
500
cliechti4a567a02009-07-27 22:09:31 +0000501 def write(self, data):
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200502 """Output the given byte string over the serial port."""
Chris Liechti033f17c2015-08-30 21:28:04 +0200503 if not self.is_open:
504 raise portNotOpenError
cliechti38077122013-10-16 02:57:27 +0000505 d = to_bytes(data)
506 tx_len = len(d)
Robert Smallshire325a7382016-03-25 21:18:38 +0100507 timeout = self._write_timeout
508 if timeout and timeout > 0: # Avoid comparing None with zero
509 timeout += time.time()
cliechti9f7c2352013-10-11 01:13:46 +0000510 while tx_len > 0:
cliechti5d4d0bd2004-11-13 03:27:39 +0000511 try:
cliechti5d4d0bd2004-11-13 03:27:39 +0000512 n = os.write(self.fd, d)
Robert Smallshire325a7382016-03-25 21:18:38 +0100513 if timeout == 0:
514 # Zero timeout indicates non-blocking - simply return the
515 # number of bytes of data actually written
516 return n
517 elif timeout and timeout > 0: # Avoid comparing None with zero
cliechti3cf46d62009-08-07 00:19:57 +0000518 # when timeout is set, use select to wait for being ready
519 # with the time left as timeout
520 timeleft = timeout - time.time()
521 if timeleft < 0:
522 raise writeTimeoutError
Chris Liechti13949c62016-05-16 22:45:38 +0200523 abort, ready, _ = select.select([self.pipe_abort_write_r], [self.fd], [], timeleft)
524 if abort:
Chris Liechti68cecce2016-06-03 23:52:34 +0200525 os.read(self.pipe_abort_write_r, 1000)
Chris Liechti13949c62016-05-16 22:45:38 +0200526 break
cliechti5d4d0bd2004-11-13 03:27:39 +0000527 if not ready:
528 raise writeTimeoutError
cliechti88c62442013-10-12 04:03:16 +0000529 else:
Robert Smallshire325a7382016-03-25 21:18:38 +0100530 assert timeout is None
cliechti88c62442013-10-12 04:03:16 +0000531 # wait for write operation
Chris Liechti13949c62016-05-16 22:45:38 +0200532 abort, ready, _ = select.select([self.pipe_abort_write_r], [self.fd], [], None)
533 if abort:
534 os.read(self.pipe_abort_write_r, 1)
535 break
cliechti88c62442013-10-12 04:03:16 +0000536 if not ready:
537 raise SerialException('write failed (select)')
cliechti5d4d0bd2004-11-13 03:27:39 +0000538 d = d[n:]
cliechti9f7c2352013-10-11 01:13:46 +0000539 tx_len -= n
Chris Liechti675f7e12015-08-03 15:48:41 +0200540 except SerialException:
541 raise
Chris Liechti68340d72015-08-03 14:15:48 +0200542 except OSError as v:
cliechti5d4d0bd2004-11-13 03:27:39 +0000543 if v.errno != errno.EAGAIN:
Chris Liechti984c5c52016-02-15 23:48:45 +0100544 raise SerialException('write failed: {}'.format(v))
Chris Liechtic6362db2015-12-13 23:44:35 +0100545 # still calculate and check timeout
546 if timeout and timeout - time.time() < 0:
547 raise writeTimeoutError
cliechtif81362e2009-07-25 03:44:33 +0000548 return len(data)
cliechtid6bf52c2003-10-01 02:28:12 +0000549
cliechtia30a8a02003-10-05 12:28:13 +0000550 def flush(self):
cliechti7d448562014-08-03 21:57:45 +0000551 """\
552 Flush of file like objects. In this case, wait until all data
553 is written.
554 """
Chris Liechti033f17c2015-08-30 21:28:04 +0200555 if not self.is_open:
556 raise portNotOpenError
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200557 termios.tcdrain(self.fd)
cliechtia30a8a02003-10-05 12:28:13 +0000558
Chris Liechtief1fe252015-08-27 23:25:21 +0200559 def reset_input_buffer(self):
cliechtid6bf52c2003-10-01 02:28:12 +0000560 """Clear input buffer, discarding all that is in the buffer."""
Chris Liechti033f17c2015-08-30 21:28:04 +0200561 if not self.is_open:
562 raise portNotOpenError
Chris Liechti11465c82015-08-04 15:55:22 +0200563 termios.tcflush(self.fd, termios.TCIFLUSH)
cliechti89b4af12002-02-12 23:24:41 +0000564
Chris Liechtief1fe252015-08-27 23:25:21 +0200565 def reset_output_buffer(self):
cliechti7d448562014-08-03 21:57:45 +0000566 """\
567 Clear output buffer, aborting the current output and discarding all
568 that is in the buffer.
569 """
Chris Liechti033f17c2015-08-30 21:28:04 +0200570 if not self.is_open:
571 raise portNotOpenError
Chris Liechti11465c82015-08-04 15:55:22 +0200572 termios.tcflush(self.fd, termios.TCOFLUSH)
cliechti89b4af12002-02-12 23:24:41 +0000573
Chris Liechtief1fe252015-08-27 23:25:21 +0200574 def send_break(self, duration=0.25):
cliechti7d448562014-08-03 21:57:45 +0000575 """\
576 Send break condition. Timed, returns to idle state after given
577 duration.
578 """
Chris Liechti033f17c2015-08-30 21:28:04 +0200579 if not self.is_open:
580 raise portNotOpenError
581 termios.tcsendbreak(self.fd, int(duration / 0.25))
cliechti89b4af12002-02-12 23:24:41 +0000582
Chris Liechtief1fe252015-08-27 23:25:21 +0200583 def _update_break_state(self):
cliechti7d448562014-08-03 21:57:45 +0000584 """\
585 Set break: Controls TXD. When active, no transmitting is possible.
586 """
Chris Liechtief1fe252015-08-27 23:25:21 +0200587 if self._break_state:
cliechti997b63c2008-06-21 00:09:31 +0000588 fcntl.ioctl(self.fd, TIOCSBRK)
589 else:
590 fcntl.ioctl(self.fd, TIOCCBRK)
591
Chris Liechtief1fe252015-08-27 23:25:21 +0200592 def _update_rts_state(self):
cliechtid6bf52c2003-10-01 02:28:12 +0000593 """Set terminal status line: Request To Send"""
Chris Liechtif7534c82016-05-07 23:35:54 +0200594 if self._rts_state:
595 fcntl.ioctl(self.fd, TIOCMBIS, TIOCM_RTS_str)
596 else:
597 fcntl.ioctl(self.fd, TIOCMBIC, TIOCM_RTS_str)
cliechtid6bf52c2003-10-01 02:28:12 +0000598
Chris Liechtief1fe252015-08-27 23:25:21 +0200599 def _update_dtr_state(self):
cliechtid6bf52c2003-10-01 02:28:12 +0000600 """Set terminal status line: Data Terminal Ready"""
Chris Liechtif7534c82016-05-07 23:35:54 +0200601 if self._dtr_state:
602 fcntl.ioctl(self.fd, TIOCMBIS, TIOCM_DTR_str)
603 else:
604 fcntl.ioctl(self.fd, TIOCMBIC, TIOCM_DTR_str)
cliechtid6bf52c2003-10-01 02:28:12 +0000605
Chris Liechtief1fe252015-08-27 23:25:21 +0200606 @property
607 def cts(self):
cliechtid6bf52c2003-10-01 02:28:12 +0000608 """Read terminal status line: Clear To Send"""
Chris Liechti033f17c2015-08-30 21:28:04 +0200609 if not self.is_open:
610 raise portNotOpenError
cliechtid6bf52c2003-10-01 02:28:12 +0000611 s = fcntl.ioctl(self.fd, TIOCMGET, TIOCM_zero_str)
Chris Liechti033f17c2015-08-30 21:28:04 +0200612 return struct.unpack('I', s)[0] & TIOCM_CTS != 0
cliechtid6bf52c2003-10-01 02:28:12 +0000613
Chris Liechtief1fe252015-08-27 23:25:21 +0200614 @property
615 def dsr(self):
cliechtid6bf52c2003-10-01 02:28:12 +0000616 """Read terminal status line: Data Set Ready"""
Chris Liechti033f17c2015-08-30 21:28:04 +0200617 if not self.is_open:
618 raise portNotOpenError
cliechtid6bf52c2003-10-01 02:28:12 +0000619 s = fcntl.ioctl(self.fd, TIOCMGET, TIOCM_zero_str)
Chris Liechti033f17c2015-08-30 21:28:04 +0200620 return struct.unpack('I', s)[0] & TIOCM_DSR != 0
cliechtid6bf52c2003-10-01 02:28:12 +0000621
Chris Liechtief1fe252015-08-27 23:25:21 +0200622 @property
623 def ri(self):
cliechtid6bf52c2003-10-01 02:28:12 +0000624 """Read terminal status line: Ring Indicator"""
Chris Liechti033f17c2015-08-30 21:28:04 +0200625 if not self.is_open:
626 raise portNotOpenError
cliechti89b4af12002-02-12 23:24:41 +0000627 s = fcntl.ioctl(self.fd, TIOCMGET, TIOCM_zero_str)
Chris Liechti033f17c2015-08-30 21:28:04 +0200628 return struct.unpack('I', s)[0] & TIOCM_RI != 0
cliechti89b4af12002-02-12 23:24:41 +0000629
Chris Liechtief1fe252015-08-27 23:25:21 +0200630 @property
631 def cd(self):
cliechtid6bf52c2003-10-01 02:28:12 +0000632 """Read terminal status line: Carrier Detect"""
Chris Liechti033f17c2015-08-30 21:28:04 +0200633 if not self.is_open:
634 raise portNotOpenError
cliechti89b4af12002-02-12 23:24:41 +0000635 s = fcntl.ioctl(self.fd, TIOCMGET, TIOCM_zero_str)
Chris Liechti033f17c2015-08-30 21:28:04 +0200636 return struct.unpack('I', s)[0] & TIOCM_CD != 0
cliechti89b4af12002-02-12 23:24:41 +0000637
cliechtia30a8a02003-10-05 12:28:13 +0000638 # - - platform specific - - - -
639
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200640 @property
641 def out_waiting(self):
642 """Return the number of bytes currently in the output buffer."""
Chris Liechti11465c82015-08-04 15:55:22 +0200643 #~ s = fcntl.ioctl(self.fd, termios.FIONREAD, TIOCM_zero_str)
cliechti28b8fd02011-12-28 21:39:42 +0000644 s = fcntl.ioctl(self.fd, TIOCOUTQ, TIOCM_zero_str)
Chris Liechti033f17c2015-08-30 21:28:04 +0200645 return struct.unpack('I', s)[0]
cliechti28b8fd02011-12-28 21:39:42 +0000646
cliechti8753bbc2005-01-15 20:32:51 +0000647 def fileno(self):
cliechti2f0f8a32011-12-28 22:10:00 +0000648 """\
649 For easier use of the serial port instance with select.
650 WARNING: this function is not portable to different platforms!
651 """
Chris Liechti033f17c2015-08-30 21:28:04 +0200652 if not self.is_open:
653 raise portNotOpenError
cliechti8753bbc2005-01-15 20:32:51 +0000654 return self.fd
cliechti89b4af12002-02-12 23:24:41 +0000655
Chris Liechti518b0d32015-08-30 02:20:39 +0200656 def set_input_flow_control(self, enable=True):
cliechti2f0f8a32011-12-28 22:10:00 +0000657 """\
658 Manually control flow - when software flow control is enabled.
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200659 This will send XON (true) or XOFF (false) to the other device.
cliechti2f0f8a32011-12-28 22:10:00 +0000660 WARNING: this function is not portable to different platforms!
661 """
Chris Liechti033f17c2015-08-30 21:28:04 +0200662 if not self.is_open:
663 raise portNotOpenError
cliechti4a601342011-12-29 02:22:17 +0000664 if enable:
Chris Liechti11465c82015-08-04 15:55:22 +0200665 termios.tcflow(self.fd, termios.TCION)
cliechti57e48a62009-08-03 22:29:58 +0000666 else:
Chris Liechti11465c82015-08-04 15:55:22 +0200667 termios.tcflow(self.fd, termios.TCIOFF)
cliechti57e48a62009-08-03 22:29:58 +0000668
Chris Liechti518b0d32015-08-30 02:20:39 +0200669 def set_output_flow_control(self, enable=True):
cliechti2f0f8a32011-12-28 22:10:00 +0000670 """\
671 Manually control flow of outgoing data - when hardware or software flow
672 control is enabled.
673 WARNING: this function is not portable to different platforms!
674 """
Chris Liechti033f17c2015-08-30 21:28:04 +0200675 if not self.is_open:
676 raise portNotOpenError
cliechti2f0f8a32011-12-28 22:10:00 +0000677 if enable:
Chris Liechti11465c82015-08-04 15:55:22 +0200678 termios.tcflow(self.fd, termios.TCOON)
cliechti2f0f8a32011-12-28 22:10:00 +0000679 else:
Chris Liechti11465c82015-08-04 15:55:22 +0200680 termios.tcflow(self.fd, termios.TCOOFF)
cliechti2f0f8a32011-12-28 22:10:00 +0000681
Chris Liechti59848422016-06-04 22:28:14 +0200682 def nonblocking(self):
683 """DEPRECATED - has no use"""
684 import warnings
685 warnings.warn("nonblocking() has no effect, already nonblocking", DeprecationWarning)
686
cliechtif81362e2009-07-25 03:44:33 +0000687
cliechtia9a093e2010-01-02 03:05:08 +0000688class PosixPollSerial(Serial):
cliechti7d448562014-08-03 21:57:45 +0000689 """\
cliechtif0a81d42014-08-04 14:03:53 +0000690 Poll based read implementation. Not all systems support poll properly.
691 However this one has better handling of errors, such as a device
cliechti7d448562014-08-03 21:57:45 +0000692 disconnecting while it's in use (e.g. USB-serial unplugged).
693 """
cliechtia9a093e2010-01-02 03:05:08 +0000694
695 def read(self, size=1):
cliechti7d448562014-08-03 21:57:45 +0000696 """\
697 Read size bytes from the serial port. If a timeout is set it may
698 return less characters as requested. With no timeout it will block
699 until the requested number of bytes is read.
700 """
Chris Liechtiacac2362016-03-29 22:37:48 +0200701 if not self.is_open:
Chris Liechti033f17c2015-08-30 21:28:04 +0200702 raise portNotOpenError
cliechtia9a093e2010-01-02 03:05:08 +0000703 read = bytearray()
704 poll = select.poll()
Chris Liechti033f17c2015-08-30 21:28:04 +0200705 poll.register(self.fd, select.POLLIN | select.POLLERR | select.POLLHUP | select.POLLNVAL)
cliechtia9a093e2010-01-02 03:05:08 +0000706 if size > 0:
707 while len(read) < size:
708 # print "\tread(): size",size, "have", len(read) #debug
709 # wait until device becomes ready to read (or something fails)
Chris Liechti033f17c2015-08-30 21:28:04 +0200710 for fd, event in poll.poll(self._timeout * 1000):
711 if event & (select.POLLERR | select.POLLHUP | select.POLLNVAL):
cliechtia9a093e2010-01-02 03:05:08 +0000712 raise SerialException('device reports error (poll)')
713 # we don't care if it is select.POLLIN or timeout, that's
714 # handled below
715 buf = os.read(self.fd, size - len(read))
716 read.extend(buf)
Chris Liechti518b0d32015-08-30 02:20:39 +0200717 if ((self._timeout is not None and self._timeout >= 0) or
Chris Liechti033f17c2015-08-30 21:28:04 +0200718 (self._inter_byte_timeout is not None and self._inter_byte_timeout > 0)) and not buf:
cliechtia9a093e2010-01-02 03:05:08 +0000719 break # early abort on timeout
720 return bytes(read)
721
cliechtif81362e2009-07-25 03:44:33 +0000722
Chris Liechti4cf54702015-10-18 00:21:56 +0200723class VTIMESerial(Serial):
724 """\
725 Implement timeout using vtime of tty device instead of using select.
726 This means that no inter character timeout can be specified and that
727 the error handling is degraded.
728
729 Overall timeout is disabled when inter-character timeout is used.
730 """
731
Chris Liechti94284702015-11-15 01:21:48 +0100732 def _reconfigure_port(self, force_update=True):
Chris Liechti4cf54702015-10-18 00:21:56 +0200733 """Set communication parameters on opened port."""
734 super(VTIMESerial, self)._reconfigure_port()
Chris Liechtid6bcaaf2016-02-01 22:55:26 +0100735 fcntl.fcntl(self.fd, fcntl.F_SETFL, 0) # clear O_NONBLOCK
Chris Liechti4cf54702015-10-18 00:21:56 +0200736
737 if self._inter_byte_timeout is not None:
738 vmin = 1
739 vtime = int(self._inter_byte_timeout * 10)
Chris Liechti3ec9c412016-08-08 01:06:46 +0200740 elif self._timeout is None:
741 vmin = 1
742 vtime = 0
Chris Liechti4cf54702015-10-18 00:21:56 +0200743 else:
744 vmin = 0
745 vtime = int(self._timeout * 10)
746 try:
747 orig_attr = termios.tcgetattr(self.fd)
748 iflag, oflag, cflag, lflag, ispeed, ospeed, cc = orig_attr
749 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 +0100750 raise serial.SerialException("Could not configure port: {}".format(msg))
Chris Liechti4cf54702015-10-18 00:21:56 +0200751
752 if vtime < 0 or vtime > 255:
Chris Liechti984c5c52016-02-15 23:48:45 +0100753 raise ValueError('Invalid vtime: {!r}'.format(vtime))
Chris Liechti4cf54702015-10-18 00:21:56 +0200754 cc[termios.VTIME] = vtime
755 cc[termios.VMIN] = vmin
756
757 termios.tcsetattr(
758 self.fd,
759 termios.TCSANOW,
760 [iflag, oflag, cflag, lflag, ispeed, ospeed, cc])
761
Chris Liechti4cf54702015-10-18 00:21:56 +0200762 def read(self, size=1):
763 """\
764 Read size bytes from the serial port. If a timeout is set it may
765 return less characters as requested. With no timeout it will block
766 until the requested number of bytes is read.
767 """
768 if not self.is_open:
769 raise portNotOpenError
770 read = bytearray()
771 while len(read) < size:
772 buf = os.read(self.fd, size - len(read))
773 if not buf:
774 break
775 read.extend(buf)
776 return bytes(read)
Chris Liechti3ec9c412016-08-08 01:06:46 +0200777
778 # hack to make hasattr return false
779 cancel_read = property()