blob: 8ac8ddf15697b9ad5d2f8c199e4b84c5831ca73e [file] [log] [blame]
cliechti41973a92009-08-06 02:18:21 +00001#! python
2#
cliechti41973a92009-08-06 02:18:21 +00003# This module implements a loop back connection receiving itself what it sent.
4#
5# The purpose of this module is.. well... You can run the unit tests with it.
6# and it was so easy to implement ;-)
7#
Chris Liechti3e02f702015-12-16 23:06:04 +01008# This file is part of pySerial. https://github.com/pyserial/pyserial
Chris Liechtic4bca9e2015-08-07 14:40:41 +02009# (C) 2001-2015 Chris Liechti <cliechti@gmx.net>
Chris Liechtifbdd8a02015-08-09 02:37:45 +020010#
11# SPDX-License-Identifier: BSD-3-Clause
cliechti41973a92009-08-06 02:18:21 +000012#
13# URL format: loop://[option[/option...]]
14# options:
15# - "debug" print diagnostic messages
Kurt McKee057387c2018-02-07 22:10:38 -060016from __future__ import absolute_import
17
Chris Liechtic4bca9e2015-08-07 14:40:41 +020018import logging
19import numbers
cliechti41973a92009-08-06 02:18:21 +000020import time
Chris Liechtic4bca9e2015-08-07 14:40:41 +020021try:
22 import urlparse
23except ImportError:
24 import urllib.parse as urlparse
Chris Liechtia469cde2015-08-11 23:05:24 +020025try:
26 import queue
27except ImportError:
28 import Queue as queue
Chris Liechtic4bca9e2015-08-07 14:40:41 +020029
Chris Liechtie99bda32020-09-14 03:59:52 +020030from serial.serialutil import SerialBase, SerialException, to_bytes, iterbytes, SerialTimeoutException, PortNotOpenError
cliechtic64ba692009-08-12 00:32:47 +000031
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
cliechti41973a92009-08-06 02:18:21 +000040
Chris Liechtief6b7b42015-08-06 22:19:26 +020041class Serial(SerialBase):
cliechtiab3d4282011-08-19 01:52:46 +000042 """Serial port implementation that simulates a loop back connection in plain software."""
cliechti41973a92009-08-06 02:18:21 +000043
44 BAUDRATES = (50, 75, 110, 134, 150, 200, 300, 600, 1200, 1800, 2400, 4800,
45 9600, 19200, 38400, 57600, 115200)
46
Chris Liechtia469cde2015-08-11 23:05:24 +020047 def __init__(self, *args, **kwargs):
Chris Liechtia469cde2015-08-11 23:05:24 +020048 self.buffer_size = 4096
Chris Liechti7806fc02015-12-10 21:15:20 +010049 self.queue = None
50 self.logger = None
Chris Liechtid6112a02016-10-04 20:27:21 +020051 self._cancel_write = False
Chris Liechti1d157152016-08-04 20:47:00 +020052 super(Serial, self).__init__(*args, **kwargs)
Chris Liechtia469cde2015-08-11 23:05:24 +020053
cliechti41973a92009-08-06 02:18:21 +000054 def open(self):
cliechti7d448562014-08-03 21:57:45 +000055 """\
56 Open port with current settings. This may throw a SerialException
57 if the port cannot be opened.
58 """
Chris Liechti3ad62fb2015-08-29 21:53:32 +020059 if self.is_open:
cliechti8f69e702011-03-19 00:22:32 +000060 raise SerialException("Port is already open.")
cliechti6a300772009-08-12 02:28:56 +000061 self.logger = None
Chris Liechtia469cde2015-08-11 23:05:24 +020062 self.queue = queue.Queue(self.buffer_size)
cliechti41973a92009-08-06 02:18:21 +000063
64 if self._port is None:
65 raise SerialException("Port must be configured before it can be used.")
66 # not that there is anything to open, but the function applies the
67 # options found in the URL
Chris Liechti3ad62fb2015-08-29 21:53:32 +020068 self.from_url(self.port)
cliechti41973a92009-08-06 02:18:21 +000069
70 # not that there anything to configure...
Chris Liechti3ad62fb2015-08-29 21:53:32 +020071 self._reconfigure_port()
cliechti41973a92009-08-06 02:18:21 +000072 # all things set up get, now a clean start
Chris Liechti3ad62fb2015-08-29 21:53:32 +020073 self.is_open = True
74 if not self._dsrdtr:
Chris Liechtief1fe252015-08-27 23:25:21 +020075 self._update_dtr_state()
cliechti41973a92009-08-06 02:18:21 +000076 if not self._rtscts:
Chris Liechtief1fe252015-08-27 23:25:21 +020077 self._update_rts_state()
78 self.reset_input_buffer()
79 self.reset_output_buffer()
cliechti41973a92009-08-06 02:18:21 +000080
Chris Liechtia469cde2015-08-11 23:05:24 +020081 def close(self):
Chris Liechti7806fc02015-12-10 21:15:20 +010082 if self.is_open:
83 self.is_open = False
84 try:
85 self.queue.put_nowait(None)
86 except queue.Full:
87 pass
Chris Liechtia469cde2015-08-11 23:05:24 +020088 super(Serial, self).close()
89
Chris Liechti3ad62fb2015-08-29 21:53:32 +020090 def _reconfigure_port(self):
cliechti7d448562014-08-03 21:57:45 +000091 """\
92 Set communication parameters on opened port. For the loop://
93 protocol all settings are ignored!
94 """
cliechti41973a92009-08-06 02:18:21 +000095 # not that's it of any real use, but it helps in the unit tests
Chris Liechti92df95a2016-02-09 23:30:37 +010096 if not isinstance(self._baudrate, numbers.Integral) or not 0 < self._baudrate < 2 ** 32:
Chris Liechtic8f3f822016-06-08 03:35:28 +020097 raise ValueError("invalid baudrate: {!r}".format(self._baudrate))
cliechti6a300772009-08-12 02:28:56 +000098 if self.logger:
Chris Liechti3ad62fb2015-08-29 21:53:32 +020099 self.logger.info('_reconfigure_port()')
cliechti41973a92009-08-06 02:18:21 +0000100
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200101 def from_url(self, url):
cliechti41973a92009-08-06 02:18:21 +0000102 """extract host and port from an URL string"""
Chris Liechtic4bca9e2015-08-07 14:40:41 +0200103 parts = urlparse.urlsplit(url)
Chris Liechtid14b1ab2015-08-21 00:28:53 +0200104 if parts.scheme != "loop":
Chris Liechti43b3b102016-06-07 21:31:47 +0200105 raise SerialException(
106 'expected a string in the form '
107 '"loop://[?logging={debug|info|warning|error}]": not starting '
Chris Liechtic8f3f822016-06-08 03:35:28 +0200108 'with loop:// ({!r})'.format(parts.scheme))
cliechti41973a92009-08-06 02:18:21 +0000109 try:
110 # 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':
cliechtic64ba692009-08-12 00:32:47 +0000113 logging.basicConfig() # XXX is that good to call it here?
cliechti6a300772009-08-12 02:28:56 +0000114 self.logger = logging.getLogger('pySerial.loop')
Chris Liechtid14b1ab2015-08-21 00:28:53 +0200115 self.logger.setLevel(LOGGER_LEVELS[values[0]])
cliechti6a300772009-08-12 02:28:56 +0000116 self.logger.debug('enabled logging')
cliechti41973a92009-08-06 02:18:21 +0000117 else:
Chris Liechtic8f3f822016-06-08 03:35:28 +0200118 raise ValueError('unknown option: {!r}'.format(option))
Chris Liechti68340d72015-08-03 14:15:48 +0200119 except ValueError as e:
Chris Liechti43b3b102016-06-07 21:31:47 +0200120 raise SerialException(
121 'expected a string in the form '
Chris Liechtic8f3f822016-06-08 03:35:28 +0200122 '"loop://[?logging={debug|info|warning|error}]": {}'.format(e))
cliechti41973a92009-08-06 02:18:21 +0000123
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."""
Chris Liechti033f17c2015-08-30 21:28:04 +0200129 if not self.is_open:
Chris Liechtie99bda32020-09-14 03:59:52 +0200130 raise PortNotOpenError()
cliechti6a300772009-08-12 02:28:56 +0000131 if self.logger:
cliechtic64ba692009-08-12 00:32:47 +0000132 # attention the logged value can differ from return value in
133 # threaded environments...
Chris Liechtic8f3f822016-06-08 03:35:28 +0200134 self.logger.debug('in_waiting -> {:d}'.format(self.queue.qsize()))
Chris Liechtia469cde2015-08-11 23:05:24 +0200135 return self.queue.qsize()
cliechti41973a92009-08-06 02:18:21 +0000136
137 def read(self, size=1):
cliechti7d448562014-08-03 21:57:45 +0000138 """\
139 Read size bytes from the serial port. If a timeout is set it may
cliechti41973a92009-08-06 02:18:21 +0000140 return less characters as requested. With no timeout it will block
cliechti7d448562014-08-03 21:57:45 +0000141 until the requested number of bytes is read.
142 """
Chris Liechti033f17c2015-08-30 21:28:04 +0200143 if not self.is_open:
Chris Liechtie99bda32020-09-14 03:59:52 +0200144 raise PortNotOpenError()
Chris Liechti220c3a52015-09-15 00:06:51 +0200145 if self._timeout is not None and self._timeout != 0:
cliechti41973a92009-08-06 02:18:21 +0000146 timeout = time.time() + self._timeout
147 else:
cliechti024b4f42009-08-07 18:43:05 +0000148 timeout = None
cliechti1de32cd2009-08-07 19:05:09 +0000149 data = bytearray()
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200150 while size > 0 and self.is_open:
Chris Liechtia469cde2015-08-11 23:05:24 +0200151 try:
Chris Liechti220c3a52015-09-15 00:06:51 +0200152 b = self.queue.get(timeout=self._timeout) # XXX inter char timeout
Chris Liechtia469cde2015-08-11 23:05:24 +0200153 except queue.Empty:
Chris Liechti220c3a52015-09-15 00:06:51 +0200154 if self._timeout == 0:
155 break
Chris Liechtia469cde2015-08-11 23:05:24 +0200156 else:
Chris Liechtid6112a02016-10-04 20:27:21 +0200157 if b is not None:
Chris Liechti220c3a52015-09-15 00:06:51 +0200158 data += b
159 size -= 1
160 else:
161 break
cliechti41973a92009-08-06 02:18:21 +0000162 # check for timeout now, after data has been read.
163 # useful for timeout = 0 (non blocking) read
cliechti024b4f42009-08-07 18:43:05 +0000164 if timeout and time.time() > timeout:
Chris Liechti220c3a52015-09-15 00:06:51 +0200165 if self.logger:
166 self.logger.info('read timeout')
cliechti41973a92009-08-06 02:18:21 +0000167 break
168 return bytes(data)
169
Chris Liechtid6112a02016-10-04 20:27:21 +0200170 def cancel_read(self):
171 self.queue.put_nowait(None)
172
173 def cancel_write(self):
174 self._cancel_write = True
175
cliechti41973a92009-08-06 02:18:21 +0000176 def write(self, data):
cliechti7d448562014-08-03 21:57:45 +0000177 """\
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200178 Output the given byte string over the serial port. Can block if the
cliechti41973a92009-08-06 02:18:21 +0000179 connection is blocked. May raise SerialException if the connection is
cliechti7d448562014-08-03 21:57:45 +0000180 closed.
181 """
Chris Liechtid6112a02016-10-04 20:27:21 +0200182 self._cancel_write = False
Chris Liechti033f17c2015-08-30 21:28:04 +0200183 if not self.is_open:
Chris Liechtie99bda32020-09-14 03:59:52 +0200184 raise PortNotOpenError()
cliechti38077122013-10-16 02:57:27 +0000185 data = to_bytes(data)
cliechti66957bf2009-08-06 23:25:37 +0000186 # calculate aprox time that would be used to send the data
Chris Liechti6594df62016-02-04 21:13:41 +0100187 time_used_to_send = 10.0 * len(data) / self._baudrate
cliechti66957bf2009-08-06 23:25:37 +0000188 # when a write timeout is configured check if we would be successful
189 # (not sending anything, not even the part that would have time)
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200190 if self._write_timeout is not None and time_used_to_send > self._write_timeout:
Chris Liechtid6112a02016-10-04 20:27:21 +0200191 # must wait so that unit test succeeds
192 time_left = self._write_timeout
193 while time_left > 0 and not self._cancel_write:
Chris Liechti8c05ebf2016-10-05 03:32:36 +0200194 time.sleep(min(time_left, 0.5))
195 time_left -= 0.5
Chris Liechtid6112a02016-10-04 20:27:21 +0200196 if self._cancel_write:
197 return 0 # XXX
Chris Liechtie99bda32020-09-14 03:59:52 +0200198 raise SerialTimeoutException('Write timeout')
Chris Liechtif99cd5c2015-08-13 22:54:16 +0200199 for byte in iterbytes(data):
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200200 self.queue.put(byte, timeout=self._write_timeout)
cliechti41973a92009-08-06 02:18:21 +0000201 return len(data)
202
Chris Liechtief1fe252015-08-27 23:25:21 +0200203 def reset_input_buffer(self):
cliechti41973a92009-08-06 02:18:21 +0000204 """Clear input buffer, discarding all that is in the buffer."""
Chris Liechti033f17c2015-08-30 21:28:04 +0200205 if not self.is_open:
Chris Liechtie99bda32020-09-14 03:59:52 +0200206 raise PortNotOpenError()
cliechti6a300772009-08-12 02:28:56 +0000207 if self.logger:
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200208 self.logger.info('reset_input_buffer()')
Chris Liechtia469cde2015-08-11 23:05:24 +0200209 try:
210 while self.queue.qsize():
211 self.queue.get_nowait()
212 except queue.Empty:
213 pass
cliechti41973a92009-08-06 02:18:21 +0000214
Chris Liechtief1fe252015-08-27 23:25:21 +0200215 def reset_output_buffer(self):
cliechti7d448562014-08-03 21:57:45 +0000216 """\
217 Clear output buffer, aborting the current output and
218 discarding all that is in the buffer.
219 """
Chris Liechti033f17c2015-08-30 21:28:04 +0200220 if not self.is_open:
Chris Liechtie99bda32020-09-14 03:59:52 +0200221 raise PortNotOpenError()
cliechti6a300772009-08-12 02:28:56 +0000222 if self.logger:
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200223 self.logger.info('reset_output_buffer()')
Chris Liechtia469cde2015-08-11 23:05:24 +0200224 try:
225 while self.queue.qsize():
226 self.queue.get_nowait()
227 except queue.Empty:
228 pass
cliechti41973a92009-08-06 02:18:21 +0000229
Chris Liechtic1cd16e2020-09-14 22:53:50 +0200230 @property
231 def out_waiting(self):
232 """Return how many bytes the in the outgoing buffer"""
233 if not self.is_open:
234 raise PortNotOpenError()
235 if self.logger:
236 # attention the logged value can differ from return value in
237 # threaded environments...
238 self.logger.debug('out_waiting -> {:d}'.format(self.queue.qsize()))
239 return self.queue.qsize()
240
Chris Liechtief1fe252015-08-27 23:25:21 +0200241 def _update_break_state(self):
cliechti7d448562014-08-03 21:57:45 +0000242 """\
243 Set break: Controls TXD. When active, to transmitting is
244 possible.
245 """
cliechti6a300772009-08-12 02:28:56 +0000246 if self.logger:
Chris Liechtic8f3f822016-06-08 03:35:28 +0200247 self.logger.info('_update_break_state({!r})'.format(self._break_state))
cliechti41973a92009-08-06 02:18:21 +0000248
Chris Liechtief1fe252015-08-27 23:25:21 +0200249 def _update_rts_state(self):
cliechti41973a92009-08-06 02:18:21 +0000250 """Set terminal status line: Request To Send"""
cliechti6a300772009-08-12 02:28:56 +0000251 if self.logger:
Chris Liechtic8f3f822016-06-08 03:35:28 +0200252 self.logger.info('_update_rts_state({!r}) -> state of CTS'.format(self._rts_state))
cliechti41973a92009-08-06 02:18:21 +0000253
Chris Liechtief1fe252015-08-27 23:25:21 +0200254 def _update_dtr_state(self):
cliechti41973a92009-08-06 02:18:21 +0000255 """Set terminal status line: Data Terminal Ready"""
cliechti6a300772009-08-12 02:28:56 +0000256 if self.logger:
Chris Liechtic8f3f822016-06-08 03:35:28 +0200257 self.logger.info('_update_dtr_state({!r}) -> state of DSR'.format(self._dtr_state))
cliechti41973a92009-08-06 02:18:21 +0000258
Chris Liechtief1fe252015-08-27 23:25:21 +0200259 @property
260 def cts(self):
cliechti41973a92009-08-06 02:18:21 +0000261 """Read terminal status line: Clear To Send"""
Chris Liechti033f17c2015-08-30 21:28:04 +0200262 if not self.is_open:
Chris Liechtie99bda32020-09-14 03:59:52 +0200263 raise PortNotOpenError()
cliechti6a300772009-08-12 02:28:56 +0000264 if self.logger:
Chris Liechtic8f3f822016-06-08 03:35:28 +0200265 self.logger.info('CTS -> state of RTS ({!r})'.format(self._rts_state))
Chris Liechtief1fe252015-08-27 23:25:21 +0200266 return self._rts_state
cliechti41973a92009-08-06 02:18:21 +0000267
Chris Liechtief1fe252015-08-27 23:25:21 +0200268 @property
269 def dsr(self):
cliechti41973a92009-08-06 02:18:21 +0000270 """Read terminal status line: Data Set Ready"""
cliechti6a300772009-08-12 02:28:56 +0000271 if self.logger:
Chris Liechtic8f3f822016-06-08 03:35:28 +0200272 self.logger.info('DSR -> state of DTR ({!r})'.format(self._dtr_state))
Chris Liechtief1fe252015-08-27 23:25:21 +0200273 return self._dtr_state
cliechti41973a92009-08-06 02:18:21 +0000274
Chris Liechtief1fe252015-08-27 23:25:21 +0200275 @property
276 def ri(self):
cliechti41973a92009-08-06 02:18:21 +0000277 """Read terminal status line: Ring Indicator"""
Chris Liechti033f17c2015-08-30 21:28:04 +0200278 if not self.is_open:
Chris Liechtie99bda32020-09-14 03:59:52 +0200279 raise PortNotOpenError()
cliechti6a300772009-08-12 02:28:56 +0000280 if self.logger:
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200281 self.logger.info('returning dummy for RI')
cliechti41973a92009-08-06 02:18:21 +0000282 return False
283
Chris Liechtief1fe252015-08-27 23:25:21 +0200284 @property
285 def cd(self):
cliechti41973a92009-08-06 02:18:21 +0000286 """Read terminal status line: Carrier Detect"""
Chris Liechti033f17c2015-08-30 21:28:04 +0200287 if not self.is_open:
Chris Liechtie99bda32020-09-14 03:59:52 +0200288 raise PortNotOpenError()
cliechti6a300772009-08-12 02:28:56 +0000289 if self.logger:
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200290 self.logger.info('returning dummy for CD')
cliechti41973a92009-08-06 02:18:21 +0000291 return True
292
293 # - - - platform specific - - -
294 # None so far
295
296
cliechti41973a92009-08-06 02:18:21 +0000297# simple client test
298if __name__ == '__main__':
299 import sys
cliechtiab3d4282011-08-19 01:52:46 +0000300 s = Serial('loop://')
Chris Liechtic8f3f822016-06-08 03:35:28 +0200301 sys.stdout.write('{}\n'.format(s))
cliechti41973a92009-08-06 02:18:21 +0000302
303 sys.stdout.write("write...\n")
304 s.write("hello\n")
305 s.flush()
Chris Liechtic8f3f822016-06-08 03:35:28 +0200306 sys.stdout.write("read: {!r}\n".format(s.read(5)))
cliechti41973a92009-08-06 02:18:21 +0000307
308 s.close()