cliechti | ab90e07 | 2009-08-06 01:44:34 +0000 | [diff] [blame] | 1 | #! python |
| 2 | # |
| 3 | # Python Serial Port Extension for Win32, Linux, BSD, Jython |
| 4 | # see __init__.py |
| 5 | # |
| 6 | # This module implements a simple socket based client. |
| 7 | # It does not support changing any port parameters and will silently ignore any |
| 8 | # requests to do so. |
| 9 | # |
| 10 | # The purpose of this module is that applications using pySerial can connect to |
| 11 | # TCP/IP to serial port converters that do not support RFC 2217. |
| 12 | # |
Chris Liechti | a422211 | 2015-08-07 01:03:12 +0200 | [diff] [blame] | 13 | # (C) 2001-2015 Chris Liechti <cliechti@gmx.net> |
Chris Liechti | fbdd8a0 | 2015-08-09 02:37:45 +0200 | [diff] [blame] | 14 | # |
| 15 | # SPDX-License-Identifier: BSD-3-Clause |
cliechti | ab90e07 | 2009-08-06 01:44:34 +0000 | [diff] [blame] | 16 | # |
| 17 | # URL format: socket://<host>:<port>[/option[/option...]] |
| 18 | # options: |
| 19 | # - "debug" print diagnostic messages |
| 20 | |
cliechti | c64ba69 | 2009-08-12 00:32:47 +0000 | [diff] [blame] | 21 | import logging |
Chris Liechti | fbdd8a0 | 2015-08-09 02:37:45 +0200 | [diff] [blame] | 22 | import select |
| 23 | import socket |
| 24 | import time |
Chris Liechti | c4bca9e | 2015-08-07 14:40:41 +0200 | [diff] [blame] | 25 | try: |
| 26 | import urlparse |
| 27 | except ImportError: |
| 28 | import urllib.parse as urlparse |
cliechti | c64ba69 | 2009-08-12 00:32:47 +0000 | [diff] [blame] | 29 | |
Chris Liechti | fbdd8a0 | 2015-08-09 02:37:45 +0200 | [diff] [blame] | 30 | from serial.serialutil import * |
| 31 | |
cliechti | c64ba69 | 2009-08-12 00:32:47 +0000 | [diff] [blame] | 32 | # map log level names to constants. used in fromURL() |
| 33 | LOGGER_LEVELS = { |
Chris Liechti | c4bca9e | 2015-08-07 14:40:41 +0200 | [diff] [blame] | 34 | 'debug': logging.DEBUG, |
| 35 | 'info': logging.INFO, |
| 36 | 'warning': logging.WARNING, |
| 37 | 'error': logging.ERROR, |
| 38 | } |
cliechti | c64ba69 | 2009-08-12 00:32:47 +0000 | [diff] [blame] | 39 | |
cliechti | 5d66a95 | 2013-10-11 02:27:30 +0000 | [diff] [blame] | 40 | POLL_TIMEOUT = 2 |
cliechti | ab90e07 | 2009-08-06 01:44:34 +0000 | [diff] [blame] | 41 | |
Chris Liechti | ef6b7b4 | 2015-08-06 22:19:26 +0200 | [diff] [blame] | 42 | class Serial(SerialBase): |
cliechti | ab90e07 | 2009-08-06 01:44:34 +0000 | [diff] [blame] | 43 | """Serial port implementation for plain sockets.""" |
| 44 | |
| 45 | BAUDRATES = (50, 75, 110, 134, 150, 200, 300, 600, 1200, 1800, 2400, 4800, |
| 46 | 9600, 19200, 38400, 57600, 115200) |
| 47 | |
| 48 | def open(self): |
cliechti | 7d44856 | 2014-08-03 21:57:45 +0000 | [diff] [blame] | 49 | """\ |
| 50 | Open port with current settings. This may throw a SerialException |
| 51 | if the port cannot be opened. |
| 52 | """ |
cliechti | 6a30077 | 2009-08-12 02:28:56 +0000 | [diff] [blame] | 53 | self.logger = None |
cliechti | ab90e07 | 2009-08-06 01:44:34 +0000 | [diff] [blame] | 54 | if self._port is None: |
| 55 | raise SerialException("Port must be configured before it can be used.") |
cliechti | 8f69e70 | 2011-03-19 00:22:32 +0000 | [diff] [blame] | 56 | if self._isOpen: |
| 57 | raise SerialException("Port is already open.") |
cliechti | ab90e07 | 2009-08-06 01:44:34 +0000 | [diff] [blame] | 58 | try: |
Chris Liechti | a422211 | 2015-08-07 01:03:12 +0200 | [diff] [blame] | 59 | self._socket = socket.create_connection(self.fromURL(self.portstr)) |
Chris Liechti | 68340d7 | 2015-08-03 14:15:48 +0200 | [diff] [blame] | 60 | except Exception as msg: |
cliechti | ab90e07 | 2009-08-06 01:44:34 +0000 | [diff] [blame] | 61 | self._socket = None |
| 62 | raise SerialException("Could not open port %s: %s" % (self.portstr, msg)) |
| 63 | |
cliechti | 5d66a95 | 2013-10-11 02:27:30 +0000 | [diff] [blame] | 64 | self._socket.settimeout(POLL_TIMEOUT) # used for write timeout support :/ |
cliechti | ab90e07 | 2009-08-06 01:44:34 +0000 | [diff] [blame] | 65 | |
| 66 | # not that there anything to configure... |
| 67 | self._reconfigurePort() |
| 68 | # all things set up get, now a clean start |
| 69 | self._isOpen = True |
| 70 | if not self._rtscts: |
| 71 | self.setRTS(True) |
| 72 | self.setDTR(True) |
| 73 | self.flushInput() |
| 74 | self.flushOutput() |
| 75 | |
| 76 | def _reconfigurePort(self): |
cliechti | 7d44856 | 2014-08-03 21:57:45 +0000 | [diff] [blame] | 77 | """\ |
| 78 | Set communication parameters on opened port. For the socket:// |
| 79 | protocol all settings are ignored! |
| 80 | """ |
cliechti | ab90e07 | 2009-08-06 01:44:34 +0000 | [diff] [blame] | 81 | if self._socket is None: |
| 82 | raise SerialException("Can only operate on open ports") |
cliechti | 6a30077 | 2009-08-12 02:28:56 +0000 | [diff] [blame] | 83 | if self.logger: |
| 84 | self.logger.info('ignored port configuration change') |
cliechti | ab90e07 | 2009-08-06 01:44:34 +0000 | [diff] [blame] | 85 | |
| 86 | def close(self): |
| 87 | """Close port""" |
| 88 | if self._isOpen: |
| 89 | if self._socket: |
| 90 | try: |
| 91 | self._socket.shutdown(socket.SHUT_RDWR) |
| 92 | self._socket.close() |
| 93 | except: |
| 94 | # ignore errors. |
| 95 | pass |
| 96 | self._socket = None |
cliechti | ab90e07 | 2009-08-06 01:44:34 +0000 | [diff] [blame] | 97 | self._isOpen = False |
| 98 | # in case of quick reconnects, give the server some time |
| 99 | time.sleep(0.3) |
| 100 | |
| 101 | def makeDeviceName(self, port): |
| 102 | raise SerialException("there is no sensible way to turn numbers into URLs") |
| 103 | |
| 104 | def fromURL(self, url): |
| 105 | """extract host and port from an URL string""" |
Chris Liechti | a422211 | 2015-08-07 01:03:12 +0200 | [diff] [blame] | 106 | parts = urlparse.urlsplit(url) |
Chris Liechti | d14b1ab | 2015-08-21 00:28:53 +0200 | [diff] [blame] | 107 | if parts.scheme != "socket": |
| 108 | raise SerialException('expected a string in the form "socket://<host>:<port>[?logging={debug|info|warning|error}]": not starting with socket:// (%r)' % (parts.scheme,)) |
cliechti | ab90e07 | 2009-08-06 01:44:34 +0000 | [diff] [blame] | 109 | try: |
Chris Liechti | a422211 | 2015-08-07 01:03:12 +0200 | [diff] [blame] | 110 | # process options now, directly altering self |
Chris Liechti | d14b1ab | 2015-08-21 00:28:53 +0200 | [diff] [blame] | 111 | for option, values in urlparse.parse_qs(parts.query, True).items(): |
| 112 | if option == 'logging': |
Chris Liechti | a422211 | 2015-08-07 01:03:12 +0200 | [diff] [blame] | 113 | logging.basicConfig() # XXX is that good to call it here? |
| 114 | self.logger = logging.getLogger('pySerial.socket') |
Chris Liechti | d14b1ab | 2015-08-21 00:28:53 +0200 | [diff] [blame] | 115 | self.logger.setLevel(LOGGER_LEVELS[values[0]]) |
Chris Liechti | a422211 | 2015-08-07 01:03:12 +0200 | [diff] [blame] | 116 | self.logger.debug('enabled logging') |
| 117 | else: |
| 118 | raise ValueError('unknown option: %r' % (option,)) |
cliechti | ab90e07 | 2009-08-06 01:44:34 +0000 | [diff] [blame] | 119 | # get host and port |
Chris Liechti | a422211 | 2015-08-07 01:03:12 +0200 | [diff] [blame] | 120 | host, port = parts.hostname, parts.port |
cliechti | ab90e07 | 2009-08-06 01:44:34 +0000 | [diff] [blame] | 121 | if not 0 <= port < 65536: raise ValueError("port not in range 0...65535") |
Chris Liechti | 68340d7 | 2015-08-03 14:15:48 +0200 | [diff] [blame] | 122 | except ValueError as e: |
Chris Liechti | d14b1ab | 2015-08-21 00:28:53 +0200 | [diff] [blame] | 123 | raise SerialException('expected a string in the form "socket://<host>:<port>[?logging={debug|info|warning|error}]": %s' % e) |
cliechti | ab90e07 | 2009-08-06 01:44:34 +0000 | [diff] [blame] | 124 | return (host, port) |
| 125 | |
| 126 | # - - - - - - - - - - - - - - - - - - - - - - - - |
| 127 | |
| 128 | def inWaiting(self): |
| 129 | """Return the number of characters currently in the input buffer.""" |
| 130 | if not self._isOpen: raise portNotOpenError |
cliechti | 77e088a | 2014-08-04 10:29:24 +0000 | [diff] [blame] | 131 | # Poll the socket to see if it is ready for reading. |
| 132 | # If ready, at least one byte will be to read. |
| 133 | lr, lw, lx = select.select([self._socket], [], [], 0) |
| 134 | return len(lr) |
cliechti | ab90e07 | 2009-08-06 01:44:34 +0000 | [diff] [blame] | 135 | |
| 136 | def read(self, size=1): |
cliechti | 7d44856 | 2014-08-03 21:57:45 +0000 | [diff] [blame] | 137 | """\ |
| 138 | Read size bytes from the serial port. If a timeout is set it may |
cliechti | ab90e07 | 2009-08-06 01:44:34 +0000 | [diff] [blame] | 139 | return less characters as requested. With no timeout it will block |
cliechti | 7d44856 | 2014-08-03 21:57:45 +0000 | [diff] [blame] | 140 | until the requested number of bytes is read. |
| 141 | """ |
cliechti | ab90e07 | 2009-08-06 01:44:34 +0000 | [diff] [blame] | 142 | if not self._isOpen: raise portNotOpenError |
| 143 | data = bytearray() |
cliechti | 20e1fae | 2013-05-31 01:33:12 +0000 | [diff] [blame] | 144 | if self._timeout is not None: |
| 145 | timeout = time.time() + self._timeout |
| 146 | else: |
| 147 | timeout = None |
Chris Liechti | 069d32a | 2015-08-05 03:21:38 +0200 | [diff] [blame] | 148 | while len(data) < size: |
cliechti | ab90e07 | 2009-08-06 01:44:34 +0000 | [diff] [blame] | 149 | try: |
| 150 | # an implementation with internal buffer would be better |
| 151 | # performing... |
cliechti | fee4e96 | 2013-05-31 00:55:43 +0000 | [diff] [blame] | 152 | block = self._socket.recv(size - len(data)) |
| 153 | if block: |
cliechti | 5d66a95 | 2013-10-11 02:27:30 +0000 | [diff] [blame] | 154 | data.extend(block) |
| 155 | else: |
| 156 | # no data -> EOF (connection probably closed) |
| 157 | break |
cliechti | ab90e07 | 2009-08-06 01:44:34 +0000 | [diff] [blame] | 158 | except socket.timeout: |
cliechti | 5d66a95 | 2013-10-11 02:27:30 +0000 | [diff] [blame] | 159 | # just need to get out of recv from time to time to check if |
Chris Liechti | 2880f0e | 2015-08-17 03:19:46 +0200 | [diff] [blame] | 160 | # still alive and timeout did not expire |
| 161 | pass |
Chris Liechti | 68340d7 | 2015-08-03 14:15:48 +0200 | [diff] [blame] | 162 | except socket.error as e: |
cliechti | ab90e07 | 2009-08-06 01:44:34 +0000 | [diff] [blame] | 163 | # connection fails -> terminate loop |
| 164 | raise SerialException('connection failed (%s)' % e) |
Chris Liechti | 069d32a | 2015-08-05 03:21:38 +0200 | [diff] [blame] | 165 | if timeout is not None and time.time() > timeout: |
| 166 | break |
cliechti | ab90e07 | 2009-08-06 01:44:34 +0000 | [diff] [blame] | 167 | return bytes(data) |
| 168 | |
| 169 | def write(self, data): |
cliechti | 7d44856 | 2014-08-03 21:57:45 +0000 | [diff] [blame] | 170 | """\ |
| 171 | Output the given string over the serial port. Can block if the |
cliechti | ab90e07 | 2009-08-06 01:44:34 +0000 | [diff] [blame] | 172 | connection is blocked. May raise SerialException if the connection is |
cliechti | 7d44856 | 2014-08-03 21:57:45 +0000 | [diff] [blame] | 173 | closed. |
| 174 | """ |
cliechti | ab90e07 | 2009-08-06 01:44:34 +0000 | [diff] [blame] | 175 | if not self._isOpen: raise portNotOpenError |
| 176 | try: |
cliechti | 3807712 | 2013-10-16 02:57:27 +0000 | [diff] [blame] | 177 | self._socket.sendall(to_bytes(data)) |
Chris Liechti | 68340d7 | 2015-08-03 14:15:48 +0200 | [diff] [blame] | 178 | except socket.error as e: |
cliechti | 5d66a95 | 2013-10-11 02:27:30 +0000 | [diff] [blame] | 179 | # XXX what exception if socket connection fails |
| 180 | raise SerialException("socket connection failed: %s" % e) |
cliechti | ab90e07 | 2009-08-06 01:44:34 +0000 | [diff] [blame] | 181 | return len(data) |
| 182 | |
| 183 | def flushInput(self): |
| 184 | """Clear input buffer, discarding all that is in the buffer.""" |
| 185 | if not self._isOpen: raise portNotOpenError |
cliechti | 6a30077 | 2009-08-12 02:28:56 +0000 | [diff] [blame] | 186 | if self.logger: |
| 187 | self.logger.info('ignored flushInput') |
cliechti | ab90e07 | 2009-08-06 01:44:34 +0000 | [diff] [blame] | 188 | |
| 189 | def flushOutput(self): |
cliechti | 7d44856 | 2014-08-03 21:57:45 +0000 | [diff] [blame] | 190 | """\ |
| 191 | Clear output buffer, aborting the current output and |
| 192 | discarding all that is in the buffer. |
| 193 | """ |
cliechti | ab90e07 | 2009-08-06 01:44:34 +0000 | [diff] [blame] | 194 | if not self._isOpen: raise portNotOpenError |
cliechti | 6a30077 | 2009-08-12 02:28:56 +0000 | [diff] [blame] | 195 | if self.logger: |
| 196 | self.logger.info('ignored flushOutput') |
cliechti | ab90e07 | 2009-08-06 01:44:34 +0000 | [diff] [blame] | 197 | |
| 198 | def sendBreak(self, duration=0.25): |
cliechti | 7d44856 | 2014-08-03 21:57:45 +0000 | [diff] [blame] | 199 | """\ |
| 200 | Send break condition. Timed, returns to idle state after given |
| 201 | duration. |
| 202 | """ |
cliechti | ab90e07 | 2009-08-06 01:44:34 +0000 | [diff] [blame] | 203 | if not self._isOpen: raise portNotOpenError |
cliechti | 6a30077 | 2009-08-12 02:28:56 +0000 | [diff] [blame] | 204 | if self.logger: |
| 205 | self.logger.info('ignored sendBreak(%r)' % (duration,)) |
cliechti | ab90e07 | 2009-08-06 01:44:34 +0000 | [diff] [blame] | 206 | |
| 207 | def setBreak(self, level=True): |
| 208 | """Set break: Controls TXD. When active, to transmitting is |
| 209 | possible.""" |
| 210 | if not self._isOpen: raise portNotOpenError |
cliechti | 6a30077 | 2009-08-12 02:28:56 +0000 | [diff] [blame] | 211 | if self.logger: |
| 212 | self.logger.info('ignored setBreak(%r)' % (level,)) |
cliechti | ab90e07 | 2009-08-06 01:44:34 +0000 | [diff] [blame] | 213 | |
| 214 | def setRTS(self, level=True): |
| 215 | """Set terminal status line: Request To Send""" |
| 216 | if not self._isOpen: raise portNotOpenError |
cliechti | 6a30077 | 2009-08-12 02:28:56 +0000 | [diff] [blame] | 217 | if self.logger: |
| 218 | self.logger.info('ignored setRTS(%r)' % (level,)) |
cliechti | ab90e07 | 2009-08-06 01:44:34 +0000 | [diff] [blame] | 219 | |
| 220 | def setDTR(self, level=True): |
| 221 | """Set terminal status line: Data Terminal Ready""" |
| 222 | if not self._isOpen: raise portNotOpenError |
cliechti | 6a30077 | 2009-08-12 02:28:56 +0000 | [diff] [blame] | 223 | if self.logger: |
| 224 | self.logger.info('ignored setDTR(%r)' % (level,)) |
cliechti | ab90e07 | 2009-08-06 01:44:34 +0000 | [diff] [blame] | 225 | |
| 226 | def getCTS(self): |
| 227 | """Read terminal status line: Clear To Send""" |
| 228 | if not self._isOpen: raise portNotOpenError |
cliechti | 6a30077 | 2009-08-12 02:28:56 +0000 | [diff] [blame] | 229 | if self.logger: |
| 230 | self.logger.info('returning dummy for getCTS()') |
cliechti | ab90e07 | 2009-08-06 01:44:34 +0000 | [diff] [blame] | 231 | return True |
| 232 | |
| 233 | def getDSR(self): |
| 234 | """Read terminal status line: Data Set Ready""" |
| 235 | if not self._isOpen: raise portNotOpenError |
cliechti | 6a30077 | 2009-08-12 02:28:56 +0000 | [diff] [blame] | 236 | if self.logger: |
| 237 | self.logger.info('returning dummy for getDSR()') |
cliechti | ab90e07 | 2009-08-06 01:44:34 +0000 | [diff] [blame] | 238 | return True |
| 239 | |
| 240 | def getRI(self): |
| 241 | """Read terminal status line: Ring Indicator""" |
| 242 | if not self._isOpen: raise portNotOpenError |
cliechti | 6a30077 | 2009-08-12 02:28:56 +0000 | [diff] [blame] | 243 | if self.logger: |
| 244 | self.logger.info('returning dummy for getRI()') |
cliechti | ab90e07 | 2009-08-06 01:44:34 +0000 | [diff] [blame] | 245 | return False |
| 246 | |
| 247 | def getCD(self): |
| 248 | """Read terminal status line: Carrier Detect""" |
| 249 | if not self._isOpen: raise portNotOpenError |
cliechti | 6a30077 | 2009-08-12 02:28:56 +0000 | [diff] [blame] | 250 | if self.logger: |
| 251 | self.logger.info('returning dummy for getCD()') |
cliechti | ab90e07 | 2009-08-06 01:44:34 +0000 | [diff] [blame] | 252 | return True |
| 253 | |
| 254 | # - - - platform specific - - - |
cliechti | b869edb | 2014-07-31 22:13:19 +0000 | [diff] [blame] | 255 | |
| 256 | # works on Linux and probably all the other POSIX systems |
| 257 | def fileno(self): |
| 258 | """Get the file handle of the underlying socket for use with select""" |
| 259 | return self._socket.fileno() |
cliechti | ab90e07 | 2009-08-06 01:44:34 +0000 | [diff] [blame] | 260 | |
| 261 | |
Chris Liechti | ef6b7b4 | 2015-08-06 22:19:26 +0200 | [diff] [blame] | 262 | # |
cliechti | ab90e07 | 2009-08-06 01:44:34 +0000 | [diff] [blame] | 263 | # simple client test |
| 264 | if __name__ == '__main__': |
| 265 | import sys |
| 266 | s = Serial('socket://localhost:7000') |
| 267 | sys.stdout.write('%s\n' % s) |
| 268 | |
| 269 | sys.stdout.write("write...\n") |
Chris Liechti | fbdd8a0 | 2015-08-09 02:37:45 +0200 | [diff] [blame] | 270 | s.write(b"hello\n") |
cliechti | ab90e07 | 2009-08-06 01:44:34 +0000 | [diff] [blame] | 271 | s.flush() |
| 272 | sys.stdout.write("read: %s\n" % s.read(5)) |
| 273 | |
| 274 | s.close() |