blob: a4297bb2619f986d2ac9d30ff93bbd6ae727dc4d [file] [log] [blame]
cliechtiab90e072009-08-06 01:44:34 +00001#! 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 Liechtia4222112015-08-07 01:03:12 +020013# (C) 2001-2015 Chris Liechti <cliechti@gmx.net>
Chris Liechtifbdd8a02015-08-09 02:37:45 +020014#
15# SPDX-License-Identifier: BSD-3-Clause
cliechtiab90e072009-08-06 01:44:34 +000016#
17# URL format: socket://<host>:<port>[/option[/option...]]
18# options:
19# - "debug" print diagnostic messages
20
cliechtic64ba692009-08-12 00:32:47 +000021import logging
Chris Liechtifbdd8a02015-08-09 02:37:45 +020022import select
23import socket
24import time
Chris Liechtic4bca9e2015-08-07 14:40:41 +020025try:
26 import urlparse
27except ImportError:
28 import urllib.parse as urlparse
cliechtic64ba692009-08-12 00:32:47 +000029
Chris Liechti033f17c2015-08-30 21:28:04 +020030from serial.serialutil import SerialBase, SerialException, portNotOpenError, to_bytes
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 Liechtic4bca9e2015-08-07 14:40:41 +020034 'debug': logging.DEBUG,
35 'info': logging.INFO,
36 'warning': logging.WARNING,
37 'error': logging.ERROR,
38 }
cliechtic64ba692009-08-12 00:32:47 +000039
cliechti5d66a952013-10-11 02:27:30 +000040POLL_TIMEOUT = 2
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 Liechti3ad62fb2015-08-29 21:53:32 +020060 self._socket = socket.create_connection(self.from_url(self.portstr))
Chris Liechti68340d72015-08-03 14:15:48 +020061 except Exception as msg:
cliechtiab90e072009-08-06 01:44:34 +000062 self._socket = None
63 raise SerialException("Could not open port %s: %s" % (self.portstr, msg))
64
Chris Liechti033f17c2015-08-30 21:28:04 +020065 self._socket.settimeout(POLL_TIMEOUT) # used for write timeout support :/
cliechtiab90e072009-08-06 01:44:34 +000066
67 # not that there anything to configure...
Chris Liechti3ad62fb2015-08-29 21:53:32 +020068 self._reconfigure_port()
cliechtiab90e072009-08-06 01:44:34 +000069 # all things set up get, now a clean start
Chris Liechti3ad62fb2015-08-29 21:53:32 +020070 self.is_open = True
71 if not self._dsrdtr:
Chris Liechtief1fe252015-08-27 23:25:21 +020072 self._update_dtr_state()
cliechtiab90e072009-08-06 01:44:34 +000073 if not self._rtscts:
Chris Liechtief1fe252015-08-27 23:25:21 +020074 self._update_rts_state()
75 self.reset_input_buffer()
76 self.reset_output_buffer()
cliechtiab90e072009-08-06 01:44:34 +000077
Chris Liechti3ad62fb2015-08-29 21:53:32 +020078 def _reconfigure_port(self):
cliechti7d448562014-08-03 21:57:45 +000079 """\
80 Set communication parameters on opened port. For the socket://
81 protocol all settings are ignored!
82 """
cliechtiab90e072009-08-06 01:44:34 +000083 if self._socket is None:
84 raise SerialException("Can only operate on open ports")
cliechti6a300772009-08-12 02:28:56 +000085 if self.logger:
86 self.logger.info('ignored port configuration change')
cliechtiab90e072009-08-06 01:44:34 +000087
88 def close(self):
89 """Close port"""
Chris Liechti3ad62fb2015-08-29 21:53:32 +020090 if self.is_open:
cliechtiab90e072009-08-06 01:44:34 +000091 if self._socket:
92 try:
93 self._socket.shutdown(socket.SHUT_RDWR)
94 self._socket.close()
95 except:
96 # ignore errors.
97 pass
98 self._socket = None
Chris Liechti3ad62fb2015-08-29 21:53:32 +020099 self.is_open = False
cliechtiab90e072009-08-06 01:44:34 +0000100 # in case of quick reconnects, give the server some time
101 time.sleep(0.3)
102
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200103 def from_url(self, url):
cliechtiab90e072009-08-06 01:44:34 +0000104 """extract host and port from an URL string"""
Chris Liechtia4222112015-08-07 01:03:12 +0200105 parts = urlparse.urlsplit(url)
Chris Liechtid14b1ab2015-08-21 00:28:53 +0200106 if parts.scheme != "socket":
107 raise SerialException('expected a string in the form "socket://<host>:<port>[?logging={debug|info|warning|error}]": not starting with socket:// (%r)' % (parts.scheme,))
cliechtiab90e072009-08-06 01:44:34 +0000108 try:
Chris Liechtia4222112015-08-07 01:03:12 +0200109 # process options now, directly altering self
Chris Liechtid14b1ab2015-08-21 00:28:53 +0200110 for option, values in urlparse.parse_qs(parts.query, True).items():
111 if option == 'logging':
Chris Liechtia4222112015-08-07 01:03:12 +0200112 logging.basicConfig() # XXX is that good to call it here?
113 self.logger = logging.getLogger('pySerial.socket')
Chris Liechtid14b1ab2015-08-21 00:28:53 +0200114 self.logger.setLevel(LOGGER_LEVELS[values[0]])
Chris Liechtia4222112015-08-07 01:03:12 +0200115 self.logger.debug('enabled logging')
116 else:
117 raise ValueError('unknown option: %r' % (option,))
cliechtiab90e072009-08-06 01:44:34 +0000118 # get host and port
Chris Liechtia4222112015-08-07 01:03:12 +0200119 host, port = parts.hostname, parts.port
Chris Liechti033f17c2015-08-30 21:28:04 +0200120 if not 0 <= port < 65536:
121 raise ValueError("port not in range 0...65535")
Chris Liechti68340d72015-08-03 14:15:48 +0200122 except ValueError as e:
Chris Liechtid14b1ab2015-08-21 00:28:53 +0200123 raise SerialException('expected a string in the form "socket://<host>:<port>[?logging={debug|info|warning|error}]": %s' % e)
cliechtiab90e072009-08-06 01:44:34 +0000124 return (host, port)
125
126 # - - - - - - - - - - - - - - - - - - - - - - - -
127
Chris Liechtief1fe252015-08-27 23:25:21 +0200128 @property
129 def in_waiting(self):
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200130 """Return the number of bytes currently in the input buffer."""
Chris Liechti033f17c2015-08-30 21:28:04 +0200131 if not self.is_open:
132 raise portNotOpenError
cliechti77e088a2014-08-04 10:29:24 +0000133 # 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)
cliechtiab90e072009-08-06 01:44:34 +0000137
138 def read(self, size=1):
cliechti7d448562014-08-03 21:57:45 +0000139 """\
140 Read size bytes from the serial port. If a timeout is set it may
cliechtiab90e072009-08-06 01:44:34 +0000141 return less characters as requested. With no timeout it will block
cliechti7d448562014-08-03 21:57:45 +0000142 until the requested number of bytes is read.
143 """
Chris Liechti033f17c2015-08-30 21:28:04 +0200144 if not self.is_open:
145 raise portNotOpenError
cliechtiab90e072009-08-06 01:44:34 +0000146 data = bytearray()
cliechti20e1fae2013-05-31 01:33:12 +0000147 if self._timeout is not None:
148 timeout = time.time() + self._timeout
149 else:
150 timeout = None
Chris Liechti069d32a2015-08-05 03:21:38 +0200151 while len(data) < size:
cliechtiab90e072009-08-06 01:44:34 +0000152 try:
153 # an implementation with internal buffer would be better
154 # performing...
cliechtifee4e962013-05-31 00:55:43 +0000155 block = self._socket.recv(size - len(data))
156 if block:
cliechti5d66a952013-10-11 02:27:30 +0000157 data.extend(block)
158 else:
159 # no data -> EOF (connection probably closed)
160 break
cliechtiab90e072009-08-06 01:44:34 +0000161 except socket.timeout:
cliechti5d66a952013-10-11 02:27:30 +0000162 # just need to get out of recv from time to time to check if
Chris Liechti2880f0e2015-08-17 03:19:46 +0200163 # still alive and timeout did not expire
164 pass
Chris Liechti68340d72015-08-03 14:15:48 +0200165 except socket.error as e:
cliechtiab90e072009-08-06 01:44:34 +0000166 # connection fails -> terminate loop
167 raise SerialException('connection failed (%s)' % e)
Chris Liechti069d32a2015-08-05 03:21:38 +0200168 if timeout is not None and time.time() > timeout:
169 break
cliechtiab90e072009-08-06 01:44:34 +0000170 return bytes(data)
171
172 def write(self, data):
cliechti7d448562014-08-03 21:57:45 +0000173 """\
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200174 Output the given byte string over the serial port. Can block if the
cliechtiab90e072009-08-06 01:44:34 +0000175 connection is blocked. May raise SerialException if the connection is
cliechti7d448562014-08-03 21:57:45 +0000176 closed.
177 """
Chris Liechti033f17c2015-08-30 21:28:04 +0200178 if not self.is_open:
179 raise portNotOpenError
cliechtiab90e072009-08-06 01:44:34 +0000180 try:
cliechti38077122013-10-16 02:57:27 +0000181 self._socket.sendall(to_bytes(data))
Chris Liechti68340d72015-08-03 14:15:48 +0200182 except socket.error as e:
cliechti5d66a952013-10-11 02:27:30 +0000183 # XXX what exception if socket connection fails
184 raise SerialException("socket connection failed: %s" % e)
cliechtiab90e072009-08-06 01:44:34 +0000185 return len(data)
186
Chris Liechtief1fe252015-08-27 23:25:21 +0200187 def reset_input_buffer(self):
cliechtiab90e072009-08-06 01:44:34 +0000188 """Clear input buffer, discarding all that is in the buffer."""
Chris Liechti033f17c2015-08-30 21:28:04 +0200189 if not self.is_open:
190 raise portNotOpenError
cliechti6a300772009-08-12 02:28:56 +0000191 if self.logger:
Chris Liechtief1fe252015-08-27 23:25:21 +0200192 self.logger.info('ignored reset_input_buffer')
cliechtiab90e072009-08-06 01:44:34 +0000193
Chris Liechtief1fe252015-08-27 23:25:21 +0200194 def reset_output_buffer(self):
cliechti7d448562014-08-03 21:57:45 +0000195 """\
196 Clear output buffer, aborting the current output and
197 discarding all that is in the buffer.
198 """
Chris Liechti033f17c2015-08-30 21:28:04 +0200199 if not self.is_open:
200 raise portNotOpenError
cliechti6a300772009-08-12 02:28:56 +0000201 if self.logger:
Chris Liechtief1fe252015-08-27 23:25:21 +0200202 self.logger.info('ignored reset_output_buffer')
cliechtiab90e072009-08-06 01:44:34 +0000203
Chris Liechtief1fe252015-08-27 23:25:21 +0200204 def send_break(self, duration=0.25):
cliechti7d448562014-08-03 21:57:45 +0000205 """\
206 Send break condition. Timed, returns to idle state after given
207 duration.
208 """
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 send_break(%r)' % (duration,))
cliechtiab90e072009-08-06 01:44:34 +0000213
Chris Liechtief1fe252015-08-27 23:25:21 +0200214 def _update_break_state(self):
cliechtiab90e072009-08-06 01:44:34 +0000215 """Set break: Controls TXD. When active, to transmitting is
216 possible."""
cliechti6a300772009-08-12 02:28:56 +0000217 if self.logger:
Chris Liechtief1fe252015-08-27 23:25:21 +0200218 self.logger.info('ignored _update_break_state(%r)' % (self._break_state,))
cliechtiab90e072009-08-06 01:44:34 +0000219
Chris Liechtief1fe252015-08-27 23:25:21 +0200220 def _update_rts_state(self):
cliechtiab90e072009-08-06 01:44:34 +0000221 """Set terminal status line: Request To Send"""
cliechti6a300772009-08-12 02:28:56 +0000222 if self.logger:
Chris Liechtief1fe252015-08-27 23:25:21 +0200223 self.logger.info('ignored _update_rts_state(%r)' % (self._rts_state,))
cliechtiab90e072009-08-06 01:44:34 +0000224
Chris Liechtief1fe252015-08-27 23:25:21 +0200225 def _update_dtr_state(self):
cliechtiab90e072009-08-06 01:44:34 +0000226 """Set terminal status line: Data Terminal Ready"""
cliechti6a300772009-08-12 02:28:56 +0000227 if self.logger:
Chris Liechtief1fe252015-08-27 23:25:21 +0200228 self.logger.info('ignored _update_dtr_state(%r)' % (self._dtr_state,))
cliechtiab90e072009-08-06 01:44:34 +0000229
Chris Liechtief1fe252015-08-27 23:25:21 +0200230 @property
231 def cts(self):
cliechtiab90e072009-08-06 01:44:34 +0000232 """Read terminal status line: Clear To Send"""
Chris Liechti033f17c2015-08-30 21:28:04 +0200233 if not self.is_open:
234 raise portNotOpenError
cliechti6a300772009-08-12 02:28:56 +0000235 if self.logger:
Chris Liechtief1fe252015-08-27 23:25:21 +0200236 self.logger.info('returning dummy for cts')
cliechtiab90e072009-08-06 01:44:34 +0000237 return True
238
Chris Liechtief1fe252015-08-27 23:25:21 +0200239 @property
240 def dsr(self):
cliechtiab90e072009-08-06 01:44:34 +0000241 """Read terminal status line: Data Set Ready"""
Chris Liechti033f17c2015-08-30 21:28:04 +0200242 if not self.is_open:
243 raise portNotOpenError
cliechti6a300772009-08-12 02:28:56 +0000244 if self.logger:
Chris Liechtief1fe252015-08-27 23:25:21 +0200245 self.logger.info('returning dummy for dsr')
cliechtiab90e072009-08-06 01:44:34 +0000246 return True
247
Chris Liechtief1fe252015-08-27 23:25:21 +0200248 @property
249 def ri(self):
cliechtiab90e072009-08-06 01:44:34 +0000250 """Read terminal status line: Ring Indicator"""
Chris Liechti033f17c2015-08-30 21:28:04 +0200251 if not self.is_open:
252 raise portNotOpenError
cliechti6a300772009-08-12 02:28:56 +0000253 if self.logger:
Chris Liechtief1fe252015-08-27 23:25:21 +0200254 self.logger.info('returning dummy for ri')
cliechtiab90e072009-08-06 01:44:34 +0000255 return False
256
Chris Liechtief1fe252015-08-27 23:25:21 +0200257 @property
258 def cd(self):
cliechtiab90e072009-08-06 01:44:34 +0000259 """Read terminal status line: Carrier Detect"""
Chris Liechti033f17c2015-08-30 21:28:04 +0200260 if not self.is_open:
261 raise portNotOpenError
cliechti6a300772009-08-12 02:28:56 +0000262 if self.logger:
Chris Liechtief1fe252015-08-27 23:25:21 +0200263 self.logger.info('returning dummy for cd)')
cliechtiab90e072009-08-06 01:44:34 +0000264 return True
265
266 # - - - platform specific - - -
cliechtib869edb2014-07-31 22:13:19 +0000267
268 # works on Linux and probably all the other POSIX systems
269 def fileno(self):
270 """Get the file handle of the underlying socket for use with select"""
271 return self._socket.fileno()
cliechtiab90e072009-08-06 01:44:34 +0000272
273
Chris Liechtief6b7b42015-08-06 22:19:26 +0200274#
cliechtiab90e072009-08-06 01:44:34 +0000275# simple client test
276if __name__ == '__main__':
277 import sys
278 s = Serial('socket://localhost:7000')
279 sys.stdout.write('%s\n' % s)
280
281 sys.stdout.write("write...\n")
Chris Liechtifbdd8a02015-08-09 02:37:45 +0200282 s.write(b"hello\n")
cliechtiab90e072009-08-06 01:44:34 +0000283 s.flush()
284 sys.stdout.write("read: %s\n" % s.read(5))
285
286 s.close()