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