blob: 5c77415568e27da9edb033d7d3d8595942005560 [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 Liechtieb163262016-12-18 22:40:22 +010029from serial.serialutil import SerialBase, SerialException, to_bytes, \
30 portNotOpenError, writeTimeoutError, Timeout
Chris Liechtifbdd8a02015-08-09 02:37:45 +020031
Chris Liechti3ad62fb2015-08-29 21:53:32 +020032# map log level names to constants. used in from_url()
cliechtic64ba692009-08-12 00:32:47 +000033LOGGER_LEVELS = {
Chris Liechti6594df62016-02-04 21:13:41 +010034 'debug': logging.DEBUG,
35 'info': logging.INFO,
36 'warning': logging.WARNING,
37 'error': logging.ERROR,
38}
cliechtic64ba692009-08-12 00:32:47 +000039
Chris Liechti4c3ec662016-04-21 22:52:31 +020040POLL_TIMEOUT = 5
cliechtiab90e072009-08-06 01:44:34 +000041
Chris Liechti033f17c2015-08-30 21:28:04 +020042
Chris Liechtief6b7b42015-08-06 22:19:26 +020043class Serial(SerialBase):
cliechtiab90e072009-08-06 01:44:34 +000044 """Serial port implementation for plain sockets."""
45
46 BAUDRATES = (50, 75, 110, 134, 150, 200, 300, 600, 1200, 1800, 2400, 4800,
47 9600, 19200, 38400, 57600, 115200)
48
49 def open(self):
cliechti7d448562014-08-03 21:57:45 +000050 """\
51 Open port with current settings. This may throw a SerialException
52 if the port cannot be opened.
53 """
cliechti6a300772009-08-12 02:28:56 +000054 self.logger = None
cliechtiab90e072009-08-06 01:44:34 +000055 if self._port is None:
56 raise SerialException("Port must be configured before it can be used.")
Chris Liechti3ad62fb2015-08-29 21:53:32 +020057 if self.is_open:
cliechti8f69e702011-03-19 00:22:32 +000058 raise SerialException("Port is already open.")
cliechtiab90e072009-08-06 01:44:34 +000059 try:
Chris Liechti4c3ec662016-04-21 22:52:31 +020060 # timeout is used for write timeout support :/ and to get an initial connection timeout
61 self._socket = socket.create_connection(self.from_url(self.portstr), timeout=POLL_TIMEOUT)
Chris Liechti68340d72015-08-03 14:15:48 +020062 except Exception as msg:
cliechtiab90e072009-08-06 01:44:34 +000063 self._socket = None
Chris Liechti4daa9d52016-03-22 00:32:01 +010064 raise SerialException("Could not open port {}: {}".format(self.portstr, msg))
Chris Liechtieb163262016-12-18 22:40:22 +010065 # after connecting, switch to non-blocking, we're using select
66 self._socket.setblocking(False)
cliechtiab90e072009-08-06 01:44:34 +000067
Chris Liechti4c3ec662016-04-21 22:52:31 +020068 # not that there is anything to configure...
Chris Liechti3ad62fb2015-08-29 21:53:32 +020069 self._reconfigure_port()
cliechtiab90e072009-08-06 01:44:34 +000070 # all things set up get, now a clean start
Chris Liechti3ad62fb2015-08-29 21:53:32 +020071 self.is_open = True
72 if not self._dsrdtr:
Chris Liechtief1fe252015-08-27 23:25:21 +020073 self._update_dtr_state()
cliechtiab90e072009-08-06 01:44:34 +000074 if not self._rtscts:
Chris Liechtief1fe252015-08-27 23:25:21 +020075 self._update_rts_state()
76 self.reset_input_buffer()
77 self.reset_output_buffer()
cliechtiab90e072009-08-06 01:44:34 +000078
Chris Liechti3ad62fb2015-08-29 21:53:32 +020079 def _reconfigure_port(self):
cliechti7d448562014-08-03 21:57:45 +000080 """\
81 Set communication parameters on opened port. For the socket://
82 protocol all settings are ignored!
83 """
cliechtiab90e072009-08-06 01:44:34 +000084 if self._socket is None:
85 raise SerialException("Can only operate on open ports")
cliechti6a300772009-08-12 02:28:56 +000086 if self.logger:
87 self.logger.info('ignored port configuration change')
cliechtiab90e072009-08-06 01:44:34 +000088
89 def close(self):
90 """Close port"""
Chris Liechti3ad62fb2015-08-29 21:53:32 +020091 if self.is_open:
cliechtiab90e072009-08-06 01:44:34 +000092 if self._socket:
93 try:
94 self._socket.shutdown(socket.SHUT_RDWR)
95 self._socket.close()
96 except:
97 # ignore errors.
98 pass
99 self._socket = None
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200100 self.is_open = False
cliechtiab90e072009-08-06 01:44:34 +0000101 # in case of quick reconnects, give the server some time
102 time.sleep(0.3)
103
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200104 def from_url(self, url):
cliechtiab90e072009-08-06 01:44:34 +0000105 """extract host and port from an URL string"""
Chris Liechtia4222112015-08-07 01:03:12 +0200106 parts = urlparse.urlsplit(url)
Chris Liechtid14b1ab2015-08-21 00:28:53 +0200107 if parts.scheme != "socket":
Chris Liechti4daa9d52016-03-22 00:32:01 +0100108 raise SerialException(
109 'expected a string in the form '
110 '"socket://<host>:<port>[?logging={debug|info|warning|error}]": '
111 'not starting with socket:// ({!r})'.format(parts.scheme))
cliechtiab90e072009-08-06 01:44:34 +0000112 try:
Chris Liechtia4222112015-08-07 01:03:12 +0200113 # process options now, directly altering self
Chris Liechtid14b1ab2015-08-21 00:28:53 +0200114 for option, values in urlparse.parse_qs(parts.query, True).items():
115 if option == 'logging':
Chris Liechtia4222112015-08-07 01:03:12 +0200116 logging.basicConfig() # XXX is that good to call it here?
117 self.logger = logging.getLogger('pySerial.socket')
Chris Liechtid14b1ab2015-08-21 00:28:53 +0200118 self.logger.setLevel(LOGGER_LEVELS[values[0]])
Chris Liechtia4222112015-08-07 01:03:12 +0200119 self.logger.debug('enabled logging')
120 else:
Chris Liechti4daa9d52016-03-22 00:32:01 +0100121 raise ValueError('unknown option: {!r}'.format(option))
122 if not 0 <= parts.port < 65536:
Chris Liechti033f17c2015-08-30 21:28:04 +0200123 raise ValueError("port not in range 0...65535")
Chris Liechti68340d72015-08-03 14:15:48 +0200124 except ValueError as e:
Chris Liechti4daa9d52016-03-22 00:32:01 +0100125 raise SerialException(
126 'expected a string in the form '
127 '"socket://<host>:<port>[?logging={debug|info|warning|error}]": {}'.format(e))
128
129 return (parts.hostname, parts.port)
cliechtiab90e072009-08-06 01:44:34 +0000130
131 # - - - - - - - - - - - - - - - - - - - - - - - -
132
Chris Liechtief1fe252015-08-27 23:25:21 +0200133 @property
134 def in_waiting(self):
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200135 """Return the number of bytes currently in the input buffer."""
Chris Liechti033f17c2015-08-30 21:28:04 +0200136 if not self.is_open:
137 raise portNotOpenError
cliechti77e088a2014-08-04 10:29:24 +0000138 # Poll the socket to see if it is ready for reading.
139 # If ready, at least one byte will be to read.
140 lr, lw, lx = select.select([self._socket], [], [], 0)
141 return len(lr)
cliechtiab90e072009-08-06 01:44:34 +0000142
Chris Liechti6032cf52016-01-15 23:12:20 +0100143 # select based implementation, similar to posix, but only using socket API
144 # to be portable, additionally handle socket timeout which is used to
145 # emulate write timeouts
cliechtiab90e072009-08-06 01:44:34 +0000146 def read(self, size=1):
cliechti7d448562014-08-03 21:57:45 +0000147 """\
148 Read size bytes from the serial port. If a timeout is set it may
cliechtiab90e072009-08-06 01:44:34 +0000149 return less characters as requested. With no timeout it will block
cliechti7d448562014-08-03 21:57:45 +0000150 until the requested number of bytes is read.
151 """
Chris Liechti033f17c2015-08-30 21:28:04 +0200152 if not self.is_open:
153 raise portNotOpenError
Chris Liechti6032cf52016-01-15 23:12:20 +0100154 read = bytearray()
Chris Liechtieb163262016-12-18 22:40:22 +0100155 timeout = Timeout(self._timeout)
Chris Liechti6032cf52016-01-15 23:12:20 +0100156 while len(read) < size:
cliechtiab90e072009-08-06 01:44:34 +0000157 try:
Chris Liechtieb163262016-12-18 22:40:22 +0100158 ready, _, _ = select.select([self._socket], [], [], timeout.time_left())
Chris Liechti6032cf52016-01-15 23:12:20 +0100159 # If select was used with a timeout, and the timeout occurs, it
160 # returns with empty lists -> thus abort read operation.
161 # For timeout == 0 (non-blocking operation) also abort when
162 # there is nothing to read.
163 if not ready:
164 break # timeout
165 buf = self._socket.recv(size - len(read))
166 # read should always return some data as select reported it was
167 # ready to read when we get to this point, unless it is EOF
168 if not buf:
169 raise SerialException('socket disconnected')
170 read.extend(buf)
Chris Liechti6032cf52016-01-15 23:12:20 +0100171 except OSError as e:
172 # this is for Python 3.x where select.error is a subclass of
Chris Liechtifc1bf5a2017-05-06 23:39:05 +0200173 # OSError ignore BlockingIOErrors and EINTR. other errors are shown
174 # https://www.python.org/dev/peps/pep-0475.
175 if e.errno not in (errno.EAGAIN, errno.EALREADY, errno.EWOULDBLOCK, errno.EINPROGRESS, errno.EINTR):
Chris Liechti4daa9d52016-03-22 00:32:01 +0100176 raise SerialException('read failed: {}'.format(e))
Chris Liechtieb163262016-12-18 22:40:22 +0100177 except (select.error, socket.error) as e:
Chris Liechti6032cf52016-01-15 23:12:20 +0100178 # this is for Python 2.x
Chris Liechtifc1bf5a2017-05-06 23:39:05 +0200179 # ignore BlockingIOErrors and EINTR. all errors are shown
Chris Liechti6032cf52016-01-15 23:12:20 +0100180 # see also http://www.python.org/dev/peps/pep-3151/#select
Chris Liechtifc1bf5a2017-05-06 23:39:05 +0200181 if e[0] not in (errno.EAGAIN, errno.EALREADY, errno.EWOULDBLOCK, errno.EINPROGRESS, errno.EINTR):
Chris Liechti4daa9d52016-03-22 00:32:01 +0100182 raise SerialException('read failed: {}'.format(e))
Chris Liechtieb163262016-12-18 22:40:22 +0100183 if timeout.expired():
184 break
Chris Liechti6032cf52016-01-15 23:12:20 +0100185 return bytes(read)
cliechtiab90e072009-08-06 01:44:34 +0000186
187 def write(self, data):
cliechti7d448562014-08-03 21:57:45 +0000188 """\
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200189 Output the given byte string over the serial port. Can block if the
cliechtiab90e072009-08-06 01:44:34 +0000190 connection is blocked. May raise SerialException if the connection is
cliechti7d448562014-08-03 21:57:45 +0000191 closed.
192 """
Chris Liechti033f17c2015-08-30 21:28:04 +0200193 if not self.is_open:
194 raise portNotOpenError
Chris Liechtieb163262016-12-18 22:40:22 +0100195
196 d = to_bytes(data)
197 tx_len = length = len(d)
198 timeout = Timeout(self._write_timeout)
199 while tx_len > 0:
200 try:
201 n = self._socket.send(d)
202 if timeout.is_non_blocking:
203 # Zero timeout indicates non-blocking - simply return the
204 # number of bytes of data actually written
205 return n
206 elif not timeout.is_infinite:
207 # when timeout is set, use select to wait for being ready
208 # with the time left as timeout
209 if timeout.expired():
210 raise writeTimeoutError
211 _, ready, _ = select.select([], [self._socket], [], timeout.time_left())
212 if not ready:
213 raise writeTimeoutError
214 else:
215 assert timeout.time_left() is None
216 # wait for write operation
217 _, ready, _ = select.select([], [self._socket], [], None)
218 if not ready:
219 raise SerialException('write failed (select)')
220 d = d[n:]
221 tx_len -= n
222 except SerialException:
223 raise
Chris Liechtifc1bf5a2017-05-06 23:39:05 +0200224 except OSError as e:
225 # this is for Python 3.x where select.error is a subclass of
226 # OSError ignore BlockingIOErrors and EINTR. other errors are shown
227 # https://www.python.org/dev/peps/pep-0475.
228 if e.errno not in (errno.EAGAIN, errno.EALREADY, errno.EWOULDBLOCK, errno.EINPROGRESS, errno.EINTR):
229 raise SerialException('write failed: {}'.format(e))
230 except select.error as e:
231 # this is for Python 2.x
232 # ignore BlockingIOErrors and EINTR. all errors are shown
233 # see also http://www.python.org/dev/peps/pep-3151/#select
234 if e[0] not in (errno.EAGAIN, errno.EALREADY, errno.EWOULDBLOCK, errno.EINPROGRESS, errno.EINTR):
235 raise SerialException('write failed: {}'.format(e))
236 if not timeout.is_non_blocking and timeout.expired():
237 raise writeTimeoutError
Chris Liechtieb163262016-12-18 22:40:22 +0100238 return length - len(d)
cliechtiab90e072009-08-06 01:44:34 +0000239
Chris Liechtief1fe252015-08-27 23:25:21 +0200240 def reset_input_buffer(self):
cliechtiab90e072009-08-06 01:44:34 +0000241 """Clear input buffer, discarding all that is in the buffer."""
Chris Liechti033f17c2015-08-30 21:28:04 +0200242 if not self.is_open:
243 raise portNotOpenError
Chris Liechti64d59922016-12-19 03:12:05 +0100244
245 # just use recv to remove input, while there is some
246 ready = True
247 while ready:
248 ready, _, _ = select.select([self._socket], [], [], 0)
249 try:
250 self._socket.recv(4096)
251 except OSError as e:
252 # this is for Python 3.x where select.error is a subclass of
Chris Liechtifc1bf5a2017-05-06 23:39:05 +0200253 # OSError ignore BlockingIOErrors and EINTR. other errors are shown
254 # https://www.python.org/dev/peps/pep-0475.
255 if e.errno not in (errno.EAGAIN, errno.EALREADY, errno.EWOULDBLOCK, errno.EINPROGRESS, errno.EINTR):
256 raise SerialException('read failed: {}'.format(e))
Chris Liechti64d59922016-12-19 03:12:05 +0100257 except (select.error, socket.error) as e:
258 # this is for Python 2.x
Chris Liechtifc1bf5a2017-05-06 23:39:05 +0200259 # ignore BlockingIOErrors and EINTR. all errors are shown
Chris Liechti64d59922016-12-19 03:12:05 +0100260 # see also http://www.python.org/dev/peps/pep-3151/#select
Chris Liechtifc1bf5a2017-05-06 23:39:05 +0200261 if e[0] not in (errno.EAGAIN, errno.EALREADY, errno.EWOULDBLOCK, errno.EINPROGRESS, errno.EINTR):
262 raise SerialException('read failed: {}'.format(e))
cliechtiab90e072009-08-06 01:44:34 +0000263
Chris Liechtief1fe252015-08-27 23:25:21 +0200264 def reset_output_buffer(self):
cliechti7d448562014-08-03 21:57:45 +0000265 """\
266 Clear output buffer, aborting the current output and
267 discarding all that is in the buffer.
268 """
Chris Liechti033f17c2015-08-30 21:28:04 +0200269 if not self.is_open:
270 raise portNotOpenError
cliechti6a300772009-08-12 02:28:56 +0000271 if self.logger:
Chris Liechtief1fe252015-08-27 23:25:21 +0200272 self.logger.info('ignored reset_output_buffer')
cliechtiab90e072009-08-06 01:44:34 +0000273
Chris Liechtief1fe252015-08-27 23:25:21 +0200274 def send_break(self, duration=0.25):
cliechti7d448562014-08-03 21:57:45 +0000275 """\
276 Send break condition. Timed, returns to idle state after given
277 duration.
278 """
Chris Liechti033f17c2015-08-30 21:28:04 +0200279 if not self.is_open:
280 raise portNotOpenError
cliechti6a300772009-08-12 02:28:56 +0000281 if self.logger:
Chris Liechti4daa9d52016-03-22 00:32:01 +0100282 self.logger.info('ignored send_break({!r})'.format(duration))
cliechtiab90e072009-08-06 01:44:34 +0000283
Chris Liechtief1fe252015-08-27 23:25:21 +0200284 def _update_break_state(self):
cliechtiab90e072009-08-06 01:44:34 +0000285 """Set break: Controls TXD. When active, to transmitting is
286 possible."""
cliechti6a300772009-08-12 02:28:56 +0000287 if self.logger:
Chris Liechti4daa9d52016-03-22 00:32:01 +0100288 self.logger.info('ignored _update_break_state({!r})'.format(self._break_state))
cliechtiab90e072009-08-06 01:44:34 +0000289
Chris Liechtief1fe252015-08-27 23:25:21 +0200290 def _update_rts_state(self):
cliechtiab90e072009-08-06 01:44:34 +0000291 """Set terminal status line: Request To Send"""
cliechti6a300772009-08-12 02:28:56 +0000292 if self.logger:
Chris Liechti4daa9d52016-03-22 00:32:01 +0100293 self.logger.info('ignored _update_rts_state({!r})'.format(self._rts_state))
cliechtiab90e072009-08-06 01:44:34 +0000294
Chris Liechtief1fe252015-08-27 23:25:21 +0200295 def _update_dtr_state(self):
cliechtiab90e072009-08-06 01:44:34 +0000296 """Set terminal status line: Data Terminal Ready"""
cliechti6a300772009-08-12 02:28:56 +0000297 if self.logger:
Chris Liechti4daa9d52016-03-22 00:32:01 +0100298 self.logger.info('ignored _update_dtr_state({!r})'.format(self._dtr_state))
cliechtiab90e072009-08-06 01:44:34 +0000299
Chris Liechtief1fe252015-08-27 23:25:21 +0200300 @property
301 def cts(self):
cliechtiab90e072009-08-06 01:44:34 +0000302 """Read terminal status line: Clear To Send"""
Chris Liechti033f17c2015-08-30 21:28:04 +0200303 if not self.is_open:
304 raise portNotOpenError
cliechti6a300772009-08-12 02:28:56 +0000305 if self.logger:
Chris Liechtief1fe252015-08-27 23:25:21 +0200306 self.logger.info('returning dummy for cts')
cliechtiab90e072009-08-06 01:44:34 +0000307 return True
308
Chris Liechtief1fe252015-08-27 23:25:21 +0200309 @property
310 def dsr(self):
cliechtiab90e072009-08-06 01:44:34 +0000311 """Read terminal status line: Data Set Ready"""
Chris Liechti033f17c2015-08-30 21:28:04 +0200312 if not self.is_open:
313 raise portNotOpenError
cliechti6a300772009-08-12 02:28:56 +0000314 if self.logger:
Chris Liechtief1fe252015-08-27 23:25:21 +0200315 self.logger.info('returning dummy for dsr')
cliechtiab90e072009-08-06 01:44:34 +0000316 return True
317
Chris Liechtief1fe252015-08-27 23:25:21 +0200318 @property
319 def ri(self):
cliechtiab90e072009-08-06 01:44:34 +0000320 """Read terminal status line: Ring Indicator"""
Chris Liechti033f17c2015-08-30 21:28:04 +0200321 if not self.is_open:
322 raise portNotOpenError
cliechti6a300772009-08-12 02:28:56 +0000323 if self.logger:
Chris Liechtief1fe252015-08-27 23:25:21 +0200324 self.logger.info('returning dummy for ri')
cliechtiab90e072009-08-06 01:44:34 +0000325 return False
326
Chris Liechtief1fe252015-08-27 23:25:21 +0200327 @property
328 def cd(self):
cliechtiab90e072009-08-06 01:44:34 +0000329 """Read terminal status line: Carrier Detect"""
Chris Liechti033f17c2015-08-30 21:28:04 +0200330 if not self.is_open:
331 raise portNotOpenError
cliechti6a300772009-08-12 02:28:56 +0000332 if self.logger:
Chris Liechtief1fe252015-08-27 23:25:21 +0200333 self.logger.info('returning dummy for cd)')
cliechtiab90e072009-08-06 01:44:34 +0000334 return True
335
336 # - - - platform specific - - -
cliechtib869edb2014-07-31 22:13:19 +0000337
338 # works on Linux and probably all the other POSIX systems
339 def fileno(self):
340 """Get the file handle of the underlying socket for use with select"""
341 return self._socket.fileno()
cliechtiab90e072009-08-06 01:44:34 +0000342
343
Chris Liechtief6b7b42015-08-06 22:19:26 +0200344#
cliechtiab90e072009-08-06 01:44:34 +0000345# simple client test
346if __name__ == '__main__':
347 import sys
348 s = Serial('socket://localhost:7000')
Chris Liechti4daa9d52016-03-22 00:32:01 +0100349 sys.stdout.write('{}\n'.format(s))
cliechtiab90e072009-08-06 01:44:34 +0000350
351 sys.stdout.write("write...\n")
Chris Liechtifbdd8a02015-08-09 02:37:45 +0200352 s.write(b"hello\n")
cliechtiab90e072009-08-06 01:44:34 +0000353 s.flush()
Chris Liechti4daa9d52016-03-22 00:32:01 +0100354 sys.stdout.write("read: {}\n".format(s.read(5)))
cliechtiab90e072009-08-06 01:44:34 +0000355
356 s.close()