blob: a35cf75d191f9eddfc81c4eb7b7eeedcabc1ef3e [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
173 # OSError ignore EAGAIN errors. all other errors are shown
174 if e.errno != errno.EAGAIN:
Chris Liechti4daa9d52016-03-22 00:32:01 +0100175 raise SerialException('read failed: {}'.format(e))
Chris Liechtieb163262016-12-18 22:40:22 +0100176 except (select.error, socket.error) as e:
Chris Liechti6032cf52016-01-15 23:12:20 +0100177 # this is for Python 2.x
178 # ignore EAGAIN errors. all other errors are shown
179 # see also http://www.python.org/dev/peps/pep-3151/#select
180 if e[0] != errno.EAGAIN:
Chris Liechti4daa9d52016-03-22 00:32:01 +0100181 raise SerialException('read failed: {}'.format(e))
Chris Liechtieb163262016-12-18 22:40:22 +0100182 if timeout.expired():
183 break
Chris Liechti6032cf52016-01-15 23:12:20 +0100184 return bytes(read)
cliechtiab90e072009-08-06 01:44:34 +0000185
186 def write(self, data):
cliechti7d448562014-08-03 21:57:45 +0000187 """\
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200188 Output the given byte string over the serial port. Can block if the
cliechtiab90e072009-08-06 01:44:34 +0000189 connection is blocked. May raise SerialException if the connection is
cliechti7d448562014-08-03 21:57:45 +0000190 closed.
191 """
Chris Liechti033f17c2015-08-30 21:28:04 +0200192 if not self.is_open:
193 raise portNotOpenError
Chris Liechtieb163262016-12-18 22:40:22 +0100194
195 d = to_bytes(data)
196 tx_len = length = len(d)
197 timeout = Timeout(self._write_timeout)
198 while tx_len > 0:
199 try:
200 n = self._socket.send(d)
201 if timeout.is_non_blocking:
202 # Zero timeout indicates non-blocking - simply return the
203 # number of bytes of data actually written
204 return n
205 elif not timeout.is_infinite:
206 # when timeout is set, use select to wait for being ready
207 # with the time left as timeout
208 if timeout.expired():
209 raise writeTimeoutError
210 _, ready, _ = select.select([], [self._socket], [], timeout.time_left())
211 if not ready:
212 raise writeTimeoutError
213 else:
214 assert timeout.time_left() is None
215 # wait for write operation
216 _, ready, _ = select.select([], [self._socket], [], None)
217 if not ready:
218 raise SerialException('write failed (select)')
219 d = d[n:]
220 tx_len -= n
221 except SerialException:
222 raise
223 except OSError as v:
224 if v.errno != errno.EAGAIN:
225 raise SerialException('write failed: {}'.format(v))
226 # still calculate and check timeout
227 if timeout.expired():
228 raise writeTimeoutError
229 return length - len(d)
cliechtiab90e072009-08-06 01:44:34 +0000230
Chris Liechtief1fe252015-08-27 23:25:21 +0200231 def reset_input_buffer(self):
cliechtiab90e072009-08-06 01:44:34 +0000232 """Clear input buffer, discarding all that is in the buffer."""
Chris Liechti033f17c2015-08-30 21:28:04 +0200233 if not self.is_open:
234 raise portNotOpenError
Chris Liechti64d59922016-12-19 03:12:05 +0100235
236 # just use recv to remove input, while there is some
237 ready = True
238 while ready:
239 ready, _, _ = select.select([self._socket], [], [], 0)
240 try:
241 self._socket.recv(4096)
242 except OSError as e:
243 # this is for Python 3.x where select.error is a subclass of
244 # OSError ignore EAGAIN errors. all other errors are shown
245 if e.errno != errno.EAGAIN:
246 raise SerialException('reset_input_buffer failed: {}'.format(e))
247 except (select.error, socket.error) as e:
248 # this is for Python 2.x
249 # ignore EAGAIN errors. all other errors are shown
250 # see also http://www.python.org/dev/peps/pep-3151/#select
251 if e[0] != errno.EAGAIN:
252 raise SerialException('reset_input_buffer failed: {}'.format(e))
cliechtiab90e072009-08-06 01:44:34 +0000253
Chris Liechtief1fe252015-08-27 23:25:21 +0200254 def reset_output_buffer(self):
cliechti7d448562014-08-03 21:57:45 +0000255 """\
256 Clear output buffer, aborting the current output and
257 discarding all that is in the buffer.
258 """
Chris Liechti033f17c2015-08-30 21:28:04 +0200259 if not self.is_open:
260 raise portNotOpenError
cliechti6a300772009-08-12 02:28:56 +0000261 if self.logger:
Chris Liechtief1fe252015-08-27 23:25:21 +0200262 self.logger.info('ignored reset_output_buffer')
cliechtiab90e072009-08-06 01:44:34 +0000263
Chris Liechtief1fe252015-08-27 23:25:21 +0200264 def send_break(self, duration=0.25):
cliechti7d448562014-08-03 21:57:45 +0000265 """\
266 Send break condition. Timed, returns to idle state after given
267 duration.
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 Liechti4daa9d52016-03-22 00:32:01 +0100272 self.logger.info('ignored send_break({!r})'.format(duration))
cliechtiab90e072009-08-06 01:44:34 +0000273
Chris Liechtief1fe252015-08-27 23:25:21 +0200274 def _update_break_state(self):
cliechtiab90e072009-08-06 01:44:34 +0000275 """Set break: Controls TXD. When active, to transmitting is
276 possible."""
cliechti6a300772009-08-12 02:28:56 +0000277 if self.logger:
Chris Liechti4daa9d52016-03-22 00:32:01 +0100278 self.logger.info('ignored _update_break_state({!r})'.format(self._break_state))
cliechtiab90e072009-08-06 01:44:34 +0000279
Chris Liechtief1fe252015-08-27 23:25:21 +0200280 def _update_rts_state(self):
cliechtiab90e072009-08-06 01:44:34 +0000281 """Set terminal status line: Request To Send"""
cliechti6a300772009-08-12 02:28:56 +0000282 if self.logger:
Chris Liechti4daa9d52016-03-22 00:32:01 +0100283 self.logger.info('ignored _update_rts_state({!r})'.format(self._rts_state))
cliechtiab90e072009-08-06 01:44:34 +0000284
Chris Liechtief1fe252015-08-27 23:25:21 +0200285 def _update_dtr_state(self):
cliechtiab90e072009-08-06 01:44:34 +0000286 """Set terminal status line: Data Terminal Ready"""
cliechti6a300772009-08-12 02:28:56 +0000287 if self.logger:
Chris Liechti4daa9d52016-03-22 00:32:01 +0100288 self.logger.info('ignored _update_dtr_state({!r})'.format(self._dtr_state))
cliechtiab90e072009-08-06 01:44:34 +0000289
Chris Liechtief1fe252015-08-27 23:25:21 +0200290 @property
291 def cts(self):
cliechtiab90e072009-08-06 01:44:34 +0000292 """Read terminal status line: Clear To Send"""
Chris Liechti033f17c2015-08-30 21:28:04 +0200293 if not self.is_open:
294 raise portNotOpenError
cliechti6a300772009-08-12 02:28:56 +0000295 if self.logger:
Chris Liechtief1fe252015-08-27 23:25:21 +0200296 self.logger.info('returning dummy for cts')
cliechtiab90e072009-08-06 01:44:34 +0000297 return True
298
Chris Liechtief1fe252015-08-27 23:25:21 +0200299 @property
300 def dsr(self):
cliechtiab90e072009-08-06 01:44:34 +0000301 """Read terminal status line: Data Set Ready"""
Chris Liechti033f17c2015-08-30 21:28:04 +0200302 if not self.is_open:
303 raise portNotOpenError
cliechti6a300772009-08-12 02:28:56 +0000304 if self.logger:
Chris Liechtief1fe252015-08-27 23:25:21 +0200305 self.logger.info('returning dummy for dsr')
cliechtiab90e072009-08-06 01:44:34 +0000306 return True
307
Chris Liechtief1fe252015-08-27 23:25:21 +0200308 @property
309 def ri(self):
cliechtiab90e072009-08-06 01:44:34 +0000310 """Read terminal status line: Ring Indicator"""
Chris Liechti033f17c2015-08-30 21:28:04 +0200311 if not self.is_open:
312 raise portNotOpenError
cliechti6a300772009-08-12 02:28:56 +0000313 if self.logger:
Chris Liechtief1fe252015-08-27 23:25:21 +0200314 self.logger.info('returning dummy for ri')
cliechtiab90e072009-08-06 01:44:34 +0000315 return False
316
Chris Liechtief1fe252015-08-27 23:25:21 +0200317 @property
318 def cd(self):
cliechtiab90e072009-08-06 01:44:34 +0000319 """Read terminal status line: Carrier Detect"""
Chris Liechti033f17c2015-08-30 21:28:04 +0200320 if not self.is_open:
321 raise portNotOpenError
cliechti6a300772009-08-12 02:28:56 +0000322 if self.logger:
Chris Liechtief1fe252015-08-27 23:25:21 +0200323 self.logger.info('returning dummy for cd)')
cliechtiab90e072009-08-06 01:44:34 +0000324 return True
325
326 # - - - platform specific - - -
cliechtib869edb2014-07-31 22:13:19 +0000327
328 # works on Linux and probably all the other POSIX systems
329 def fileno(self):
330 """Get the file handle of the underlying socket for use with select"""
331 return self._socket.fileno()
cliechtiab90e072009-08-06 01:44:34 +0000332
333
Chris Liechtief6b7b42015-08-06 22:19:26 +0200334#
cliechtiab90e072009-08-06 01:44:34 +0000335# simple client test
336if __name__ == '__main__':
337 import sys
338 s = Serial('socket://localhost:7000')
Chris Liechti4daa9d52016-03-22 00:32:01 +0100339 sys.stdout.write('{}\n'.format(s))
cliechtiab90e072009-08-06 01:44:34 +0000340
341 sys.stdout.write("write...\n")
Chris Liechtifbdd8a02015-08-09 02:37:45 +0200342 s.write(b"hello\n")
cliechtiab90e072009-08-06 01:44:34 +0000343 s.flush()
Chris Liechti4daa9d52016-03-22 00:32:01 +0100344 sys.stdout.write("read: {}\n".format(s.read(5)))
cliechtiab90e072009-08-06 01:44:34 +0000345
346 s.close()