blob: d9099def5cbad2e9057ae90dfa62194bf28a0aa8 [file] [log] [blame]
cliechti41973a92009-08-06 02:18:21 +00001#! python
2#
3# Python Serial Port Extension for Win32, Linux, BSD, Jython
4# see __init__.py
5#
6# This module implements a loop back connection receiving itself what it sent.
7#
8# The purpose of this module is.. well... You can run the unit tests with it.
9# and it was so easy to implement ;-)
10#
Chris Liechtic4bca9e2015-08-07 14:40:41 +020011# (C) 2001-2015 Chris Liechti <cliechti@gmx.net>
Chris Liechtifbdd8a02015-08-09 02:37:45 +020012#
13# SPDX-License-Identifier: BSD-3-Clause
cliechti41973a92009-08-06 02:18:21 +000014#
15# URL format: loop://[option[/option...]]
16# options:
17# - "debug" print diagnostic messages
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
30from serial.serialutil import *
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 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
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):
48 super(Serial, self).__init__(*args, **kwargs)
49 self.buffer_size = 4096
Chris Liechti7806fc02015-12-10 21:15:20 +010050 self.queue = None
51 self.logger = None
Chris Liechtia469cde2015-08-11 23:05:24 +020052
cliechti41973a92009-08-06 02:18:21 +000053 def open(self):
cliechti7d448562014-08-03 21:57:45 +000054 """\
55 Open port with current settings. This may throw a SerialException
56 if the port cannot be opened.
57 """
Chris Liechti3ad62fb2015-08-29 21:53:32 +020058 if self.is_open:
cliechti8f69e702011-03-19 00:22:32 +000059 raise SerialException("Port is already open.")
cliechti6a300772009-08-12 02:28:56 +000060 self.logger = None
Chris Liechtia469cde2015-08-11 23:05:24 +020061 self.queue = queue.Queue(self.buffer_size)
cliechti41973a92009-08-06 02:18:21 +000062
63 if self._port is None:
64 raise SerialException("Port must be configured before it can be used.")
65 # not that there is anything to open, but the function applies the
66 # options found in the URL
Chris Liechti3ad62fb2015-08-29 21:53:32 +020067 self.from_url(self.port)
cliechti41973a92009-08-06 02:18:21 +000068
69 # not that there anything to configure...
Chris Liechti3ad62fb2015-08-29 21:53:32 +020070 self._reconfigure_port()
cliechti41973a92009-08-06 02:18:21 +000071 # all things set up get, now a clean start
Chris Liechti3ad62fb2015-08-29 21:53:32 +020072 self.is_open = True
73 if not self._dsrdtr:
Chris Liechtief1fe252015-08-27 23:25:21 +020074 self._update_dtr_state()
cliechti41973a92009-08-06 02:18:21 +000075 if not self._rtscts:
Chris Liechtief1fe252015-08-27 23:25:21 +020076 self._update_rts_state()
77 self.reset_input_buffer()
78 self.reset_output_buffer()
cliechti41973a92009-08-06 02:18:21 +000079
Chris Liechtia469cde2015-08-11 23:05:24 +020080 def close(self):
Chris Liechti7806fc02015-12-10 21:15:20 +010081 if self.is_open:
82 self.is_open = False
83 try:
84 self.queue.put_nowait(None)
85 except queue.Full:
86 pass
Chris Liechtia469cde2015-08-11 23:05:24 +020087 super(Serial, self).close()
88
Chris Liechti3ad62fb2015-08-29 21:53:32 +020089 def _reconfigure_port(self):
cliechti7d448562014-08-03 21:57:45 +000090 """\
91 Set communication parameters on opened port. For the loop://
92 protocol all settings are ignored!
93 """
cliechti41973a92009-08-06 02:18:21 +000094 # not that's it of any real use, but it helps in the unit tests
Chris Liechtic4bca9e2015-08-07 14:40:41 +020095 if not isinstance(self._baudrate, numbers.Integral) or not 0 < self._baudrate < 2**32:
cliechti41973a92009-08-06 02:18:21 +000096 raise ValueError("invalid baudrate: %r" % (self._baudrate))
cliechti6a300772009-08-12 02:28:56 +000097 if self.logger:
Chris Liechti3ad62fb2015-08-29 21:53:32 +020098 self.logger.info('_reconfigure_port()')
cliechti41973a92009-08-06 02:18:21 +000099
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200100 def from_url(self, url):
cliechti41973a92009-08-06 02:18:21 +0000101 """extract host and port from an URL string"""
Chris Liechtic4bca9e2015-08-07 14:40:41 +0200102 parts = urlparse.urlsplit(url)
Chris Liechtid14b1ab2015-08-21 00:28:53 +0200103 if parts.scheme != "loop":
104 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 +0000105 try:
106 # process options now, directly altering self
Chris Liechtid14b1ab2015-08-21 00:28:53 +0200107 for option, values in urlparse.parse_qs(parts.query, True).items():
108 if option == 'logging':
cliechtic64ba692009-08-12 00:32:47 +0000109 logging.basicConfig() # XXX is that good to call it here?
cliechti6a300772009-08-12 02:28:56 +0000110 self.logger = logging.getLogger('pySerial.loop')
Chris Liechtid14b1ab2015-08-21 00:28:53 +0200111 self.logger.setLevel(LOGGER_LEVELS[values[0]])
cliechti6a300772009-08-12 02:28:56 +0000112 self.logger.debug('enabled logging')
cliechti41973a92009-08-06 02:18:21 +0000113 else:
114 raise ValueError('unknown option: %r' % (option,))
Chris Liechti68340d72015-08-03 14:15:48 +0200115 except ValueError as e:
Chris Liechtid14b1ab2015-08-21 00:28:53 +0200116 raise SerialException('expected a string in the form "loop://[?logging={debug|info|warning|error}]": %s' % e)
cliechti41973a92009-08-06 02:18:21 +0000117
118 # - - - - - - - - - - - - - - - - - - - - - - - -
119
Chris Liechtief1fe252015-08-27 23:25:21 +0200120 @property
121 def in_waiting(self):
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200122 """Return the number of bytes currently in the input buffer."""
Chris Liechti033f17c2015-08-30 21:28:04 +0200123 if not self.is_open:
124 raise portNotOpenError
cliechti6a300772009-08-12 02:28:56 +0000125 if self.logger:
cliechtic64ba692009-08-12 00:32:47 +0000126 # attention the logged value can differ from return value in
127 # threaded environments...
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200128 self.logger.debug('in_waiting -> %d' % (self.queue.qsize(),))
Chris Liechtia469cde2015-08-11 23:05:24 +0200129 return self.queue.qsize()
cliechti41973a92009-08-06 02:18:21 +0000130
131 def read(self, size=1):
cliechti7d448562014-08-03 21:57:45 +0000132 """\
133 Read size bytes from the serial port. If a timeout is set it may
cliechti41973a92009-08-06 02:18:21 +0000134 return less characters as requested. With no timeout it will block
cliechti7d448562014-08-03 21:57:45 +0000135 until the requested number of bytes is read.
136 """
Chris Liechti033f17c2015-08-30 21:28:04 +0200137 if not self.is_open:
138 raise portNotOpenError
Chris Liechti220c3a52015-09-15 00:06:51 +0200139 if self._timeout is not None and self._timeout != 0:
cliechti41973a92009-08-06 02:18:21 +0000140 timeout = time.time() + self._timeout
141 else:
cliechti024b4f42009-08-07 18:43:05 +0000142 timeout = None
cliechti1de32cd2009-08-07 19:05:09 +0000143 data = bytearray()
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200144 while size > 0 and self.is_open:
Chris Liechtia469cde2015-08-11 23:05:24 +0200145 try:
Chris Liechti220c3a52015-09-15 00:06:51 +0200146 b = self.queue.get(timeout=self._timeout) # XXX inter char timeout
Chris Liechtia469cde2015-08-11 23:05:24 +0200147 except queue.Empty:
Chris Liechti220c3a52015-09-15 00:06:51 +0200148 if self._timeout == 0:
149 break
Chris Liechtia469cde2015-08-11 23:05:24 +0200150 else:
Chris Liechti220c3a52015-09-15 00:06:51 +0200151 if data is not None:
152 data += b
153 size -= 1
154 else:
155 break
cliechti41973a92009-08-06 02:18:21 +0000156 # check for timeout now, after data has been read.
157 # useful for timeout = 0 (non blocking) read
cliechti024b4f42009-08-07 18:43:05 +0000158 if timeout and time.time() > timeout:
Chris Liechti220c3a52015-09-15 00:06:51 +0200159 if self.logger:
160 self.logger.info('read timeout')
cliechti41973a92009-08-06 02:18:21 +0000161 break
162 return bytes(data)
163
164 def write(self, data):
cliechti7d448562014-08-03 21:57:45 +0000165 """\
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200166 Output the given byte string over the serial port. Can block if the
cliechti41973a92009-08-06 02:18:21 +0000167 connection is blocked. May raise SerialException if the connection is
cliechti7d448562014-08-03 21:57:45 +0000168 closed.
169 """
Chris Liechti033f17c2015-08-30 21:28:04 +0200170 if not self.is_open:
171 raise portNotOpenError
cliechti38077122013-10-16 02:57:27 +0000172 data = to_bytes(data)
cliechti66957bf2009-08-06 23:25:37 +0000173 # calculate aprox time that would be used to send the data
174 time_used_to_send = 10.0*len(data) / self._baudrate
175 # when a write timeout is configured check if we would be successful
176 # (not sending anything, not even the part that would have time)
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200177 if self._write_timeout is not None and time_used_to_send > self._write_timeout:
Chris Liechti033f17c2015-08-30 21:28:04 +0200178 time.sleep(self._write_timeout) # must wait so that unit test succeeds
cliechti66957bf2009-08-06 23:25:37 +0000179 raise writeTimeoutError
Chris Liechtif99cd5c2015-08-13 22:54:16 +0200180 for byte in iterbytes(data):
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200181 self.queue.put(byte, timeout=self._write_timeout)
cliechti41973a92009-08-06 02:18:21 +0000182 return len(data)
183
Chris Liechtief1fe252015-08-27 23:25:21 +0200184 def reset_input_buffer(self):
cliechti41973a92009-08-06 02:18:21 +0000185 """Clear input buffer, discarding all that is in the buffer."""
Chris Liechti033f17c2015-08-30 21:28:04 +0200186 if not self.is_open:
187 raise portNotOpenError
cliechti6a300772009-08-12 02:28:56 +0000188 if self.logger:
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200189 self.logger.info('reset_input_buffer()')
Chris Liechtia469cde2015-08-11 23:05:24 +0200190 try:
191 while self.queue.qsize():
192 self.queue.get_nowait()
193 except queue.Empty:
194 pass
cliechti41973a92009-08-06 02:18:21 +0000195
Chris Liechtief1fe252015-08-27 23:25:21 +0200196 def reset_output_buffer(self):
cliechti7d448562014-08-03 21:57:45 +0000197 """\
198 Clear output buffer, aborting the current output and
199 discarding all that is in the buffer.
200 """
Chris Liechti033f17c2015-08-30 21:28:04 +0200201 if not self.is_open:
202 raise portNotOpenError
cliechti6a300772009-08-12 02:28:56 +0000203 if self.logger:
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200204 self.logger.info('reset_output_buffer()')
Chris Liechtia469cde2015-08-11 23:05:24 +0200205 try:
206 while self.queue.qsize():
207 self.queue.get_nowait()
208 except queue.Empty:
209 pass
cliechti41973a92009-08-06 02:18:21 +0000210
Chris Liechtief1fe252015-08-27 23:25:21 +0200211 def _update_break_state(self):
cliechti7d448562014-08-03 21:57:45 +0000212 """\
213 Set break: Controls TXD. When active, to transmitting is
214 possible.
215 """
cliechti6a300772009-08-12 02:28:56 +0000216 if self.logger:
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200217 self.logger.info('_update_break_state(%r)' % (self._break_state,))
cliechti41973a92009-08-06 02:18:21 +0000218
Chris Liechtief1fe252015-08-27 23:25:21 +0200219 def _update_rts_state(self):
cliechti41973a92009-08-06 02:18:21 +0000220 """Set terminal status line: Request To Send"""
cliechti6a300772009-08-12 02:28:56 +0000221 if self.logger:
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200222 self.logger.info('_update_rts_state(%r) -> state of CTS' % (self._rts_state,))
cliechti41973a92009-08-06 02:18:21 +0000223
Chris Liechtief1fe252015-08-27 23:25:21 +0200224 def _update_dtr_state(self):
cliechti41973a92009-08-06 02:18:21 +0000225 """Set terminal status line: Data Terminal Ready"""
cliechti6a300772009-08-12 02:28:56 +0000226 if self.logger:
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200227 self.logger.info('_update_dtr_state(%r) -> state of DSR' % (self._dtr_state,))
cliechti41973a92009-08-06 02:18:21 +0000228
Chris Liechtief1fe252015-08-27 23:25:21 +0200229 @property
230 def cts(self):
cliechti41973a92009-08-06 02:18:21 +0000231 """Read terminal status line: Clear To Send"""
Chris Liechti033f17c2015-08-30 21:28:04 +0200232 if not self.is_open:
233 raise portNotOpenError
cliechti6a300772009-08-12 02:28:56 +0000234 if self.logger:
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200235 self.logger.info('CTS -> state of RTS (%r)' % (self._rts_state,))
Chris Liechtief1fe252015-08-27 23:25:21 +0200236 return self._rts_state
cliechti41973a92009-08-06 02:18:21 +0000237
Chris Liechtief1fe252015-08-27 23:25:21 +0200238 @property
239 def dsr(self):
cliechti41973a92009-08-06 02:18:21 +0000240 """Read terminal status line: Data Set Ready"""
cliechti6a300772009-08-12 02:28:56 +0000241 if self.logger:
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200242 self.logger.info('DSR -> state of DTR (%r)' % (self._dtr_state,))
Chris Liechtief1fe252015-08-27 23:25:21 +0200243 return self._dtr_state
cliechti41973a92009-08-06 02:18:21 +0000244
Chris Liechtief1fe252015-08-27 23:25:21 +0200245 @property
246 def ri(self):
cliechti41973a92009-08-06 02:18:21 +0000247 """Read terminal status line: Ring Indicator"""
Chris Liechti033f17c2015-08-30 21:28:04 +0200248 if not self.is_open:
249 raise portNotOpenError
cliechti6a300772009-08-12 02:28:56 +0000250 if self.logger:
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200251 self.logger.info('returning dummy for RI')
cliechti41973a92009-08-06 02:18:21 +0000252 return False
253
Chris Liechtief1fe252015-08-27 23:25:21 +0200254 @property
255 def cd(self):
cliechti41973a92009-08-06 02:18:21 +0000256 """Read terminal status line: Carrier Detect"""
Chris Liechti033f17c2015-08-30 21:28:04 +0200257 if not self.is_open:
258 raise portNotOpenError
cliechti6a300772009-08-12 02:28:56 +0000259 if self.logger:
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200260 self.logger.info('returning dummy for CD')
cliechti41973a92009-08-06 02:18:21 +0000261 return True
262
263 # - - - platform specific - - -
264 # None so far
265
266
cliechti41973a92009-08-06 02:18:21 +0000267# simple client test
268if __name__ == '__main__':
269 import sys
cliechtiab3d4282011-08-19 01:52:46 +0000270 s = Serial('loop://')
cliechti41973a92009-08-06 02:18:21 +0000271 sys.stdout.write('%s\n' % s)
272
273 sys.stdout.write("write...\n")
274 s.write("hello\n")
275 s.flush()
276 sys.stdout.write("read: %s\n" % s.read(5))
277
278 s.close()