blob: 99e532fd417c2c98f24d2d51c5b98b786abbc89c [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 Liechtifbdd8a02015-08-09 02:37:45 +020030from serial.serialutil import *
31
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 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 Liechti3ad62fb2015-08-29 21:53:32 +020059 self._socket = socket.create_connection(self.from_url(self.portstr))
Chris Liechti68340d72015-08-03 14:15:48 +020060 except Exception as msg:
cliechtiab90e072009-08-06 01:44:34 +000061 self._socket = None
62 raise SerialException("Could not open port %s: %s" % (self.portstr, msg))
63
cliechti5d66a952013-10-11 02:27:30 +000064 self._socket.settimeout(POLL_TIMEOUT) # used for write timeout support :/
cliechtiab90e072009-08-06 01:44:34 +000065
66 # not that there anything to configure...
Chris Liechti3ad62fb2015-08-29 21:53:32 +020067 self._reconfigure_port()
cliechtiab90e072009-08-06 01:44:34 +000068 # all things set up get, now a clean start
Chris Liechti3ad62fb2015-08-29 21:53:32 +020069 self.is_open = True
70 if not self._dsrdtr:
Chris Liechtief1fe252015-08-27 23:25:21 +020071 self._update_dtr_state()
cliechtiab90e072009-08-06 01:44:34 +000072 if not self._rtscts:
Chris Liechtief1fe252015-08-27 23:25:21 +020073 self._update_rts_state()
74 self.reset_input_buffer()
75 self.reset_output_buffer()
cliechtiab90e072009-08-06 01:44:34 +000076
Chris Liechti3ad62fb2015-08-29 21:53:32 +020077 def _reconfigure_port(self):
cliechti7d448562014-08-03 21:57:45 +000078 """\
79 Set communication parameters on opened port. For the socket://
80 protocol all settings are ignored!
81 """
cliechtiab90e072009-08-06 01:44:34 +000082 if self._socket is None:
83 raise SerialException("Can only operate on open ports")
cliechti6a300772009-08-12 02:28:56 +000084 if self.logger:
85 self.logger.info('ignored port configuration change')
cliechtiab90e072009-08-06 01:44:34 +000086
87 def close(self):
88 """Close port"""
Chris Liechti3ad62fb2015-08-29 21:53:32 +020089 if self.is_open:
cliechtiab90e072009-08-06 01:44:34 +000090 if self._socket:
91 try:
92 self._socket.shutdown(socket.SHUT_RDWR)
93 self._socket.close()
94 except:
95 # ignore errors.
96 pass
97 self._socket = None
Chris Liechti3ad62fb2015-08-29 21:53:32 +020098 self.is_open = False
cliechtiab90e072009-08-06 01:44:34 +000099 # in case of quick reconnects, give the server some time
100 time.sleep(0.3)
101
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200102 def from_url(self, url):
cliechtiab90e072009-08-06 01:44:34 +0000103 """extract host and port from an URL string"""
Chris Liechtia4222112015-08-07 01:03:12 +0200104 parts = urlparse.urlsplit(url)
Chris Liechtid14b1ab2015-08-21 00:28:53 +0200105 if parts.scheme != "socket":
106 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 +0000107 try:
Chris Liechtia4222112015-08-07 01:03:12 +0200108 # process options now, directly altering self
Chris Liechtid14b1ab2015-08-21 00:28:53 +0200109 for option, values in urlparse.parse_qs(parts.query, True).items():
110 if option == 'logging':
Chris Liechtia4222112015-08-07 01:03:12 +0200111 logging.basicConfig() # XXX is that good to call it here?
112 self.logger = logging.getLogger('pySerial.socket')
Chris Liechtid14b1ab2015-08-21 00:28:53 +0200113 self.logger.setLevel(LOGGER_LEVELS[values[0]])
Chris Liechtia4222112015-08-07 01:03:12 +0200114 self.logger.debug('enabled logging')
115 else:
116 raise ValueError('unknown option: %r' % (option,))
cliechtiab90e072009-08-06 01:44:34 +0000117 # get host and port
Chris Liechtia4222112015-08-07 01:03:12 +0200118 host, port = parts.hostname, parts.port
cliechtiab90e072009-08-06 01:44:34 +0000119 if not 0 <= port < 65536: raise ValueError("port not in range 0...65535")
Chris Liechti68340d72015-08-03 14:15:48 +0200120 except ValueError as e:
Chris Liechtid14b1ab2015-08-21 00:28:53 +0200121 raise SerialException('expected a string in the form "socket://<host>:<port>[?logging={debug|info|warning|error}]": %s' % e)
cliechtiab90e072009-08-06 01:44:34 +0000122 return (host, port)
123
124 # - - - - - - - - - - - - - - - - - - - - - - - -
125
Chris Liechtief1fe252015-08-27 23:25:21 +0200126 @property
127 def in_waiting(self):
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200128 """Return the number of bytes currently in the input buffer."""
129 if not self.is_open: raise portNotOpenError
cliechti77e088a2014-08-04 10:29:24 +0000130 # Poll the socket to see if it is ready for reading.
131 # If ready, at least one byte will be to read.
132 lr, lw, lx = select.select([self._socket], [], [], 0)
133 return len(lr)
cliechtiab90e072009-08-06 01:44:34 +0000134
135 def read(self, size=1):
cliechti7d448562014-08-03 21:57:45 +0000136 """\
137 Read size bytes from the serial port. If a timeout is set it may
cliechtiab90e072009-08-06 01:44:34 +0000138 return less characters as requested. With no timeout it will block
cliechti7d448562014-08-03 21:57:45 +0000139 until the requested number of bytes is read.
140 """
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200141 if not self.is_open: raise portNotOpenError
cliechtiab90e072009-08-06 01:44:34 +0000142 data = bytearray()
cliechti20e1fae2013-05-31 01:33:12 +0000143 if self._timeout is not None:
144 timeout = time.time() + self._timeout
145 else:
146 timeout = None
Chris Liechti069d32a2015-08-05 03:21:38 +0200147 while len(data) < size:
cliechtiab90e072009-08-06 01:44:34 +0000148 try:
149 # an implementation with internal buffer would be better
150 # performing...
cliechtifee4e962013-05-31 00:55:43 +0000151 block = self._socket.recv(size - len(data))
152 if block:
cliechti5d66a952013-10-11 02:27:30 +0000153 data.extend(block)
154 else:
155 # no data -> EOF (connection probably closed)
156 break
cliechtiab90e072009-08-06 01:44:34 +0000157 except socket.timeout:
cliechti5d66a952013-10-11 02:27:30 +0000158 # just need to get out of recv from time to time to check if
Chris Liechti2880f0e2015-08-17 03:19:46 +0200159 # still alive and timeout did not expire
160 pass
Chris Liechti68340d72015-08-03 14:15:48 +0200161 except socket.error as e:
cliechtiab90e072009-08-06 01:44:34 +0000162 # connection fails -> terminate loop
163 raise SerialException('connection failed (%s)' % e)
Chris Liechti069d32a2015-08-05 03:21:38 +0200164 if timeout is not None and time.time() > timeout:
165 break
cliechtiab90e072009-08-06 01:44:34 +0000166 return bytes(data)
167
168 def write(self, data):
cliechti7d448562014-08-03 21:57:45 +0000169 """\
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200170 Output the given byte string over the serial port. Can block if the
cliechtiab90e072009-08-06 01:44:34 +0000171 connection is blocked. May raise SerialException if the connection is
cliechti7d448562014-08-03 21:57:45 +0000172 closed.
173 """
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200174 if not self.is_open: raise portNotOpenError
cliechtiab90e072009-08-06 01:44:34 +0000175 try:
cliechti38077122013-10-16 02:57:27 +0000176 self._socket.sendall(to_bytes(data))
Chris Liechti68340d72015-08-03 14:15:48 +0200177 except socket.error as e:
cliechti5d66a952013-10-11 02:27:30 +0000178 # XXX what exception if socket connection fails
179 raise SerialException("socket connection failed: %s" % e)
cliechtiab90e072009-08-06 01:44:34 +0000180 return len(data)
181
Chris Liechtief1fe252015-08-27 23:25:21 +0200182 def reset_input_buffer(self):
cliechtiab90e072009-08-06 01:44:34 +0000183 """Clear input buffer, discarding all that is in the buffer."""
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200184 if not self.is_open: raise portNotOpenError
cliechti6a300772009-08-12 02:28:56 +0000185 if self.logger:
Chris Liechtief1fe252015-08-27 23:25:21 +0200186 self.logger.info('ignored reset_input_buffer')
cliechtiab90e072009-08-06 01:44:34 +0000187
Chris Liechtief1fe252015-08-27 23:25:21 +0200188 def reset_output_buffer(self):
cliechti7d448562014-08-03 21:57:45 +0000189 """\
190 Clear output buffer, aborting the current output and
191 discarding all that is in the buffer.
192 """
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200193 if not self.is_open: raise portNotOpenError
cliechti6a300772009-08-12 02:28:56 +0000194 if self.logger:
Chris Liechtief1fe252015-08-27 23:25:21 +0200195 self.logger.info('ignored reset_output_buffer')
cliechtiab90e072009-08-06 01:44:34 +0000196
Chris Liechtief1fe252015-08-27 23:25:21 +0200197 def send_break(self, duration=0.25):
cliechti7d448562014-08-03 21:57:45 +0000198 """\
199 Send break condition. Timed, returns to idle state after given
200 duration.
201 """
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200202 if not self.is_open: raise portNotOpenError
cliechti6a300772009-08-12 02:28:56 +0000203 if self.logger:
Chris Liechtief1fe252015-08-27 23:25:21 +0200204 self.logger.info('ignored send_break(%r)' % (duration,))
cliechtiab90e072009-08-06 01:44:34 +0000205
Chris Liechtief1fe252015-08-27 23:25:21 +0200206 def _update_break_state(self):
cliechtiab90e072009-08-06 01:44:34 +0000207 """Set break: Controls TXD. When active, to transmitting is
208 possible."""
cliechti6a300772009-08-12 02:28:56 +0000209 if self.logger:
Chris Liechtief1fe252015-08-27 23:25:21 +0200210 self.logger.info('ignored _update_break_state(%r)' % (self._break_state,))
cliechtiab90e072009-08-06 01:44:34 +0000211
Chris Liechtief1fe252015-08-27 23:25:21 +0200212 def _update_rts_state(self):
cliechtiab90e072009-08-06 01:44:34 +0000213 """Set terminal status line: Request To Send"""
cliechti6a300772009-08-12 02:28:56 +0000214 if self.logger:
Chris Liechtief1fe252015-08-27 23:25:21 +0200215 self.logger.info('ignored _update_rts_state(%r)' % (self._rts_state,))
cliechtiab90e072009-08-06 01:44:34 +0000216
Chris Liechtief1fe252015-08-27 23:25:21 +0200217 def _update_dtr_state(self):
cliechtiab90e072009-08-06 01:44:34 +0000218 """Set terminal status line: Data Terminal Ready"""
cliechti6a300772009-08-12 02:28:56 +0000219 if self.logger:
Chris Liechtief1fe252015-08-27 23:25:21 +0200220 self.logger.info('ignored _update_dtr_state(%r)' % (self._dtr_state,))
cliechtiab90e072009-08-06 01:44:34 +0000221
Chris Liechtief1fe252015-08-27 23:25:21 +0200222 @property
223 def cts(self):
cliechtiab90e072009-08-06 01:44:34 +0000224 """Read terminal status line: Clear To Send"""
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200225 if not self.is_open: raise portNotOpenError
cliechti6a300772009-08-12 02:28:56 +0000226 if self.logger:
Chris Liechtief1fe252015-08-27 23:25:21 +0200227 self.logger.info('returning dummy for cts')
cliechtiab90e072009-08-06 01:44:34 +0000228 return True
229
Chris Liechtief1fe252015-08-27 23:25:21 +0200230 @property
231 def dsr(self):
cliechtiab90e072009-08-06 01:44:34 +0000232 """Read terminal status line: Data Set Ready"""
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200233 if not self.is_open: raise portNotOpenError
cliechti6a300772009-08-12 02:28:56 +0000234 if self.logger:
Chris Liechtief1fe252015-08-27 23:25:21 +0200235 self.logger.info('returning dummy for dsr')
cliechtiab90e072009-08-06 01:44:34 +0000236 return True
237
Chris Liechtief1fe252015-08-27 23:25:21 +0200238 @property
239 def ri(self):
cliechtiab90e072009-08-06 01:44:34 +0000240 """Read terminal status line: Ring Indicator"""
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200241 if not self.is_open: raise portNotOpenError
cliechti6a300772009-08-12 02:28:56 +0000242 if self.logger:
Chris Liechtief1fe252015-08-27 23:25:21 +0200243 self.logger.info('returning dummy for ri')
cliechtiab90e072009-08-06 01:44:34 +0000244 return False
245
Chris Liechtief1fe252015-08-27 23:25:21 +0200246 @property
247 def cd(self):
cliechtiab90e072009-08-06 01:44:34 +0000248 """Read terminal status line: Carrier Detect"""
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200249 if not self.is_open: raise portNotOpenError
cliechti6a300772009-08-12 02:28:56 +0000250 if self.logger:
Chris Liechtief1fe252015-08-27 23:25:21 +0200251 self.logger.info('returning dummy for cd)')
cliechtiab90e072009-08-06 01:44:34 +0000252 return True
253
254 # - - - platform specific - - -
cliechtib869edb2014-07-31 22:13:19 +0000255
256 # works on Linux and probably all the other POSIX systems
257 def fileno(self):
258 """Get the file handle of the underlying socket for use with select"""
259 return self._socket.fileno()
cliechtiab90e072009-08-06 01:44:34 +0000260
261
Chris Liechtief6b7b42015-08-06 22:19:26 +0200262#
cliechtiab90e072009-08-06 01:44:34 +0000263# simple client test
264if __name__ == '__main__':
265 import sys
266 s = Serial('socket://localhost:7000')
267 sys.stdout.write('%s\n' % s)
268
269 sys.stdout.write("write...\n")
Chris Liechtifbdd8a02015-08-09 02:37:45 +0200270 s.write(b"hello\n")
cliechtiab90e072009-08-06 01:44:34 +0000271 s.flush()
272 sys.stdout.write("read: %s\n" % s.read(5))
273
274 s.close()