blob: cce9f7d8840ff492c4d23d8ad5bff333c69b5ec6 [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
Chris Liechtic4bca9e2015-08-07 14:40:41 +020016import logging
17import numbers
cliechti41973a92009-08-06 02:18:21 +000018import time
Chris Liechtic4bca9e2015-08-07 14:40:41 +020019try:
20 import urlparse
21except ImportError:
22 import urllib.parse as urlparse
Chris Liechtia469cde2015-08-11 23:05:24 +020023try:
24 import queue
25except ImportError:
26 import Queue as queue
Chris Liechtic4bca9e2015-08-07 14:40:41 +020027
Chris Liechti6ba7d6f2016-01-28 21:02:49 +010028from serial.serialutil import SerialBase, SerialException, to_bytes, iterbytes, writeTimeoutError, portNotOpenError
cliechtic64ba692009-08-12 00:32:47 +000029
Chris Liechti3ad62fb2015-08-29 21:53:32 +020030# map log level names to constants. used in from_url()
cliechtic64ba692009-08-12 00:32:47 +000031LOGGER_LEVELS = {
Chris Liechti6594df62016-02-04 21:13:41 +010032 'debug': logging.DEBUG,
33 'info': logging.INFO,
34 'warning': logging.WARNING,
35 'error': logging.ERROR,
36}
cliechtic64ba692009-08-12 00:32:47 +000037
cliechti41973a92009-08-06 02:18:21 +000038
Chris Liechtief6b7b42015-08-06 22:19:26 +020039class Serial(SerialBase):
cliechtiab3d4282011-08-19 01:52:46 +000040 """Serial port implementation that simulates a loop back connection in plain software."""
cliechti41973a92009-08-06 02:18:21 +000041
42 BAUDRATES = (50, 75, 110, 134, 150, 200, 300, 600, 1200, 1800, 2400, 4800,
43 9600, 19200, 38400, 57600, 115200)
44
Chris Liechtia469cde2015-08-11 23:05:24 +020045 def __init__(self, *args, **kwargs):
46 super(Serial, self).__init__(*args, **kwargs)
47 self.buffer_size = 4096
Chris Liechti7806fc02015-12-10 21:15:20 +010048 self.queue = None
49 self.logger = None
Chris Liechtia469cde2015-08-11 23:05:24 +020050
cliechti41973a92009-08-06 02:18:21 +000051 def open(self):
cliechti7d448562014-08-03 21:57:45 +000052 """\
53 Open port with current settings. This may throw a SerialException
54 if the port cannot be opened.
55 """
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.")
cliechti6a300772009-08-12 02:28:56 +000058 self.logger = None
Chris Liechtia469cde2015-08-11 23:05:24 +020059 self.queue = queue.Queue(self.buffer_size)
cliechti41973a92009-08-06 02:18:21 +000060
61 if self._port is None:
62 raise SerialException("Port must be configured before it can be used.")
63 # not that there is anything to open, but the function applies the
64 # options found in the URL
Chris Liechti3ad62fb2015-08-29 21:53:32 +020065 self.from_url(self.port)
cliechti41973a92009-08-06 02:18:21 +000066
67 # not that there anything to configure...
Chris Liechti3ad62fb2015-08-29 21:53:32 +020068 self._reconfigure_port()
cliechti41973a92009-08-06 02:18:21 +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()
cliechti41973a92009-08-06 02:18:21 +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()
cliechti41973a92009-08-06 02:18:21 +000077
Chris Liechtia469cde2015-08-11 23:05:24 +020078 def close(self):
Chris Liechti7806fc02015-12-10 21:15:20 +010079 if self.is_open:
80 self.is_open = False
81 try:
82 self.queue.put_nowait(None)
83 except queue.Full:
84 pass
Chris Liechtia469cde2015-08-11 23:05:24 +020085 super(Serial, self).close()
86
Chris Liechti3ad62fb2015-08-29 21:53:32 +020087 def _reconfigure_port(self):
cliechti7d448562014-08-03 21:57:45 +000088 """\
89 Set communication parameters on opened port. For the loop://
90 protocol all settings are ignored!
91 """
cliechti41973a92009-08-06 02:18:21 +000092 # not that's it of any real use, but it helps in the unit tests
Chris Liechti92df95a2016-02-09 23:30:37 +010093 if not isinstance(self._baudrate, numbers.Integral) or not 0 < self._baudrate < 2 ** 32:
cliechti41973a92009-08-06 02:18:21 +000094 raise ValueError("invalid baudrate: %r" % (self._baudrate))
cliechti6a300772009-08-12 02:28:56 +000095 if self.logger:
Chris Liechti3ad62fb2015-08-29 21:53:32 +020096 self.logger.info('_reconfigure_port()')
cliechti41973a92009-08-06 02:18:21 +000097
Chris Liechti3ad62fb2015-08-29 21:53:32 +020098 def from_url(self, url):
cliechti41973a92009-08-06 02:18:21 +000099 """extract host and port from an URL string"""
Chris Liechtic4bca9e2015-08-07 14:40:41 +0200100 parts = urlparse.urlsplit(url)
Chris Liechtid14b1ab2015-08-21 00:28:53 +0200101 if parts.scheme != "loop":
102 raise SerialException('expected a string in the form "loop://[?logging={debug|info|warning|error}]": not starting with loop:// (%r)' % (parts.scheme,))
cliechti41973a92009-08-06 02:18:21 +0000103 try:
104 # process options now, directly altering self
Chris Liechtid14b1ab2015-08-21 00:28:53 +0200105 for option, values in urlparse.parse_qs(parts.query, True).items():
106 if option == 'logging':
cliechtic64ba692009-08-12 00:32:47 +0000107 logging.basicConfig() # XXX is that good to call it here?
cliechti6a300772009-08-12 02:28:56 +0000108 self.logger = logging.getLogger('pySerial.loop')
Chris Liechtid14b1ab2015-08-21 00:28:53 +0200109 self.logger.setLevel(LOGGER_LEVELS[values[0]])
cliechti6a300772009-08-12 02:28:56 +0000110 self.logger.debug('enabled logging')
cliechti41973a92009-08-06 02:18:21 +0000111 else:
112 raise ValueError('unknown option: %r' % (option,))
Chris Liechti68340d72015-08-03 14:15:48 +0200113 except ValueError as e:
Chris Liechtid14b1ab2015-08-21 00:28:53 +0200114 raise SerialException('expected a string in the form "loop://[?logging={debug|info|warning|error}]": %s' % e)
cliechti41973a92009-08-06 02:18:21 +0000115
116 # - - - - - - - - - - - - - - - - - - - - - - - -
117
Chris Liechtief1fe252015-08-27 23:25:21 +0200118 @property
119 def in_waiting(self):
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200120 """Return the number of bytes currently in the input buffer."""
Chris Liechti033f17c2015-08-30 21:28:04 +0200121 if not self.is_open:
122 raise portNotOpenError
cliechti6a300772009-08-12 02:28:56 +0000123 if self.logger:
cliechtic64ba692009-08-12 00:32:47 +0000124 # attention the logged value can differ from return value in
125 # threaded environments...
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200126 self.logger.debug('in_waiting -> %d' % (self.queue.qsize(),))
Chris Liechtia469cde2015-08-11 23:05:24 +0200127 return self.queue.qsize()
cliechti41973a92009-08-06 02:18:21 +0000128
129 def read(self, size=1):
cliechti7d448562014-08-03 21:57:45 +0000130 """\
131 Read size bytes from the serial port. If a timeout is set it may
cliechti41973a92009-08-06 02:18:21 +0000132 return less characters as requested. With no timeout it will block
cliechti7d448562014-08-03 21:57:45 +0000133 until the requested number of bytes is read.
134 """
Chris Liechti033f17c2015-08-30 21:28:04 +0200135 if not self.is_open:
136 raise portNotOpenError
Chris Liechti220c3a52015-09-15 00:06:51 +0200137 if self._timeout is not None and self._timeout != 0:
cliechti41973a92009-08-06 02:18:21 +0000138 timeout = time.time() + self._timeout
139 else:
cliechti024b4f42009-08-07 18:43:05 +0000140 timeout = None
cliechti1de32cd2009-08-07 19:05:09 +0000141 data = bytearray()
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200142 while size > 0 and self.is_open:
Chris Liechtia469cde2015-08-11 23:05:24 +0200143 try:
Chris Liechti220c3a52015-09-15 00:06:51 +0200144 b = self.queue.get(timeout=self._timeout) # XXX inter char timeout
Chris Liechtia469cde2015-08-11 23:05:24 +0200145 except queue.Empty:
Chris Liechti220c3a52015-09-15 00:06:51 +0200146 if self._timeout == 0:
147 break
Chris Liechtia469cde2015-08-11 23:05:24 +0200148 else:
Chris Liechti220c3a52015-09-15 00:06:51 +0200149 if data is not None:
150 data += b
151 size -= 1
152 else:
153 break
cliechti41973a92009-08-06 02:18:21 +0000154 # check for timeout now, after data has been read.
155 # useful for timeout = 0 (non blocking) read
cliechti024b4f42009-08-07 18:43:05 +0000156 if timeout and time.time() > timeout:
Chris Liechti220c3a52015-09-15 00:06:51 +0200157 if self.logger:
158 self.logger.info('read timeout')
cliechti41973a92009-08-06 02:18:21 +0000159 break
160 return bytes(data)
161
162 def write(self, data):
cliechti7d448562014-08-03 21:57:45 +0000163 """\
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200164 Output the given byte string over the serial port. Can block if the
cliechti41973a92009-08-06 02:18:21 +0000165 connection is blocked. May raise SerialException if the connection is
cliechti7d448562014-08-03 21:57:45 +0000166 closed.
167 """
Chris Liechti033f17c2015-08-30 21:28:04 +0200168 if not self.is_open:
169 raise portNotOpenError
cliechti38077122013-10-16 02:57:27 +0000170 data = to_bytes(data)
cliechti66957bf2009-08-06 23:25:37 +0000171 # calculate aprox time that would be used to send the data
Chris Liechti6594df62016-02-04 21:13:41 +0100172 time_used_to_send = 10.0 * len(data) / self._baudrate
cliechti66957bf2009-08-06 23:25:37 +0000173 # when a write timeout is configured check if we would be successful
174 # (not sending anything, not even the part that would have time)
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200175 if self._write_timeout is not None and time_used_to_send > self._write_timeout:
Chris Liechti033f17c2015-08-30 21:28:04 +0200176 time.sleep(self._write_timeout) # must wait so that unit test succeeds
cliechti66957bf2009-08-06 23:25:37 +0000177 raise writeTimeoutError
Chris Liechtif99cd5c2015-08-13 22:54:16 +0200178 for byte in iterbytes(data):
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200179 self.queue.put(byte, timeout=self._write_timeout)
cliechti41973a92009-08-06 02:18:21 +0000180 return len(data)
181
Chris Liechtief1fe252015-08-27 23:25:21 +0200182 def reset_input_buffer(self):
cliechti41973a92009-08-06 02:18:21 +0000183 """Clear input buffer, discarding all that is in the buffer."""
Chris Liechti033f17c2015-08-30 21:28:04 +0200184 if not self.is_open:
185 raise portNotOpenError
cliechti6a300772009-08-12 02:28:56 +0000186 if self.logger:
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200187 self.logger.info('reset_input_buffer()')
Chris Liechtia469cde2015-08-11 23:05:24 +0200188 try:
189 while self.queue.qsize():
190 self.queue.get_nowait()
191 except queue.Empty:
192 pass
cliechti41973a92009-08-06 02:18:21 +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 Liechti3ad62fb2015-08-29 21:53:32 +0200202 self.logger.info('reset_output_buffer()')
Chris Liechtia469cde2015-08-11 23:05:24 +0200203 try:
204 while self.queue.qsize():
205 self.queue.get_nowait()
206 except queue.Empty:
207 pass
cliechti41973a92009-08-06 02:18:21 +0000208
Chris Liechtief1fe252015-08-27 23:25:21 +0200209 def _update_break_state(self):
cliechti7d448562014-08-03 21:57:45 +0000210 """\
211 Set break: Controls TXD. When active, to transmitting is
212 possible.
213 """
cliechti6a300772009-08-12 02:28:56 +0000214 if self.logger:
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200215 self.logger.info('_update_break_state(%r)' % (self._break_state,))
cliechti41973a92009-08-06 02:18:21 +0000216
Chris Liechtief1fe252015-08-27 23:25:21 +0200217 def _update_rts_state(self):
cliechti41973a92009-08-06 02:18:21 +0000218 """Set terminal status line: Request To Send"""
cliechti6a300772009-08-12 02:28:56 +0000219 if self.logger:
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200220 self.logger.info('_update_rts_state(%r) -> state of CTS' % (self._rts_state,))
cliechti41973a92009-08-06 02:18:21 +0000221
Chris Liechtief1fe252015-08-27 23:25:21 +0200222 def _update_dtr_state(self):
cliechti41973a92009-08-06 02:18:21 +0000223 """Set terminal status line: Data Terminal Ready"""
cliechti6a300772009-08-12 02:28:56 +0000224 if self.logger:
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200225 self.logger.info('_update_dtr_state(%r) -> state of DSR' % (self._dtr_state,))
cliechti41973a92009-08-06 02:18:21 +0000226
Chris Liechtief1fe252015-08-27 23:25:21 +0200227 @property
228 def cts(self):
cliechti41973a92009-08-06 02:18:21 +0000229 """Read terminal status line: Clear To Send"""
Chris Liechti033f17c2015-08-30 21:28:04 +0200230 if not self.is_open:
231 raise portNotOpenError
cliechti6a300772009-08-12 02:28:56 +0000232 if self.logger:
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200233 self.logger.info('CTS -> state of RTS (%r)' % (self._rts_state,))
Chris Liechtief1fe252015-08-27 23:25:21 +0200234 return self._rts_state
cliechti41973a92009-08-06 02:18:21 +0000235
Chris Liechtief1fe252015-08-27 23:25:21 +0200236 @property
237 def dsr(self):
cliechti41973a92009-08-06 02:18:21 +0000238 """Read terminal status line: Data Set Ready"""
cliechti6a300772009-08-12 02:28:56 +0000239 if self.logger:
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200240 self.logger.info('DSR -> state of DTR (%r)' % (self._dtr_state,))
Chris Liechtief1fe252015-08-27 23:25:21 +0200241 return self._dtr_state
cliechti41973a92009-08-06 02:18:21 +0000242
Chris Liechtief1fe252015-08-27 23:25:21 +0200243 @property
244 def ri(self):
cliechti41973a92009-08-06 02:18:21 +0000245 """Read terminal status line: Ring Indicator"""
Chris Liechti033f17c2015-08-30 21:28:04 +0200246 if not self.is_open:
247 raise portNotOpenError
cliechti6a300772009-08-12 02:28:56 +0000248 if self.logger:
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200249 self.logger.info('returning dummy for RI')
cliechti41973a92009-08-06 02:18:21 +0000250 return False
251
Chris Liechtief1fe252015-08-27 23:25:21 +0200252 @property
253 def cd(self):
cliechti41973a92009-08-06 02:18:21 +0000254 """Read terminal status line: Carrier Detect"""
Chris Liechti033f17c2015-08-30 21:28:04 +0200255 if not self.is_open:
256 raise portNotOpenError
cliechti6a300772009-08-12 02:28:56 +0000257 if self.logger:
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200258 self.logger.info('returning dummy for CD')
cliechti41973a92009-08-06 02:18:21 +0000259 return True
260
261 # - - - platform specific - - -
262 # None so far
263
264
cliechti41973a92009-08-06 02:18:21 +0000265# simple client test
266if __name__ == '__main__':
267 import sys
cliechtiab3d4282011-08-19 01:52:46 +0000268 s = Serial('loop://')
cliechti41973a92009-08-06 02:18:21 +0000269 sys.stdout.write('%s\n' % s)
270
271 sys.stdout.write("write...\n")
272 s.write("hello\n")
273 s.flush()
274 sys.stdout.write("read: %s\n" % s.read(5))
275
276 s.close()