blob: 0c3052a9a5d30050fd1d96462d128741caac4929 [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
cliechti3cf46d62009-08-07 00:19:57 +000015import sys, os, fcntl, termios, struct, select, errno, time
Chris Liechtiaf6d0462015-08-03 17:21:14 +020016import io
cliechti39cfb7b2011-08-22 00:30:07 +000017from serial.serialutil import *
cliechti89b4af12002-02-12 23:24:41 +000018
cliechti89b4af12002-02-12 23:24:41 +000019
cliechti3172d3d2009-07-21 22:33:40 +000020# try to detect the OS so that a device can be selected...
cliechti53c9fd42009-07-23 23:51:51 +000021# this code block should supply a device() and set_special_baudrate() function
22# for the platform
cliechtid6bf52c2003-10-01 02:28:12 +000023plat = sys.platform.lower()
cliechti89b4af12002-02-12 23:24:41 +000024
cliechti3172d3d2009-07-21 22:33:40 +000025if plat[:5] == 'linux': # Linux (confirmed)
cliechti53c9fd42009-07-23 23:51:51 +000026
cliechti89b4af12002-02-12 23:24:41 +000027 def device(port):
28 return '/dev/ttyS%d' % port
29
cliechti1877c522013-10-11 14:02:26 +000030 TCGETS2 = 0x802C542A
31 TCSETS2 = 0x402C542B
32 BOTHER = 0o010000
cliechti53c9fd42009-07-23 23:51:51 +000033
34 def set_special_baudrate(port, baudrate):
cliechti1877c522013-10-11 14:02:26 +000035 # right size is 44 on x86_64, allow for some growth
cliechti53c9fd42009-07-23 23:51:51 +000036 import array
cliechti1877c522013-10-11 14:02:26 +000037 buf = array.array('i', [0] * 64)
cliechti53c9fd42009-07-23 23:51:51 +000038
cliechti53c9fd42009-07-23 23:51:51 +000039 try:
cliechti95772d32013-10-11 14:38:13 +000040 # get serial_struct
Chris Liechti11465c82015-08-04 15:55:22 +020041 fcntl.ioctl(port.fd, TCGETS2, buf)
cliechti95772d32013-10-11 14:38:13 +000042 # set custom speed
Chris Liechti11465c82015-08-04 15:55:22 +020043 buf[2] &= ~termios.CBAUD
cliechti95772d32013-10-11 14:38:13 +000044 buf[2] |= BOTHER
45 buf[9] = buf[10] = baudrate
46
47 # set serial_struct
Chris Liechti11465c82015-08-04 15:55:22 +020048 res = fcntl.ioctl(port.fd, TCSETS2, buf)
Chris Liechti68340d72015-08-03 14:15:48 +020049 except IOError as e:
cliechti95772d32013-10-11 14:38:13 +000050 raise ValueError('Failed to set custom baud rate (%s): %s' % (baudrate, e))
cliechti53c9fd42009-07-23 23:51:51 +000051
cliechti99220a02009-08-14 00:21:25 +000052 baudrate_constants = {
Chris Liechti68340d72015-08-03 14:15:48 +020053 0: 0o000000, # hang up
54 50: 0o000001,
55 75: 0o000002,
56 110: 0o000003,
57 134: 0o000004,
58 150: 0o000005,
59 200: 0o000006,
60 300: 0o000007,
61 600: 0o000010,
62 1200: 0o000011,
63 1800: 0o000012,
64 2400: 0o000013,
65 4800: 0o000014,
66 9600: 0o000015,
67 19200: 0o000016,
68 38400: 0o000017,
69 57600: 0o010001,
70 115200: 0o010002,
71 230400: 0o010003,
72 460800: 0o010004,
73 500000: 0o010005,
74 576000: 0o010006,
75 921600: 0o010007,
76 1000000: 0o010010,
77 1152000: 0o010011,
78 1500000: 0o010012,
79 2000000: 0o010013,
80 2500000: 0o010014,
81 3000000: 0o010015,
82 3500000: 0o010016,
83 4000000: 0o010017
cliechti99220a02009-08-14 00:21:25 +000084 }
85
cliechti53c9fd42009-07-23 23:51:51 +000086elif plat == 'cygwin': # cygwin/win32 (confirmed)
87
cliechtif281fde2002-06-07 21:53:40 +000088 def device(port):
cliechtif5831e02002-12-05 23:15:27 +000089 return '/dev/com%d' % (port + 1)
cliechtif281fde2002-06-07 21:53:40 +000090
cliechti53c9fd42009-07-23 23:51:51 +000091 def set_special_baudrate(port, baudrate):
cliechti99220a02009-08-14 00:21:25 +000092 raise ValueError("sorry don't know how to handle non standard baud rate on this platform")
cliechti53c9fd42009-07-23 23:51:51 +000093
cliechtia505de32013-05-31 01:27:25 +000094 baudrate_constants = {
95 128000: 0x01003,
96 256000: 0x01005,
97 500000: 0x01007,
98 576000: 0x01008,
99 921600: 0x01009,
100 1000000: 0x0100a,
101 1152000: 0x0100b,
102 1500000: 0x0100c,
103 2000000: 0x0100d,
104 2500000: 0x0100e,
105 3000000: 0x0100f
106 }
cliechti53c9fd42009-07-23 23:51:51 +0000107
cliechti4a601342011-12-29 02:22:17 +0000108elif plat[:7] == 'openbsd': # OpenBSD
cliechti53c9fd42009-07-23 23:51:51 +0000109
cliechti89b4af12002-02-12 23:24:41 +0000110 def device(port):
cliechti4a601342011-12-29 02:22:17 +0000111 return '/dev/cua%02d' % port
cliechti89b4af12002-02-12 23:24:41 +0000112
cliechti53c9fd42009-07-23 23:51:51 +0000113 def set_special_baudrate(port, baudrate):
114 raise ValueError("sorry don't know how to handle non standard baud rate on this platform")
115
cliechti99220a02009-08-14 00:21:25 +0000116 baudrate_constants = {}
117
cliechti89b4af12002-02-12 23:24:41 +0000118elif plat[:3] == 'bsd' or \
cliechti4a601342011-12-29 02:22:17 +0000119 plat[:7] == 'freebsd':
cliechti53c9fd42009-07-23 23:51:51 +0000120
cliechti89b4af12002-02-12 23:24:41 +0000121 def device(port):
cliechtieaa96882008-06-16 22:59:20 +0000122 return '/dev/cuad%d' % port
cliechti89b4af12002-02-12 23:24:41 +0000123
cliechti53c9fd42009-07-23 23:51:51 +0000124 def set_special_baudrate(port, baudrate):
125 raise ValueError("sorry don't know how to handle non standard baud rate on this platform")
126
cliechti99220a02009-08-14 00:21:25 +0000127 baudrate_constants = {}
128
cliechti53c9fd42009-07-23 23:51:51 +0000129elif plat[:6] == 'darwin': # OS X
130
131 version = os.uname()[2].split('.')
132 # Tiger or above can support arbitrary serial speeds
133 if int(version[0]) >= 8:
cliechti53c9fd42009-07-23 23:51:51 +0000134 def set_special_baudrate(port, baudrate):
135 # use IOKit-specific call to set up high speeds
Chris Liechti11465c82015-08-04 15:55:22 +0200136 import array
cliechti53c9fd42009-07-23 23:51:51 +0000137 buf = array.array('i', [baudrate])
138 IOSSIOSPEED = 0x80045402 #_IOW('T', 2, speed_t)
139 fcntl.ioctl(port.fd, IOSSIOSPEED, buf, 1)
140 else: # version < 8
141 def set_special_baudrate(port, baudrate):
142 raise ValueError("baud rate not supported")
143
144 def device(port):
145 return '/dev/cuad%d' % port
146
cliechti99220a02009-08-14 00:21:25 +0000147 baudrate_constants = {}
148
cliechti53c9fd42009-07-23 23:51:51 +0000149
cliechti3172d3d2009-07-21 22:33:40 +0000150elif plat[:6] == 'netbsd': # NetBSD 1.6 testing by Erk
cliechti53c9fd42009-07-23 23:51:51 +0000151
cliechti835996a2004-06-02 19:45:07 +0000152 def device(port):
153 return '/dev/dty%02d' % port
154
cliechti53c9fd42009-07-23 23:51:51 +0000155 def set_special_baudrate(port, baudrate):
156 raise ValueError("sorry don't know how to handle non standard baud rate on this platform")
157
cliechti99220a02009-08-14 00:21:25 +0000158 baudrate_constants = {}
159
cliechti3172d3d2009-07-21 22:33:40 +0000160elif plat[:4] == 'irix': # IRIX (partially tested)
cliechti53c9fd42009-07-23 23:51:51 +0000161
cliechti89b4af12002-02-12 23:24:41 +0000162 def device(port):
cliechtie2418e92006-06-05 20:03:17 +0000163 return '/dev/ttyf%d' % (port+1) #XXX different device names depending on flow control
cliechti89b4af12002-02-12 23:24:41 +0000164
cliechti53c9fd42009-07-23 23:51:51 +0000165 def set_special_baudrate(port, baudrate):
166 raise ValueError("sorry don't know how to handle non standard baud rate on this platform")
167
cliechti99220a02009-08-14 00:21:25 +0000168 baudrate_constants = {}
169
cliechti3172d3d2009-07-21 22:33:40 +0000170elif plat[:2] == 'hp': # HP-UX (not tested)
cliechti53c9fd42009-07-23 23:51:51 +0000171
cliechti89b4af12002-02-12 23:24:41 +0000172 def device(port):
173 return '/dev/tty%dp0' % (port+1)
174
cliechti53c9fd42009-07-23 23:51:51 +0000175 def set_special_baudrate(port, baudrate):
176 raise ValueError("sorry don't know how to handle non standard baud rate on this platform")
177
cliechti99220a02009-08-14 00:21:25 +0000178 baudrate_constants = {}
179
cliechti3172d3d2009-07-21 22:33:40 +0000180elif plat[:5] == 'sunos': # Solaris/SunOS (confirmed)
cliechti53c9fd42009-07-23 23:51:51 +0000181
cliechti89b4af12002-02-12 23:24:41 +0000182 def device(port):
183 return '/dev/tty%c' % (ord('a')+port)
cliechti58b481c2009-02-16 20:42:32 +0000184
cliechti53c9fd42009-07-23 23:51:51 +0000185 def set_special_baudrate(port, baudrate):
186 raise ValueError("sorry don't know how to handle non standard baud rate on this platform")
187
cliechti99220a02009-08-14 00:21:25 +0000188 baudrate_constants = {}
189
cliechti3172d3d2009-07-21 22:33:40 +0000190elif plat[:3] == 'aix': # AIX
cliechti53c9fd42009-07-23 23:51:51 +0000191
cliechti40e1b072005-03-12 12:05:26 +0000192 def device(port):
193 return '/dev/tty%d' % (port)
cliechti89b4af12002-02-12 23:24:41 +0000194
cliechti53c9fd42009-07-23 23:51:51 +0000195 def set_special_baudrate(port, baudrate):
196 raise ValueError("sorry don't know how to handle non standard baud rate on this platform")
197
cliechti99220a02009-08-14 00:21:25 +0000198 baudrate_constants = {}
199
cliechti89b4af12002-02-12 23:24:41 +0000200else:
cliechtia9a093e2010-01-02 03:05:08 +0000201 # platform detection has failed...
cliechti7aaead32009-07-23 14:02:41 +0000202 sys.stderr.write("""\
203don't know how to number ttys on this system.
cliechti895e8302004-04-20 02:40:28 +0000204! Use an explicit path (eg /dev/ttyS1) or send this information to
205! the author of this module:
cliechti89b4af12002-02-12 23:24:41 +0000206
cliechti895e8302004-04-20 02:40:28 +0000207sys.platform = %r
208os.name = %r
209serialposix.py version = %s
cliechti89b4af12002-02-12 23:24:41 +0000210
211also add the device name of the serial port and where the
212counting starts for the first serial port.
213e.g. 'first serial port: /dev/ttyS0'
214and with a bit luck you can get this module running...
cliechti7aaead32009-07-23 14:02:41 +0000215""" % (sys.platform, os.name, VERSION))
cliechti58b481c2009-02-16 20:42:32 +0000216 # no exception, just continue with a brave attempt to build a device name
217 # even if the device name is not correct for the platform it has chances
cliechti3172d3d2009-07-21 22:33:40 +0000218 # to work using a string with the real device name as port parameter.
cliechtid6bf52c2003-10-01 02:28:12 +0000219 def device(portum):
220 return '/dev/ttyS%d' % portnum
cliechti53c9fd42009-07-23 23:51:51 +0000221 def set_special_baudrate(port, baudrate):
222 raise SerialException("sorry don't know how to handle non standard baud rate on this platform")
cliechti99220a02009-08-14 00:21:25 +0000223 baudrate_constants = {}
cliechtid6bf52c2003-10-01 02:28:12 +0000224 #~ raise Exception, "this module does not run on this platform, sorry."
cliechti89b4af12002-02-12 23:24:41 +0000225
cliechti58b481c2009-02-16 20:42:32 +0000226# whats up with "aix", "beos", ....
227# they should work, just need to know the device names.
cliechti89b4af12002-02-12 23:24:41 +0000228
229
cliechti58b481c2009-02-16 20:42:32 +0000230# load some constants for later use.
Chris Liechti11465c82015-08-04 15:55:22 +0200231# try to use values from termios, use defaults from linux otherwise
232TIOCMGET = hasattr(termios, 'TIOCMGET') and termios.TIOCMGET or 0x5415
233TIOCMBIS = hasattr(termios, 'TIOCMBIS') and termios.TIOCMBIS or 0x5416
234TIOCMBIC = hasattr(termios, 'TIOCMBIC') and termios.TIOCMBIC or 0x5417
235TIOCMSET = hasattr(termios, 'TIOCMSET') and termios.TIOCMSET or 0x5418
cliechti89b4af12002-02-12 23:24:41 +0000236
Chris Liechti11465c82015-08-04 15:55:22 +0200237#TIOCM_LE = hasattr(termios, 'TIOCM_LE') and termios.TIOCM_LE or 0x001
238TIOCM_DTR = hasattr(termios, 'TIOCM_DTR') and termios.TIOCM_DTR or 0x002
239TIOCM_RTS = hasattr(termios, 'TIOCM_RTS') and termios.TIOCM_RTS or 0x004
240#TIOCM_ST = hasattr(termios, 'TIOCM_ST') and termios.TIOCM_ST or 0x008
241#TIOCM_SR = hasattr(termios, 'TIOCM_SR') and termios.TIOCM_SR or 0x010
cliechti89b4af12002-02-12 23:24:41 +0000242
Chris Liechti11465c82015-08-04 15:55:22 +0200243TIOCM_CTS = hasattr(termios, 'TIOCM_CTS') and termios.TIOCM_CTS or 0x020
244TIOCM_CAR = hasattr(termios, 'TIOCM_CAR') and termios.TIOCM_CAR or 0x040
245TIOCM_RNG = hasattr(termios, 'TIOCM_RNG') and termios.TIOCM_RNG or 0x080
246TIOCM_DSR = hasattr(termios, 'TIOCM_DSR') and termios.TIOCM_DSR or 0x100
247TIOCM_CD = hasattr(termios, 'TIOCM_CD') and termios.TIOCM_CD or TIOCM_CAR
248TIOCM_RI = hasattr(termios, 'TIOCM_RI') and termios.TIOCM_RI or TIOCM_RNG
249#TIOCM_OUT1 = hasattr(termios, 'TIOCM_OUT1') and termios.TIOCM_OUT1 or 0x2000
250#TIOCM_OUT2 = hasattr(termios, 'TIOCM_OUT2') and termios.TIOCM_OUT2 or 0x4000
251if hasattr(termios, 'TIOCINQ'):
252 TIOCINQ = termios.TIOCINQ
cliechti28b8fd02011-12-28 21:39:42 +0000253else:
Chris Liechti11465c82015-08-04 15:55:22 +0200254 TIOCINQ = hasattr(termios, 'FIONREAD') and termios.FIONREAD or 0x541B
255TIOCOUTQ = hasattr(termios, 'TIOCOUTQ') and termios.TIOCOUTQ or 0x5411
cliechti89b4af12002-02-12 23:24:41 +0000256
257TIOCM_zero_str = struct.pack('I', 0)
258TIOCM_RTS_str = struct.pack('I', TIOCM_RTS)
259TIOCM_DTR_str = struct.pack('I', TIOCM_DTR)
260
Chris Liechti11465c82015-08-04 15:55:22 +0200261TIOCSBRK = hasattr(termios, 'TIOCSBRK') and termios.TIOCSBRK or 0x5427
262TIOCCBRK = hasattr(termios, 'TIOCCBRK') and termios.TIOCCBRK or 0x5428
cliechti997b63c2008-06-21 00:09:31 +0000263
Chris Liechti68340d72015-08-03 14:15:48 +0200264CMSPAR = 0o10000000000 # Use "stick" (mark/space) parity
cliechtiaec27ab2014-07-31 22:21:24 +0000265
cliechti89b4af12002-02-12 23:24:41 +0000266
Chris Liechtiaf6d0462015-08-03 17:21:14 +0200267class Serial(SerialBase, io.RawIOBase):
cliechti7d448562014-08-03 21:57:45 +0000268 """\
269 Serial port class POSIX implementation. Serial port configuration is
cliechtid6bf52c2003-10-01 02:28:12 +0000270 done with termios and fcntl. Runs on Linux and many other Un*x like
cliechtif0a81d42014-08-04 14:03:53 +0000271 systems.
272 """
cliechtid6bf52c2003-10-01 02:28:12 +0000273
274 def open(self):
cliechti7d448562014-08-03 21:57:45 +0000275 """\
276 Open port with current settings. This may throw a SerialException
277 if the port cannot be opened."""
cliechtid6bf52c2003-10-01 02:28:12 +0000278 if self._port is None:
279 raise SerialException("Port must be configured before it can be used.")
cliechti02ef43a2011-03-24 23:33:12 +0000280 if self._isOpen:
281 raise SerialException("Port is already open.")
282 self.fd = None
cliechti58b481c2009-02-16 20:42:32 +0000283 # open
cliechti4616bf12002-04-08 23:13:14 +0000284 try:
285 self.fd = os.open(self.portstr, os.O_RDWR|os.O_NOCTTY|os.O_NONBLOCK)
Chris Liechti68340d72015-08-03 14:15:48 +0200286 except OSError as msg:
cliechti4616bf12002-04-08 23:13:14 +0000287 self.fd = None
cliechtiaf84daa2013-10-10 23:57:00 +0000288 raise SerialException(msg.errno, "could not open port %s: %s" % (self._port, msg))
Chris Liechti11465c82015-08-04 15:55:22 +0200289 #~ fcntl.fcntl(self.fd, fcntl.F_SETFL, 0) # set blocking
cliechti58b481c2009-02-16 20:42:32 +0000290
cliechtib2f5fc82006-10-20 00:09:07 +0000291 try:
292 self._reconfigurePort()
293 except:
cliechti2750b832009-07-28 00:13:52 +0000294 try:
295 os.close(self.fd)
296 except:
297 # ignore any exception when closing the port
298 # also to keep original exception that happened when setting up
299 pass
cliechtib2f5fc82006-10-20 00:09:07 +0000300 self.fd = None
cliechtif0a4f0f2009-07-21 21:12:37 +0000301 raise
cliechtib2f5fc82006-10-20 00:09:07 +0000302 else:
303 self._isOpen = True
cliechti5c9b0722013-10-17 03:19:39 +0000304 self.flushInput()
cliechti58b481c2009-02-16 20:42:32 +0000305
306
cliechtid6bf52c2003-10-01 02:28:12 +0000307 def _reconfigurePort(self):
cliechtib2f5fc82006-10-20 00:09:07 +0000308 """Set communication parameters on opened port."""
cliechtic6178262004-03-22 22:04:52 +0000309 if self.fd is None:
cliechtia9a093e2010-01-02 03:05:08 +0000310 raise SerialException("Can only operate on a valid file descriptor")
cliechtie8c45422008-06-20 23:23:14 +0000311 custom_baud = None
cliechti58b481c2009-02-16 20:42:32 +0000312
cliechti2750b832009-07-28 00:13:52 +0000313 vmin = vtime = 0 # timeout is done via select
cliechti679bfa62008-06-20 23:58:15 +0000314 if self._interCharTimeout is not None:
315 vmin = 1
316 vtime = int(self._interCharTimeout * 10)
cliechti6ce7ab12002-11-07 02:15:00 +0000317 try:
cliechti4d0af5e2011-08-05 02:18:16 +0000318 orig_attr = termios.tcgetattr(self.fd)
319 iflag, oflag, cflag, lflag, ispeed, ospeed, cc = orig_attr
Chris Liechti68340d72015-08-03 14:15:48 +0200320 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 +0000321 raise SerialException("Could not configure port: %s" % msg)
cliechti58b481c2009-02-16 20:42:32 +0000322 # set up raw mode / no echo / binary
Chris Liechti11465c82015-08-04 15:55:22 +0200323 cflag |= (termios.CLOCAL|termios.CREAD)
324 lflag &= ~(termios.ICANON|termios.ECHO|termios.ECHOE|termios.ECHOK|termios.ECHONL|
325 termios.ISIG|termios.IEXTEN) #|termios.ECHOPRT
cliechti2750b832009-07-28 00:13:52 +0000326 for flag in ('ECHOCTL', 'ECHOKE'): # netbsd workaround for Erk
Chris Liechti11465c82015-08-04 15:55:22 +0200327 if hasattr(termios, flag):
328 lflag &= ~getattr(termios, flag)
cliechti58b481c2009-02-16 20:42:32 +0000329
Chris Liechti11465c82015-08-04 15:55:22 +0200330 oflag &= ~(termios.OPOST|termios.ONLCR|termios.OCRNL)
331 iflag &= ~(termios.INLCR|termios.IGNCR|termios.ICRNL|termios.IGNBRK)
332 if hasattr(termios, 'IUCLC'):
333 iflag &= ~termios.IUCLC
334 if hasattr(termios, 'PARMRK'):
335 iflag &= ~termios.PARMRK
cliechti58b481c2009-02-16 20:42:32 +0000336
cliechtif0a4f0f2009-07-21 21:12:37 +0000337 # setup baud rate
cliechti89b4af12002-02-12 23:24:41 +0000338 try:
Chris Liechti11465c82015-08-04 15:55:22 +0200339 ispeed = ospeed = getattr(termios, 'B%s' % (self._baudrate))
cliechti895e8302004-04-20 02:40:28 +0000340 except AttributeError:
cliechtif1559d02007-11-08 23:43:58 +0000341 try:
342 ispeed = ospeed = baudrate_constants[self._baudrate]
343 except KeyError:
cliechtie8c45422008-06-20 23:23:14 +0000344 #~ raise ValueError('Invalid baud rate: %r' % self._baudrate)
cliechtif0a4f0f2009-07-21 21:12:37 +0000345 # may need custom baud rate, it isn't in our list.
Chris Liechti11465c82015-08-04 15:55:22 +0200346 ispeed = ospeed = getattr(termios, 'B38400')
cliechtif0a4f0f2009-07-21 21:12:37 +0000347 try:
348 custom_baud = int(self._baudrate) # store for later
349 except ValueError:
350 raise ValueError('Invalid baud rate: %r' % self._baudrate)
351 else:
352 if custom_baud < 0:
353 raise ValueError('Invalid baud rate: %r' % self._baudrate)
cliechti58b481c2009-02-16 20:42:32 +0000354
355 # setup char len
Chris Liechti11465c82015-08-04 15:55:22 +0200356 cflag &= ~termios.CSIZE
cliechtid6bf52c2003-10-01 02:28:12 +0000357 if self._bytesize == 8:
Chris Liechti11465c82015-08-04 15:55:22 +0200358 cflag |= termios.CS8
cliechtid6bf52c2003-10-01 02:28:12 +0000359 elif self._bytesize == 7:
Chris Liechti11465c82015-08-04 15:55:22 +0200360 cflag |= termios.CS7
cliechtid6bf52c2003-10-01 02:28:12 +0000361 elif self._bytesize == 6:
Chris Liechti11465c82015-08-04 15:55:22 +0200362 cflag |= termios.CS6
cliechtid6bf52c2003-10-01 02:28:12 +0000363 elif self._bytesize == 5:
Chris Liechti11465c82015-08-04 15:55:22 +0200364 cflag |= termios.CS5
cliechti89b4af12002-02-12 23:24:41 +0000365 else:
cliechtid6bf52c2003-10-01 02:28:12 +0000366 raise ValueError('Invalid char len: %r' % self._bytesize)
cliechtif0a81d42014-08-04 14:03:53 +0000367 # setup stop bits
cliechtid6bf52c2003-10-01 02:28:12 +0000368 if self._stopbits == STOPBITS_ONE:
Chris Liechti11465c82015-08-04 15:55:22 +0200369 cflag &= ~(termios.CSTOPB)
cliechti58b481c2009-02-16 20:42:32 +0000370 elif self._stopbits == STOPBITS_ONE_POINT_FIVE:
Chris Liechti11465c82015-08-04 15:55:22 +0200371 cflag |= (termios.CSTOPB) # XXX same as TWO.. there is no POSIX support for 1.5
cliechtid6bf52c2003-10-01 02:28:12 +0000372 elif self._stopbits == STOPBITS_TWO:
Chris Liechti11465c82015-08-04 15:55:22 +0200373 cflag |= (termios.CSTOPB)
cliechti89b4af12002-02-12 23:24:41 +0000374 else:
cliechti3172d3d2009-07-21 22:33:40 +0000375 raise ValueError('Invalid stop bit specification: %r' % self._stopbits)
cliechti58b481c2009-02-16 20:42:32 +0000376 # setup parity
Chris Liechti11465c82015-08-04 15:55:22 +0200377 iflag &= ~(termios.INPCK|termios.ISTRIP)
cliechtid6bf52c2003-10-01 02:28:12 +0000378 if self._parity == PARITY_NONE:
Chris Liechti11465c82015-08-04 15:55:22 +0200379 cflag &= ~(termios.PARENB|termios.PARODD)
cliechtid6bf52c2003-10-01 02:28:12 +0000380 elif self._parity == PARITY_EVEN:
Chris Liechti11465c82015-08-04 15:55:22 +0200381 cflag &= ~(termios.PARODD)
382 cflag |= (termios.PARENB)
cliechtid6bf52c2003-10-01 02:28:12 +0000383 elif self._parity == PARITY_ODD:
Chris Liechti11465c82015-08-04 15:55:22 +0200384 cflag |= (termios.PARENB|termios.PARODD)
cliechtiaec27ab2014-07-31 22:21:24 +0000385 elif self._parity == PARITY_MARK and plat[:5] == 'linux':
Chris Liechti11465c82015-08-04 15:55:22 +0200386 cflag |= (termios.PARENB|CMSPAR|termios.PARODD)
cliechtiaec27ab2014-07-31 22:21:24 +0000387 elif self._parity == PARITY_SPACE and plat[:5] == 'linux':
Chris Liechti11465c82015-08-04 15:55:22 +0200388 cflag |= (termios.PARENB|CMSPAR)
389 cflag &= ~(termios.PARODD)
cliechti89b4af12002-02-12 23:24:41 +0000390 else:
cliechtid6bf52c2003-10-01 02:28:12 +0000391 raise ValueError('Invalid parity: %r' % self._parity)
cliechti58b481c2009-02-16 20:42:32 +0000392 # setup flow control
393 # xonxoff
Chris Liechti11465c82015-08-04 15:55:22 +0200394 if hasattr(termios, 'IXANY'):
cliechtid6bf52c2003-10-01 02:28:12 +0000395 if self._xonxoff:
Chris Liechti11465c82015-08-04 15:55:22 +0200396 iflag |= (termios.IXON|termios.IXOFF) #|termios.IXANY)
cliechti89b4af12002-02-12 23:24:41 +0000397 else:
Chris Liechti11465c82015-08-04 15:55:22 +0200398 iflag &= ~(termios.IXON|termios.IXOFF|termios.IXANY)
cliechti89b4af12002-02-12 23:24:41 +0000399 else:
cliechtid6bf52c2003-10-01 02:28:12 +0000400 if self._xonxoff:
Chris Liechti11465c82015-08-04 15:55:22 +0200401 iflag |= (termios.IXON|termios.IXOFF)
cliechti89b4af12002-02-12 23:24:41 +0000402 else:
Chris Liechti11465c82015-08-04 15:55:22 +0200403 iflag &= ~(termios.IXON|termios.IXOFF)
cliechti58b481c2009-02-16 20:42:32 +0000404 # rtscts
Chris Liechti11465c82015-08-04 15:55:22 +0200405 if hasattr(termios, 'CRTSCTS'):
cliechtid6bf52c2003-10-01 02:28:12 +0000406 if self._rtscts:
Chris Liechti11465c82015-08-04 15:55:22 +0200407 cflag |= (termios.CRTSCTS)
cliechti89b4af12002-02-12 23:24:41 +0000408 else:
Chris Liechti11465c82015-08-04 15:55:22 +0200409 cflag &= ~(termios.CRTSCTS)
410 elif hasattr(termios, 'CNEW_RTSCTS'): # try it with alternate constant name
cliechtid6bf52c2003-10-01 02:28:12 +0000411 if self._rtscts:
Chris Liechti11465c82015-08-04 15:55:22 +0200412 cflag |= (termios.CNEW_RTSCTS)
cliechtid4743692002-04-08 22:39:53 +0000413 else:
Chris Liechti11465c82015-08-04 15:55:22 +0200414 cflag &= ~(termios.CNEW_RTSCTS)
cliechti2750b832009-07-28 00:13:52 +0000415 # XXX should there be a warning if setting up rtscts (and xonxoff etc) fails??
cliechti58b481c2009-02-16 20:42:32 +0000416
417 # buffer
cliechtif0a81d42014-08-04 14:03:53 +0000418 # vmin "minimal number of characters to be read. 0 for non blocking"
cliechtid6bf52c2003-10-01 02:28:12 +0000419 if vmin < 0 or vmin > 255:
420 raise ValueError('Invalid vmin: %r ' % vmin)
Chris Liechti11465c82015-08-04 15:55:22 +0200421 cc[termios.VMIN] = vmin
cliechti58b481c2009-02-16 20:42:32 +0000422 # vtime
cliechtid6bf52c2003-10-01 02:28:12 +0000423 if vtime < 0 or vtime > 255:
424 raise ValueError('Invalid vtime: %r' % vtime)
Chris Liechti11465c82015-08-04 15:55:22 +0200425 cc[termios.VTIME] = vtime
cliechti58b481c2009-02-16 20:42:32 +0000426 # activate settings
cliechti4d0af5e2011-08-05 02:18:16 +0000427 if [iflag, oflag, cflag, lflag, ispeed, ospeed, cc] != orig_attr:
Chris Liechti11465c82015-08-04 15:55:22 +0200428 termios.tcsetattr(self.fd, termios.TCSANOW, [iflag, oflag, cflag, lflag, ispeed, ospeed, cc])
cliechti58b481c2009-02-16 20:42:32 +0000429
cliechtie8c45422008-06-20 23:23:14 +0000430 # apply custom baud rate, if any
431 if custom_baud is not None:
cliechti53c9fd42009-07-23 23:51:51 +0000432 set_special_baudrate(self, custom_baud)
cliechti89b4af12002-02-12 23:24:41 +0000433
434 def close(self):
cliechtid6bf52c2003-10-01 02:28:12 +0000435 """Close port"""
436 if self._isOpen:
cliechtic6178262004-03-22 22:04:52 +0000437 if self.fd is not None:
cliechtid6bf52c2003-10-01 02:28:12 +0000438 os.close(self.fd)
439 self.fd = None
440 self._isOpen = False
cliechti89b4af12002-02-12 23:24:41 +0000441
cliechtid6bf52c2003-10-01 02:28:12 +0000442 def makeDeviceName(self, port):
443 return device(port)
444
445 # - - - - - - - - - - - - - - - - - - - - - - - -
cliechti95c62212002-03-04 22:17:53 +0000446
cliechti89b4af12002-02-12 23:24:41 +0000447 def inWaiting(self):
cliechtid6bf52c2003-10-01 02:28:12 +0000448 """Return the number of characters currently in the input buffer."""
Chris Liechti11465c82015-08-04 15:55:22 +0200449 #~ s = fcntl.ioctl(self.fd, termios.FIONREAD, TIOCM_zero_str)
cliechtif5831e02002-12-05 23:15:27 +0000450 s = fcntl.ioctl(self.fd, TIOCINQ, TIOCM_zero_str)
cliechti89b4af12002-02-12 23:24:41 +0000451 return struct.unpack('I',s)[0]
452
cliechtia9a093e2010-01-02 03:05:08 +0000453 # select based implementation, proved to work on many systems
454 def read(self, size=1):
cliechti7d448562014-08-03 21:57:45 +0000455 """\
456 Read size bytes from the serial port. If a timeout is set it may
457 return less characters as requested. With no timeout it will block
458 until the requested number of bytes is read.
459 """
cliechti899c9c42011-06-14 23:01:23 +0000460 if not self._isOpen: raise portNotOpenError
cliechtia9a093e2010-01-02 03:05:08 +0000461 read = bytearray()
462 while len(read) < size:
cliechti8d744de2013-10-11 14:31:13 +0000463 try:
464 ready,_,_ = select.select([self.fd],[],[], self._timeout)
465 # If select was used with a timeout, and the timeout occurs, it
466 # returns with empty lists -> thus abort read operation.
467 # For timeout == 0 (non-blocking operation) also abort when there
468 # is nothing to read.
469 if not ready:
470 break # timeout
471 buf = os.read(self.fd, size-len(read))
472 # read should always return some data as select reported it was
473 # ready to read when we get to this point.
474 if not buf:
475 # Disconnected devices, at least on Linux, show the
476 # behavior that they are always ready to read immediately
477 # but reading returns nothing.
478 raise SerialException('device reports readiness to read but returned no data (device disconnected or multiple access on port?)')
479 read.extend(buf)
Chris Liechti68340d72015-08-03 14:15:48 +0200480 except OSError as e:
cliechtic7cd7212014-08-03 21:34:38 +0000481 # this is for Python 3.x where select.error is a subclass of OSError
482 # ignore EAGAIN errors. all other errors are shown
483 if e.errno != errno.EAGAIN:
484 raise SerialException('read failed: %s' % (e,))
Chris Liechti68340d72015-08-03 14:15:48 +0200485 except select.error as e:
cliechtic7cd7212014-08-03 21:34:38 +0000486 # this is for Python 2.x
cliechti8d744de2013-10-11 14:31:13 +0000487 # ignore EAGAIN errors. all other errors are shown
488 # see also http://www.python.org/dev/peps/pep-3151/#select
489 if e[0] != errno.EAGAIN:
490 raise SerialException('read failed: %s' % (e,))
cliechtia9a093e2010-01-02 03:05:08 +0000491 return bytes(read)
cliechti89b4af12002-02-12 23:24:41 +0000492
cliechti4a567a02009-07-27 22:09:31 +0000493 def write(self, data):
cliechtid6bf52c2003-10-01 02:28:12 +0000494 """Output the given string over the serial port."""
cliechti899c9c42011-06-14 23:01:23 +0000495 if not self._isOpen: raise portNotOpenError
cliechti38077122013-10-16 02:57:27 +0000496 d = to_bytes(data)
497 tx_len = len(d)
cliechti3cf46d62009-08-07 00:19:57 +0000498 if self._writeTimeout is not None and self._writeTimeout > 0:
499 timeout = time.time() + self._writeTimeout
500 else:
501 timeout = None
cliechti9f7c2352013-10-11 01:13:46 +0000502 while tx_len > 0:
cliechti5d4d0bd2004-11-13 03:27:39 +0000503 try:
cliechti5d4d0bd2004-11-13 03:27:39 +0000504 n = os.write(self.fd, d)
cliechti3cf46d62009-08-07 00:19:57 +0000505 if timeout:
506 # when timeout is set, use select to wait for being ready
507 # with the time left as timeout
508 timeleft = timeout - time.time()
509 if timeleft < 0:
510 raise writeTimeoutError
511 _, ready, _ = select.select([], [self.fd], [], timeleft)
cliechti5d4d0bd2004-11-13 03:27:39 +0000512 if not ready:
513 raise writeTimeoutError
cliechti88c62442013-10-12 04:03:16 +0000514 else:
515 # wait for write operation
516 _, ready, _ = select.select([], [self.fd], [], None)
517 if not ready:
518 raise SerialException('write failed (select)')
cliechti5d4d0bd2004-11-13 03:27:39 +0000519 d = d[n:]
cliechti9f7c2352013-10-11 01:13:46 +0000520 tx_len -= n
Chris Liechti675f7e12015-08-03 15:48:41 +0200521 except SerialException:
522 raise
Chris Liechti68340d72015-08-03 14:15:48 +0200523 except OSError as v:
cliechti5d4d0bd2004-11-13 03:27:39 +0000524 if v.errno != errno.EAGAIN:
cliechti65722c92009-08-07 00:48:53 +0000525 raise SerialException('write failed: %s' % (v,))
cliechtif81362e2009-07-25 03:44:33 +0000526 return len(data)
cliechtid6bf52c2003-10-01 02:28:12 +0000527
cliechtia30a8a02003-10-05 12:28:13 +0000528 def flush(self):
cliechti7d448562014-08-03 21:57:45 +0000529 """\
530 Flush of file like objects. In this case, wait until all data
531 is written.
532 """
cliechtia30a8a02003-10-05 12:28:13 +0000533 self.drainOutput()
534
cliechti89b4af12002-02-12 23:24:41 +0000535 def flushInput(self):
cliechtid6bf52c2003-10-01 02:28:12 +0000536 """Clear input buffer, discarding all that is in the buffer."""
cliechti899c9c42011-06-14 23:01:23 +0000537 if not self._isOpen: raise portNotOpenError
Chris Liechti11465c82015-08-04 15:55:22 +0200538 termios.tcflush(self.fd, termios.TCIFLUSH)
cliechti89b4af12002-02-12 23:24:41 +0000539
540 def flushOutput(self):
cliechti7d448562014-08-03 21:57:45 +0000541 """\
542 Clear output buffer, aborting the current output and discarding all
543 that is in the buffer.
544 """
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.TCOFLUSH)
cliechti89b4af12002-02-12 23:24:41 +0000547
cliechtiaaa04602006-02-05 23:02:46 +0000548 def sendBreak(self, duration=0.25):
cliechti7d448562014-08-03 21:57:45 +0000549 """\
550 Send break condition. Timed, returns to idle state after given
551 duration.
552 """
cliechti899c9c42011-06-14 23:01:23 +0000553 if not self._isOpen: raise portNotOpenError
cliechtiaaa04602006-02-05 23:02:46 +0000554 termios.tcsendbreak(self.fd, int(duration/0.25))
cliechti89b4af12002-02-12 23:24:41 +0000555
cliechti997b63c2008-06-21 00:09:31 +0000556 def setBreak(self, level=1):
cliechti7d448562014-08-03 21:57:45 +0000557 """\
558 Set break: Controls TXD. When active, no transmitting is possible.
559 """
cliechti997b63c2008-06-21 00:09:31 +0000560 if self.fd is None: raise portNotOpenError
561 if level:
562 fcntl.ioctl(self.fd, TIOCSBRK)
563 else:
564 fcntl.ioctl(self.fd, TIOCCBRK)
565
cliechti93db61b2006-08-26 19:16:18 +0000566 def setRTS(self, level=1):
cliechtid6bf52c2003-10-01 02:28:12 +0000567 """Set terminal status line: Request To Send"""
cliechti899c9c42011-06-14 23:01:23 +0000568 if not self._isOpen: raise portNotOpenError
cliechtib2f5fc82006-10-20 00:09:07 +0000569 if level:
cliechtid6bf52c2003-10-01 02:28:12 +0000570 fcntl.ioctl(self.fd, TIOCMBIS, TIOCM_RTS_str)
571 else:
572 fcntl.ioctl(self.fd, TIOCMBIC, TIOCM_RTS_str)
573
cliechti93db61b2006-08-26 19:16:18 +0000574 def setDTR(self, level=1):
cliechtid6bf52c2003-10-01 02:28:12 +0000575 """Set terminal status line: Data Terminal Ready"""
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_DTR_str)
579 else:
580 fcntl.ioctl(self.fd, TIOCMBIC, TIOCM_DTR_str)
581
582 def getCTS(self):
583 """Read terminal status line: Clear To Send"""
cliechti899c9c42011-06-14 23:01:23 +0000584 if not self._isOpen: raise portNotOpenError
cliechtid6bf52c2003-10-01 02:28:12 +0000585 s = fcntl.ioctl(self.fd, TIOCMGET, TIOCM_zero_str)
586 return struct.unpack('I',s)[0] & TIOCM_CTS != 0
587
588 def getDSR(self):
589 """Read terminal status line: Data Set Ready"""
cliechti899c9c42011-06-14 23:01:23 +0000590 if not self._isOpen: raise portNotOpenError
cliechtid6bf52c2003-10-01 02:28:12 +0000591 s = fcntl.ioctl(self.fd, TIOCMGET, TIOCM_zero_str)
592 return struct.unpack('I',s)[0] & TIOCM_DSR != 0
593
cliechtid6bf52c2003-10-01 02:28:12 +0000594 def getRI(self):
595 """Read terminal status line: Ring Indicator"""
cliechti899c9c42011-06-14 23:01:23 +0000596 if not self._isOpen: raise portNotOpenError
cliechti89b4af12002-02-12 23:24:41 +0000597 s = fcntl.ioctl(self.fd, TIOCMGET, TIOCM_zero_str)
cliechtid6bf52c2003-10-01 02:28:12 +0000598 return struct.unpack('I',s)[0] & TIOCM_RI != 0
cliechti89b4af12002-02-12 23:24:41 +0000599
600 def getCD(self):
cliechtid6bf52c2003-10-01 02:28:12 +0000601 """Read terminal status line: Carrier Detect"""
cliechti899c9c42011-06-14 23:01:23 +0000602 if not self._isOpen: raise portNotOpenError
cliechti89b4af12002-02-12 23:24:41 +0000603 s = fcntl.ioctl(self.fd, TIOCMGET, TIOCM_zero_str)
cliechtid6bf52c2003-10-01 02:28:12 +0000604 return struct.unpack('I',s)[0] & TIOCM_CD != 0
cliechti89b4af12002-02-12 23:24:41 +0000605
cliechtia30a8a02003-10-05 12:28:13 +0000606 # - - platform specific - - - -
607
cliechti28b8fd02011-12-28 21:39:42 +0000608 def outWaiting(self):
609 """Return the number of characters currently in the output buffer."""
Chris Liechti11465c82015-08-04 15:55:22 +0200610 #~ s = fcntl.ioctl(self.fd, termios.FIONREAD, TIOCM_zero_str)
cliechti28b8fd02011-12-28 21:39:42 +0000611 s = fcntl.ioctl(self.fd, TIOCOUTQ, TIOCM_zero_str)
612 return struct.unpack('I',s)[0]
613
cliechtia30a8a02003-10-05 12:28:13 +0000614 def drainOutput(self):
615 """internal - not portable!"""
cliechti899c9c42011-06-14 23:01:23 +0000616 if not self._isOpen: raise portNotOpenError
cliechtia30a8a02003-10-05 12:28:13 +0000617 termios.tcdrain(self.fd)
618
619 def nonblocking(self):
620 """internal - not portable!"""
cliechti899c9c42011-06-14 23:01:23 +0000621 if not self._isOpen: raise portNotOpenError
Chris Liechti11465c82015-08-04 15:55:22 +0200622 fcntl.fcntl(self.fd, fcntl.F_SETFL, os.O_NONBLOCK)
cliechtia30a8a02003-10-05 12:28:13 +0000623
cliechti8753bbc2005-01-15 20:32:51 +0000624 def fileno(self):
cliechti2f0f8a32011-12-28 22:10:00 +0000625 """\
626 For easier use of the serial port instance with select.
627 WARNING: this function is not portable to different platforms!
628 """
cliechti899c9c42011-06-14 23:01:23 +0000629 if not self._isOpen: raise portNotOpenError
cliechti8753bbc2005-01-15 20:32:51 +0000630 return self.fd
cliechti89b4af12002-02-12 23:24:41 +0000631
cliechti2f0f8a32011-12-28 22:10:00 +0000632 def setXON(self, level=True):
633 """\
634 Manually control flow - when software flow control is enabled.
635 This will send XON (true) and XOFF (false) to the other device.
636 WARNING: this function is not portable to different platforms!
637 """
Chris Liechti905d5072015-08-03 21:41:49 +0200638 if not self._isOpen: raise portNotOpenError
cliechti4a601342011-12-29 02:22:17 +0000639 if enable:
Chris Liechti11465c82015-08-04 15:55:22 +0200640 termios.tcflow(self.fd, termios.TCION)
cliechti57e48a62009-08-03 22:29:58 +0000641 else:
Chris Liechti11465c82015-08-04 15:55:22 +0200642 termios.tcflow(self.fd, termios.TCIOFF)
cliechti57e48a62009-08-03 22:29:58 +0000643
cliechti2f0f8a32011-12-28 22:10:00 +0000644 def flowControlOut(self, enable):
645 """\
646 Manually control flow of outgoing data - when hardware or software flow
647 control is enabled.
648 WARNING: this function is not portable to different platforms!
649 """
650 if not self._isOpen: raise portNotOpenError
651 if enable:
Chris Liechti11465c82015-08-04 15:55:22 +0200652 termios.tcflow(self.fd, termios.TCOON)
cliechti2f0f8a32011-12-28 22:10:00 +0000653 else:
Chris Liechti11465c82015-08-04 15:55:22 +0200654 termios.tcflow(self.fd, termios.TCOOFF)
cliechti2f0f8a32011-12-28 22:10:00 +0000655
cliechtif81362e2009-07-25 03:44:33 +0000656
cliechtif81362e2009-07-25 03:44:33 +0000657
cliechtia9a093e2010-01-02 03:05:08 +0000658class PosixPollSerial(Serial):
cliechti7d448562014-08-03 21:57:45 +0000659 """\
cliechtif0a81d42014-08-04 14:03:53 +0000660 Poll based read implementation. Not all systems support poll properly.
661 However this one has better handling of errors, such as a device
cliechti7d448562014-08-03 21:57:45 +0000662 disconnecting while it's in use (e.g. USB-serial unplugged).
663 """
cliechtia9a093e2010-01-02 03:05:08 +0000664
665 def read(self, size=1):
cliechti7d448562014-08-03 21:57:45 +0000666 """\
667 Read size bytes from the serial port. If a timeout is set it may
668 return less characters as requested. With no timeout it will block
669 until the requested number of bytes is read.
670 """
cliechtia9a093e2010-01-02 03:05:08 +0000671 if self.fd is None: raise portNotOpenError
672 read = bytearray()
673 poll = select.poll()
674 poll.register(self.fd, select.POLLIN|select.POLLERR|select.POLLHUP|select.POLLNVAL)
675 if size > 0:
676 while len(read) < size:
677 # print "\tread(): size",size, "have", len(read) #debug
678 # wait until device becomes ready to read (or something fails)
cliechti4cd0d2e2010-07-21 01:15:25 +0000679 for fd, event in poll.poll(self._timeout*1000):
cliechtia9a093e2010-01-02 03:05:08 +0000680 if event & (select.POLLERR|select.POLLHUP|select.POLLNVAL):
681 raise SerialException('device reports error (poll)')
682 # we don't care if it is select.POLLIN or timeout, that's
683 # handled below
684 buf = os.read(self.fd, size - len(read))
685 read.extend(buf)
686 if ((self._timeout is not None and self._timeout >= 0) or
687 (self._interCharTimeout is not None and self._interCharTimeout > 0)) and not buf:
688 break # early abort on timeout
689 return bytes(read)
690
cliechtif81362e2009-07-25 03:44:33 +0000691
cliechti89b4af12002-02-12 23:24:41 +0000692if __name__ == '__main__':
693 s = Serial(0,
cliechti53c9fd42009-07-23 23:51:51 +0000694 baudrate=19200, # baud rate
695 bytesize=EIGHTBITS, # number of data bits
cliechti3172d3d2009-07-21 22:33:40 +0000696 parity=PARITY_EVEN, # enable parity checking
cliechti53c9fd42009-07-23 23:51:51 +0000697 stopbits=STOPBITS_ONE, # number of stop bits
cliechti3172d3d2009-07-21 22:33:40 +0000698 timeout=3, # set a timeout value, None for waiting forever
699 xonxoff=0, # enable software flow control
700 rtscts=0, # enable RTS/CTS flow control
cliechti89b4af12002-02-12 23:24:41 +0000701 )
702 s.setRTS(1)
703 s.setDTR(1)
704 s.flushInput()
705 s.flushOutput()
706 s.write('hello')
cliechti109486b2009-08-02 00:00:11 +0000707 sys.stdout.write('%r\n' % s.read(5))
708 sys.stdout.write('%s\n' % s.inWaiting())
cliechti89b4af12002-02-12 23:24:41 +0000709 del s
cliechti4569bac2007-11-08 21:57:19 +0000710