blob: 5bba4d39c4a84a677d9abdac707d217d56fe0a5e [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):
Chris Liechtia469cde2015-08-11 23:05:24 +020046 self.buffer_size = 4096
Chris Liechti7806fc02015-12-10 21:15:20 +010047 self.queue = None
48 self.logger = None
Chris Liechtid6112a02016-10-04 20:27:21 +020049 self._cancel_write = False
Chris Liechti1d157152016-08-04 20:47:00 +020050 super(Serial, self).__init__(*args, **kwargs)
Chris Liechtia469cde2015-08-11 23:05:24 +020051
cliechti41973a92009-08-06 02:18:21 +000052 def open(self):
cliechti7d448562014-08-03 21:57:45 +000053 """\
54 Open port with current settings. This may throw a SerialException
55 if the port cannot be opened.
56 """
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.")
cliechti6a300772009-08-12 02:28:56 +000059 self.logger = None
Chris Liechtia469cde2015-08-11 23:05:24 +020060 self.queue = queue.Queue(self.buffer_size)
cliechti41973a92009-08-06 02:18:21 +000061
62 if self._port is None:
63 raise SerialException("Port must be configured before it can be used.")
64 # not that there is anything to open, but the function applies the
65 # options found in the URL
Chris Liechti3ad62fb2015-08-29 21:53:32 +020066 self.from_url(self.port)
cliechti41973a92009-08-06 02:18:21 +000067
68 # not that there anything to configure...
Chris Liechti3ad62fb2015-08-29 21:53:32 +020069 self._reconfigure_port()
cliechti41973a92009-08-06 02:18:21 +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()
cliechti41973a92009-08-06 02:18:21 +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()
cliechti41973a92009-08-06 02:18:21 +000078
Chris Liechtia469cde2015-08-11 23:05:24 +020079 def close(self):
Chris Liechti7806fc02015-12-10 21:15:20 +010080 if self.is_open:
81 self.is_open = False
82 try:
83 self.queue.put_nowait(None)
84 except queue.Full:
85 pass
Chris Liechtia469cde2015-08-11 23:05:24 +020086 super(Serial, self).close()
87
Chris Liechti3ad62fb2015-08-29 21:53:32 +020088 def _reconfigure_port(self):
cliechti7d448562014-08-03 21:57:45 +000089 """\
90 Set communication parameters on opened port. For the loop://
91 protocol all settings are ignored!
92 """
cliechti41973a92009-08-06 02:18:21 +000093 # not that's it of any real use, but it helps in the unit tests
Chris Liechti92df95a2016-02-09 23:30:37 +010094 if not isinstance(self._baudrate, numbers.Integral) or not 0 < self._baudrate < 2 ** 32:
Chris Liechtic8f3f822016-06-08 03:35:28 +020095 raise ValueError("invalid baudrate: {!r}".format(self._baudrate))
cliechti6a300772009-08-12 02:28:56 +000096 if self.logger:
Chris Liechti3ad62fb2015-08-29 21:53:32 +020097 self.logger.info('_reconfigure_port()')
cliechti41973a92009-08-06 02:18:21 +000098
Chris Liechti3ad62fb2015-08-29 21:53:32 +020099 def from_url(self, url):
cliechti41973a92009-08-06 02:18:21 +0000100 """extract host and port from an URL string"""
Chris Liechtic4bca9e2015-08-07 14:40:41 +0200101 parts = urlparse.urlsplit(url)
Chris Liechtid14b1ab2015-08-21 00:28:53 +0200102 if parts.scheme != "loop":
Chris Liechti43b3b102016-06-07 21:31:47 +0200103 raise SerialException(
104 'expected a string in the form '
105 '"loop://[?logging={debug|info|warning|error}]": not starting '
Chris Liechtic8f3f822016-06-08 03:35:28 +0200106 'with loop:// ({!r})'.format(parts.scheme))
cliechti41973a92009-08-06 02:18:21 +0000107 try:
108 # 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':
cliechtic64ba692009-08-12 00:32:47 +0000111 logging.basicConfig() # XXX is that good to call it here?
cliechti6a300772009-08-12 02:28:56 +0000112 self.logger = logging.getLogger('pySerial.loop')
Chris Liechtid14b1ab2015-08-21 00:28:53 +0200113 self.logger.setLevel(LOGGER_LEVELS[values[0]])
cliechti6a300772009-08-12 02:28:56 +0000114 self.logger.debug('enabled logging')
cliechti41973a92009-08-06 02:18:21 +0000115 else:
Chris Liechtic8f3f822016-06-08 03:35:28 +0200116 raise ValueError('unknown option: {!r}'.format(option))
Chris Liechti68340d72015-08-03 14:15:48 +0200117 except ValueError as e:
Chris Liechti43b3b102016-06-07 21:31:47 +0200118 raise SerialException(
119 'expected a string in the form '
Chris Liechtic8f3f822016-06-08 03:35:28 +0200120 '"loop://[?logging={debug|info|warning|error}]": {}'.format(e))
cliechti41973a92009-08-06 02:18:21 +0000121
122 # - - - - - - - - - - - - - - - - - - - - - - - -
123
Chris Liechtief1fe252015-08-27 23:25:21 +0200124 @property
125 def in_waiting(self):
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200126 """Return the number of bytes currently in the input buffer."""
Chris Liechti033f17c2015-08-30 21:28:04 +0200127 if not self.is_open:
128 raise portNotOpenError
cliechti6a300772009-08-12 02:28:56 +0000129 if self.logger:
cliechtic64ba692009-08-12 00:32:47 +0000130 # attention the logged value can differ from return value in
131 # threaded environments...
Chris Liechtic8f3f822016-06-08 03:35:28 +0200132 self.logger.debug('in_waiting -> {:d}'.format(self.queue.qsize()))
Chris Liechtia469cde2015-08-11 23:05:24 +0200133 return self.queue.qsize()
cliechti41973a92009-08-06 02:18:21 +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
cliechti41973a92009-08-06 02:18:21 +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 Liechti033f17c2015-08-30 21:28:04 +0200141 if not self.is_open:
142 raise portNotOpenError
Chris Liechti220c3a52015-09-15 00:06:51 +0200143 if self._timeout is not None and self._timeout != 0:
cliechti41973a92009-08-06 02:18:21 +0000144 timeout = time.time() + self._timeout
145 else:
cliechti024b4f42009-08-07 18:43:05 +0000146 timeout = None
cliechti1de32cd2009-08-07 19:05:09 +0000147 data = bytearray()
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200148 while size > 0 and self.is_open:
Chris Liechtia469cde2015-08-11 23:05:24 +0200149 try:
Chris Liechti220c3a52015-09-15 00:06:51 +0200150 b = self.queue.get(timeout=self._timeout) # XXX inter char timeout
Chris Liechtia469cde2015-08-11 23:05:24 +0200151 except queue.Empty:
Chris Liechti220c3a52015-09-15 00:06:51 +0200152 if self._timeout == 0:
153 break
Chris Liechtia469cde2015-08-11 23:05:24 +0200154 else:
Chris Liechtid6112a02016-10-04 20:27:21 +0200155 if b is not None:
Chris Liechti220c3a52015-09-15 00:06:51 +0200156 data += b
157 size -= 1
158 else:
159 break
cliechti41973a92009-08-06 02:18:21 +0000160 # check for timeout now, after data has been read.
161 # useful for timeout = 0 (non blocking) read
cliechti024b4f42009-08-07 18:43:05 +0000162 if timeout and time.time() > timeout:
Chris Liechti220c3a52015-09-15 00:06:51 +0200163 if self.logger:
164 self.logger.info('read timeout')
cliechti41973a92009-08-06 02:18:21 +0000165 break
166 return bytes(data)
167
Chris Liechtid6112a02016-10-04 20:27:21 +0200168 def cancel_read(self):
169 self.queue.put_nowait(None)
170
171 def cancel_write(self):
172 self._cancel_write = True
173
cliechti41973a92009-08-06 02:18:21 +0000174 def write(self, data):
cliechti7d448562014-08-03 21:57:45 +0000175 """\
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200176 Output the given byte string over the serial port. Can block if the
cliechti41973a92009-08-06 02:18:21 +0000177 connection is blocked. May raise SerialException if the connection is
cliechti7d448562014-08-03 21:57:45 +0000178 closed.
179 """
Chris Liechtid6112a02016-10-04 20:27:21 +0200180 self._cancel_write = False
Chris Liechti033f17c2015-08-30 21:28:04 +0200181 if not self.is_open:
182 raise portNotOpenError
cliechti38077122013-10-16 02:57:27 +0000183 data = to_bytes(data)
cliechti66957bf2009-08-06 23:25:37 +0000184 # calculate aprox time that would be used to send the data
Chris Liechti6594df62016-02-04 21:13:41 +0100185 time_used_to_send = 10.0 * len(data) / self._baudrate
cliechti66957bf2009-08-06 23:25:37 +0000186 # when a write timeout is configured check if we would be successful
187 # (not sending anything, not even the part that would have time)
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200188 if self._write_timeout is not None and time_used_to_send > self._write_timeout:
Chris Liechtid6112a02016-10-04 20:27:21 +0200189 # must wait so that unit test succeeds
190 time_left = self._write_timeout
191 while time_left > 0 and not self._cancel_write:
192 time.sleep(min(time_left, 1))
193 time_left -= 1
194 if self._cancel_write:
195 return 0 # XXX
cliechti66957bf2009-08-06 23:25:37 +0000196 raise writeTimeoutError
Chris Liechtif99cd5c2015-08-13 22:54:16 +0200197 for byte in iterbytes(data):
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200198 self.queue.put(byte, timeout=self._write_timeout)
cliechti41973a92009-08-06 02:18:21 +0000199 return len(data)
200
Chris Liechtief1fe252015-08-27 23:25:21 +0200201 def reset_input_buffer(self):
cliechti41973a92009-08-06 02:18:21 +0000202 """Clear input buffer, discarding all that is in the buffer."""
Chris Liechti033f17c2015-08-30 21:28:04 +0200203 if not self.is_open:
204 raise portNotOpenError
cliechti6a300772009-08-12 02:28:56 +0000205 if self.logger:
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200206 self.logger.info('reset_input_buffer()')
Chris Liechtia469cde2015-08-11 23:05:24 +0200207 try:
208 while self.queue.qsize():
209 self.queue.get_nowait()
210 except queue.Empty:
211 pass
cliechti41973a92009-08-06 02:18:21 +0000212
Chris Liechtief1fe252015-08-27 23:25:21 +0200213 def reset_output_buffer(self):
cliechti7d448562014-08-03 21:57:45 +0000214 """\
215 Clear output buffer, aborting the current output and
216 discarding all that is in the buffer.
217 """
Chris Liechti033f17c2015-08-30 21:28:04 +0200218 if not self.is_open:
219 raise portNotOpenError
cliechti6a300772009-08-12 02:28:56 +0000220 if self.logger:
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200221 self.logger.info('reset_output_buffer()')
Chris Liechtia469cde2015-08-11 23:05:24 +0200222 try:
223 while self.queue.qsize():
224 self.queue.get_nowait()
225 except queue.Empty:
226 pass
cliechti41973a92009-08-06 02:18:21 +0000227
Chris Liechtief1fe252015-08-27 23:25:21 +0200228 def _update_break_state(self):
cliechti7d448562014-08-03 21:57:45 +0000229 """\
230 Set break: Controls TXD. When active, to transmitting is
231 possible.
232 """
cliechti6a300772009-08-12 02:28:56 +0000233 if self.logger:
Chris Liechtic8f3f822016-06-08 03:35:28 +0200234 self.logger.info('_update_break_state({!r})'.format(self._break_state))
cliechti41973a92009-08-06 02:18:21 +0000235
Chris Liechtief1fe252015-08-27 23:25:21 +0200236 def _update_rts_state(self):
cliechti41973a92009-08-06 02:18:21 +0000237 """Set terminal status line: Request To Send"""
cliechti6a300772009-08-12 02:28:56 +0000238 if self.logger:
Chris Liechtic8f3f822016-06-08 03:35:28 +0200239 self.logger.info('_update_rts_state({!r}) -> state of CTS'.format(self._rts_state))
cliechti41973a92009-08-06 02:18:21 +0000240
Chris Liechtief1fe252015-08-27 23:25:21 +0200241 def _update_dtr_state(self):
cliechti41973a92009-08-06 02:18:21 +0000242 """Set terminal status line: Data Terminal Ready"""
cliechti6a300772009-08-12 02:28:56 +0000243 if self.logger:
Chris Liechtic8f3f822016-06-08 03:35:28 +0200244 self.logger.info('_update_dtr_state({!r}) -> state of DSR'.format(self._dtr_state))
cliechti41973a92009-08-06 02:18:21 +0000245
Chris Liechtief1fe252015-08-27 23:25:21 +0200246 @property
247 def cts(self):
cliechti41973a92009-08-06 02:18:21 +0000248 """Read terminal status line: Clear To Send"""
Chris Liechti033f17c2015-08-30 21:28:04 +0200249 if not self.is_open:
250 raise portNotOpenError
cliechti6a300772009-08-12 02:28:56 +0000251 if self.logger:
Chris Liechtic8f3f822016-06-08 03:35:28 +0200252 self.logger.info('CTS -> state of RTS ({!r})'.format(self._rts_state))
Chris Liechtief1fe252015-08-27 23:25:21 +0200253 return self._rts_state
cliechti41973a92009-08-06 02:18:21 +0000254
Chris Liechtief1fe252015-08-27 23:25:21 +0200255 @property
256 def dsr(self):
cliechti41973a92009-08-06 02:18:21 +0000257 """Read terminal status line: Data Set Ready"""
cliechti6a300772009-08-12 02:28:56 +0000258 if self.logger:
Chris Liechtic8f3f822016-06-08 03:35:28 +0200259 self.logger.info('DSR -> state of DTR ({!r})'.format(self._dtr_state))
Chris Liechtief1fe252015-08-27 23:25:21 +0200260 return self._dtr_state
cliechti41973a92009-08-06 02:18:21 +0000261
Chris Liechtief1fe252015-08-27 23:25:21 +0200262 @property
263 def ri(self):
cliechti41973a92009-08-06 02:18:21 +0000264 """Read terminal status line: Ring Indicator"""
Chris Liechti033f17c2015-08-30 21:28:04 +0200265 if not self.is_open:
266 raise portNotOpenError
cliechti6a300772009-08-12 02:28:56 +0000267 if self.logger:
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200268 self.logger.info('returning dummy for RI')
cliechti41973a92009-08-06 02:18:21 +0000269 return False
270
Chris Liechtief1fe252015-08-27 23:25:21 +0200271 @property
272 def cd(self):
cliechti41973a92009-08-06 02:18:21 +0000273 """Read terminal status line: Carrier Detect"""
Chris Liechti033f17c2015-08-30 21:28:04 +0200274 if not self.is_open:
275 raise portNotOpenError
cliechti6a300772009-08-12 02:28:56 +0000276 if self.logger:
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200277 self.logger.info('returning dummy for CD')
cliechti41973a92009-08-06 02:18:21 +0000278 return True
279
280 # - - - platform specific - - -
281 # None so far
282
283
cliechti41973a92009-08-06 02:18:21 +0000284# simple client test
285if __name__ == '__main__':
286 import sys
cliechtiab3d4282011-08-19 01:52:46 +0000287 s = Serial('loop://')
Chris Liechtic8f3f822016-06-08 03:35:28 +0200288 sys.stdout.write('{}\n'.format(s))
cliechti41973a92009-08-06 02:18:21 +0000289
290 sys.stdout.write("write...\n")
291 s.write("hello\n")
292 s.flush()
Chris Liechtic8f3f822016-06-08 03:35:28 +0200293 sys.stdout.write("read: {!r}\n".format(s.read(5)))
cliechti41973a92009-08-06 02:18:21 +0000294
295 s.close()