blob: a017ee3fa630c7119a9c2b23fcac0b06eb657982 [file] [log] [blame]
cliechtiab90e072009-08-06 01:44:34 +00001#! python
2#
cliechtiab90e072009-08-06 01:44:34 +00003# This module implements a simple socket based client.
4# It does not support changing any port parameters and will silently ignore any
5# requests to do so.
6#
7# The purpose of this module is that applications using pySerial can connect to
8# TCP/IP to serial port converters that do not support RFC 2217.
9#
Chris Liechti3e02f702015-12-16 23:06:04 +010010# This file is part of pySerial. https://github.com/pyserial/pyserial
Chris Liechtia4222112015-08-07 01:03:12 +020011# (C) 2001-2015 Chris Liechti <cliechti@gmx.net>
Chris Liechtifbdd8a02015-08-09 02:37:45 +020012#
13# SPDX-License-Identifier: BSD-3-Clause
cliechtiab90e072009-08-06 01:44:34 +000014#
15# URL format: socket://<host>:<port>[/option[/option...]]
16# options:
17# - "debug" print diagnostic messages
18
Chris Liechtib10daf42016-01-26 00:27:10 +010019import errno
cliechtic64ba692009-08-12 00:32:47 +000020import logging
Chris Liechtifbdd8a02015-08-09 02:37:45 +020021import select
22import socket
23import time
Chris Liechtic4bca9e2015-08-07 14:40:41 +020024try:
25 import urlparse
26except ImportError:
27 import urllib.parse as urlparse
cliechtic64ba692009-08-12 00:32:47 +000028
Chris Liechti033f17c2015-08-30 21:28:04 +020029from serial.serialutil import SerialBase, SerialException, portNotOpenError, to_bytes
Chris Liechtifbdd8a02015-08-09 02:37:45 +020030
Chris Liechti3ad62fb2015-08-29 21:53:32 +020031# map log level names to constants. used in from_url()
cliechtic64ba692009-08-12 00:32:47 +000032LOGGER_LEVELS = {
Chris Liechti6594df62016-02-04 21:13:41 +010033 'debug': logging.DEBUG,
34 'info': logging.INFO,
35 'warning': logging.WARNING,
36 'error': logging.ERROR,
37}
cliechtic64ba692009-08-12 00:32:47 +000038
Chris Liechti4c3ec662016-04-21 22:52:31 +020039POLL_TIMEOUT = 5
cliechtiab90e072009-08-06 01:44:34 +000040
Chris Liechti033f17c2015-08-30 21:28:04 +020041
Chris Liechtief6b7b42015-08-06 22:19:26 +020042class Serial(SerialBase):
cliechtiab90e072009-08-06 01:44:34 +000043 """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):
cliechti7d448562014-08-03 21:57:45 +000049 """\
50 Open port with current settings. This may throw a SerialException
51 if the port cannot be opened.
52 """
cliechti6a300772009-08-12 02:28:56 +000053 self.logger = None
cliechtiab90e072009-08-06 01:44:34 +000054 if self._port is None:
55 raise SerialException("Port must be configured before it can be used.")
Chris Liechti3ad62fb2015-08-29 21:53:32 +020056 if self.is_open:
cliechti8f69e702011-03-19 00:22:32 +000057 raise SerialException("Port is already open.")
cliechtiab90e072009-08-06 01:44:34 +000058 try:
Chris Liechti4c3ec662016-04-21 22:52:31 +020059 # timeout is used for write timeout support :/ and to get an initial connection timeout
60 self._socket = socket.create_connection(self.from_url(self.portstr), timeout=POLL_TIMEOUT)
Chris Liechti68340d72015-08-03 14:15:48 +020061 except Exception as msg:
cliechtiab90e072009-08-06 01:44:34 +000062 self._socket = None
Chris Liechti4daa9d52016-03-22 00:32:01 +010063 raise SerialException("Could not open port {}: {}".format(self.portstr, msg))
cliechtiab90e072009-08-06 01:44:34 +000064
Chris Liechti4c3ec662016-04-21 22:52:31 +020065 # not that there is anything to configure...
Chris Liechti3ad62fb2015-08-29 21:53:32 +020066 self._reconfigure_port()
cliechtiab90e072009-08-06 01:44:34 +000067 # all things set up get, now a clean start
Chris Liechti3ad62fb2015-08-29 21:53:32 +020068 self.is_open = True
69 if not self._dsrdtr:
Chris Liechtief1fe252015-08-27 23:25:21 +020070 self._update_dtr_state()
cliechtiab90e072009-08-06 01:44:34 +000071 if not self._rtscts:
Chris Liechtief1fe252015-08-27 23:25:21 +020072 self._update_rts_state()
73 self.reset_input_buffer()
74 self.reset_output_buffer()
cliechtiab90e072009-08-06 01:44:34 +000075
Chris Liechti3ad62fb2015-08-29 21:53:32 +020076 def _reconfigure_port(self):
cliechti7d448562014-08-03 21:57:45 +000077 """\
78 Set communication parameters on opened port. For the socket://
79 protocol all settings are ignored!
80 """
cliechtiab90e072009-08-06 01:44:34 +000081 if self._socket is None:
82 raise SerialException("Can only operate on open ports")
cliechti6a300772009-08-12 02:28:56 +000083 if self.logger:
84 self.logger.info('ignored port configuration change')
cliechtiab90e072009-08-06 01:44:34 +000085
86 def close(self):
87 """Close port"""
Chris Liechti3ad62fb2015-08-29 21:53:32 +020088 if self.is_open:
cliechtiab90e072009-08-06 01:44:34 +000089 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
Chris Liechti3ad62fb2015-08-29 21:53:32 +020097 self.is_open = False
cliechtiab90e072009-08-06 01:44:34 +000098 # in case of quick reconnects, give the server some time
99 time.sleep(0.3)
100
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200101 def from_url(self, url):
cliechtiab90e072009-08-06 01:44:34 +0000102 """extract host and port from an URL string"""
Chris Liechtia4222112015-08-07 01:03:12 +0200103 parts = urlparse.urlsplit(url)
Chris Liechtid14b1ab2015-08-21 00:28:53 +0200104 if parts.scheme != "socket":
Chris Liechti4daa9d52016-03-22 00:32:01 +0100105 raise SerialException(
106 'expected a string in the form '
107 '"socket://<host>:<port>[?logging={debug|info|warning|error}]": '
108 'not starting with socket:// ({!r})'.format(parts.scheme))
cliechtiab90e072009-08-06 01:44:34 +0000109 try:
Chris Liechtia4222112015-08-07 01:03:12 +0200110 # process options now, directly altering self
Chris Liechtid14b1ab2015-08-21 00:28:53 +0200111 for option, values in urlparse.parse_qs(parts.query, True).items():
112 if option == 'logging':
Chris Liechtia4222112015-08-07 01:03:12 +0200113 logging.basicConfig() # XXX is that good to call it here?
114 self.logger = logging.getLogger('pySerial.socket')
Chris Liechtid14b1ab2015-08-21 00:28:53 +0200115 self.logger.setLevel(LOGGER_LEVELS[values[0]])
Chris Liechtia4222112015-08-07 01:03:12 +0200116 self.logger.debug('enabled logging')
117 else:
Chris Liechti4daa9d52016-03-22 00:32:01 +0100118 raise ValueError('unknown option: {!r}'.format(option))
119 if not 0 <= parts.port < 65536:
Chris Liechti033f17c2015-08-30 21:28:04 +0200120 raise ValueError("port not in range 0...65535")
Chris Liechti68340d72015-08-03 14:15:48 +0200121 except ValueError as e:
Chris Liechti4daa9d52016-03-22 00:32:01 +0100122 raise SerialException(
123 'expected a string in the form '
124 '"socket://<host>:<port>[?logging={debug|info|warning|error}]": {}'.format(e))
125
126 return (parts.hostname, parts.port)
cliechtiab90e072009-08-06 01:44:34 +0000127
128 # - - - - - - - - - - - - - - - - - - - - - - - -
129
Chris Liechtief1fe252015-08-27 23:25:21 +0200130 @property
131 def in_waiting(self):
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200132 """Return the number of bytes currently in the input buffer."""
Chris Liechti033f17c2015-08-30 21:28:04 +0200133 if not self.is_open:
134 raise portNotOpenError
cliechti77e088a2014-08-04 10:29:24 +0000135 # Poll the socket to see if it is ready for reading.
136 # If ready, at least one byte will be to read.
137 lr, lw, lx = select.select([self._socket], [], [], 0)
138 return len(lr)
cliechtiab90e072009-08-06 01:44:34 +0000139
Chris Liechti6032cf52016-01-15 23:12:20 +0100140 # select based implementation, similar to posix, but only using socket API
141 # to be portable, additionally handle socket timeout which is used to
142 # emulate write timeouts
cliechtiab90e072009-08-06 01:44:34 +0000143 def read(self, size=1):
cliechti7d448562014-08-03 21:57:45 +0000144 """\
145 Read size bytes from the serial port. If a timeout is set it may
cliechtiab90e072009-08-06 01:44:34 +0000146 return less characters as requested. With no timeout it will block
cliechti7d448562014-08-03 21:57:45 +0000147 until the requested number of bytes is read.
148 """
Chris Liechti033f17c2015-08-30 21:28:04 +0200149 if not self.is_open:
150 raise portNotOpenError
Chris Liechti6032cf52016-01-15 23:12:20 +0100151 read = bytearray()
152 timeout = self._timeout
153 while len(read) < size:
cliechtiab90e072009-08-06 01:44:34 +0000154 try:
Chris Liechti6032cf52016-01-15 23:12:20 +0100155 start_time = time.time()
156 ready, _, _ = select.select([self._socket], [], [], timeout)
157 # If select was used with a timeout, and the timeout occurs, it
158 # returns with empty lists -> thus abort read operation.
159 # For timeout == 0 (non-blocking operation) also abort when
160 # there is nothing to read.
161 if not ready:
162 break # timeout
163 buf = self._socket.recv(size - len(read))
164 # read should always return some data as select reported it was
165 # ready to read when we get to this point, unless it is EOF
166 if not buf:
167 raise SerialException('socket disconnected')
168 read.extend(buf)
169 if timeout is not None:
170 timeout -= time.time() - start_time
171 if timeout <= 0:
172 break
cliechtiab90e072009-08-06 01:44:34 +0000173 except socket.timeout:
Chris Liechti6032cf52016-01-15 23:12:20 +0100174 # timeout is used for write support, just go reading again
Chris Liechti2880f0e2015-08-17 03:19:46 +0200175 pass
Chris Liechti68340d72015-08-03 14:15:48 +0200176 except socket.error as e:
cliechtiab90e072009-08-06 01:44:34 +0000177 # connection fails -> terminate loop
Chris Liechti4daa9d52016-03-22 00:32:01 +0100178 raise SerialException('connection failed ({})'.format(e))
Chris Liechti6032cf52016-01-15 23:12:20 +0100179 except OSError as e:
180 # this is for Python 3.x where select.error is a subclass of
181 # OSError ignore EAGAIN errors. all other errors are shown
182 if e.errno != errno.EAGAIN:
Chris Liechti4daa9d52016-03-22 00:32:01 +0100183 raise SerialException('read failed: {}'.format(e))
Chris Liechti6032cf52016-01-15 23:12:20 +0100184 except select.error as e:
185 # this is for Python 2.x
186 # ignore EAGAIN errors. all other errors are shown
187 # see also http://www.python.org/dev/peps/pep-3151/#select
188 if e[0] != errno.EAGAIN:
Chris Liechti4daa9d52016-03-22 00:32:01 +0100189 raise SerialException('read failed: {}'.format(e))
Chris Liechti6032cf52016-01-15 23:12:20 +0100190 return bytes(read)
cliechtiab90e072009-08-06 01:44:34 +0000191
192 def write(self, data):
cliechti7d448562014-08-03 21:57:45 +0000193 """\
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200194 Output the given byte string over the serial port. Can block if the
cliechtiab90e072009-08-06 01:44:34 +0000195 connection is blocked. May raise SerialException if the connection is
cliechti7d448562014-08-03 21:57:45 +0000196 closed.
197 """
Chris Liechti033f17c2015-08-30 21:28:04 +0200198 if not self.is_open:
199 raise portNotOpenError
cliechtiab90e072009-08-06 01:44:34 +0000200 try:
cliechti38077122013-10-16 02:57:27 +0000201 self._socket.sendall(to_bytes(data))
Chris Liechti68340d72015-08-03 14:15:48 +0200202 except socket.error as e:
cliechti5d66a952013-10-11 02:27:30 +0000203 # XXX what exception if socket connection fails
Chris Liechti4daa9d52016-03-22 00:32:01 +0100204 raise SerialException("socket connection failed: {}".format(e))
cliechtiab90e072009-08-06 01:44:34 +0000205 return len(data)
206
Chris Liechtief1fe252015-08-27 23:25:21 +0200207 def reset_input_buffer(self):
cliechtiab90e072009-08-06 01:44:34 +0000208 """Clear input buffer, discarding all that is in the buffer."""
Chris Liechti033f17c2015-08-30 21:28:04 +0200209 if not self.is_open:
210 raise portNotOpenError
cliechti6a300772009-08-12 02:28:56 +0000211 if self.logger:
Chris Liechtief1fe252015-08-27 23:25:21 +0200212 self.logger.info('ignored reset_input_buffer')
cliechtiab90e072009-08-06 01:44:34 +0000213
Chris Liechtief1fe252015-08-27 23:25:21 +0200214 def reset_output_buffer(self):
cliechti7d448562014-08-03 21:57:45 +0000215 """\
216 Clear output buffer, aborting the current output and
217 discarding all that is in the buffer.
218 """
Chris Liechti033f17c2015-08-30 21:28:04 +0200219 if not self.is_open:
220 raise portNotOpenError
cliechti6a300772009-08-12 02:28:56 +0000221 if self.logger:
Chris Liechtief1fe252015-08-27 23:25:21 +0200222 self.logger.info('ignored reset_output_buffer')
cliechtiab90e072009-08-06 01:44:34 +0000223
Chris Liechtief1fe252015-08-27 23:25:21 +0200224 def send_break(self, duration=0.25):
cliechti7d448562014-08-03 21:57:45 +0000225 """\
226 Send break condition. Timed, returns to idle state after given
227 duration.
228 """
Chris Liechti033f17c2015-08-30 21:28:04 +0200229 if not self.is_open:
230 raise portNotOpenError
cliechti6a300772009-08-12 02:28:56 +0000231 if self.logger:
Chris Liechti4daa9d52016-03-22 00:32:01 +0100232 self.logger.info('ignored send_break({!r})'.format(duration))
cliechtiab90e072009-08-06 01:44:34 +0000233
Chris Liechtief1fe252015-08-27 23:25:21 +0200234 def _update_break_state(self):
cliechtiab90e072009-08-06 01:44:34 +0000235 """Set break: Controls TXD. When active, to transmitting is
236 possible."""
cliechti6a300772009-08-12 02:28:56 +0000237 if self.logger:
Chris Liechti4daa9d52016-03-22 00:32:01 +0100238 self.logger.info('ignored _update_break_state({!r})'.format(self._break_state))
cliechtiab90e072009-08-06 01:44:34 +0000239
Chris Liechtief1fe252015-08-27 23:25:21 +0200240 def _update_rts_state(self):
cliechtiab90e072009-08-06 01:44:34 +0000241 """Set terminal status line: Request To Send"""
cliechti6a300772009-08-12 02:28:56 +0000242 if self.logger:
Chris Liechti4daa9d52016-03-22 00:32:01 +0100243 self.logger.info('ignored _update_rts_state({!r})'.format(self._rts_state))
cliechtiab90e072009-08-06 01:44:34 +0000244
Chris Liechtief1fe252015-08-27 23:25:21 +0200245 def _update_dtr_state(self):
cliechtiab90e072009-08-06 01:44:34 +0000246 """Set terminal status line: Data Terminal Ready"""
cliechti6a300772009-08-12 02:28:56 +0000247 if self.logger:
Chris Liechti4daa9d52016-03-22 00:32:01 +0100248 self.logger.info('ignored _update_dtr_state({!r})'.format(self._dtr_state))
cliechtiab90e072009-08-06 01:44:34 +0000249
Chris Liechtief1fe252015-08-27 23:25:21 +0200250 @property
251 def cts(self):
cliechtiab90e072009-08-06 01:44:34 +0000252 """Read terminal status line: Clear To Send"""
Chris Liechti033f17c2015-08-30 21:28:04 +0200253 if not self.is_open:
254 raise portNotOpenError
cliechti6a300772009-08-12 02:28:56 +0000255 if self.logger:
Chris Liechtief1fe252015-08-27 23:25:21 +0200256 self.logger.info('returning dummy for cts')
cliechtiab90e072009-08-06 01:44:34 +0000257 return True
258
Chris Liechtief1fe252015-08-27 23:25:21 +0200259 @property
260 def dsr(self):
cliechtiab90e072009-08-06 01:44:34 +0000261 """Read terminal status line: Data Set Ready"""
Chris Liechti033f17c2015-08-30 21:28:04 +0200262 if not self.is_open:
263 raise portNotOpenError
cliechti6a300772009-08-12 02:28:56 +0000264 if self.logger:
Chris Liechtief1fe252015-08-27 23:25:21 +0200265 self.logger.info('returning dummy for dsr')
cliechtiab90e072009-08-06 01:44:34 +0000266 return True
267
Chris Liechtief1fe252015-08-27 23:25:21 +0200268 @property
269 def ri(self):
cliechtiab90e072009-08-06 01:44:34 +0000270 """Read terminal status line: Ring Indicator"""
Chris Liechti033f17c2015-08-30 21:28:04 +0200271 if not self.is_open:
272 raise portNotOpenError
cliechti6a300772009-08-12 02:28:56 +0000273 if self.logger:
Chris Liechtief1fe252015-08-27 23:25:21 +0200274 self.logger.info('returning dummy for ri')
cliechtiab90e072009-08-06 01:44:34 +0000275 return False
276
Chris Liechtief1fe252015-08-27 23:25:21 +0200277 @property
278 def cd(self):
cliechtiab90e072009-08-06 01:44:34 +0000279 """Read terminal status line: Carrier Detect"""
Chris Liechti033f17c2015-08-30 21:28:04 +0200280 if not self.is_open:
281 raise portNotOpenError
cliechti6a300772009-08-12 02:28:56 +0000282 if self.logger:
Chris Liechtief1fe252015-08-27 23:25:21 +0200283 self.logger.info('returning dummy for cd)')
cliechtiab90e072009-08-06 01:44:34 +0000284 return True
285
286 # - - - platform specific - - -
cliechtib869edb2014-07-31 22:13:19 +0000287
288 # works on Linux and probably all the other POSIX systems
289 def fileno(self):
290 """Get the file handle of the underlying socket for use with select"""
291 return self._socket.fileno()
cliechtiab90e072009-08-06 01:44:34 +0000292
293
Chris Liechtief6b7b42015-08-06 22:19:26 +0200294#
cliechtiab90e072009-08-06 01:44:34 +0000295# simple client test
296if __name__ == '__main__':
297 import sys
298 s = Serial('socket://localhost:7000')
Chris Liechti4daa9d52016-03-22 00:32:01 +0100299 sys.stdout.write('{}\n'.format(s))
cliechtiab90e072009-08-06 01:44:34 +0000300
301 sys.stdout.write("write...\n")
Chris Liechtifbdd8a02015-08-09 02:37:45 +0200302 s.write(b"hello\n")
cliechtiab90e072009-08-06 01:44:34 +0000303 s.flush()
Chris Liechti4daa9d52016-03-22 00:32:01 +0100304 sys.stdout.write("read: {}\n".format(s.read(5)))
cliechtiab90e072009-08-06 01:44:34 +0000305
306 s.close()