blob: 2052f7406b16003bbccf784298f4ed419959a644 [file] [log] [blame]
cliechti89b4af12002-02-12 23:24:41 +00001#!/usr/bin/env python
cliechti58b481c2009-02-16 20:42:32 +00002#
cliechtic54b2c82008-06-21 01:59:08 +00003# Python Serial Port Extension for Win32, Linux, BSD, Jython
4# module for serial IO for POSIX compatible systems, like Linux
5# see __init__.py
cliechti89b4af12002-02-12 23:24:41 +00006#
Chris Liechti68340d72015-08-03 14:15:48 +02007# (C) 2001-2015 Chris Liechti <cliechti@gmx.net>
cliechti89b4af12002-02-12 23:24:41 +00008# this is distributed under a free software license, see license.txt
9#
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 Liechti33f0ec52015-08-06 16:37:21 +020015import errno
16import fcntl
Chris Liechti33f0ec52015-08-06 16:37:21 +020017import os
18import select
19import struct
20import sys
21import termios
22import time
cliechti39cfb7b2011-08-22 00:30:07 +000023from serial.serialutil import *
cliechti89b4af12002-02-12 23:24:41 +000024
cliechti89b4af12002-02-12 23:24:41 +000025
Chris Liechtid6847af2015-08-06 17:54:30 +020026class PlatformSpecificBase(object):
27 BAUDRATE_CONSTANTS = {}
cliechti89b4af12002-02-12 23:24:41 +000028
Chris Liechtid6847af2015-08-06 17:54:30 +020029 def number_to_device(self, port_number):
30 sys.stderr.write("""\
cliechti7aaead32009-07-23 14:02:41 +000031don't know how to number ttys on this system.
cliechti895e8302004-04-20 02:40:28 +000032! Use an explicit path (eg /dev/ttyS1) or send this information to
33! the author of this module:
cliechti89b4af12002-02-12 23:24:41 +000034
cliechti895e8302004-04-20 02:40:28 +000035sys.platform = %r
36os.name = %r
37serialposix.py version = %s
cliechti89b4af12002-02-12 23:24:41 +000038
39also add the device name of the serial port and where the
40counting starts for the first serial port.
41e.g. 'first serial port: /dev/ttyS0'
42and with a bit luck you can get this module running...
cliechti7aaead32009-07-23 14:02:41 +000043""" % (sys.platform, os.name, VERSION))
Chris Liechtid6847af2015-08-06 17:54:30 +020044 raise NotImplementedError('no number-to-device mapping defined on this platform')
45
46 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
57if plat[:5] == 'linux': # Linux (confirmed)
58 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
68 SER_RS485_ENABLED = 0b00000001
69 SER_RS485_RTS_ON_SEND = 0b00000010
70 SER_RS485_RTS_AFTER_SEND = 0b00000100
71 SER_RS485_RX_DURING_TX = 0b00010000
72
73
74 class PlatformSpecific(PlatformSpecificBase):
75 BAUDRATE_CONSTANTS = {
76 0: 0o000000, # hang up
77 50: 0o000001,
78 75: 0o000002,
79 110: 0o000003,
80 134: 0o000004,
81 150: 0o000005,
82 200: 0o000006,
83 300: 0o000007,
84 600: 0o000010,
85 1200: 0o000011,
86 1800: 0o000012,
87 2400: 0o000013,
88 4800: 0o000014,
89 9600: 0o000015,
90 19200: 0o000016,
91 38400: 0o000017,
92 57600: 0o010001,
93 115200: 0o010002,
94 230400: 0o010003,
95 460800: 0o010004,
96 500000: 0o010005,
97 576000: 0o010006,
98 921600: 0o010007,
99 1000000: 0o010010,
100 1152000: 0o010011,
101 1500000: 0o010012,
102 2000000: 0o010013,
103 2500000: 0o010014,
104 3000000: 0o010015,
105 3500000: 0o010016,
106 4000000: 0o010017
107 }
108
109 def number_to_device(self, port_number):
110 return '/dev/ttyS%d' % (port_number,)
111
112 def _set_special_baudrate(self, baudrate):
113 # right size is 44 on x86_64, allow for some growth
114 buf = array.array('i', [0] * 64)
115 try:
116 # get serial_struct
117 fcntl.ioctl(self.fd, TCGETS2, buf)
118 # set custom speed
119 buf[2] &= ~termios.CBAUD
120 buf[2] |= BOTHER
121 buf[9] = buf[10] = baudrate
122
123 # set serial_struct
124 res = fcntl.ioctl(self.fd, TCSETS2, buf)
125 except IOError as e:
126 raise ValueError('Failed to set custom baud rate (%s): %s' % (baudrate, e))
127
128 def _set_rs485_mode(self, rs485_settings):
129 buf = array.array('i', [0] * 8) # flags, delaytx, delayrx, padding
130 try:
131 fcntl.ioctl(self.fd, TIOCGRS485, buf)
132 if rs485_settings is not None:
133 if rs485_settings.loopback:
134 buf[0] |= SER_RS485_RX_DURING_TX
135 else:
136 buf[0] &= ~SER_RS485_RX_DURING_TX
137 if rs485_settings.rts_level_for_tx:
138 buf[0] |= SER_RS485_RTS_ON_SEND
139 else:
140 buf[0] &= ~SER_RS485_RTS_ON_SEND
141 if rs485_settings.rts_level_for_rx:
142 buf[0] |= SER_RS485_RTS_AFTER_SEND
143 else:
144 buf[0] &= ~SER_RS485_RTS_AFTER_SEND
145 buf[1] = int(rs485_settings.delay_rts_before_send * 1000)
146 buf[2] = int(rs485_settings.delay_rts_after_send * 1000)
147 else:
148 buf[0] = 0 # clear SER_RS485_ENABLED
149 res = fcntl.ioctl(self.fd, TIOCSRS485, buf)
150 except IOError as e:
151 raise ValueError('Failed to set RS485 mode: %s' % (e,))
152
153
154elif plat == 'cygwin': # cygwin/win32 (confirmed)
155
156 class PlatformSpecific(PlatformSpecificBase):
157 BAUDRATE_CONSTANTS = {
158 128000: 0x01003,
159 256000: 0x01005,
160 500000: 0x01007,
161 576000: 0x01008,
162 921600: 0x01009,
163 1000000: 0x0100a,
164 1152000: 0x0100b,
165 1500000: 0x0100c,
166 2000000: 0x0100d,
167 2500000: 0x0100e,
168 3000000: 0x0100f
169 }
170
171 def number_to_device(self, port_number):
172 return '/dev/com%d' % (port_number + 1,)
173
174
175elif plat[:7] == 'openbsd': # OpenBSD
176 class PlatformSpecific(PlatformSpecificBase):
177 def number_to_device(self, port_number):
178 return '/dev/cua%02d' % (port_number,)
179
180elif plat[:3] == 'bsd' or plat[:7] == 'freebsd':
181 class PlatformSpecific(PlatformSpecificBase):
182 def number_to_device(self, port_number):
183 return '/dev/cuad%d' % (port_number,)
184
185elif plat[:6] == 'darwin': # OS X
186 import array
187 IOSSIOSPEED = 0x80045402 #_IOW('T', 2, speed_t)
188
189 class PlatformSpecific(PlatformSpecificBase):
190 def number_to_device(self, port_number):
191 return '/dev/cuad%d' % (port_number,)
192
193 osx_version = os.uname()[2].split('.')
194 # Tiger or above can support arbitrary serial speeds
195 if int(osx_version[0]) >= 8:
196 def _set_special_baudrate(self, baudrate):
197 # use IOKit-specific call to set up high speeds
198 buf = array.array('i', [baudrate])
199 fcntl.ioctl(self.fd, IOSSIOSPEED, buf, 1)
200
201
202elif plat[:6] == 'netbsd': # NetBSD 1.6 testing by Erk
203 class PlatformSpecific(PlatformSpecificBase):
204 def number_to_device(self, port_number):
205 return '/dev/dty%02d' % (port_number,)
206
207elif plat[:4] == 'irix': # IRIX (partially tested)
208 class PlatformSpecific(PlatformSpecificBase):
209 def number_to_device(self, port_number):
210 return '/dev/ttyf%d' % (port_number + 1,) #XXX different device names depending on flow control
211
212elif plat[:2] == 'hp': # HP-UX (not tested)
213 class PlatformSpecific(PlatformSpecificBase):
214 def number_to_device(self, port_number):
215 return '/dev/tty%dp0' % (port_number + 1,)
216
217elif plat[:5] == 'sunos': # Solaris/SunOS (confirmed)
218 class PlatformSpecific(PlatformSpecificBase):
219 def number_to_device(self, port_number):
220 return '/dev/tty%c' % (ord('a') + port_number,)
221
222elif plat[:3] == 'aix': # AIX
223 class PlatformSpecific(PlatformSpecificBase):
224 def number_to_device(self, port_number):
225 return '/dev/tty%d' % (port_number,)
226
227else:
228 class PlatformSpecific(PlatformSpecificBase):
229 pass
cliechti89b4af12002-02-12 23:24:41 +0000230
cliechti58b481c2009-02-16 20:42:32 +0000231# whats up with "aix", "beos", ....
232# they should work, just need to know the device names.
cliechti89b4af12002-02-12 23:24:41 +0000233
234
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 Liechtid6847af2015-08-06 17:54:30 +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 Liechtid6847af2015-08-06 17:54:30 +0200242#TIOCM_LE = getattr(termios, 'TIOCM_LE', 0x001)
243TIOCM_DTR = getattr(termios, 'TIOCM_DTR', 0x002)
244TIOCM_RTS = getattr(termios, 'TIOCM_RTS', 0x004)
245#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)
252TIOCM_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)
260TIOCOUTQ = 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 Liechtid6847af2015-08-06 17:54:30 +0200266TIOCSBRK = getattr(termios, 'TIOCSBRK', 0x5427)
267TIOCCBRK = getattr(termios, 'TIOCCBRK', 0x5428)
cliechti997b63c2008-06-21 00:09:31 +0000268
Chris Liechti68340d72015-08-03 14:15:48 +0200269CMSPAR = 0o10000000000 # Use "stick" (mark/space) parity
cliechtiaec27ab2014-07-31 22:21:24 +0000270
cliechti89b4af12002-02-12 23:24:41 +0000271
Chris Liechtief6b7b42015-08-06 22:19:26 +0200272class Serial(SerialBase, PlatformSpecific):
cliechti7d448562014-08-03 21:57:45 +0000273 """\
274 Serial port class POSIX implementation. Serial port configuration is
cliechtid6bf52c2003-10-01 02:28:12 +0000275 done with termios and fcntl. Runs on Linux and many other Un*x like
cliechtif0a81d42014-08-04 14:03:53 +0000276 systems.
277 """
cliechtid6bf52c2003-10-01 02:28:12 +0000278
279 def open(self):
cliechti7d448562014-08-03 21:57:45 +0000280 """\
281 Open port with current settings. This may throw a SerialException
282 if the port cannot be opened."""
cliechtid6bf52c2003-10-01 02:28:12 +0000283 if self._port is None:
284 raise SerialException("Port must be configured before it can be used.")
cliechti02ef43a2011-03-24 23:33:12 +0000285 if self._isOpen:
286 raise SerialException("Port is already open.")
287 self.fd = None
cliechti58b481c2009-02-16 20:42:32 +0000288 # open
cliechti4616bf12002-04-08 23:13:14 +0000289 try:
290 self.fd = os.open(self.portstr, os.O_RDWR|os.O_NOCTTY|os.O_NONBLOCK)
Chris Liechti68340d72015-08-03 14:15:48 +0200291 except OSError as msg:
cliechti4616bf12002-04-08 23:13:14 +0000292 self.fd = None
cliechtiaf84daa2013-10-10 23:57:00 +0000293 raise SerialException(msg.errno, "could not open port %s: %s" % (self._port, msg))
Chris Liechti11465c82015-08-04 15:55:22 +0200294 #~ fcntl.fcntl(self.fd, fcntl.F_SETFL, 0) # set blocking
cliechti58b481c2009-02-16 20:42:32 +0000295
cliechtib2f5fc82006-10-20 00:09:07 +0000296 try:
297 self._reconfigurePort()
298 except:
cliechti2750b832009-07-28 00:13:52 +0000299 try:
300 os.close(self.fd)
301 except:
302 # ignore any exception when closing the port
303 # also to keep original exception that happened when setting up
304 pass
cliechtib2f5fc82006-10-20 00:09:07 +0000305 self.fd = None
cliechtif0a4f0f2009-07-21 21:12:37 +0000306 raise
cliechtib2f5fc82006-10-20 00:09:07 +0000307 else:
308 self._isOpen = True
cliechti5c9b0722013-10-17 03:19:39 +0000309 self.flushInput()
cliechti58b481c2009-02-16 20:42:32 +0000310
311
cliechtid6bf52c2003-10-01 02:28:12 +0000312 def _reconfigurePort(self):
cliechtib2f5fc82006-10-20 00:09:07 +0000313 """Set communication parameters on opened port."""
cliechtic6178262004-03-22 22:04:52 +0000314 if self.fd is None:
cliechtia9a093e2010-01-02 03:05:08 +0000315 raise SerialException("Can only operate on a valid file descriptor")
cliechtie8c45422008-06-20 23:23:14 +0000316 custom_baud = None
cliechti58b481c2009-02-16 20:42:32 +0000317
cliechti2750b832009-07-28 00:13:52 +0000318 vmin = vtime = 0 # timeout is done via select
cliechti679bfa62008-06-20 23:58:15 +0000319 if self._interCharTimeout is not None:
320 vmin = 1
321 vtime = int(self._interCharTimeout * 10)
cliechti6ce7ab12002-11-07 02:15:00 +0000322 try:
cliechti4d0af5e2011-08-05 02:18:16 +0000323 orig_attr = termios.tcgetattr(self.fd)
324 iflag, oflag, cflag, lflag, ispeed, ospeed, cc = orig_attr
Chris Liechti68340d72015-08-03 14:15:48 +0200325 except termios.error as msg: # if a port is nonexistent but has a /dev file, it'll fail here
cliechtid6bf52c2003-10-01 02:28:12 +0000326 raise SerialException("Could not configure port: %s" % msg)
cliechti58b481c2009-02-16 20:42:32 +0000327 # set up raw mode / no echo / binary
Chris Liechti11465c82015-08-04 15:55:22 +0200328 cflag |= (termios.CLOCAL|termios.CREAD)
329 lflag &= ~(termios.ICANON|termios.ECHO|termios.ECHOE|termios.ECHOK|termios.ECHONL|
330 termios.ISIG|termios.IEXTEN) #|termios.ECHOPRT
cliechti2750b832009-07-28 00:13:52 +0000331 for flag in ('ECHOCTL', 'ECHOKE'): # netbsd workaround for Erk
Chris Liechti11465c82015-08-04 15:55:22 +0200332 if hasattr(termios, flag):
333 lflag &= ~getattr(termios, flag)
cliechti58b481c2009-02-16 20:42:32 +0000334
Chris Liechti11465c82015-08-04 15:55:22 +0200335 oflag &= ~(termios.OPOST|termios.ONLCR|termios.OCRNL)
336 iflag &= ~(termios.INLCR|termios.IGNCR|termios.ICRNL|termios.IGNBRK)
337 if hasattr(termios, 'IUCLC'):
338 iflag &= ~termios.IUCLC
339 if hasattr(termios, 'PARMRK'):
340 iflag &= ~termios.PARMRK
cliechti58b481c2009-02-16 20:42:32 +0000341
cliechtif0a4f0f2009-07-21 21:12:37 +0000342 # setup baud rate
cliechti89b4af12002-02-12 23:24:41 +0000343 try:
Chris Liechti11465c82015-08-04 15:55:22 +0200344 ispeed = ospeed = getattr(termios, 'B%s' % (self._baudrate))
cliechti895e8302004-04-20 02:40:28 +0000345 except AttributeError:
cliechtif1559d02007-11-08 23:43:58 +0000346 try:
Chris Liechtid6847af2015-08-06 17:54:30 +0200347 ispeed = ospeed = self.BAUDRATE_CONSTANTS[self._baudrate]
cliechtif1559d02007-11-08 23:43:58 +0000348 except KeyError:
cliechtie8c45422008-06-20 23:23:14 +0000349 #~ raise ValueError('Invalid baud rate: %r' % self._baudrate)
cliechtif0a4f0f2009-07-21 21:12:37 +0000350 # may need custom baud rate, it isn't in our list.
Chris Liechti11465c82015-08-04 15:55:22 +0200351 ispeed = ospeed = getattr(termios, 'B38400')
cliechtif0a4f0f2009-07-21 21:12:37 +0000352 try:
353 custom_baud = int(self._baudrate) # store for later
354 except ValueError:
355 raise ValueError('Invalid baud rate: %r' % self._baudrate)
356 else:
357 if custom_baud < 0:
358 raise ValueError('Invalid baud rate: %r' % self._baudrate)
cliechti58b481c2009-02-16 20:42:32 +0000359
360 # setup char len
Chris Liechti11465c82015-08-04 15:55:22 +0200361 cflag &= ~termios.CSIZE
cliechtid6bf52c2003-10-01 02:28:12 +0000362 if self._bytesize == 8:
Chris Liechti11465c82015-08-04 15:55:22 +0200363 cflag |= termios.CS8
cliechtid6bf52c2003-10-01 02:28:12 +0000364 elif self._bytesize == 7:
Chris Liechti11465c82015-08-04 15:55:22 +0200365 cflag |= termios.CS7
cliechtid6bf52c2003-10-01 02:28:12 +0000366 elif self._bytesize == 6:
Chris Liechti11465c82015-08-04 15:55:22 +0200367 cflag |= termios.CS6
cliechtid6bf52c2003-10-01 02:28:12 +0000368 elif self._bytesize == 5:
Chris Liechti11465c82015-08-04 15:55:22 +0200369 cflag |= termios.CS5
cliechti89b4af12002-02-12 23:24:41 +0000370 else:
cliechtid6bf52c2003-10-01 02:28:12 +0000371 raise ValueError('Invalid char len: %r' % self._bytesize)
cliechtif0a81d42014-08-04 14:03:53 +0000372 # setup stop bits
cliechtid6bf52c2003-10-01 02:28:12 +0000373 if self._stopbits == STOPBITS_ONE:
Chris Liechti11465c82015-08-04 15:55:22 +0200374 cflag &= ~(termios.CSTOPB)
cliechti58b481c2009-02-16 20:42:32 +0000375 elif self._stopbits == STOPBITS_ONE_POINT_FIVE:
Chris Liechti11465c82015-08-04 15:55:22 +0200376 cflag |= (termios.CSTOPB) # XXX same as TWO.. there is no POSIX support for 1.5
cliechtid6bf52c2003-10-01 02:28:12 +0000377 elif self._stopbits == STOPBITS_TWO:
Chris Liechti11465c82015-08-04 15:55:22 +0200378 cflag |= (termios.CSTOPB)
cliechti89b4af12002-02-12 23:24:41 +0000379 else:
cliechti3172d3d2009-07-21 22:33:40 +0000380 raise ValueError('Invalid stop bit specification: %r' % self._stopbits)
cliechti58b481c2009-02-16 20:42:32 +0000381 # setup parity
Chris Liechti11465c82015-08-04 15:55:22 +0200382 iflag &= ~(termios.INPCK|termios.ISTRIP)
cliechtid6bf52c2003-10-01 02:28:12 +0000383 if self._parity == PARITY_NONE:
Chris Liechti11465c82015-08-04 15:55:22 +0200384 cflag &= ~(termios.PARENB|termios.PARODD)
cliechtid6bf52c2003-10-01 02:28:12 +0000385 elif self._parity == PARITY_EVEN:
Chris Liechti11465c82015-08-04 15:55:22 +0200386 cflag &= ~(termios.PARODD)
387 cflag |= (termios.PARENB)
cliechtid6bf52c2003-10-01 02:28:12 +0000388 elif self._parity == PARITY_ODD:
Chris Liechti11465c82015-08-04 15:55:22 +0200389 cflag |= (termios.PARENB|termios.PARODD)
cliechtiaec27ab2014-07-31 22:21:24 +0000390 elif self._parity == PARITY_MARK and plat[:5] == 'linux':
Chris Liechti11465c82015-08-04 15:55:22 +0200391 cflag |= (termios.PARENB|CMSPAR|termios.PARODD)
cliechtiaec27ab2014-07-31 22:21:24 +0000392 elif self._parity == PARITY_SPACE and plat[:5] == 'linux':
Chris Liechti11465c82015-08-04 15:55:22 +0200393 cflag |= (termios.PARENB|CMSPAR)
394 cflag &= ~(termios.PARODD)
cliechti89b4af12002-02-12 23:24:41 +0000395 else:
cliechtid6bf52c2003-10-01 02:28:12 +0000396 raise ValueError('Invalid parity: %r' % self._parity)
cliechti58b481c2009-02-16 20:42:32 +0000397 # setup flow control
398 # xonxoff
Chris Liechti11465c82015-08-04 15:55:22 +0200399 if hasattr(termios, 'IXANY'):
cliechtid6bf52c2003-10-01 02:28:12 +0000400 if self._xonxoff:
Chris Liechti11465c82015-08-04 15:55:22 +0200401 iflag |= (termios.IXON|termios.IXOFF) #|termios.IXANY)
cliechti89b4af12002-02-12 23:24:41 +0000402 else:
Chris Liechti11465c82015-08-04 15:55:22 +0200403 iflag &= ~(termios.IXON|termios.IXOFF|termios.IXANY)
cliechti89b4af12002-02-12 23:24:41 +0000404 else:
cliechtid6bf52c2003-10-01 02:28:12 +0000405 if self._xonxoff:
Chris Liechti11465c82015-08-04 15:55:22 +0200406 iflag |= (termios.IXON|termios.IXOFF)
cliechti89b4af12002-02-12 23:24:41 +0000407 else:
Chris Liechti11465c82015-08-04 15:55:22 +0200408 iflag &= ~(termios.IXON|termios.IXOFF)
cliechti58b481c2009-02-16 20:42:32 +0000409 # rtscts
Chris Liechti11465c82015-08-04 15:55:22 +0200410 if hasattr(termios, 'CRTSCTS'):
cliechtid6bf52c2003-10-01 02:28:12 +0000411 if self._rtscts:
Chris Liechti11465c82015-08-04 15:55:22 +0200412 cflag |= (termios.CRTSCTS)
cliechti89b4af12002-02-12 23:24:41 +0000413 else:
Chris Liechti11465c82015-08-04 15:55:22 +0200414 cflag &= ~(termios.CRTSCTS)
415 elif hasattr(termios, 'CNEW_RTSCTS'): # try it with alternate constant name
cliechtid6bf52c2003-10-01 02:28:12 +0000416 if self._rtscts:
Chris Liechti11465c82015-08-04 15:55:22 +0200417 cflag |= (termios.CNEW_RTSCTS)
cliechtid4743692002-04-08 22:39:53 +0000418 else:
Chris Liechti11465c82015-08-04 15:55:22 +0200419 cflag &= ~(termios.CNEW_RTSCTS)
cliechti2750b832009-07-28 00:13:52 +0000420 # XXX should there be a warning if setting up rtscts (and xonxoff etc) fails??
cliechti58b481c2009-02-16 20:42:32 +0000421
422 # buffer
cliechtif0a81d42014-08-04 14:03:53 +0000423 # vmin "minimal number of characters to be read. 0 for non blocking"
cliechtid6bf52c2003-10-01 02:28:12 +0000424 if vmin < 0 or vmin > 255:
425 raise ValueError('Invalid vmin: %r ' % vmin)
Chris Liechti11465c82015-08-04 15:55:22 +0200426 cc[termios.VMIN] = vmin
cliechti58b481c2009-02-16 20:42:32 +0000427 # vtime
cliechtid6bf52c2003-10-01 02:28:12 +0000428 if vtime < 0 or vtime > 255:
429 raise ValueError('Invalid vtime: %r' % vtime)
Chris Liechti11465c82015-08-04 15:55:22 +0200430 cc[termios.VTIME] = vtime
cliechti58b481c2009-02-16 20:42:32 +0000431 # activate settings
cliechti4d0af5e2011-08-05 02:18:16 +0000432 if [iflag, oflag, cflag, lflag, ispeed, ospeed, cc] != orig_attr:
Chris Liechti11465c82015-08-04 15:55:22 +0200433 termios.tcsetattr(self.fd, termios.TCSANOW, [iflag, oflag, cflag, lflag, ispeed, ospeed, cc])
cliechti58b481c2009-02-16 20:42:32 +0000434
cliechtie8c45422008-06-20 23:23:14 +0000435 # apply custom baud rate, if any
436 if custom_baud is not None:
Chris Liechtid6847af2015-08-06 17:54:30 +0200437 self._set_special_baudrate(custom_baud)
438
439 if self._rs485_mode is not None:
440 self._set_rs485_mode(self._rs485_mode)
cliechti89b4af12002-02-12 23:24:41 +0000441
442 def close(self):
cliechtid6bf52c2003-10-01 02:28:12 +0000443 """Close port"""
444 if self._isOpen:
cliechtic6178262004-03-22 22:04:52 +0000445 if self.fd is not None:
cliechtid6bf52c2003-10-01 02:28:12 +0000446 os.close(self.fd)
447 self.fd = None
448 self._isOpen = False
cliechti89b4af12002-02-12 23:24:41 +0000449
cliechtid6bf52c2003-10-01 02:28:12 +0000450 def makeDeviceName(self, port):
Chris Liechtid6847af2015-08-06 17:54:30 +0200451 return self.number_to_device(port)
cliechtid6bf52c2003-10-01 02:28:12 +0000452
453 # - - - - - - - - - - - - - - - - - - - - - - - -
cliechti95c62212002-03-04 22:17:53 +0000454
cliechti89b4af12002-02-12 23:24:41 +0000455 def inWaiting(self):
cliechtid6bf52c2003-10-01 02:28:12 +0000456 """Return the number of characters currently in the input buffer."""
Chris Liechti11465c82015-08-04 15:55:22 +0200457 #~ s = fcntl.ioctl(self.fd, termios.FIONREAD, TIOCM_zero_str)
cliechtif5831e02002-12-05 23:15:27 +0000458 s = fcntl.ioctl(self.fd, TIOCINQ, TIOCM_zero_str)
cliechti89b4af12002-02-12 23:24:41 +0000459 return struct.unpack('I',s)[0]
460
cliechtia9a093e2010-01-02 03:05:08 +0000461 # select based implementation, proved to work on many systems
462 def read(self, size=1):
cliechti7d448562014-08-03 21:57:45 +0000463 """\
464 Read size bytes from the serial port. If a timeout is set it may
465 return less characters as requested. With no timeout it will block
466 until the requested number of bytes is read.
467 """
cliechti899c9c42011-06-14 23:01:23 +0000468 if not self._isOpen: raise portNotOpenError
cliechtia9a093e2010-01-02 03:05:08 +0000469 read = bytearray()
470 while len(read) < size:
cliechti8d744de2013-10-11 14:31:13 +0000471 try:
472 ready,_,_ = select.select([self.fd],[],[], self._timeout)
473 # If select was used with a timeout, and the timeout occurs, it
474 # returns with empty lists -> thus abort read operation.
475 # For timeout == 0 (non-blocking operation) also abort when there
476 # is nothing to read.
477 if not ready:
478 break # timeout
479 buf = os.read(self.fd, size-len(read))
480 # read should always return some data as select reported it was
481 # ready to read when we get to this point.
482 if not buf:
483 # Disconnected devices, at least on Linux, show the
484 # behavior that they are always ready to read immediately
485 # but reading returns nothing.
486 raise SerialException('device reports readiness to read but returned no data (device disconnected or multiple access on port?)')
487 read.extend(buf)
Chris Liechti68340d72015-08-03 14:15:48 +0200488 except OSError as e:
cliechtic7cd7212014-08-03 21:34:38 +0000489 # this is for Python 3.x where select.error is a subclass of OSError
490 # ignore EAGAIN errors. all other errors are shown
491 if e.errno != errno.EAGAIN:
492 raise SerialException('read failed: %s' % (e,))
Chris Liechti68340d72015-08-03 14:15:48 +0200493 except select.error as e:
cliechtic7cd7212014-08-03 21:34:38 +0000494 # this is for Python 2.x
cliechti8d744de2013-10-11 14:31:13 +0000495 # ignore EAGAIN errors. all other errors are shown
496 # see also http://www.python.org/dev/peps/pep-3151/#select
497 if e[0] != errno.EAGAIN:
498 raise SerialException('read failed: %s' % (e,))
cliechtia9a093e2010-01-02 03:05:08 +0000499 return bytes(read)
cliechti89b4af12002-02-12 23:24:41 +0000500
cliechti4a567a02009-07-27 22:09:31 +0000501 def write(self, data):
cliechtid6bf52c2003-10-01 02:28:12 +0000502 """Output the given string over the serial port."""
cliechti899c9c42011-06-14 23:01:23 +0000503 if not self._isOpen: raise portNotOpenError
cliechti38077122013-10-16 02:57:27 +0000504 d = to_bytes(data)
505 tx_len = len(d)
cliechti3cf46d62009-08-07 00:19:57 +0000506 if self._writeTimeout is not None and self._writeTimeout > 0:
507 timeout = time.time() + self._writeTimeout
508 else:
509 timeout = None
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)
cliechti3cf46d62009-08-07 00:19:57 +0000513 if timeout:
514 # when timeout is set, use select to wait for being ready
515 # with the time left as timeout
516 timeleft = timeout - time.time()
517 if timeleft < 0:
518 raise writeTimeoutError
519 _, ready, _ = select.select([], [self.fd], [], timeleft)
cliechti5d4d0bd2004-11-13 03:27:39 +0000520 if not ready:
521 raise writeTimeoutError
cliechti88c62442013-10-12 04:03:16 +0000522 else:
523 # wait for write operation
524 _, ready, _ = select.select([], [self.fd], [], None)
525 if not ready:
526 raise SerialException('write failed (select)')
cliechti5d4d0bd2004-11-13 03:27:39 +0000527 d = d[n:]
cliechti9f7c2352013-10-11 01:13:46 +0000528 tx_len -= n
Chris Liechti675f7e12015-08-03 15:48:41 +0200529 except SerialException:
530 raise
Chris Liechti68340d72015-08-03 14:15:48 +0200531 except OSError as v:
cliechti5d4d0bd2004-11-13 03:27:39 +0000532 if v.errno != errno.EAGAIN:
cliechti65722c92009-08-07 00:48:53 +0000533 raise SerialException('write failed: %s' % (v,))
cliechtif81362e2009-07-25 03:44:33 +0000534 return len(data)
cliechtid6bf52c2003-10-01 02:28:12 +0000535
cliechtia30a8a02003-10-05 12:28:13 +0000536 def flush(self):
cliechti7d448562014-08-03 21:57:45 +0000537 """\
538 Flush of file like objects. In this case, wait until all data
539 is written.
540 """
cliechtia30a8a02003-10-05 12:28:13 +0000541 self.drainOutput()
542
cliechti89b4af12002-02-12 23:24:41 +0000543 def flushInput(self):
cliechtid6bf52c2003-10-01 02:28:12 +0000544 """Clear input buffer, discarding all that is in the buffer."""
cliechti899c9c42011-06-14 23:01:23 +0000545 if not self._isOpen: raise portNotOpenError
Chris Liechti11465c82015-08-04 15:55:22 +0200546 termios.tcflush(self.fd, termios.TCIFLUSH)
cliechti89b4af12002-02-12 23:24:41 +0000547
548 def flushOutput(self):
cliechti7d448562014-08-03 21:57:45 +0000549 """\
550 Clear output buffer, aborting the current output and discarding all
551 that is in the buffer.
552 """
cliechti899c9c42011-06-14 23:01:23 +0000553 if not self._isOpen: raise portNotOpenError
Chris Liechti11465c82015-08-04 15:55:22 +0200554 termios.tcflush(self.fd, termios.TCOFLUSH)
cliechti89b4af12002-02-12 23:24:41 +0000555
cliechtiaaa04602006-02-05 23:02:46 +0000556 def sendBreak(self, duration=0.25):
cliechti7d448562014-08-03 21:57:45 +0000557 """\
558 Send break condition. Timed, returns to idle state after given
559 duration.
560 """
cliechti899c9c42011-06-14 23:01:23 +0000561 if not self._isOpen: raise portNotOpenError
cliechtiaaa04602006-02-05 23:02:46 +0000562 termios.tcsendbreak(self.fd, int(duration/0.25))
cliechti89b4af12002-02-12 23:24:41 +0000563
cliechti997b63c2008-06-21 00:09:31 +0000564 def setBreak(self, level=1):
cliechti7d448562014-08-03 21:57:45 +0000565 """\
566 Set break: Controls TXD. When active, no transmitting is possible.
567 """
cliechti997b63c2008-06-21 00:09:31 +0000568 if self.fd is None: raise portNotOpenError
569 if level:
570 fcntl.ioctl(self.fd, TIOCSBRK)
571 else:
572 fcntl.ioctl(self.fd, TIOCCBRK)
573
cliechti93db61b2006-08-26 19:16:18 +0000574 def setRTS(self, level=1):
cliechtid6bf52c2003-10-01 02:28:12 +0000575 """Set terminal status line: Request To Send"""
cliechti899c9c42011-06-14 23:01:23 +0000576 if not self._isOpen: raise portNotOpenError
cliechtib2f5fc82006-10-20 00:09:07 +0000577 if level:
cliechtid6bf52c2003-10-01 02:28:12 +0000578 fcntl.ioctl(self.fd, TIOCMBIS, TIOCM_RTS_str)
579 else:
580 fcntl.ioctl(self.fd, TIOCMBIC, TIOCM_RTS_str)
581
cliechti93db61b2006-08-26 19:16:18 +0000582 def setDTR(self, level=1):
cliechtid6bf52c2003-10-01 02:28:12 +0000583 """Set terminal status line: Data Terminal Ready"""
cliechti899c9c42011-06-14 23:01:23 +0000584 if not self._isOpen: raise portNotOpenError
cliechtib2f5fc82006-10-20 00:09:07 +0000585 if level:
cliechtid6bf52c2003-10-01 02:28:12 +0000586 fcntl.ioctl(self.fd, TIOCMBIS, TIOCM_DTR_str)
587 else:
588 fcntl.ioctl(self.fd, TIOCMBIC, TIOCM_DTR_str)
589
590 def getCTS(self):
591 """Read terminal status line: Clear To Send"""
cliechti899c9c42011-06-14 23:01:23 +0000592 if not self._isOpen: raise portNotOpenError
cliechtid6bf52c2003-10-01 02:28:12 +0000593 s = fcntl.ioctl(self.fd, TIOCMGET, TIOCM_zero_str)
594 return struct.unpack('I',s)[0] & TIOCM_CTS != 0
595
596 def getDSR(self):
597 """Read terminal status line: Data Set Ready"""
cliechti899c9c42011-06-14 23:01:23 +0000598 if not self._isOpen: raise portNotOpenError
cliechtid6bf52c2003-10-01 02:28:12 +0000599 s = fcntl.ioctl(self.fd, TIOCMGET, TIOCM_zero_str)
600 return struct.unpack('I',s)[0] & TIOCM_DSR != 0
601
cliechtid6bf52c2003-10-01 02:28:12 +0000602 def getRI(self):
603 """Read terminal status line: Ring Indicator"""
cliechti899c9c42011-06-14 23:01:23 +0000604 if not self._isOpen: raise portNotOpenError
cliechti89b4af12002-02-12 23:24:41 +0000605 s = fcntl.ioctl(self.fd, TIOCMGET, TIOCM_zero_str)
cliechtid6bf52c2003-10-01 02:28:12 +0000606 return struct.unpack('I',s)[0] & TIOCM_RI != 0
cliechti89b4af12002-02-12 23:24:41 +0000607
608 def getCD(self):
cliechtid6bf52c2003-10-01 02:28:12 +0000609 """Read terminal status line: Carrier Detect"""
cliechti899c9c42011-06-14 23:01:23 +0000610 if not self._isOpen: raise portNotOpenError
cliechti89b4af12002-02-12 23:24:41 +0000611 s = fcntl.ioctl(self.fd, TIOCMGET, TIOCM_zero_str)
cliechtid6bf52c2003-10-01 02:28:12 +0000612 return struct.unpack('I',s)[0] & TIOCM_CD != 0
cliechti89b4af12002-02-12 23:24:41 +0000613
cliechtia30a8a02003-10-05 12:28:13 +0000614 # - - platform specific - - - -
615
cliechti28b8fd02011-12-28 21:39:42 +0000616 def outWaiting(self):
617 """Return the number of characters currently in the output buffer."""
Chris Liechti11465c82015-08-04 15:55:22 +0200618 #~ s = fcntl.ioctl(self.fd, termios.FIONREAD, TIOCM_zero_str)
cliechti28b8fd02011-12-28 21:39:42 +0000619 s = fcntl.ioctl(self.fd, TIOCOUTQ, TIOCM_zero_str)
620 return struct.unpack('I',s)[0]
621
cliechtia30a8a02003-10-05 12:28:13 +0000622 def drainOutput(self):
623 """internal - not portable!"""
cliechti899c9c42011-06-14 23:01:23 +0000624 if not self._isOpen: raise portNotOpenError
cliechtia30a8a02003-10-05 12:28:13 +0000625 termios.tcdrain(self.fd)
626
627 def nonblocking(self):
628 """internal - not portable!"""
cliechti899c9c42011-06-14 23:01:23 +0000629 if not self._isOpen: raise portNotOpenError
Chris Liechti11465c82015-08-04 15:55:22 +0200630 fcntl.fcntl(self.fd, fcntl.F_SETFL, os.O_NONBLOCK)
cliechtia30a8a02003-10-05 12:28:13 +0000631
cliechti8753bbc2005-01-15 20:32:51 +0000632 def fileno(self):
cliechti2f0f8a32011-12-28 22:10:00 +0000633 """\
634 For easier use of the serial port instance with select.
635 WARNING: this function is not portable to different platforms!
636 """
cliechti899c9c42011-06-14 23:01:23 +0000637 if not self._isOpen: raise portNotOpenError
cliechti8753bbc2005-01-15 20:32:51 +0000638 return self.fd
cliechti89b4af12002-02-12 23:24:41 +0000639
cliechti2f0f8a32011-12-28 22:10:00 +0000640 def setXON(self, level=True):
641 """\
642 Manually control flow - when software flow control is enabled.
643 This will send XON (true) and XOFF (false) to the other device.
644 WARNING: this function is not portable to different platforms!
645 """
Chris Liechti905d5072015-08-03 21:41:49 +0200646 if not self._isOpen: raise portNotOpenError
cliechti4a601342011-12-29 02:22:17 +0000647 if enable:
Chris Liechti11465c82015-08-04 15:55:22 +0200648 termios.tcflow(self.fd, termios.TCION)
cliechti57e48a62009-08-03 22:29:58 +0000649 else:
Chris Liechti11465c82015-08-04 15:55:22 +0200650 termios.tcflow(self.fd, termios.TCIOFF)
cliechti57e48a62009-08-03 22:29:58 +0000651
cliechti2f0f8a32011-12-28 22:10:00 +0000652 def flowControlOut(self, enable):
653 """\
654 Manually control flow of outgoing data - when hardware or software flow
655 control is enabled.
656 WARNING: this function is not portable to different platforms!
657 """
658 if not self._isOpen: raise portNotOpenError
659 if enable:
Chris Liechti11465c82015-08-04 15:55:22 +0200660 termios.tcflow(self.fd, termios.TCOON)
cliechti2f0f8a32011-12-28 22:10:00 +0000661 else:
Chris Liechti11465c82015-08-04 15:55:22 +0200662 termios.tcflow(self.fd, termios.TCOOFF)
cliechti2f0f8a32011-12-28 22:10:00 +0000663
cliechtif81362e2009-07-25 03:44:33 +0000664
cliechtif81362e2009-07-25 03:44:33 +0000665
cliechtia9a093e2010-01-02 03:05:08 +0000666class PosixPollSerial(Serial):
cliechti7d448562014-08-03 21:57:45 +0000667 """\
cliechtif0a81d42014-08-04 14:03:53 +0000668 Poll based read implementation. Not all systems support poll properly.
669 However this one has better handling of errors, such as a device
cliechti7d448562014-08-03 21:57:45 +0000670 disconnecting while it's in use (e.g. USB-serial unplugged).
671 """
cliechtia9a093e2010-01-02 03:05:08 +0000672
673 def read(self, size=1):
cliechti7d448562014-08-03 21:57:45 +0000674 """\
675 Read size bytes from the serial port. If a timeout is set it may
676 return less characters as requested. With no timeout it will block
677 until the requested number of bytes is read.
678 """
cliechtia9a093e2010-01-02 03:05:08 +0000679 if self.fd is None: raise portNotOpenError
680 read = bytearray()
681 poll = select.poll()
682 poll.register(self.fd, select.POLLIN|select.POLLERR|select.POLLHUP|select.POLLNVAL)
683 if size > 0:
684 while len(read) < size:
685 # print "\tread(): size",size, "have", len(read) #debug
686 # wait until device becomes ready to read (or something fails)
cliechti4cd0d2e2010-07-21 01:15:25 +0000687 for fd, event in poll.poll(self._timeout*1000):
cliechtia9a093e2010-01-02 03:05:08 +0000688 if event & (select.POLLERR|select.POLLHUP|select.POLLNVAL):
689 raise SerialException('device reports error (poll)')
690 # we don't care if it is select.POLLIN or timeout, that's
691 # handled below
692 buf = os.read(self.fd, size - len(read))
693 read.extend(buf)
694 if ((self._timeout is not None and self._timeout >= 0) or
695 (self._interCharTimeout is not None and self._interCharTimeout > 0)) and not buf:
696 break # early abort on timeout
697 return bytes(read)
698
cliechtif81362e2009-07-25 03:44:33 +0000699
cliechti89b4af12002-02-12 23:24:41 +0000700if __name__ == '__main__':
701 s = Serial(0,
cliechti53c9fd42009-07-23 23:51:51 +0000702 baudrate=19200, # baud rate
703 bytesize=EIGHTBITS, # number of data bits
cliechti3172d3d2009-07-21 22:33:40 +0000704 parity=PARITY_EVEN, # enable parity checking
cliechti53c9fd42009-07-23 23:51:51 +0000705 stopbits=STOPBITS_ONE, # number of stop bits
cliechti3172d3d2009-07-21 22:33:40 +0000706 timeout=3, # set a timeout value, None for waiting forever
707 xonxoff=0, # enable software flow control
708 rtscts=0, # enable RTS/CTS flow control
cliechti89b4af12002-02-12 23:24:41 +0000709 )
710 s.setRTS(1)
711 s.setDTR(1)
712 s.flushInput()
713 s.flushOutput()
714 s.write('hello')
cliechti109486b2009-08-02 00:00:11 +0000715 sys.stdout.write('%r\n' % s.read(5))
716 sys.stdout.write('%s\n' % s.inWaiting())
cliechti89b4af12002-02-12 23:24:41 +0000717 del s
cliechti4569bac2007-11-08 21:57:19 +0000718