blob: 507e2fe061edd60a08c5ada846941dc3ace13d9c [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
Kurt McKee057387c2018-02-07 22:10:38 -060029from __future__ import absolute_import
30
Chris Liechti9eaa40c2016-02-12 23:32:59 +010031# pylint: disable=abstract-method
Chris Liechti33f0ec52015-08-06 16:37:21 +020032import errno
33import fcntl
Chris Liechti33f0ec52015-08-06 16:37:21 +020034import os
35import select
36import struct
37import sys
38import termios
Chris Liechti033f17c2015-08-30 21:28:04 +020039
40import serial
Chris Liechti935a2622016-08-30 23:39:15 +020041from serial.serialutil import SerialBase, SerialException, to_bytes, \
42 portNotOpenError, writeTimeoutError, Timeout
cliechti89b4af12002-02-12 23:24:41 +000043
cliechti89b4af12002-02-12 23:24:41 +000044
Chris Liechtid6847af2015-08-06 17:54:30 +020045class PlatformSpecificBase(object):
46 BAUDRATE_CONSTANTS = {}
cliechti89b4af12002-02-12 23:24:41 +000047
Chris Liechtid6847af2015-08-06 17:54:30 +020048 def _set_special_baudrate(self, baudrate):
49 raise NotImplementedError('non-standard baudrates are not supported on this platform')
50
51 def _set_rs485_mode(self, rs485_settings):
52 raise NotImplementedError('RS485 not supported on this platform')
53
Jan Kantert1b2658a2018-05-07 21:17:37 +020054 def set_low_latency_mode(self, low_latency_settings):
55 raise NotImplementedError('Low latency not supported on this platform')
56
Chris Liechti6dc58e82016-08-29 23:02:13 +020057
58# some systems support an extra flag to enable the two in POSIX unsupported
Chris Liechti11538242016-09-06 22:20:09 +020059# paritiy settings for MARK and SPACE
Chris Liechti6dc58e82016-08-29 23:02:13 +020060CMSPAR = 0 # default, for unsupported platforms, override below
61
Chris Liechtid6847af2015-08-06 17:54:30 +020062# try to detect the OS so that a device can be selected...
63# this code block should supply a device() and set_special_baudrate() function
64# for the platform
65plat = sys.platform.lower()
66
Chris Liechtiba45c522016-02-06 23:53:23 +010067if plat[:5] == 'linux': # Linux (confirmed) # noqa
Chris Liechtid6847af2015-08-06 17:54:30 +020068 import array
69
Chris Liechti6dc58e82016-08-29 23:02:13 +020070 # extra termios flags
71 CMSPAR = 0o10000000000 # Use "stick" (mark/space) parity
72
Chris Liechtid6847af2015-08-06 17:54:30 +020073 # baudrate ioctls
74 TCGETS2 = 0x802C542A
75 TCSETS2 = 0x402C542B
76 BOTHER = 0o010000
77
78 # RS485 ioctls
79 TIOCGRS485 = 0x542E
80 TIOCSRS485 = 0x542F
Chris Liechti033f17c2015-08-30 21:28:04 +020081 SER_RS485_ENABLED = 0b00000001
82 SER_RS485_RTS_ON_SEND = 0b00000010
Chris Liechtid6847af2015-08-06 17:54:30 +020083 SER_RS485_RTS_AFTER_SEND = 0b00000100
Chris Liechti033f17c2015-08-30 21:28:04 +020084 SER_RS485_RX_DURING_TX = 0b00010000
Chris Liechtid6847af2015-08-06 17:54:30 +020085
86 class PlatformSpecific(PlatformSpecificBase):
87 BAUDRATE_CONSTANTS = {
88 0: 0o000000, # hang up
89 50: 0o000001,
90 75: 0o000002,
91 110: 0o000003,
92 134: 0o000004,
93 150: 0o000005,
94 200: 0o000006,
95 300: 0o000007,
96 600: 0o000010,
97 1200: 0o000011,
98 1800: 0o000012,
99 2400: 0o000013,
100 4800: 0o000014,
101 9600: 0o000015,
102 19200: 0o000016,
103 38400: 0o000017,
104 57600: 0o010001,
105 115200: 0o010002,
106 230400: 0o010003,
107 460800: 0o010004,
108 500000: 0o010005,
109 576000: 0o010006,
110 921600: 0o010007,
111 1000000: 0o010010,
112 1152000: 0o010011,
113 1500000: 0o010012,
114 2000000: 0o010013,
115 2500000: 0o010014,
116 3000000: 0o010015,
117 3500000: 0o010016,
118 4000000: 0o010017
119 }
120
Jan Kantert1b2658a2018-05-07 21:17:37 +0200121 def set_low_latency_mode(self, low_latency_settings):
122 buf = array.array('i', [0] * 32)
123
124 try:
125 # get serial_struct
126 fcntl.ioctl(self.fd, termios.TIOCGSERIAL, buf)
127
128 # set or unset ASYNC_LOW_LATENCY flag
129 if low_latency_settings:
130 buf[4] |= 0x2000
131 else:
132 buf[4] &= ~0x2000
133
134 # set serial_struct
135 fcntl.ioctl(self.fd, termios.TIOCSSERIAL, buf)
136 except IOError as e:
137 raise ValueError('Failed to update ASYNC_LOW_LATENCY flag to {}: {}'.format(low_latency_settings, e))
138
Chris Liechtid6847af2015-08-06 17:54:30 +0200139 def _set_special_baudrate(self, baudrate):
140 # right size is 44 on x86_64, allow for some growth
141 buf = array.array('i', [0] * 64)
142 try:
143 # get serial_struct
144 fcntl.ioctl(self.fd, TCGETS2, buf)
145 # set custom speed
146 buf[2] &= ~termios.CBAUD
147 buf[2] |= BOTHER
148 buf[9] = buf[10] = baudrate
149
150 # set serial_struct
Chris Liechti033f17c2015-08-30 21:28:04 +0200151 fcntl.ioctl(self.fd, TCSETS2, buf)
Chris Liechtid6847af2015-08-06 17:54:30 +0200152 except IOError as e:
Chris Liechti984c5c52016-02-15 23:48:45 +0100153 raise ValueError('Failed to set custom baud rate ({}): {}'.format(baudrate, e))
Chris Liechtid6847af2015-08-06 17:54:30 +0200154
155 def _set_rs485_mode(self, rs485_settings):
Chris Liechti033f17c2015-08-30 21:28:04 +0200156 buf = array.array('i', [0] * 8) # flags, delaytx, delayrx, padding
Chris Liechtid6847af2015-08-06 17:54:30 +0200157 try:
158 fcntl.ioctl(self.fd, TIOCGRS485, buf)
Chris Liechti7a554462016-03-24 21:17:22 +0100159 buf[0] |= SER_RS485_ENABLED
Chris Liechtid6847af2015-08-06 17:54:30 +0200160 if rs485_settings is not None:
161 if rs485_settings.loopback:
162 buf[0] |= SER_RS485_RX_DURING_TX
163 else:
164 buf[0] &= ~SER_RS485_RX_DURING_TX
165 if rs485_settings.rts_level_for_tx:
166 buf[0] |= SER_RS485_RTS_ON_SEND
167 else:
168 buf[0] &= ~SER_RS485_RTS_ON_SEND
169 if rs485_settings.rts_level_for_rx:
170 buf[0] |= SER_RS485_RTS_AFTER_SEND
171 else:
172 buf[0] &= ~SER_RS485_RTS_AFTER_SEND
Chris Liechti279201b2016-06-09 20:27:05 +0200173 if rs485_settings.delay_before_tx is not None:
174 buf[1] = int(rs485_settings.delay_before_tx * 1000)
175 if rs485_settings.delay_before_rx is not None:
176 buf[2] = int(rs485_settings.delay_before_rx * 1000)
Chris Liechtid6847af2015-08-06 17:54:30 +0200177 else:
178 buf[0] = 0 # clear SER_RS485_ENABLED
Chris Liechti033f17c2015-08-30 21:28:04 +0200179 fcntl.ioctl(self.fd, TIOCSRS485, buf)
Chris Liechtid6847af2015-08-06 17:54:30 +0200180 except IOError as e:
Chris Liechti984c5c52016-02-15 23:48:45 +0100181 raise ValueError('Failed to set RS485 mode: {}'.format(e))
Chris Liechtid6847af2015-08-06 17:54:30 +0200182
183
184elif plat == 'cygwin': # cygwin/win32 (confirmed)
185
186 class PlatformSpecific(PlatformSpecificBase):
187 BAUDRATE_CONSTANTS = {
188 128000: 0x01003,
189 256000: 0x01005,
190 500000: 0x01007,
191 576000: 0x01008,
192 921600: 0x01009,
193 1000000: 0x0100a,
194 1152000: 0x0100b,
195 1500000: 0x0100c,
196 2000000: 0x0100d,
197 2500000: 0x0100e,
198 3000000: 0x0100f
199 }
200
Chris Liechtid6847af2015-08-06 17:54:30 +0200201
202elif plat[:6] == 'darwin': # OS X
203 import array
Chris Liechti033f17c2015-08-30 21:28:04 +0200204 IOSSIOSPEED = 0x80045402 # _IOW('T', 2, speed_t)
Chris Liechtid6847af2015-08-06 17:54:30 +0200205
206 class PlatformSpecific(PlatformSpecificBase):
Chris Liechtid6847af2015-08-06 17:54:30 +0200207 osx_version = os.uname()[2].split('.')
208 # Tiger or above can support arbitrary serial speeds
209 if int(osx_version[0]) >= 8:
210 def _set_special_baudrate(self, baudrate):
211 # use IOKit-specific call to set up high speeds
212 buf = array.array('i', [baudrate])
213 fcntl.ioctl(self.fd, IOSSIOSPEED, buf, 1)
214
Chris Liechti21a306b2016-10-09 23:41:26 +0200215elif plat[:3] == 'bsd' or \
216 plat[:7] == 'freebsd' or \
217 plat[:6] == 'netbsd' or \
218 plat[:7] == 'openbsd':
219
220 class ReturnBaudrate(object):
221 def __getitem__(self, key):
222 return key
223
224 class PlatformSpecific(PlatformSpecificBase):
225 # Only tested on FreeBSD:
226 # The baud rate may be passed in as
227 # a literal value.
228 BAUDRATE_CONSTANTS = ReturnBaudrate()
229
Chris Liechtid6847af2015-08-06 17:54:30 +0200230else:
231 class PlatformSpecific(PlatformSpecificBase):
232 pass
cliechti89b4af12002-02-12 23:24:41 +0000233
cliechti89b4af12002-02-12 23:24:41 +0000234
cliechti58b481c2009-02-16 20:42:32 +0000235# load some constants for later use.
Chris Liechti11465c82015-08-04 15:55:22 +0200236# try to use values from termios, use defaults from linux otherwise
Chris Liechti033f17c2015-08-30 21:28:04 +0200237TIOCMGET = getattr(termios, 'TIOCMGET', 0x5415)
238TIOCMBIS = getattr(termios, 'TIOCMBIS', 0x5416)
239TIOCMBIC = getattr(termios, 'TIOCMBIC', 0x5417)
240TIOCMSET = getattr(termios, 'TIOCMSET', 0x5418)
cliechti89b4af12002-02-12 23:24:41 +0000241
Chris Liechti033f17c2015-08-30 21:28:04 +0200242# TIOCM_LE = getattr(termios, 'TIOCM_LE', 0x001)
Chris Liechtid6847af2015-08-06 17:54:30 +0200243TIOCM_DTR = getattr(termios, 'TIOCM_DTR', 0x002)
244TIOCM_RTS = getattr(termios, 'TIOCM_RTS', 0x004)
Chris Liechti033f17c2015-08-30 21:28:04 +0200245# TIOCM_ST = getattr(termios, 'TIOCM_ST', 0x008)
246# TIOCM_SR = getattr(termios, 'TIOCM_SR', 0x010)
cliechti89b4af12002-02-12 23:24:41 +0000247
Chris Liechtid6847af2015-08-06 17:54:30 +0200248TIOCM_CTS = getattr(termios, 'TIOCM_CTS', 0x020)
249TIOCM_CAR = getattr(termios, 'TIOCM_CAR', 0x040)
250TIOCM_RNG = getattr(termios, 'TIOCM_RNG', 0x080)
251TIOCM_DSR = getattr(termios, 'TIOCM_DSR', 0x100)
Chris Liechti033f17c2015-08-30 21:28:04 +0200252TIOCM_CD = getattr(termios, 'TIOCM_CD', TIOCM_CAR)
253TIOCM_RI = getattr(termios, 'TIOCM_RI', TIOCM_RNG)
254# TIOCM_OUT1 = getattr(termios, 'TIOCM_OUT1', 0x2000)
255# TIOCM_OUT2 = getattr(termios, 'TIOCM_OUT2', 0x4000)
Chris Liechti11465c82015-08-04 15:55:22 +0200256if hasattr(termios, 'TIOCINQ'):
257 TIOCINQ = termios.TIOCINQ
cliechti28b8fd02011-12-28 21:39:42 +0000258else:
Chris Liechtid6847af2015-08-06 17:54:30 +0200259 TIOCINQ = getattr(termios, 'FIONREAD', 0x541B)
Chris Liechti033f17c2015-08-30 21:28:04 +0200260TIOCOUTQ = getattr(termios, 'TIOCOUTQ', 0x5411)
cliechti89b4af12002-02-12 23:24:41 +0000261
262TIOCM_zero_str = struct.pack('I', 0)
263TIOCM_RTS_str = struct.pack('I', TIOCM_RTS)
264TIOCM_DTR_str = struct.pack('I', TIOCM_DTR)
265
Chris Liechti033f17c2015-08-30 21:28:04 +0200266TIOCSBRK = getattr(termios, 'TIOCSBRK', 0x5427)
267TIOCCBRK = getattr(termios, 'TIOCCBRK', 0x5428)
cliechti997b63c2008-06-21 00:09:31 +0000268
cliechti89b4af12002-02-12 23:24:41 +0000269
Chris Liechtief6b7b42015-08-06 22:19:26 +0200270class Serial(SerialBase, PlatformSpecific):
cliechti7d448562014-08-03 21:57:45 +0000271 """\
Chris Liechti033f17c2015-08-30 21:28:04 +0200272 Serial port class POSIX implementation. Serial port configuration is
cliechtid6bf52c2003-10-01 02:28:12 +0000273 done with termios and fcntl. Runs on Linux and many other Un*x like
cliechtif0a81d42014-08-04 14:03:53 +0000274 systems.
275 """
cliechtid6bf52c2003-10-01 02:28:12 +0000276
277 def open(self):
cliechti7d448562014-08-03 21:57:45 +0000278 """\
279 Open port with current settings. This may throw a SerialException
280 if the port cannot be opened."""
cliechtid6bf52c2003-10-01 02:28:12 +0000281 if self._port is None:
282 raise SerialException("Port must be configured before it can be used.")
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200283 if self.is_open:
cliechti02ef43a2011-03-24 23:33:12 +0000284 raise SerialException("Port is already open.")
285 self.fd = None
cliechti58b481c2009-02-16 20:42:32 +0000286 # open
cliechti4616bf12002-04-08 23:13:14 +0000287 try:
Chris Liechti033f17c2015-08-30 21:28:04 +0200288 self.fd = os.open(self.portstr, os.O_RDWR | os.O_NOCTTY | os.O_NONBLOCK)
Chris Liechti68340d72015-08-03 14:15:48 +0200289 except OSError as msg:
cliechti4616bf12002-04-08 23:13:14 +0000290 self.fd = None
Chris Liechti984c5c52016-02-15 23:48:45 +0100291 raise SerialException(msg.errno, "could not open port {}: {}".format(self._port, msg))
Chris Liechti11465c82015-08-04 15:55:22 +0200292 #~ fcntl.fcntl(self.fd, fcntl.F_SETFL, 0) # set blocking
cliechti58b481c2009-02-16 20:42:32 +0000293
cliechtib2f5fc82006-10-20 00:09:07 +0000294 try:
Chris Liechti94284702015-11-15 01:21:48 +0100295 self._reconfigure_port(force_update=True)
cliechtib2f5fc82006-10-20 00:09:07 +0000296 except:
cliechti2750b832009-07-28 00:13:52 +0000297 try:
298 os.close(self.fd)
299 except:
300 # ignore any exception when closing the port
301 # also to keep original exception that happened when setting up
302 pass
cliechtib2f5fc82006-10-20 00:09:07 +0000303 self.fd = None
cliechtif0a4f0f2009-07-21 21:12:37 +0000304 raise
cliechtib2f5fc82006-10-20 00:09:07 +0000305 else:
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200306 self.is_open = True
Chris Liechtif2fdeb92016-05-07 23:57:50 +0200307 try:
308 if not self._dsrdtr:
309 self._update_dtr_state()
310 if not self._rtscts:
311 self._update_rts_state()
312 except IOError as e:
Chris Liechtie1029622016-10-02 23:54:36 +0200313 if e.errno in (errno.EINVAL, errno.ENOTTY):
314 # ignore Invalid argument and Inappropriate ioctl
Chris Liechtif2fdeb92016-05-07 23:57:50 +0200315 pass
316 else:
317 raise
Chris Liechtief1fe252015-08-27 23:25:21 +0200318 self.reset_input_buffer()
Chris Liechti42ab2b42016-05-15 23:35:05 +0200319 self.pipe_abort_read_r, self.pipe_abort_read_w = os.pipe()
Chris Liechti13949c62016-05-16 22:45:38 +0200320 self.pipe_abort_write_r, self.pipe_abort_write_w = os.pipe()
Chris Liechti68cecce2016-06-03 23:52:34 +0200321 fcntl.fcntl(self.pipe_abort_read_r, fcntl.F_SETFL, os.O_NONBLOCK)
322 fcntl.fcntl(self.pipe_abort_write_r, fcntl.F_SETFL, os.O_NONBLOCK)
cliechti58b481c2009-02-16 20:42:32 +0000323
Chris Liechti94284702015-11-15 01:21:48 +0100324 def _reconfigure_port(self, force_update=False):
cliechtib2f5fc82006-10-20 00:09:07 +0000325 """Set communication parameters on opened port."""
cliechtic6178262004-03-22 22:04:52 +0000326 if self.fd is None:
cliechtia9a093e2010-01-02 03:05:08 +0000327 raise SerialException("Can only operate on a valid file descriptor")
Chris Liechti1c4bc812017-03-08 02:44:04 +0100328
Rob Gaddi636cc642017-02-24 11:39:46 -0800329 # if exclusive lock is requested, create it before we modify anything else
330 if self._exclusive is not None:
331 if self._exclusive:
332 try:
333 fcntl.flock(self.fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
334 except IOError as msg:
335 raise SerialException(msg.errno, "Could not exclusively lock port {}: {}".format(self._port, msg))
336 else:
337 fcntl.flock(self.fd, fcntl.LOCK_UN)
Chris Liechti1c4bc812017-03-08 02:44:04 +0100338
cliechtie8c45422008-06-20 23:23:14 +0000339 custom_baud = None
cliechti58b481c2009-02-16 20:42:32 +0000340
cliechti2750b832009-07-28 00:13:52 +0000341 vmin = vtime = 0 # timeout is done via select
Chris Liechti518b0d32015-08-30 02:20:39 +0200342 if self._inter_byte_timeout is not None:
cliechti679bfa62008-06-20 23:58:15 +0000343 vmin = 1
Chris Liechti518b0d32015-08-30 02:20:39 +0200344 vtime = int(self._inter_byte_timeout * 10)
cliechti6ce7ab12002-11-07 02:15:00 +0000345 try:
cliechti4d0af5e2011-08-05 02:18:16 +0000346 orig_attr = termios.tcgetattr(self.fd)
347 iflag, oflag, cflag, lflag, ispeed, ospeed, cc = orig_attr
Chris Liechti68340d72015-08-03 14:15:48 +0200348 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 +0100349 raise SerialException("Could not configure port: {}".format(msg))
cliechti58b481c2009-02-16 20:42:32 +0000350 # set up raw mode / no echo / binary
Chris Liechti033f17c2015-08-30 21:28:04 +0200351 cflag |= (termios.CLOCAL | termios.CREAD)
352 lflag &= ~(termios.ICANON | termios.ECHO | termios.ECHOE |
353 termios.ECHOK | termios.ECHONL |
354 termios.ISIG | termios.IEXTEN) # |termios.ECHOPRT
355 for flag in ('ECHOCTL', 'ECHOKE'): # netbsd workaround for Erk
Chris Liechti11465c82015-08-04 15:55:22 +0200356 if hasattr(termios, flag):
357 lflag &= ~getattr(termios, flag)
cliechti58b481c2009-02-16 20:42:32 +0000358
Chris Liechti033f17c2015-08-30 21:28:04 +0200359 oflag &= ~(termios.OPOST | termios.ONLCR | termios.OCRNL)
360 iflag &= ~(termios.INLCR | termios.IGNCR | termios.ICRNL | termios.IGNBRK)
Chris Liechti11465c82015-08-04 15:55:22 +0200361 if hasattr(termios, 'IUCLC'):
362 iflag &= ~termios.IUCLC
363 if hasattr(termios, 'PARMRK'):
364 iflag &= ~termios.PARMRK
cliechti58b481c2009-02-16 20:42:32 +0000365
cliechtif0a4f0f2009-07-21 21:12:37 +0000366 # setup baud rate
cliechti89b4af12002-02-12 23:24:41 +0000367 try:
Chris Liechti984c5c52016-02-15 23:48:45 +0100368 ispeed = ospeed = getattr(termios, 'B{}'.format(self._baudrate))
cliechti895e8302004-04-20 02:40:28 +0000369 except AttributeError:
cliechtif1559d02007-11-08 23:43:58 +0000370 try:
Chris Liechtid6847af2015-08-06 17:54:30 +0200371 ispeed = ospeed = self.BAUDRATE_CONSTANTS[self._baudrate]
cliechtif1559d02007-11-08 23:43:58 +0000372 except KeyError:
cliechtie8c45422008-06-20 23:23:14 +0000373 #~ raise ValueError('Invalid baud rate: %r' % self._baudrate)
cliechtif0a4f0f2009-07-21 21:12:37 +0000374 # may need custom baud rate, it isn't in our list.
Chris Liechti11465c82015-08-04 15:55:22 +0200375 ispeed = ospeed = getattr(termios, 'B38400')
cliechtif0a4f0f2009-07-21 21:12:37 +0000376 try:
Chris Liechti033f17c2015-08-30 21:28:04 +0200377 custom_baud = int(self._baudrate) # store for later
cliechtif0a4f0f2009-07-21 21:12:37 +0000378 except ValueError:
Chris Liechti984c5c52016-02-15 23:48:45 +0100379 raise ValueError('Invalid baud rate: {!r}'.format(self._baudrate))
cliechtif0a4f0f2009-07-21 21:12:37 +0000380 else:
381 if custom_baud < 0:
Chris Liechti984c5c52016-02-15 23:48:45 +0100382 raise ValueError('Invalid baud rate: {!r}'.format(self._baudrate))
cliechti58b481c2009-02-16 20:42:32 +0000383
384 # setup char len
Chris Liechti11465c82015-08-04 15:55:22 +0200385 cflag &= ~termios.CSIZE
cliechtid6bf52c2003-10-01 02:28:12 +0000386 if self._bytesize == 8:
Chris Liechti11465c82015-08-04 15:55:22 +0200387 cflag |= termios.CS8
cliechtid6bf52c2003-10-01 02:28:12 +0000388 elif self._bytesize == 7:
Chris Liechti11465c82015-08-04 15:55:22 +0200389 cflag |= termios.CS7
cliechtid6bf52c2003-10-01 02:28:12 +0000390 elif self._bytesize == 6:
Chris Liechti11465c82015-08-04 15:55:22 +0200391 cflag |= termios.CS6
cliechtid6bf52c2003-10-01 02:28:12 +0000392 elif self._bytesize == 5:
Chris Liechti11465c82015-08-04 15:55:22 +0200393 cflag |= termios.CS5
cliechti89b4af12002-02-12 23:24:41 +0000394 else:
Chris Liechti984c5c52016-02-15 23:48:45 +0100395 raise ValueError('Invalid char len: {!r}'.format(self._bytesize))
cliechtif0a81d42014-08-04 14:03:53 +0000396 # setup stop bits
Chris Liechti033f17c2015-08-30 21:28:04 +0200397 if self._stopbits == serial.STOPBITS_ONE:
Chris Liechti11465c82015-08-04 15:55:22 +0200398 cflag &= ~(termios.CSTOPB)
Chris Liechti033f17c2015-08-30 21:28:04 +0200399 elif self._stopbits == serial.STOPBITS_ONE_POINT_FIVE:
400 cflag |= (termios.CSTOPB) # XXX same as TWO.. there is no POSIX support for 1.5
401 elif self._stopbits == serial.STOPBITS_TWO:
402 cflag |= (termios.CSTOPB)
cliechti89b4af12002-02-12 23:24:41 +0000403 else:
Chris Liechti984c5c52016-02-15 23:48:45 +0100404 raise ValueError('Invalid stop bit specification: {!r}'.format(self._stopbits))
cliechti58b481c2009-02-16 20:42:32 +0000405 # setup parity
Chris Liechti033f17c2015-08-30 21:28:04 +0200406 iflag &= ~(termios.INPCK | termios.ISTRIP)
407 if self._parity == serial.PARITY_NONE:
Chris Liechti6dc58e82016-08-29 23:02:13 +0200408 cflag &= ~(termios.PARENB | termios.PARODD | CMSPAR)
Chris Liechti033f17c2015-08-30 21:28:04 +0200409 elif self._parity == serial.PARITY_EVEN:
Chris Liechti6dc58e82016-08-29 23:02:13 +0200410 cflag &= ~(termios.PARODD | CMSPAR)
Chris Liechti033f17c2015-08-30 21:28:04 +0200411 cflag |= (termios.PARENB)
412 elif self._parity == serial.PARITY_ODD:
Chris Liechti6dc58e82016-08-29 23:02:13 +0200413 cflag &= ~CMSPAR
Chris Liechti033f17c2015-08-30 21:28:04 +0200414 cflag |= (termios.PARENB | termios.PARODD)
Chris Liechti6dc58e82016-08-29 23:02:13 +0200415 elif self._parity == serial.PARITY_MARK and CMSPAR:
Chris Liechti033f17c2015-08-30 21:28:04 +0200416 cflag |= (termios.PARENB | CMSPAR | termios.PARODD)
Chris Liechti6dc58e82016-08-29 23:02:13 +0200417 elif self._parity == serial.PARITY_SPACE and CMSPAR:
Chris Liechti033f17c2015-08-30 21:28:04 +0200418 cflag |= (termios.PARENB | CMSPAR)
Chris Liechti11465c82015-08-04 15:55:22 +0200419 cflag &= ~(termios.PARODD)
cliechti89b4af12002-02-12 23:24:41 +0000420 else:
Chris Liechti984c5c52016-02-15 23:48:45 +0100421 raise ValueError('Invalid parity: {!r}'.format(self._parity))
cliechti58b481c2009-02-16 20:42:32 +0000422 # setup flow control
423 # xonxoff
Chris Liechti11465c82015-08-04 15:55:22 +0200424 if hasattr(termios, 'IXANY'):
cliechtid6bf52c2003-10-01 02:28:12 +0000425 if self._xonxoff:
Chris Liechti033f17c2015-08-30 21:28:04 +0200426 iflag |= (termios.IXON | termios.IXOFF) # |termios.IXANY)
cliechti89b4af12002-02-12 23:24:41 +0000427 else:
Chris Liechti033f17c2015-08-30 21:28:04 +0200428 iflag &= ~(termios.IXON | termios.IXOFF | termios.IXANY)
cliechti89b4af12002-02-12 23:24:41 +0000429 else:
cliechtid6bf52c2003-10-01 02:28:12 +0000430 if self._xonxoff:
Chris Liechti033f17c2015-08-30 21:28:04 +0200431 iflag |= (termios.IXON | termios.IXOFF)
cliechti89b4af12002-02-12 23:24:41 +0000432 else:
Chris Liechti033f17c2015-08-30 21:28:04 +0200433 iflag &= ~(termios.IXON | termios.IXOFF)
cliechti58b481c2009-02-16 20:42:32 +0000434 # rtscts
Chris Liechti11465c82015-08-04 15:55:22 +0200435 if hasattr(termios, 'CRTSCTS'):
cliechtid6bf52c2003-10-01 02:28:12 +0000436 if self._rtscts:
Chris Liechti033f17c2015-08-30 21:28:04 +0200437 cflag |= (termios.CRTSCTS)
cliechti89b4af12002-02-12 23:24:41 +0000438 else:
Chris Liechti11465c82015-08-04 15:55:22 +0200439 cflag &= ~(termios.CRTSCTS)
440 elif hasattr(termios, 'CNEW_RTSCTS'): # try it with alternate constant name
cliechtid6bf52c2003-10-01 02:28:12 +0000441 if self._rtscts:
Chris Liechti033f17c2015-08-30 21:28:04 +0200442 cflag |= (termios.CNEW_RTSCTS)
cliechtid4743692002-04-08 22:39:53 +0000443 else:
Chris Liechti11465c82015-08-04 15:55:22 +0200444 cflag &= ~(termios.CNEW_RTSCTS)
cliechti2750b832009-07-28 00:13:52 +0000445 # XXX should there be a warning if setting up rtscts (and xonxoff etc) fails??
cliechti58b481c2009-02-16 20:42:32 +0000446
447 # buffer
cliechtif0a81d42014-08-04 14:03:53 +0000448 # vmin "minimal number of characters to be read. 0 for non blocking"
cliechtid6bf52c2003-10-01 02:28:12 +0000449 if vmin < 0 or vmin > 255:
Chris Liechti984c5c52016-02-15 23:48:45 +0100450 raise ValueError('Invalid vmin: {!r}'.format(vmin))
Chris Liechti11465c82015-08-04 15:55:22 +0200451 cc[termios.VMIN] = vmin
cliechti58b481c2009-02-16 20:42:32 +0000452 # vtime
cliechtid6bf52c2003-10-01 02:28:12 +0000453 if vtime < 0 or vtime > 255:
Chris Liechti984c5c52016-02-15 23:48:45 +0100454 raise ValueError('Invalid vtime: {!r}'.format(vtime))
Chris Liechti11465c82015-08-04 15:55:22 +0200455 cc[termios.VTIME] = vtime
cliechti58b481c2009-02-16 20:42:32 +0000456 # activate settings
Chris Liechti94284702015-11-15 01:21:48 +0100457 if force_update or [iflag, oflag, cflag, lflag, ispeed, ospeed, cc] != orig_attr:
Chris Liechti033f17c2015-08-30 21:28:04 +0200458 termios.tcsetattr(
Chris Liechti9eaa40c2016-02-12 23:32:59 +0100459 self.fd,
460 termios.TCSANOW,
461 [iflag, oflag, cflag, lflag, ispeed, ospeed, cc])
cliechti58b481c2009-02-16 20:42:32 +0000462
cliechtie8c45422008-06-20 23:23:14 +0000463 # apply custom baud rate, if any
464 if custom_baud is not None:
Chris Liechtid6847af2015-08-06 17:54:30 +0200465 self._set_special_baudrate(custom_baud)
466
467 if self._rs485_mode is not None:
468 self._set_rs485_mode(self._rs485_mode)
cliechti89b4af12002-02-12 23:24:41 +0000469
470 def close(self):
cliechtid6bf52c2003-10-01 02:28:12 +0000471 """Close port"""
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200472 if self.is_open:
cliechtic6178262004-03-22 22:04:52 +0000473 if self.fd is not None:
cliechtid6bf52c2003-10-01 02:28:12 +0000474 os.close(self.fd)
475 self.fd = None
Chris Liechtib658eac2016-05-22 20:51:44 +0200476 os.close(self.pipe_abort_read_w)
477 os.close(self.pipe_abort_read_r)
478 os.close(self.pipe_abort_write_w)
479 os.close(self.pipe_abort_write_r)
480 self.pipe_abort_read_r, self.pipe_abort_read_w = None, None
481 self.pipe_abort_write_r, self.pipe_abort_write_w = None, None
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200482 self.is_open = False
cliechtid6bf52c2003-10-01 02:28:12 +0000483
484 # - - - - - - - - - - - - - - - - - - - - - - - -
cliechti95c62212002-03-04 22:17:53 +0000485
Chris Liechtief1fe252015-08-27 23:25:21 +0200486 @property
487 def in_waiting(self):
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200488 """Return the number of bytes currently in the input buffer."""
Chris Liechti11465c82015-08-04 15:55:22 +0200489 #~ s = fcntl.ioctl(self.fd, termios.FIONREAD, TIOCM_zero_str)
cliechtif5831e02002-12-05 23:15:27 +0000490 s = fcntl.ioctl(self.fd, TIOCINQ, TIOCM_zero_str)
Chris Liechti033f17c2015-08-30 21:28:04 +0200491 return struct.unpack('I', s)[0]
cliechti89b4af12002-02-12 23:24:41 +0000492
cliechtia9a093e2010-01-02 03:05:08 +0000493 # select based implementation, proved to work on many systems
494 def read(self, size=1):
cliechti7d448562014-08-03 21:57:45 +0000495 """\
496 Read size bytes from the serial port. If a timeout is set it may
497 return less characters as requested. With no timeout it will block
498 until the requested number of bytes is read.
499 """
Chris Liechti033f17c2015-08-30 21:28:04 +0200500 if not self.is_open:
501 raise portNotOpenError
cliechtia9a093e2010-01-02 03:05:08 +0000502 read = bytearray()
Chris Liechti935a2622016-08-30 23:39:15 +0200503 timeout = Timeout(self._timeout)
cliechtia9a093e2010-01-02 03:05:08 +0000504 while len(read) < size:
cliechti8d744de2013-10-11 14:31:13 +0000505 try:
Chris Liechti935a2622016-08-30 23:39:15 +0200506 ready, _, _ = select.select([self.fd, self.pipe_abort_read_r], [], [], timeout.time_left())
Chris Liechti42ab2b42016-05-15 23:35:05 +0200507 if self.pipe_abort_read_r in ready:
Chris Liechti68cecce2016-06-03 23:52:34 +0200508 os.read(self.pipe_abort_read_r, 1000)
Chris Liechti42ab2b42016-05-15 23:35:05 +0200509 break
cliechti8d744de2013-10-11 14:31:13 +0000510 # If select was used with a timeout, and the timeout occurs, it
511 # returns with empty lists -> thus abort read operation.
Chris Liechti033f17c2015-08-30 21:28:04 +0200512 # For timeout == 0 (non-blocking operation) also abort when
513 # there is nothing to read.
cliechti8d744de2013-10-11 14:31:13 +0000514 if not ready:
515 break # timeout
Chris Liechti033f17c2015-08-30 21:28:04 +0200516 buf = os.read(self.fd, size - len(read))
cliechti8d744de2013-10-11 14:31:13 +0000517 # read should always return some data as select reported it was
518 # ready to read when we get to this point.
519 if not buf:
520 # Disconnected devices, at least on Linux, show the
521 # behavior that they are always ready to read immediately
522 # but reading returns nothing.
Chris Liechti92df95a2016-02-09 23:30:37 +0100523 raise SerialException(
524 'device reports readiness to read but returned no data '
525 '(device disconnected or multiple access on port?)')
cliechti8d744de2013-10-11 14:31:13 +0000526 read.extend(buf)
Chris Liechti68340d72015-08-03 14:15:48 +0200527 except OSError as e:
Chris Liechti033f17c2015-08-30 21:28:04 +0200528 # this is for Python 3.x where select.error is a subclass of
Chris Liechti17660ee2017-05-04 23:39:05 +0200529 # OSError ignore BlockingIOErrors and EINTR. other errors are shown
530 # https://www.python.org/dev/peps/pep-0475.
531 if e.errno not in (errno.EAGAIN, errno.EALREADY, errno.EWOULDBLOCK, errno.EINPROGRESS, errno.EINTR):
Chris Liechti984c5c52016-02-15 23:48:45 +0100532 raise SerialException('read failed: {}'.format(e))
Chris Liechti68340d72015-08-03 14:15:48 +0200533 except select.error as e:
cliechtic7cd7212014-08-03 21:34:38 +0000534 # this is for Python 2.x
Chris Liechti17660ee2017-05-04 23:39:05 +0200535 # ignore BlockingIOErrors and EINTR. all errors are shown
cliechti8d744de2013-10-11 14:31:13 +0000536 # see also http://www.python.org/dev/peps/pep-3151/#select
Chris Liechti1c8dbee2017-05-05 03:26:51 +0200537 if e[0] not in (errno.EAGAIN, errno.EALREADY, errno.EWOULDBLOCK, errno.EINPROGRESS, errno.EINTR):
Chris Liechti984c5c52016-02-15 23:48:45 +0100538 raise SerialException('read failed: {}'.format(e))
Chris Liechti935a2622016-08-30 23:39:15 +0200539 if timeout.expired():
540 break
cliechtia9a093e2010-01-02 03:05:08 +0000541 return bytes(read)
cliechti89b4af12002-02-12 23:24:41 +0000542
Chris Liechti42ab2b42016-05-15 23:35:05 +0200543 def cancel_read(self):
Chris Liechti9c326282017-07-15 01:58:56 +0200544 if self.is_open:
545 os.write(self.pipe_abort_read_w, b"x")
Chris Liechti42ab2b42016-05-15 23:35:05 +0200546
Chris Liechti13949c62016-05-16 22:45:38 +0200547 def cancel_write(self):
Chris Liechti9c326282017-07-15 01:58:56 +0200548 if self.is_open:
549 os.write(self.pipe_abort_write_w, b"x")
Chris Liechti13949c62016-05-16 22:45:38 +0200550
cliechti4a567a02009-07-27 22:09:31 +0000551 def write(self, data):
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200552 """Output the given byte string over the serial port."""
Chris Liechti033f17c2015-08-30 21:28:04 +0200553 if not self.is_open:
554 raise portNotOpenError
cliechti38077122013-10-16 02:57:27 +0000555 d = to_bytes(data)
Chris Liechtie0063f12016-12-17 23:44:18 +0100556 tx_len = length = len(d)
Chris Liechti935a2622016-08-30 23:39:15 +0200557 timeout = Timeout(self._write_timeout)
cliechti9f7c2352013-10-11 01:13:46 +0000558 while tx_len > 0:
cliechti5d4d0bd2004-11-13 03:27:39 +0000559 try:
cliechti5d4d0bd2004-11-13 03:27:39 +0000560 n = os.write(self.fd, d)
Chris Liechti935a2622016-08-30 23:39:15 +0200561 if timeout.is_non_blocking:
Robert Smallshire325a7382016-03-25 21:18:38 +0100562 # Zero timeout indicates non-blocking - simply return the
563 # number of bytes of data actually written
564 return n
Chris Liechti935a2622016-08-30 23:39:15 +0200565 elif not timeout.is_infinite:
cliechti3cf46d62009-08-07 00:19:57 +0000566 # when timeout is set, use select to wait for being ready
567 # with the time left as timeout
Chris Liechti935a2622016-08-30 23:39:15 +0200568 if timeout.expired():
cliechti3cf46d62009-08-07 00:19:57 +0000569 raise writeTimeoutError
Chris Liechti935a2622016-08-30 23:39:15 +0200570 abort, ready, _ = select.select([self.pipe_abort_write_r], [self.fd], [], timeout.time_left())
Chris Liechti13949c62016-05-16 22:45:38 +0200571 if abort:
Chris Liechti68cecce2016-06-03 23:52:34 +0200572 os.read(self.pipe_abort_write_r, 1000)
Chris Liechti13949c62016-05-16 22:45:38 +0200573 break
cliechti5d4d0bd2004-11-13 03:27:39 +0000574 if not ready:
575 raise writeTimeoutError
cliechti88c62442013-10-12 04:03:16 +0000576 else:
Chris Liechti935a2622016-08-30 23:39:15 +0200577 assert timeout.time_left() is None
cliechti88c62442013-10-12 04:03:16 +0000578 # wait for write operation
Chris Liechti13949c62016-05-16 22:45:38 +0200579 abort, ready, _ = select.select([self.pipe_abort_write_r], [self.fd], [], None)
580 if abort:
581 os.read(self.pipe_abort_write_r, 1)
582 break
cliechti88c62442013-10-12 04:03:16 +0000583 if not ready:
584 raise SerialException('write failed (select)')
cliechti5d4d0bd2004-11-13 03:27:39 +0000585 d = d[n:]
cliechti9f7c2352013-10-11 01:13:46 +0000586 tx_len -= n
Chris Liechti675f7e12015-08-03 15:48:41 +0200587 except SerialException:
588 raise
Chris Liechti10d79d92017-05-05 00:05:23 +0200589 except OSError as e:
590 # this is for Python 3.x where select.error is a subclass of
591 # OSError ignore BlockingIOErrors and EINTR. other errors are shown
592 # https://www.python.org/dev/peps/pep-0475.
593 if e.errno not in (errno.EAGAIN, errno.EALREADY, errno.EWOULDBLOCK, errno.EINPROGRESS, errno.EINTR):
594 raise SerialException('write failed: {}'.format(e))
595 except select.error as e:
596 # this is for Python 2.x
597 # ignore BlockingIOErrors and EINTR. all errors are shown
598 # see also http://www.python.org/dev/peps/pep-3151/#select
Chris Liechti1c8dbee2017-05-05 03:26:51 +0200599 if e[0] not in (errno.EAGAIN, errno.EALREADY, errno.EWOULDBLOCK, errno.EINPROGRESS, errno.EINTR):
Chris Liechti10d79d92017-05-05 00:05:23 +0200600 raise SerialException('write failed: {}'.format(e))
Chris Liechtifc70fd72017-05-05 02:59:06 +0200601 if not timeout.is_non_blocking and timeout.expired():
Chris Liechti10d79d92017-05-05 00:05:23 +0200602 raise writeTimeoutError
Chris Liechtie0063f12016-12-17 23:44:18 +0100603 return length - len(d)
cliechtid6bf52c2003-10-01 02:28:12 +0000604
cliechtia30a8a02003-10-05 12:28:13 +0000605 def flush(self):
cliechti7d448562014-08-03 21:57:45 +0000606 """\
607 Flush of file like objects. In this case, wait until all data
608 is written.
609 """
Chris Liechti033f17c2015-08-30 21:28:04 +0200610 if not self.is_open:
611 raise portNotOpenError
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200612 termios.tcdrain(self.fd)
cliechtia30a8a02003-10-05 12:28:13 +0000613
Chris Liechtief1fe252015-08-27 23:25:21 +0200614 def reset_input_buffer(self):
cliechtid6bf52c2003-10-01 02:28:12 +0000615 """Clear input buffer, discarding all that is in the buffer."""
Chris Liechti033f17c2015-08-30 21:28:04 +0200616 if not self.is_open:
617 raise portNotOpenError
Chris Liechti11465c82015-08-04 15:55:22 +0200618 termios.tcflush(self.fd, termios.TCIFLUSH)
cliechti89b4af12002-02-12 23:24:41 +0000619
Chris Liechtief1fe252015-08-27 23:25:21 +0200620 def reset_output_buffer(self):
cliechti7d448562014-08-03 21:57:45 +0000621 """\
622 Clear output buffer, aborting the current output and discarding all
623 that is in the buffer.
624 """
Chris Liechti033f17c2015-08-30 21:28:04 +0200625 if not self.is_open:
626 raise portNotOpenError
Chris Liechti11465c82015-08-04 15:55:22 +0200627 termios.tcflush(self.fd, termios.TCOFLUSH)
cliechti89b4af12002-02-12 23:24:41 +0000628
Chris Liechtief1fe252015-08-27 23:25:21 +0200629 def send_break(self, duration=0.25):
cliechti7d448562014-08-03 21:57:45 +0000630 """\
631 Send break condition. Timed, returns to idle state after given
632 duration.
633 """
Chris Liechti033f17c2015-08-30 21:28:04 +0200634 if not self.is_open:
635 raise portNotOpenError
636 termios.tcsendbreak(self.fd, int(duration / 0.25))
cliechti89b4af12002-02-12 23:24:41 +0000637
Chris Liechtief1fe252015-08-27 23:25:21 +0200638 def _update_break_state(self):
cliechti7d448562014-08-03 21:57:45 +0000639 """\
640 Set break: Controls TXD. When active, no transmitting is possible.
641 """
Chris Liechtief1fe252015-08-27 23:25:21 +0200642 if self._break_state:
cliechti997b63c2008-06-21 00:09:31 +0000643 fcntl.ioctl(self.fd, TIOCSBRK)
644 else:
645 fcntl.ioctl(self.fd, TIOCCBRK)
646
Chris Liechtief1fe252015-08-27 23:25:21 +0200647 def _update_rts_state(self):
cliechtid6bf52c2003-10-01 02:28:12 +0000648 """Set terminal status line: Request To Send"""
Chris Liechtif7534c82016-05-07 23:35:54 +0200649 if self._rts_state:
650 fcntl.ioctl(self.fd, TIOCMBIS, TIOCM_RTS_str)
651 else:
652 fcntl.ioctl(self.fd, TIOCMBIC, TIOCM_RTS_str)
cliechtid6bf52c2003-10-01 02:28:12 +0000653
Chris Liechtief1fe252015-08-27 23:25:21 +0200654 def _update_dtr_state(self):
cliechtid6bf52c2003-10-01 02:28:12 +0000655 """Set terminal status line: Data Terminal Ready"""
Chris Liechtif7534c82016-05-07 23:35:54 +0200656 if self._dtr_state:
657 fcntl.ioctl(self.fd, TIOCMBIS, TIOCM_DTR_str)
658 else:
659 fcntl.ioctl(self.fd, TIOCMBIC, TIOCM_DTR_str)
cliechtid6bf52c2003-10-01 02:28:12 +0000660
Chris Liechtief1fe252015-08-27 23:25:21 +0200661 @property
662 def cts(self):
cliechtid6bf52c2003-10-01 02:28:12 +0000663 """Read terminal status line: Clear To Send"""
Chris Liechti033f17c2015-08-30 21:28:04 +0200664 if not self.is_open:
665 raise portNotOpenError
cliechtid6bf52c2003-10-01 02:28:12 +0000666 s = fcntl.ioctl(self.fd, TIOCMGET, TIOCM_zero_str)
Chris Liechti033f17c2015-08-30 21:28:04 +0200667 return struct.unpack('I', s)[0] & TIOCM_CTS != 0
cliechtid6bf52c2003-10-01 02:28:12 +0000668
Chris Liechtief1fe252015-08-27 23:25:21 +0200669 @property
670 def dsr(self):
cliechtid6bf52c2003-10-01 02:28:12 +0000671 """Read terminal status line: Data Set Ready"""
Chris Liechti033f17c2015-08-30 21:28:04 +0200672 if not self.is_open:
673 raise portNotOpenError
cliechtid6bf52c2003-10-01 02:28:12 +0000674 s = fcntl.ioctl(self.fd, TIOCMGET, TIOCM_zero_str)
Chris Liechti033f17c2015-08-30 21:28:04 +0200675 return struct.unpack('I', s)[0] & TIOCM_DSR != 0
cliechtid6bf52c2003-10-01 02:28:12 +0000676
Chris Liechtief1fe252015-08-27 23:25:21 +0200677 @property
678 def ri(self):
cliechtid6bf52c2003-10-01 02:28:12 +0000679 """Read terminal status line: Ring Indicator"""
Chris Liechti033f17c2015-08-30 21:28:04 +0200680 if not self.is_open:
681 raise portNotOpenError
cliechti89b4af12002-02-12 23:24:41 +0000682 s = fcntl.ioctl(self.fd, TIOCMGET, TIOCM_zero_str)
Chris Liechti033f17c2015-08-30 21:28:04 +0200683 return struct.unpack('I', s)[0] & TIOCM_RI != 0
cliechti89b4af12002-02-12 23:24:41 +0000684
Chris Liechtief1fe252015-08-27 23:25:21 +0200685 @property
686 def cd(self):
cliechtid6bf52c2003-10-01 02:28:12 +0000687 """Read terminal status line: Carrier Detect"""
Chris Liechti033f17c2015-08-30 21:28:04 +0200688 if not self.is_open:
689 raise portNotOpenError
cliechti89b4af12002-02-12 23:24:41 +0000690 s = fcntl.ioctl(self.fd, TIOCMGET, TIOCM_zero_str)
Chris Liechti033f17c2015-08-30 21:28:04 +0200691 return struct.unpack('I', s)[0] & TIOCM_CD != 0
cliechti89b4af12002-02-12 23:24:41 +0000692
cliechtia30a8a02003-10-05 12:28:13 +0000693 # - - platform specific - - - -
694
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200695 @property
696 def out_waiting(self):
697 """Return the number of bytes currently in the output buffer."""
Chris Liechti11465c82015-08-04 15:55:22 +0200698 #~ s = fcntl.ioctl(self.fd, termios.FIONREAD, TIOCM_zero_str)
cliechti28b8fd02011-12-28 21:39:42 +0000699 s = fcntl.ioctl(self.fd, TIOCOUTQ, TIOCM_zero_str)
Chris Liechti033f17c2015-08-30 21:28:04 +0200700 return struct.unpack('I', s)[0]
cliechti28b8fd02011-12-28 21:39:42 +0000701
cliechti8753bbc2005-01-15 20:32:51 +0000702 def fileno(self):
cliechti2f0f8a32011-12-28 22:10:00 +0000703 """\
704 For easier use of the serial port instance with select.
705 WARNING: this function is not portable to different platforms!
706 """
Chris Liechti033f17c2015-08-30 21:28:04 +0200707 if not self.is_open:
708 raise portNotOpenError
cliechti8753bbc2005-01-15 20:32:51 +0000709 return self.fd
cliechti89b4af12002-02-12 23:24:41 +0000710
Chris Liechti518b0d32015-08-30 02:20:39 +0200711 def set_input_flow_control(self, enable=True):
cliechti2f0f8a32011-12-28 22:10:00 +0000712 """\
713 Manually control flow - when software flow control is enabled.
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200714 This will send XON (true) or XOFF (false) to the other device.
cliechti2f0f8a32011-12-28 22:10:00 +0000715 WARNING: this function is not portable to different platforms!
716 """
Chris Liechti033f17c2015-08-30 21:28:04 +0200717 if not self.is_open:
718 raise portNotOpenError
cliechti4a601342011-12-29 02:22:17 +0000719 if enable:
Chris Liechti11465c82015-08-04 15:55:22 +0200720 termios.tcflow(self.fd, termios.TCION)
cliechti57e48a62009-08-03 22:29:58 +0000721 else:
Chris Liechti11465c82015-08-04 15:55:22 +0200722 termios.tcflow(self.fd, termios.TCIOFF)
cliechti57e48a62009-08-03 22:29:58 +0000723
Chris Liechti518b0d32015-08-30 02:20:39 +0200724 def set_output_flow_control(self, enable=True):
cliechti2f0f8a32011-12-28 22:10:00 +0000725 """\
726 Manually control flow of outgoing data - when hardware or software flow
727 control is enabled.
728 WARNING: this function is not portable to different platforms!
729 """
Chris Liechti033f17c2015-08-30 21:28:04 +0200730 if not self.is_open:
731 raise portNotOpenError
cliechti2f0f8a32011-12-28 22:10:00 +0000732 if enable:
Chris Liechti11465c82015-08-04 15:55:22 +0200733 termios.tcflow(self.fd, termios.TCOON)
cliechti2f0f8a32011-12-28 22:10:00 +0000734 else:
Chris Liechti11465c82015-08-04 15:55:22 +0200735 termios.tcflow(self.fd, termios.TCOOFF)
cliechti2f0f8a32011-12-28 22:10:00 +0000736
Chris Liechti59848422016-06-04 22:28:14 +0200737 def nonblocking(self):
738 """DEPRECATED - has no use"""
739 import warnings
740 warnings.warn("nonblocking() has no effect, already nonblocking", DeprecationWarning)
741
cliechtif81362e2009-07-25 03:44:33 +0000742
cliechtia9a093e2010-01-02 03:05:08 +0000743class PosixPollSerial(Serial):
cliechti7d448562014-08-03 21:57:45 +0000744 """\
cliechtif0a81d42014-08-04 14:03:53 +0000745 Poll based read implementation. Not all systems support poll properly.
746 However this one has better handling of errors, such as a device
cliechti7d448562014-08-03 21:57:45 +0000747 disconnecting while it's in use (e.g. USB-serial unplugged).
748 """
cliechtia9a093e2010-01-02 03:05:08 +0000749
750 def read(self, size=1):
cliechti7d448562014-08-03 21:57:45 +0000751 """\
752 Read size bytes from the serial port. If a timeout is set it may
753 return less characters as requested. With no timeout it will block
754 until the requested number of bytes is read.
755 """
Chris Liechtiacac2362016-03-29 22:37:48 +0200756 if not self.is_open:
Chris Liechti033f17c2015-08-30 21:28:04 +0200757 raise portNotOpenError
cliechtia9a093e2010-01-02 03:05:08 +0000758 read = bytearray()
Chris Liechtia5726382017-08-24 23:43:23 +0200759 timeout = Timeout(self._timeout)
cliechtia9a093e2010-01-02 03:05:08 +0000760 poll = select.poll()
Chris Liechti033f17c2015-08-30 21:28:04 +0200761 poll.register(self.fd, select.POLLIN | select.POLLERR | select.POLLHUP | select.POLLNVAL)
Chris Liechtia5726382017-08-24 23:43:23 +0200762 poll.register(self.pipe_abort_read_r, select.POLLIN | select.POLLERR | select.POLLHUP | select.POLLNVAL)
cliechtia9a093e2010-01-02 03:05:08 +0000763 if size > 0:
764 while len(read) < size:
765 # print "\tread(): size",size, "have", len(read) #debug
766 # wait until device becomes ready to read (or something fails)
Chris Liechtia5726382017-08-24 23:43:23 +0200767 for fd, event in poll.poll(None if timeout.is_infinite else (timeout.time_left() * 1000)):
768 if fd == self.pipe_abort_read_r:
769 break
Chris Liechti033f17c2015-08-30 21:28:04 +0200770 if event & (select.POLLERR | select.POLLHUP | select.POLLNVAL):
cliechtia9a093e2010-01-02 03:05:08 +0000771 raise SerialException('device reports error (poll)')
772 # we don't care if it is select.POLLIN or timeout, that's
773 # handled below
Chris Liechtia5726382017-08-24 23:43:23 +0200774 if fd == self.pipe_abort_read_r:
775 os.read(self.pipe_abort_read_r, 1000)
776 break
cliechtia9a093e2010-01-02 03:05:08 +0000777 buf = os.read(self.fd, size - len(read))
778 read.extend(buf)
Chris Liechtia5726382017-08-24 23:43:23 +0200779 if timeout.expired() \
780 or (self._inter_byte_timeout is not None and self._inter_byte_timeout > 0) and not buf:
cliechtia9a093e2010-01-02 03:05:08 +0000781 break # early abort on timeout
782 return bytes(read)
783
cliechtif81362e2009-07-25 03:44:33 +0000784
Chris Liechti4cf54702015-10-18 00:21:56 +0200785class VTIMESerial(Serial):
786 """\
787 Implement timeout using vtime of tty device instead of using select.
788 This means that no inter character timeout can be specified and that
789 the error handling is degraded.
790
791 Overall timeout is disabled when inter-character timeout is used.
Chris Liechti22d39002018-05-08 03:39:20 +0200792
793 Note that this implementation does NOT support cancel_read(), it will
794 just ignore that.
Chris Liechti4cf54702015-10-18 00:21:56 +0200795 """
796
Chris Liechti94284702015-11-15 01:21:48 +0100797 def _reconfigure_port(self, force_update=True):
Chris Liechti4cf54702015-10-18 00:21:56 +0200798 """Set communication parameters on opened port."""
799 super(VTIMESerial, self)._reconfigure_port()
Chris Liechtid6bcaaf2016-02-01 22:55:26 +0100800 fcntl.fcntl(self.fd, fcntl.F_SETFL, 0) # clear O_NONBLOCK
Chris Liechti4cf54702015-10-18 00:21:56 +0200801
802 if self._inter_byte_timeout is not None:
803 vmin = 1
804 vtime = int(self._inter_byte_timeout * 10)
Chris Liechti3ec9c412016-08-08 01:06:46 +0200805 elif self._timeout is None:
806 vmin = 1
807 vtime = 0
Chris Liechti4cf54702015-10-18 00:21:56 +0200808 else:
809 vmin = 0
810 vtime = int(self._timeout * 10)
811 try:
812 orig_attr = termios.tcgetattr(self.fd)
813 iflag, oflag, cflag, lflag, ispeed, ospeed, cc = orig_attr
814 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 +0100815 raise serial.SerialException("Could not configure port: {}".format(msg))
Chris Liechti4cf54702015-10-18 00:21:56 +0200816
817 if vtime < 0 or vtime > 255:
Chris Liechti984c5c52016-02-15 23:48:45 +0100818 raise ValueError('Invalid vtime: {!r}'.format(vtime))
Chris Liechti4cf54702015-10-18 00:21:56 +0200819 cc[termios.VTIME] = vtime
820 cc[termios.VMIN] = vmin
821
822 termios.tcsetattr(
823 self.fd,
824 termios.TCSANOW,
825 [iflag, oflag, cflag, lflag, ispeed, ospeed, cc])
826
Chris Liechti4cf54702015-10-18 00:21:56 +0200827 def read(self, size=1):
828 """\
829 Read size bytes from the serial port. If a timeout is set it may
830 return less characters as requested. With no timeout it will block
831 until the requested number of bytes is read.
832 """
833 if not self.is_open:
834 raise portNotOpenError
835 read = bytearray()
836 while len(read) < size:
837 buf = os.read(self.fd, size - len(read))
838 if not buf:
839 break
840 read.extend(buf)
841 return bytes(read)
Chris Liechti3ec9c412016-08-08 01:06:46 +0200842
843 # hack to make hasattr return false
844 cancel_read = property()