cliechti | 89b4af1 | 2002-02-12 23:24:41 +0000 | [diff] [blame] | 1 | #!/usr/bin/env python |
cliechti | 58b481c | 2009-02-16 20:42:32 +0000 | [diff] [blame] | 2 | # |
cliechti | c54b2c8 | 2008-06-21 01:59:08 +0000 | [diff] [blame] | 3 | # Python Serial Port Extension for Win32, Linux, BSD, Jython |
| 4 | # module for serial IO for POSIX compatible systems, like Linux |
| 5 | # see __init__.py |
cliechti | 89b4af1 | 2002-02-12 23:24:41 +0000 | [diff] [blame] | 6 | # |
Chris Liechti | 68340d7 | 2015-08-03 14:15:48 +0200 | [diff] [blame] | 7 | # (C) 2001-2015 Chris Liechti <cliechti@gmx.net> |
cliechti | 89b4af1 | 2002-02-12 23:24:41 +0000 | [diff] [blame] | 8 | # this is distributed under a free software license, see license.txt |
| 9 | # |
cliechti | c54b2c8 | 2008-06-21 01:59:08 +0000 | [diff] [blame] | 10 | # parts based on code from Grant B. Edwards <grante@visi.com>: |
cliechti | 89b4af1 | 2002-02-12 23:24:41 +0000 | [diff] [blame] | 11 | # ftp://ftp.visi.com/users/grante/python/PosixSerial.py |
cliechti | 53c9fd4 | 2009-07-23 23:51:51 +0000 | [diff] [blame] | 12 | # |
cliechti | 89b4af1 | 2002-02-12 23:24:41 +0000 | [diff] [blame] | 13 | # references: http://www.easysw.com/~mike/serial/serial.html |
| 14 | |
Chris Liechti | 33f0ec5 | 2015-08-06 16:37:21 +0200 | [diff] [blame] | 15 | import errno |
| 16 | import fcntl |
Chris Liechti | 33f0ec5 | 2015-08-06 16:37:21 +0200 | [diff] [blame] | 17 | import os |
| 18 | import select |
| 19 | import struct |
| 20 | import sys |
| 21 | import termios |
| 22 | import time |
cliechti | 39cfb7b | 2011-08-22 00:30:07 +0000 | [diff] [blame] | 23 | from serial.serialutil import * |
cliechti | 89b4af1 | 2002-02-12 23:24:41 +0000 | [diff] [blame] | 24 | |
cliechti | 89b4af1 | 2002-02-12 23:24:41 +0000 | [diff] [blame] | 25 | |
Chris Liechti | d6847af | 2015-08-06 17:54:30 +0200 | [diff] [blame] | 26 | class PlatformSpecificBase(object): |
| 27 | BAUDRATE_CONSTANTS = {} |
cliechti | 89b4af1 | 2002-02-12 23:24:41 +0000 | [diff] [blame] | 28 | |
Chris Liechti | d6847af | 2015-08-06 17:54:30 +0200 | [diff] [blame] | 29 | def number_to_device(self, port_number): |
| 30 | sys.stderr.write("""\ |
cliechti | 7aaead3 | 2009-07-23 14:02:41 +0000 | [diff] [blame] | 31 | don't know how to number ttys on this system. |
cliechti | 895e830 | 2004-04-20 02:40:28 +0000 | [diff] [blame] | 32 | ! Use an explicit path (eg /dev/ttyS1) or send this information to |
| 33 | ! the author of this module: |
cliechti | 89b4af1 | 2002-02-12 23:24:41 +0000 | [diff] [blame] | 34 | |
cliechti | 895e830 | 2004-04-20 02:40:28 +0000 | [diff] [blame] | 35 | sys.platform = %r |
| 36 | os.name = %r |
| 37 | serialposix.py version = %s |
cliechti | 89b4af1 | 2002-02-12 23:24:41 +0000 | [diff] [blame] | 38 | |
| 39 | also add the device name of the serial port and where the |
| 40 | counting starts for the first serial port. |
| 41 | e.g. 'first serial port: /dev/ttyS0' |
| 42 | and with a bit luck you can get this module running... |
cliechti | 7aaead3 | 2009-07-23 14:02:41 +0000 | [diff] [blame] | 43 | """ % (sys.platform, os.name, VERSION)) |
Chris Liechti | d6847af | 2015-08-06 17:54:30 +0200 | [diff] [blame] | 44 | 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 |
| 55 | plat = sys.platform.lower() |
| 56 | |
| 57 | if 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 | |
| 154 | elif 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 | |
| 175 | elif plat[:7] == 'openbsd': # OpenBSD |
| 176 | class PlatformSpecific(PlatformSpecificBase): |
| 177 | def number_to_device(self, port_number): |
| 178 | return '/dev/cua%02d' % (port_number,) |
| 179 | |
| 180 | elif 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 | |
| 185 | elif 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 | |
| 202 | elif 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 | |
| 207 | elif 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 | |
| 212 | elif 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 | |
| 217 | elif 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 | |
| 222 | elif plat[:3] == 'aix': # AIX |
| 223 | class PlatformSpecific(PlatformSpecificBase): |
| 224 | def number_to_device(self, port_number): |
| 225 | return '/dev/tty%d' % (port_number,) |
| 226 | |
| 227 | else: |
| 228 | class PlatformSpecific(PlatformSpecificBase): |
| 229 | pass |
cliechti | 89b4af1 | 2002-02-12 23:24:41 +0000 | [diff] [blame] | 230 | |
cliechti | 58b481c | 2009-02-16 20:42:32 +0000 | [diff] [blame] | 231 | # whats up with "aix", "beos", .... |
| 232 | # they should work, just need to know the device names. |
cliechti | 89b4af1 | 2002-02-12 23:24:41 +0000 | [diff] [blame] | 233 | |
| 234 | |
cliechti | 58b481c | 2009-02-16 20:42:32 +0000 | [diff] [blame] | 235 | # load some constants for later use. |
Chris Liechti | 11465c8 | 2015-08-04 15:55:22 +0200 | [diff] [blame] | 236 | # try to use values from termios, use defaults from linux otherwise |
Chris Liechti | d6847af | 2015-08-06 17:54:30 +0200 | [diff] [blame] | 237 | TIOCMGET = getattr(termios, 'TIOCMGET', 0x5415) |
| 238 | TIOCMBIS = getattr(termios, 'TIOCMBIS', 0x5416) |
| 239 | TIOCMBIC = getattr(termios, 'TIOCMBIC', 0x5417) |
| 240 | TIOCMSET = getattr(termios, 'TIOCMSET', 0x5418) |
cliechti | 89b4af1 | 2002-02-12 23:24:41 +0000 | [diff] [blame] | 241 | |
Chris Liechti | d6847af | 2015-08-06 17:54:30 +0200 | [diff] [blame] | 242 | #TIOCM_LE = getattr(termios, 'TIOCM_LE', 0x001) |
| 243 | TIOCM_DTR = getattr(termios, 'TIOCM_DTR', 0x002) |
| 244 | TIOCM_RTS = getattr(termios, 'TIOCM_RTS', 0x004) |
| 245 | #TIOCM_ST = getattr(termios, 'TIOCM_ST', 0x008) |
| 246 | #TIOCM_SR = getattr(termios, 'TIOCM_SR', 0x010) |
cliechti | 89b4af1 | 2002-02-12 23:24:41 +0000 | [diff] [blame] | 247 | |
Chris Liechti | d6847af | 2015-08-06 17:54:30 +0200 | [diff] [blame] | 248 | TIOCM_CTS = getattr(termios, 'TIOCM_CTS', 0x020) |
| 249 | TIOCM_CAR = getattr(termios, 'TIOCM_CAR', 0x040) |
| 250 | TIOCM_RNG = getattr(termios, 'TIOCM_RNG', 0x080) |
| 251 | TIOCM_DSR = getattr(termios, 'TIOCM_DSR', 0x100) |
| 252 | TIOCM_CD = getattr(termios, 'TIOCM_CD', TIOCM_CAR) |
| 253 | TIOCM_RI = getattr(termios, 'TIOCM_RI', TIOCM_RNG) |
| 254 | #TIOCM_OUT1 = getattr(termios, 'TIOCM_OUT1', 0x2000) |
| 255 | #TIOCM_OUT2 = getattr(termios, 'TIOCM_OUT2', 0x4000) |
Chris Liechti | 11465c8 | 2015-08-04 15:55:22 +0200 | [diff] [blame] | 256 | if hasattr(termios, 'TIOCINQ'): |
| 257 | TIOCINQ = termios.TIOCINQ |
cliechti | 28b8fd0 | 2011-12-28 21:39:42 +0000 | [diff] [blame] | 258 | else: |
Chris Liechti | d6847af | 2015-08-06 17:54:30 +0200 | [diff] [blame] | 259 | TIOCINQ = getattr(termios, 'FIONREAD', 0x541B) |
| 260 | TIOCOUTQ = getattr(termios, 'TIOCOUTQ', 0x5411) |
cliechti | 89b4af1 | 2002-02-12 23:24:41 +0000 | [diff] [blame] | 261 | |
| 262 | TIOCM_zero_str = struct.pack('I', 0) |
| 263 | TIOCM_RTS_str = struct.pack('I', TIOCM_RTS) |
| 264 | TIOCM_DTR_str = struct.pack('I', TIOCM_DTR) |
| 265 | |
Chris Liechti | d6847af | 2015-08-06 17:54:30 +0200 | [diff] [blame] | 266 | TIOCSBRK = getattr(termios, 'TIOCSBRK', 0x5427) |
| 267 | TIOCCBRK = getattr(termios, 'TIOCCBRK', 0x5428) |
cliechti | 997b63c | 2008-06-21 00:09:31 +0000 | [diff] [blame] | 268 | |
Chris Liechti | 68340d7 | 2015-08-03 14:15:48 +0200 | [diff] [blame] | 269 | CMSPAR = 0o10000000000 # Use "stick" (mark/space) parity |
cliechti | aec27ab | 2014-07-31 22:21:24 +0000 | [diff] [blame] | 270 | |
cliechti | 89b4af1 | 2002-02-12 23:24:41 +0000 | [diff] [blame] | 271 | |
Chris Liechti | ef6b7b4 | 2015-08-06 22:19:26 +0200 | [diff] [blame^] | 272 | class Serial(SerialBase, PlatformSpecific): |
cliechti | 7d44856 | 2014-08-03 21:57:45 +0000 | [diff] [blame] | 273 | """\ |
| 274 | Serial port class POSIX implementation. Serial port configuration is |
cliechti | d6bf52c | 2003-10-01 02:28:12 +0000 | [diff] [blame] | 275 | done with termios and fcntl. Runs on Linux and many other Un*x like |
cliechti | f0a81d4 | 2014-08-04 14:03:53 +0000 | [diff] [blame] | 276 | systems. |
| 277 | """ |
cliechti | d6bf52c | 2003-10-01 02:28:12 +0000 | [diff] [blame] | 278 | |
| 279 | def open(self): |
cliechti | 7d44856 | 2014-08-03 21:57:45 +0000 | [diff] [blame] | 280 | """\ |
| 281 | Open port with current settings. This may throw a SerialException |
| 282 | if the port cannot be opened.""" |
cliechti | d6bf52c | 2003-10-01 02:28:12 +0000 | [diff] [blame] | 283 | if self._port is None: |
| 284 | raise SerialException("Port must be configured before it can be used.") |
cliechti | 02ef43a | 2011-03-24 23:33:12 +0000 | [diff] [blame] | 285 | if self._isOpen: |
| 286 | raise SerialException("Port is already open.") |
| 287 | self.fd = None |
cliechti | 58b481c | 2009-02-16 20:42:32 +0000 | [diff] [blame] | 288 | # open |
cliechti | 4616bf1 | 2002-04-08 23:13:14 +0000 | [diff] [blame] | 289 | try: |
| 290 | self.fd = os.open(self.portstr, os.O_RDWR|os.O_NOCTTY|os.O_NONBLOCK) |
Chris Liechti | 68340d7 | 2015-08-03 14:15:48 +0200 | [diff] [blame] | 291 | except OSError as msg: |
cliechti | 4616bf1 | 2002-04-08 23:13:14 +0000 | [diff] [blame] | 292 | self.fd = None |
cliechti | af84daa | 2013-10-10 23:57:00 +0000 | [diff] [blame] | 293 | raise SerialException(msg.errno, "could not open port %s: %s" % (self._port, msg)) |
Chris Liechti | 11465c8 | 2015-08-04 15:55:22 +0200 | [diff] [blame] | 294 | #~ fcntl.fcntl(self.fd, fcntl.F_SETFL, 0) # set blocking |
cliechti | 58b481c | 2009-02-16 20:42:32 +0000 | [diff] [blame] | 295 | |
cliechti | b2f5fc8 | 2006-10-20 00:09:07 +0000 | [diff] [blame] | 296 | try: |
| 297 | self._reconfigurePort() |
| 298 | except: |
cliechti | 2750b83 | 2009-07-28 00:13:52 +0000 | [diff] [blame] | 299 | 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 |
cliechti | b2f5fc8 | 2006-10-20 00:09:07 +0000 | [diff] [blame] | 305 | self.fd = None |
cliechti | f0a4f0f | 2009-07-21 21:12:37 +0000 | [diff] [blame] | 306 | raise |
cliechti | b2f5fc8 | 2006-10-20 00:09:07 +0000 | [diff] [blame] | 307 | else: |
| 308 | self._isOpen = True |
cliechti | 5c9b072 | 2013-10-17 03:19:39 +0000 | [diff] [blame] | 309 | self.flushInput() |
cliechti | 58b481c | 2009-02-16 20:42:32 +0000 | [diff] [blame] | 310 | |
| 311 | |
cliechti | d6bf52c | 2003-10-01 02:28:12 +0000 | [diff] [blame] | 312 | def _reconfigurePort(self): |
cliechti | b2f5fc8 | 2006-10-20 00:09:07 +0000 | [diff] [blame] | 313 | """Set communication parameters on opened port.""" |
cliechti | c617826 | 2004-03-22 22:04:52 +0000 | [diff] [blame] | 314 | if self.fd is None: |
cliechti | a9a093e | 2010-01-02 03:05:08 +0000 | [diff] [blame] | 315 | raise SerialException("Can only operate on a valid file descriptor") |
cliechti | e8c4542 | 2008-06-20 23:23:14 +0000 | [diff] [blame] | 316 | custom_baud = None |
cliechti | 58b481c | 2009-02-16 20:42:32 +0000 | [diff] [blame] | 317 | |
cliechti | 2750b83 | 2009-07-28 00:13:52 +0000 | [diff] [blame] | 318 | vmin = vtime = 0 # timeout is done via select |
cliechti | 679bfa6 | 2008-06-20 23:58:15 +0000 | [diff] [blame] | 319 | if self._interCharTimeout is not None: |
| 320 | vmin = 1 |
| 321 | vtime = int(self._interCharTimeout * 10) |
cliechti | 6ce7ab1 | 2002-11-07 02:15:00 +0000 | [diff] [blame] | 322 | try: |
cliechti | 4d0af5e | 2011-08-05 02:18:16 +0000 | [diff] [blame] | 323 | orig_attr = termios.tcgetattr(self.fd) |
| 324 | iflag, oflag, cflag, lflag, ispeed, ospeed, cc = orig_attr |
Chris Liechti | 68340d7 | 2015-08-03 14:15:48 +0200 | [diff] [blame] | 325 | except termios.error as msg: # if a port is nonexistent but has a /dev file, it'll fail here |
cliechti | d6bf52c | 2003-10-01 02:28:12 +0000 | [diff] [blame] | 326 | raise SerialException("Could not configure port: %s" % msg) |
cliechti | 58b481c | 2009-02-16 20:42:32 +0000 | [diff] [blame] | 327 | # set up raw mode / no echo / binary |
Chris Liechti | 11465c8 | 2015-08-04 15:55:22 +0200 | [diff] [blame] | 328 | cflag |= (termios.CLOCAL|termios.CREAD) |
| 329 | lflag &= ~(termios.ICANON|termios.ECHO|termios.ECHOE|termios.ECHOK|termios.ECHONL| |
| 330 | termios.ISIG|termios.IEXTEN) #|termios.ECHOPRT |
cliechti | 2750b83 | 2009-07-28 00:13:52 +0000 | [diff] [blame] | 331 | for flag in ('ECHOCTL', 'ECHOKE'): # netbsd workaround for Erk |
Chris Liechti | 11465c8 | 2015-08-04 15:55:22 +0200 | [diff] [blame] | 332 | if hasattr(termios, flag): |
| 333 | lflag &= ~getattr(termios, flag) |
cliechti | 58b481c | 2009-02-16 20:42:32 +0000 | [diff] [blame] | 334 | |
Chris Liechti | 11465c8 | 2015-08-04 15:55:22 +0200 | [diff] [blame] | 335 | 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 |
cliechti | 58b481c | 2009-02-16 20:42:32 +0000 | [diff] [blame] | 341 | |
cliechti | f0a4f0f | 2009-07-21 21:12:37 +0000 | [diff] [blame] | 342 | # setup baud rate |
cliechti | 89b4af1 | 2002-02-12 23:24:41 +0000 | [diff] [blame] | 343 | try: |
Chris Liechti | 11465c8 | 2015-08-04 15:55:22 +0200 | [diff] [blame] | 344 | ispeed = ospeed = getattr(termios, 'B%s' % (self._baudrate)) |
cliechti | 895e830 | 2004-04-20 02:40:28 +0000 | [diff] [blame] | 345 | except AttributeError: |
cliechti | f1559d0 | 2007-11-08 23:43:58 +0000 | [diff] [blame] | 346 | try: |
Chris Liechti | d6847af | 2015-08-06 17:54:30 +0200 | [diff] [blame] | 347 | ispeed = ospeed = self.BAUDRATE_CONSTANTS[self._baudrate] |
cliechti | f1559d0 | 2007-11-08 23:43:58 +0000 | [diff] [blame] | 348 | except KeyError: |
cliechti | e8c4542 | 2008-06-20 23:23:14 +0000 | [diff] [blame] | 349 | #~ raise ValueError('Invalid baud rate: %r' % self._baudrate) |
cliechti | f0a4f0f | 2009-07-21 21:12:37 +0000 | [diff] [blame] | 350 | # may need custom baud rate, it isn't in our list. |
Chris Liechti | 11465c8 | 2015-08-04 15:55:22 +0200 | [diff] [blame] | 351 | ispeed = ospeed = getattr(termios, 'B38400') |
cliechti | f0a4f0f | 2009-07-21 21:12:37 +0000 | [diff] [blame] | 352 | 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) |
cliechti | 58b481c | 2009-02-16 20:42:32 +0000 | [diff] [blame] | 359 | |
| 360 | # setup char len |
Chris Liechti | 11465c8 | 2015-08-04 15:55:22 +0200 | [diff] [blame] | 361 | cflag &= ~termios.CSIZE |
cliechti | d6bf52c | 2003-10-01 02:28:12 +0000 | [diff] [blame] | 362 | if self._bytesize == 8: |
Chris Liechti | 11465c8 | 2015-08-04 15:55:22 +0200 | [diff] [blame] | 363 | cflag |= termios.CS8 |
cliechti | d6bf52c | 2003-10-01 02:28:12 +0000 | [diff] [blame] | 364 | elif self._bytesize == 7: |
Chris Liechti | 11465c8 | 2015-08-04 15:55:22 +0200 | [diff] [blame] | 365 | cflag |= termios.CS7 |
cliechti | d6bf52c | 2003-10-01 02:28:12 +0000 | [diff] [blame] | 366 | elif self._bytesize == 6: |
Chris Liechti | 11465c8 | 2015-08-04 15:55:22 +0200 | [diff] [blame] | 367 | cflag |= termios.CS6 |
cliechti | d6bf52c | 2003-10-01 02:28:12 +0000 | [diff] [blame] | 368 | elif self._bytesize == 5: |
Chris Liechti | 11465c8 | 2015-08-04 15:55:22 +0200 | [diff] [blame] | 369 | cflag |= termios.CS5 |
cliechti | 89b4af1 | 2002-02-12 23:24:41 +0000 | [diff] [blame] | 370 | else: |
cliechti | d6bf52c | 2003-10-01 02:28:12 +0000 | [diff] [blame] | 371 | raise ValueError('Invalid char len: %r' % self._bytesize) |
cliechti | f0a81d4 | 2014-08-04 14:03:53 +0000 | [diff] [blame] | 372 | # setup stop bits |
cliechti | d6bf52c | 2003-10-01 02:28:12 +0000 | [diff] [blame] | 373 | if self._stopbits == STOPBITS_ONE: |
Chris Liechti | 11465c8 | 2015-08-04 15:55:22 +0200 | [diff] [blame] | 374 | cflag &= ~(termios.CSTOPB) |
cliechti | 58b481c | 2009-02-16 20:42:32 +0000 | [diff] [blame] | 375 | elif self._stopbits == STOPBITS_ONE_POINT_FIVE: |
Chris Liechti | 11465c8 | 2015-08-04 15:55:22 +0200 | [diff] [blame] | 376 | cflag |= (termios.CSTOPB) # XXX same as TWO.. there is no POSIX support for 1.5 |
cliechti | d6bf52c | 2003-10-01 02:28:12 +0000 | [diff] [blame] | 377 | elif self._stopbits == STOPBITS_TWO: |
Chris Liechti | 11465c8 | 2015-08-04 15:55:22 +0200 | [diff] [blame] | 378 | cflag |= (termios.CSTOPB) |
cliechti | 89b4af1 | 2002-02-12 23:24:41 +0000 | [diff] [blame] | 379 | else: |
cliechti | 3172d3d | 2009-07-21 22:33:40 +0000 | [diff] [blame] | 380 | raise ValueError('Invalid stop bit specification: %r' % self._stopbits) |
cliechti | 58b481c | 2009-02-16 20:42:32 +0000 | [diff] [blame] | 381 | # setup parity |
Chris Liechti | 11465c8 | 2015-08-04 15:55:22 +0200 | [diff] [blame] | 382 | iflag &= ~(termios.INPCK|termios.ISTRIP) |
cliechti | d6bf52c | 2003-10-01 02:28:12 +0000 | [diff] [blame] | 383 | if self._parity == PARITY_NONE: |
Chris Liechti | 11465c8 | 2015-08-04 15:55:22 +0200 | [diff] [blame] | 384 | cflag &= ~(termios.PARENB|termios.PARODD) |
cliechti | d6bf52c | 2003-10-01 02:28:12 +0000 | [diff] [blame] | 385 | elif self._parity == PARITY_EVEN: |
Chris Liechti | 11465c8 | 2015-08-04 15:55:22 +0200 | [diff] [blame] | 386 | cflag &= ~(termios.PARODD) |
| 387 | cflag |= (termios.PARENB) |
cliechti | d6bf52c | 2003-10-01 02:28:12 +0000 | [diff] [blame] | 388 | elif self._parity == PARITY_ODD: |
Chris Liechti | 11465c8 | 2015-08-04 15:55:22 +0200 | [diff] [blame] | 389 | cflag |= (termios.PARENB|termios.PARODD) |
cliechti | aec27ab | 2014-07-31 22:21:24 +0000 | [diff] [blame] | 390 | elif self._parity == PARITY_MARK and plat[:5] == 'linux': |
Chris Liechti | 11465c8 | 2015-08-04 15:55:22 +0200 | [diff] [blame] | 391 | cflag |= (termios.PARENB|CMSPAR|termios.PARODD) |
cliechti | aec27ab | 2014-07-31 22:21:24 +0000 | [diff] [blame] | 392 | elif self._parity == PARITY_SPACE and plat[:5] == 'linux': |
Chris Liechti | 11465c8 | 2015-08-04 15:55:22 +0200 | [diff] [blame] | 393 | cflag |= (termios.PARENB|CMSPAR) |
| 394 | cflag &= ~(termios.PARODD) |
cliechti | 89b4af1 | 2002-02-12 23:24:41 +0000 | [diff] [blame] | 395 | else: |
cliechti | d6bf52c | 2003-10-01 02:28:12 +0000 | [diff] [blame] | 396 | raise ValueError('Invalid parity: %r' % self._parity) |
cliechti | 58b481c | 2009-02-16 20:42:32 +0000 | [diff] [blame] | 397 | # setup flow control |
| 398 | # xonxoff |
Chris Liechti | 11465c8 | 2015-08-04 15:55:22 +0200 | [diff] [blame] | 399 | if hasattr(termios, 'IXANY'): |
cliechti | d6bf52c | 2003-10-01 02:28:12 +0000 | [diff] [blame] | 400 | if self._xonxoff: |
Chris Liechti | 11465c8 | 2015-08-04 15:55:22 +0200 | [diff] [blame] | 401 | iflag |= (termios.IXON|termios.IXOFF) #|termios.IXANY) |
cliechti | 89b4af1 | 2002-02-12 23:24:41 +0000 | [diff] [blame] | 402 | else: |
Chris Liechti | 11465c8 | 2015-08-04 15:55:22 +0200 | [diff] [blame] | 403 | iflag &= ~(termios.IXON|termios.IXOFF|termios.IXANY) |
cliechti | 89b4af1 | 2002-02-12 23:24:41 +0000 | [diff] [blame] | 404 | else: |
cliechti | d6bf52c | 2003-10-01 02:28:12 +0000 | [diff] [blame] | 405 | if self._xonxoff: |
Chris Liechti | 11465c8 | 2015-08-04 15:55:22 +0200 | [diff] [blame] | 406 | iflag |= (termios.IXON|termios.IXOFF) |
cliechti | 89b4af1 | 2002-02-12 23:24:41 +0000 | [diff] [blame] | 407 | else: |
Chris Liechti | 11465c8 | 2015-08-04 15:55:22 +0200 | [diff] [blame] | 408 | iflag &= ~(termios.IXON|termios.IXOFF) |
cliechti | 58b481c | 2009-02-16 20:42:32 +0000 | [diff] [blame] | 409 | # rtscts |
Chris Liechti | 11465c8 | 2015-08-04 15:55:22 +0200 | [diff] [blame] | 410 | if hasattr(termios, 'CRTSCTS'): |
cliechti | d6bf52c | 2003-10-01 02:28:12 +0000 | [diff] [blame] | 411 | if self._rtscts: |
Chris Liechti | 11465c8 | 2015-08-04 15:55:22 +0200 | [diff] [blame] | 412 | cflag |= (termios.CRTSCTS) |
cliechti | 89b4af1 | 2002-02-12 23:24:41 +0000 | [diff] [blame] | 413 | else: |
Chris Liechti | 11465c8 | 2015-08-04 15:55:22 +0200 | [diff] [blame] | 414 | cflag &= ~(termios.CRTSCTS) |
| 415 | elif hasattr(termios, 'CNEW_RTSCTS'): # try it with alternate constant name |
cliechti | d6bf52c | 2003-10-01 02:28:12 +0000 | [diff] [blame] | 416 | if self._rtscts: |
Chris Liechti | 11465c8 | 2015-08-04 15:55:22 +0200 | [diff] [blame] | 417 | cflag |= (termios.CNEW_RTSCTS) |
cliechti | d474369 | 2002-04-08 22:39:53 +0000 | [diff] [blame] | 418 | else: |
Chris Liechti | 11465c8 | 2015-08-04 15:55:22 +0200 | [diff] [blame] | 419 | cflag &= ~(termios.CNEW_RTSCTS) |
cliechti | 2750b83 | 2009-07-28 00:13:52 +0000 | [diff] [blame] | 420 | # XXX should there be a warning if setting up rtscts (and xonxoff etc) fails?? |
cliechti | 58b481c | 2009-02-16 20:42:32 +0000 | [diff] [blame] | 421 | |
| 422 | # buffer |
cliechti | f0a81d4 | 2014-08-04 14:03:53 +0000 | [diff] [blame] | 423 | # vmin "minimal number of characters to be read. 0 for non blocking" |
cliechti | d6bf52c | 2003-10-01 02:28:12 +0000 | [diff] [blame] | 424 | if vmin < 0 or vmin > 255: |
| 425 | raise ValueError('Invalid vmin: %r ' % vmin) |
Chris Liechti | 11465c8 | 2015-08-04 15:55:22 +0200 | [diff] [blame] | 426 | cc[termios.VMIN] = vmin |
cliechti | 58b481c | 2009-02-16 20:42:32 +0000 | [diff] [blame] | 427 | # vtime |
cliechti | d6bf52c | 2003-10-01 02:28:12 +0000 | [diff] [blame] | 428 | if vtime < 0 or vtime > 255: |
| 429 | raise ValueError('Invalid vtime: %r' % vtime) |
Chris Liechti | 11465c8 | 2015-08-04 15:55:22 +0200 | [diff] [blame] | 430 | cc[termios.VTIME] = vtime |
cliechti | 58b481c | 2009-02-16 20:42:32 +0000 | [diff] [blame] | 431 | # activate settings |
cliechti | 4d0af5e | 2011-08-05 02:18:16 +0000 | [diff] [blame] | 432 | if [iflag, oflag, cflag, lflag, ispeed, ospeed, cc] != orig_attr: |
Chris Liechti | 11465c8 | 2015-08-04 15:55:22 +0200 | [diff] [blame] | 433 | termios.tcsetattr(self.fd, termios.TCSANOW, [iflag, oflag, cflag, lflag, ispeed, ospeed, cc]) |
cliechti | 58b481c | 2009-02-16 20:42:32 +0000 | [diff] [blame] | 434 | |
cliechti | e8c4542 | 2008-06-20 23:23:14 +0000 | [diff] [blame] | 435 | # apply custom baud rate, if any |
| 436 | if custom_baud is not None: |
Chris Liechti | d6847af | 2015-08-06 17:54:30 +0200 | [diff] [blame] | 437 | self._set_special_baudrate(custom_baud) |
| 438 | |
| 439 | if self._rs485_mode is not None: |
| 440 | self._set_rs485_mode(self._rs485_mode) |
cliechti | 89b4af1 | 2002-02-12 23:24:41 +0000 | [diff] [blame] | 441 | |
| 442 | def close(self): |
cliechti | d6bf52c | 2003-10-01 02:28:12 +0000 | [diff] [blame] | 443 | """Close port""" |
| 444 | if self._isOpen: |
cliechti | c617826 | 2004-03-22 22:04:52 +0000 | [diff] [blame] | 445 | if self.fd is not None: |
cliechti | d6bf52c | 2003-10-01 02:28:12 +0000 | [diff] [blame] | 446 | os.close(self.fd) |
| 447 | self.fd = None |
| 448 | self._isOpen = False |
cliechti | 89b4af1 | 2002-02-12 23:24:41 +0000 | [diff] [blame] | 449 | |
cliechti | d6bf52c | 2003-10-01 02:28:12 +0000 | [diff] [blame] | 450 | def makeDeviceName(self, port): |
Chris Liechti | d6847af | 2015-08-06 17:54:30 +0200 | [diff] [blame] | 451 | return self.number_to_device(port) |
cliechti | d6bf52c | 2003-10-01 02:28:12 +0000 | [diff] [blame] | 452 | |
| 453 | # - - - - - - - - - - - - - - - - - - - - - - - - |
cliechti | 95c6221 | 2002-03-04 22:17:53 +0000 | [diff] [blame] | 454 | |
cliechti | 89b4af1 | 2002-02-12 23:24:41 +0000 | [diff] [blame] | 455 | def inWaiting(self): |
cliechti | d6bf52c | 2003-10-01 02:28:12 +0000 | [diff] [blame] | 456 | """Return the number of characters currently in the input buffer.""" |
Chris Liechti | 11465c8 | 2015-08-04 15:55:22 +0200 | [diff] [blame] | 457 | #~ s = fcntl.ioctl(self.fd, termios.FIONREAD, TIOCM_zero_str) |
cliechti | f5831e0 | 2002-12-05 23:15:27 +0000 | [diff] [blame] | 458 | s = fcntl.ioctl(self.fd, TIOCINQ, TIOCM_zero_str) |
cliechti | 89b4af1 | 2002-02-12 23:24:41 +0000 | [diff] [blame] | 459 | return struct.unpack('I',s)[0] |
| 460 | |
cliechti | a9a093e | 2010-01-02 03:05:08 +0000 | [diff] [blame] | 461 | # select based implementation, proved to work on many systems |
| 462 | def read(self, size=1): |
cliechti | 7d44856 | 2014-08-03 21:57:45 +0000 | [diff] [blame] | 463 | """\ |
| 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 | """ |
cliechti | 899c9c4 | 2011-06-14 23:01:23 +0000 | [diff] [blame] | 468 | if not self._isOpen: raise portNotOpenError |
cliechti | a9a093e | 2010-01-02 03:05:08 +0000 | [diff] [blame] | 469 | read = bytearray() |
| 470 | while len(read) < size: |
cliechti | 8d744de | 2013-10-11 14:31:13 +0000 | [diff] [blame] | 471 | 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 Liechti | 68340d7 | 2015-08-03 14:15:48 +0200 | [diff] [blame] | 488 | except OSError as e: |
cliechti | c7cd721 | 2014-08-03 21:34:38 +0000 | [diff] [blame] | 489 | # 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 Liechti | 68340d7 | 2015-08-03 14:15:48 +0200 | [diff] [blame] | 493 | except select.error as e: |
cliechti | c7cd721 | 2014-08-03 21:34:38 +0000 | [diff] [blame] | 494 | # this is for Python 2.x |
cliechti | 8d744de | 2013-10-11 14:31:13 +0000 | [diff] [blame] | 495 | # 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,)) |
cliechti | a9a093e | 2010-01-02 03:05:08 +0000 | [diff] [blame] | 499 | return bytes(read) |
cliechti | 89b4af1 | 2002-02-12 23:24:41 +0000 | [diff] [blame] | 500 | |
cliechti | 4a567a0 | 2009-07-27 22:09:31 +0000 | [diff] [blame] | 501 | def write(self, data): |
cliechti | d6bf52c | 2003-10-01 02:28:12 +0000 | [diff] [blame] | 502 | """Output the given string over the serial port.""" |
cliechti | 899c9c4 | 2011-06-14 23:01:23 +0000 | [diff] [blame] | 503 | if not self._isOpen: raise portNotOpenError |
cliechti | 3807712 | 2013-10-16 02:57:27 +0000 | [diff] [blame] | 504 | d = to_bytes(data) |
| 505 | tx_len = len(d) |
cliechti | 3cf46d6 | 2009-08-07 00:19:57 +0000 | [diff] [blame] | 506 | if self._writeTimeout is not None and self._writeTimeout > 0: |
| 507 | timeout = time.time() + self._writeTimeout |
| 508 | else: |
| 509 | timeout = None |
cliechti | 9f7c235 | 2013-10-11 01:13:46 +0000 | [diff] [blame] | 510 | while tx_len > 0: |
cliechti | 5d4d0bd | 2004-11-13 03:27:39 +0000 | [diff] [blame] | 511 | try: |
cliechti | 5d4d0bd | 2004-11-13 03:27:39 +0000 | [diff] [blame] | 512 | n = os.write(self.fd, d) |
cliechti | 3cf46d6 | 2009-08-07 00:19:57 +0000 | [diff] [blame] | 513 | 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) |
cliechti | 5d4d0bd | 2004-11-13 03:27:39 +0000 | [diff] [blame] | 520 | if not ready: |
| 521 | raise writeTimeoutError |
cliechti | 88c6244 | 2013-10-12 04:03:16 +0000 | [diff] [blame] | 522 | else: |
| 523 | # wait for write operation |
| 524 | _, ready, _ = select.select([], [self.fd], [], None) |
| 525 | if not ready: |
| 526 | raise SerialException('write failed (select)') |
cliechti | 5d4d0bd | 2004-11-13 03:27:39 +0000 | [diff] [blame] | 527 | d = d[n:] |
cliechti | 9f7c235 | 2013-10-11 01:13:46 +0000 | [diff] [blame] | 528 | tx_len -= n |
Chris Liechti | 675f7e1 | 2015-08-03 15:48:41 +0200 | [diff] [blame] | 529 | except SerialException: |
| 530 | raise |
Chris Liechti | 68340d7 | 2015-08-03 14:15:48 +0200 | [diff] [blame] | 531 | except OSError as v: |
cliechti | 5d4d0bd | 2004-11-13 03:27:39 +0000 | [diff] [blame] | 532 | if v.errno != errno.EAGAIN: |
cliechti | 65722c9 | 2009-08-07 00:48:53 +0000 | [diff] [blame] | 533 | raise SerialException('write failed: %s' % (v,)) |
cliechti | f81362e | 2009-07-25 03:44:33 +0000 | [diff] [blame] | 534 | return len(data) |
cliechti | d6bf52c | 2003-10-01 02:28:12 +0000 | [diff] [blame] | 535 | |
cliechti | a30a8a0 | 2003-10-05 12:28:13 +0000 | [diff] [blame] | 536 | def flush(self): |
cliechti | 7d44856 | 2014-08-03 21:57:45 +0000 | [diff] [blame] | 537 | """\ |
| 538 | Flush of file like objects. In this case, wait until all data |
| 539 | is written. |
| 540 | """ |
cliechti | a30a8a0 | 2003-10-05 12:28:13 +0000 | [diff] [blame] | 541 | self.drainOutput() |
| 542 | |
cliechti | 89b4af1 | 2002-02-12 23:24:41 +0000 | [diff] [blame] | 543 | def flushInput(self): |
cliechti | d6bf52c | 2003-10-01 02:28:12 +0000 | [diff] [blame] | 544 | """Clear input buffer, discarding all that is in the buffer.""" |
cliechti | 899c9c4 | 2011-06-14 23:01:23 +0000 | [diff] [blame] | 545 | if not self._isOpen: raise portNotOpenError |
Chris Liechti | 11465c8 | 2015-08-04 15:55:22 +0200 | [diff] [blame] | 546 | termios.tcflush(self.fd, termios.TCIFLUSH) |
cliechti | 89b4af1 | 2002-02-12 23:24:41 +0000 | [diff] [blame] | 547 | |
| 548 | def flushOutput(self): |
cliechti | 7d44856 | 2014-08-03 21:57:45 +0000 | [diff] [blame] | 549 | """\ |
| 550 | Clear output buffer, aborting the current output and discarding all |
| 551 | that is in the buffer. |
| 552 | """ |
cliechti | 899c9c4 | 2011-06-14 23:01:23 +0000 | [diff] [blame] | 553 | if not self._isOpen: raise portNotOpenError |
Chris Liechti | 11465c8 | 2015-08-04 15:55:22 +0200 | [diff] [blame] | 554 | termios.tcflush(self.fd, termios.TCOFLUSH) |
cliechti | 89b4af1 | 2002-02-12 23:24:41 +0000 | [diff] [blame] | 555 | |
cliechti | aaa0460 | 2006-02-05 23:02:46 +0000 | [diff] [blame] | 556 | def sendBreak(self, duration=0.25): |
cliechti | 7d44856 | 2014-08-03 21:57:45 +0000 | [diff] [blame] | 557 | """\ |
| 558 | Send break condition. Timed, returns to idle state after given |
| 559 | duration. |
| 560 | """ |
cliechti | 899c9c4 | 2011-06-14 23:01:23 +0000 | [diff] [blame] | 561 | if not self._isOpen: raise portNotOpenError |
cliechti | aaa0460 | 2006-02-05 23:02:46 +0000 | [diff] [blame] | 562 | termios.tcsendbreak(self.fd, int(duration/0.25)) |
cliechti | 89b4af1 | 2002-02-12 23:24:41 +0000 | [diff] [blame] | 563 | |
cliechti | 997b63c | 2008-06-21 00:09:31 +0000 | [diff] [blame] | 564 | def setBreak(self, level=1): |
cliechti | 7d44856 | 2014-08-03 21:57:45 +0000 | [diff] [blame] | 565 | """\ |
| 566 | Set break: Controls TXD. When active, no transmitting is possible. |
| 567 | """ |
cliechti | 997b63c | 2008-06-21 00:09:31 +0000 | [diff] [blame] | 568 | 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 | |
cliechti | 93db61b | 2006-08-26 19:16:18 +0000 | [diff] [blame] | 574 | def setRTS(self, level=1): |
cliechti | d6bf52c | 2003-10-01 02:28:12 +0000 | [diff] [blame] | 575 | """Set terminal status line: Request To Send""" |
cliechti | 899c9c4 | 2011-06-14 23:01:23 +0000 | [diff] [blame] | 576 | if not self._isOpen: raise portNotOpenError |
cliechti | b2f5fc8 | 2006-10-20 00:09:07 +0000 | [diff] [blame] | 577 | if level: |
cliechti | d6bf52c | 2003-10-01 02:28:12 +0000 | [diff] [blame] | 578 | fcntl.ioctl(self.fd, TIOCMBIS, TIOCM_RTS_str) |
| 579 | else: |
| 580 | fcntl.ioctl(self.fd, TIOCMBIC, TIOCM_RTS_str) |
| 581 | |
cliechti | 93db61b | 2006-08-26 19:16:18 +0000 | [diff] [blame] | 582 | def setDTR(self, level=1): |
cliechti | d6bf52c | 2003-10-01 02:28:12 +0000 | [diff] [blame] | 583 | """Set terminal status line: Data Terminal Ready""" |
cliechti | 899c9c4 | 2011-06-14 23:01:23 +0000 | [diff] [blame] | 584 | if not self._isOpen: raise portNotOpenError |
cliechti | b2f5fc8 | 2006-10-20 00:09:07 +0000 | [diff] [blame] | 585 | if level: |
cliechti | d6bf52c | 2003-10-01 02:28:12 +0000 | [diff] [blame] | 586 | 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""" |
cliechti | 899c9c4 | 2011-06-14 23:01:23 +0000 | [diff] [blame] | 592 | if not self._isOpen: raise portNotOpenError |
cliechti | d6bf52c | 2003-10-01 02:28:12 +0000 | [diff] [blame] | 593 | 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""" |
cliechti | 899c9c4 | 2011-06-14 23:01:23 +0000 | [diff] [blame] | 598 | if not self._isOpen: raise portNotOpenError |
cliechti | d6bf52c | 2003-10-01 02:28:12 +0000 | [diff] [blame] | 599 | s = fcntl.ioctl(self.fd, TIOCMGET, TIOCM_zero_str) |
| 600 | return struct.unpack('I',s)[0] & TIOCM_DSR != 0 |
| 601 | |
cliechti | d6bf52c | 2003-10-01 02:28:12 +0000 | [diff] [blame] | 602 | def getRI(self): |
| 603 | """Read terminal status line: Ring Indicator""" |
cliechti | 899c9c4 | 2011-06-14 23:01:23 +0000 | [diff] [blame] | 604 | if not self._isOpen: raise portNotOpenError |
cliechti | 89b4af1 | 2002-02-12 23:24:41 +0000 | [diff] [blame] | 605 | s = fcntl.ioctl(self.fd, TIOCMGET, TIOCM_zero_str) |
cliechti | d6bf52c | 2003-10-01 02:28:12 +0000 | [diff] [blame] | 606 | return struct.unpack('I',s)[0] & TIOCM_RI != 0 |
cliechti | 89b4af1 | 2002-02-12 23:24:41 +0000 | [diff] [blame] | 607 | |
| 608 | def getCD(self): |
cliechti | d6bf52c | 2003-10-01 02:28:12 +0000 | [diff] [blame] | 609 | """Read terminal status line: Carrier Detect""" |
cliechti | 899c9c4 | 2011-06-14 23:01:23 +0000 | [diff] [blame] | 610 | if not self._isOpen: raise portNotOpenError |
cliechti | 89b4af1 | 2002-02-12 23:24:41 +0000 | [diff] [blame] | 611 | s = fcntl.ioctl(self.fd, TIOCMGET, TIOCM_zero_str) |
cliechti | d6bf52c | 2003-10-01 02:28:12 +0000 | [diff] [blame] | 612 | return struct.unpack('I',s)[0] & TIOCM_CD != 0 |
cliechti | 89b4af1 | 2002-02-12 23:24:41 +0000 | [diff] [blame] | 613 | |
cliechti | a30a8a0 | 2003-10-05 12:28:13 +0000 | [diff] [blame] | 614 | # - - platform specific - - - - |
| 615 | |
cliechti | 28b8fd0 | 2011-12-28 21:39:42 +0000 | [diff] [blame] | 616 | def outWaiting(self): |
| 617 | """Return the number of characters currently in the output buffer.""" |
Chris Liechti | 11465c8 | 2015-08-04 15:55:22 +0200 | [diff] [blame] | 618 | #~ s = fcntl.ioctl(self.fd, termios.FIONREAD, TIOCM_zero_str) |
cliechti | 28b8fd0 | 2011-12-28 21:39:42 +0000 | [diff] [blame] | 619 | s = fcntl.ioctl(self.fd, TIOCOUTQ, TIOCM_zero_str) |
| 620 | return struct.unpack('I',s)[0] |
| 621 | |
cliechti | a30a8a0 | 2003-10-05 12:28:13 +0000 | [diff] [blame] | 622 | def drainOutput(self): |
| 623 | """internal - not portable!""" |
cliechti | 899c9c4 | 2011-06-14 23:01:23 +0000 | [diff] [blame] | 624 | if not self._isOpen: raise portNotOpenError |
cliechti | a30a8a0 | 2003-10-05 12:28:13 +0000 | [diff] [blame] | 625 | termios.tcdrain(self.fd) |
| 626 | |
| 627 | def nonblocking(self): |
| 628 | """internal - not portable!""" |
cliechti | 899c9c4 | 2011-06-14 23:01:23 +0000 | [diff] [blame] | 629 | if not self._isOpen: raise portNotOpenError |
Chris Liechti | 11465c8 | 2015-08-04 15:55:22 +0200 | [diff] [blame] | 630 | fcntl.fcntl(self.fd, fcntl.F_SETFL, os.O_NONBLOCK) |
cliechti | a30a8a0 | 2003-10-05 12:28:13 +0000 | [diff] [blame] | 631 | |
cliechti | 8753bbc | 2005-01-15 20:32:51 +0000 | [diff] [blame] | 632 | def fileno(self): |
cliechti | 2f0f8a3 | 2011-12-28 22:10:00 +0000 | [diff] [blame] | 633 | """\ |
| 634 | For easier use of the serial port instance with select. |
| 635 | WARNING: this function is not portable to different platforms! |
| 636 | """ |
cliechti | 899c9c4 | 2011-06-14 23:01:23 +0000 | [diff] [blame] | 637 | if not self._isOpen: raise portNotOpenError |
cliechti | 8753bbc | 2005-01-15 20:32:51 +0000 | [diff] [blame] | 638 | return self.fd |
cliechti | 89b4af1 | 2002-02-12 23:24:41 +0000 | [diff] [blame] | 639 | |
cliechti | 2f0f8a3 | 2011-12-28 22:10:00 +0000 | [diff] [blame] | 640 | 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 Liechti | 905d507 | 2015-08-03 21:41:49 +0200 | [diff] [blame] | 646 | if not self._isOpen: raise portNotOpenError |
cliechti | 4a60134 | 2011-12-29 02:22:17 +0000 | [diff] [blame] | 647 | if enable: |
Chris Liechti | 11465c8 | 2015-08-04 15:55:22 +0200 | [diff] [blame] | 648 | termios.tcflow(self.fd, termios.TCION) |
cliechti | 57e48a6 | 2009-08-03 22:29:58 +0000 | [diff] [blame] | 649 | else: |
Chris Liechti | 11465c8 | 2015-08-04 15:55:22 +0200 | [diff] [blame] | 650 | termios.tcflow(self.fd, termios.TCIOFF) |
cliechti | 57e48a6 | 2009-08-03 22:29:58 +0000 | [diff] [blame] | 651 | |
cliechti | 2f0f8a3 | 2011-12-28 22:10:00 +0000 | [diff] [blame] | 652 | 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 Liechti | 11465c8 | 2015-08-04 15:55:22 +0200 | [diff] [blame] | 660 | termios.tcflow(self.fd, termios.TCOON) |
cliechti | 2f0f8a3 | 2011-12-28 22:10:00 +0000 | [diff] [blame] | 661 | else: |
Chris Liechti | 11465c8 | 2015-08-04 15:55:22 +0200 | [diff] [blame] | 662 | termios.tcflow(self.fd, termios.TCOOFF) |
cliechti | 2f0f8a3 | 2011-12-28 22:10:00 +0000 | [diff] [blame] | 663 | |
cliechti | f81362e | 2009-07-25 03:44:33 +0000 | [diff] [blame] | 664 | |
cliechti | f81362e | 2009-07-25 03:44:33 +0000 | [diff] [blame] | 665 | |
cliechti | a9a093e | 2010-01-02 03:05:08 +0000 | [diff] [blame] | 666 | class PosixPollSerial(Serial): |
cliechti | 7d44856 | 2014-08-03 21:57:45 +0000 | [diff] [blame] | 667 | """\ |
cliechti | f0a81d4 | 2014-08-04 14:03:53 +0000 | [diff] [blame] | 668 | Poll based read implementation. Not all systems support poll properly. |
| 669 | However this one has better handling of errors, such as a device |
cliechti | 7d44856 | 2014-08-03 21:57:45 +0000 | [diff] [blame] | 670 | disconnecting while it's in use (e.g. USB-serial unplugged). |
| 671 | """ |
cliechti | a9a093e | 2010-01-02 03:05:08 +0000 | [diff] [blame] | 672 | |
| 673 | def read(self, size=1): |
cliechti | 7d44856 | 2014-08-03 21:57:45 +0000 | [diff] [blame] | 674 | """\ |
| 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 | """ |
cliechti | a9a093e | 2010-01-02 03:05:08 +0000 | [diff] [blame] | 679 | 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) |
cliechti | 4cd0d2e | 2010-07-21 01:15:25 +0000 | [diff] [blame] | 687 | for fd, event in poll.poll(self._timeout*1000): |
cliechti | a9a093e | 2010-01-02 03:05:08 +0000 | [diff] [blame] | 688 | 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 | |
cliechti | f81362e | 2009-07-25 03:44:33 +0000 | [diff] [blame] | 699 | |
cliechti | 89b4af1 | 2002-02-12 23:24:41 +0000 | [diff] [blame] | 700 | if __name__ == '__main__': |
| 701 | s = Serial(0, |
cliechti | 53c9fd4 | 2009-07-23 23:51:51 +0000 | [diff] [blame] | 702 | baudrate=19200, # baud rate |
| 703 | bytesize=EIGHTBITS, # number of data bits |
cliechti | 3172d3d | 2009-07-21 22:33:40 +0000 | [diff] [blame] | 704 | parity=PARITY_EVEN, # enable parity checking |
cliechti | 53c9fd4 | 2009-07-23 23:51:51 +0000 | [diff] [blame] | 705 | stopbits=STOPBITS_ONE, # number of stop bits |
cliechti | 3172d3d | 2009-07-21 22:33:40 +0000 | [diff] [blame] | 706 | 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 |
cliechti | 89b4af1 | 2002-02-12 23:24:41 +0000 | [diff] [blame] | 709 | ) |
| 710 | s.setRTS(1) |
| 711 | s.setDTR(1) |
| 712 | s.flushInput() |
| 713 | s.flushOutput() |
| 714 | s.write('hello') |
cliechti | 109486b | 2009-08-02 00:00:11 +0000 | [diff] [blame] | 715 | sys.stdout.write('%r\n' % s.read(5)) |
| 716 | sys.stdout.write('%s\n' % s.inWaiting()) |
cliechti | 89b4af1 | 2002-02-12 23:24:41 +0000 | [diff] [blame] | 717 | del s |
cliechti | 4569bac | 2007-11-08 21:57:19 +0000 | [diff] [blame] | 718 | |