blob: 10dedebedf953e27888691eb1af9711e22318d6a [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 threading
21import time
Chris Liechtic4bca9e2015-08-07 14:40:41 +020022try:
23 import urlparse
24except ImportError:
25 import urllib.parse as urlparse
Chris Liechtia469cde2015-08-11 23:05:24 +020026try:
27 import queue
28except ImportError:
29 import Queue as queue
Chris Liechtic4bca9e2015-08-07 14:40:41 +020030
31from serial.serialutil import *
cliechtic64ba692009-08-12 00:32:47 +000032
33# map log level names to constants. used in fromURL()
34LOGGER_LEVELS = {
Chris Liechtic4bca9e2015-08-07 14:40:41 +020035 'debug': logging.DEBUG,
36 'info': logging.INFO,
37 'warning': logging.WARNING,
38 'error': logging.ERROR,
39 }
cliechtic64ba692009-08-12 00:32:47 +000040
cliechti41973a92009-08-06 02:18:21 +000041
Chris Liechtief6b7b42015-08-06 22:19:26 +020042class Serial(SerialBase):
cliechtiab3d4282011-08-19 01:52:46 +000043 """Serial port implementation that simulates a loop back connection in plain software."""
cliechti41973a92009-08-06 02:18:21 +000044
45 BAUDRATES = (50, 75, 110, 134, 150, 200, 300, 600, 1200, 1800, 2400, 4800,
46 9600, 19200, 38400, 57600, 115200)
47
Chris Liechtia469cde2015-08-11 23:05:24 +020048 def __init__(self, *args, **kwargs):
49 super(Serial, self).__init__(*args, **kwargs)
50 self.buffer_size = 4096
51
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 """
cliechti8f69e702011-03-19 00:22:32 +000057 if self._isOpen:
58 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 self.cts = False
62 self.dsr = False
63
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
68 self.fromURL(self.port)
69
70 # not that there anything to configure...
71 self._reconfigurePort()
72 # all things set up get, now a clean start
73 self._isOpen = True
74 if not self._rtscts:
75 self.setRTS(True)
76 self.setDTR(True)
77 self.flushInput()
78 self.flushOutput()
79
Chris Liechtia469cde2015-08-11 23:05:24 +020080 def close(self):
81 self.queue.put(None)
82 super(Serial, self).close()
83
cliechti41973a92009-08-06 02:18:21 +000084 def _reconfigurePort(self):
cliechti7d448562014-08-03 21:57:45 +000085 """\
86 Set communication parameters on opened port. For the loop://
87 protocol all settings are ignored!
88 """
cliechti41973a92009-08-06 02:18:21 +000089 # not that's it of any real use, but it helps in the unit tests
Chris Liechtic4bca9e2015-08-07 14:40:41 +020090 if not isinstance(self._baudrate, numbers.Integral) or not 0 < self._baudrate < 2**32:
cliechti41973a92009-08-06 02:18:21 +000091 raise ValueError("invalid baudrate: %r" % (self._baudrate))
cliechti6a300772009-08-12 02:28:56 +000092 if self.logger:
93 self.logger.info('_reconfigurePort()')
cliechti41973a92009-08-06 02:18:21 +000094
95 def close(self):
96 """Close port"""
97 if self._isOpen:
98 self._isOpen = False
99 # in case of quick reconnects, give the server some time
100 time.sleep(0.3)
101
cliechti41973a92009-08-06 02:18:21 +0000102 def fromURL(self, url):
103 """extract host and port from an URL string"""
Chris Liechtic4bca9e2015-08-07 14:40:41 +0200104 parts = urlparse.urlsplit(url)
Chris Liechtid14b1ab2015-08-21 00:28:53 +0200105 if parts.scheme != "loop":
106 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 +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:
116 raise ValueError('unknown option: %r' % (option,))
Chris Liechti68340d72015-08-03 14:15:48 +0200117 except ValueError as e:
Chris Liechtid14b1ab2015-08-21 00:28:53 +0200118 raise SerialException('expected a string in the form "loop://[?logging={debug|info|warning|error}]": %s' % e)
cliechti41973a92009-08-06 02:18:21 +0000119
120 # - - - - - - - - - - - - - - - - - - - - - - - -
121
122 def inWaiting(self):
123 """Return the number of characters currently in the input buffer."""
124 if not self._isOpen: 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 Liechtia469cde2015-08-11 23:05:24 +0200128 self.logger.debug('inWaiting() -> %d' % (self.queue.qsize(),))
129 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 """
cliechti41973a92009-08-06 02:18:21 +0000137 if not self._isOpen: raise portNotOpenError
cliechti41973a92009-08-06 02:18:21 +0000138 if self._timeout is not None:
139 timeout = time.time() + self._timeout
140 else:
cliechti024b4f42009-08-07 18:43:05 +0000141 timeout = None
cliechti1de32cd2009-08-07 19:05:09 +0000142 data = bytearray()
Chris Liechtia469cde2015-08-11 23:05:24 +0200143 while size > 0 and self._isOpen:
144 try:
145 data += self.queue.get(timeout=self._timeout) # XXX inter char timeout
146 except queue.Empty:
147 break
148 else:
149 size -= 1
cliechti41973a92009-08-06 02:18:21 +0000150 # check for timeout now, after data has been read.
151 # useful for timeout = 0 (non blocking) read
cliechti024b4f42009-08-07 18:43:05 +0000152 if timeout and time.time() > timeout:
cliechti41973a92009-08-06 02:18:21 +0000153 break
154 return bytes(data)
155
156 def write(self, data):
cliechti7d448562014-08-03 21:57:45 +0000157 """\
158 Output the given string over the serial port. Can block if the
cliechti41973a92009-08-06 02:18:21 +0000159 connection is blocked. May raise SerialException if the connection is
cliechti7d448562014-08-03 21:57:45 +0000160 closed.
161 """
cliechti41973a92009-08-06 02:18:21 +0000162 if not self._isOpen: raise portNotOpenError
cliechti38077122013-10-16 02:57:27 +0000163 data = to_bytes(data)
cliechti66957bf2009-08-06 23:25:37 +0000164 # calculate aprox time that would be used to send the data
165 time_used_to_send = 10.0*len(data) / self._baudrate
166 # when a write timeout is configured check if we would be successful
167 # (not sending anything, not even the part that would have time)
168 if self._writeTimeout is not None and time_used_to_send > self._writeTimeout:
169 time.sleep(self._writeTimeout) # must wait so that unit test succeeds
170 raise writeTimeoutError
Chris Liechtif99cd5c2015-08-13 22:54:16 +0200171 for byte in iterbytes(data):
Chris Liechtia469cde2015-08-11 23:05:24 +0200172 self.queue.put(byte, timeout=self._writeTimeout)
cliechti41973a92009-08-06 02:18:21 +0000173 return len(data)
174
175 def flushInput(self):
176 """Clear input buffer, discarding all that is in the buffer."""
177 if not self._isOpen: raise portNotOpenError
cliechti6a300772009-08-12 02:28:56 +0000178 if self.logger:
179 self.logger.info('flushInput()')
Chris Liechtia469cde2015-08-11 23:05:24 +0200180 try:
181 while self.queue.qsize():
182 self.queue.get_nowait()
183 except queue.Empty:
184 pass
cliechti41973a92009-08-06 02:18:21 +0000185
186 def flushOutput(self):
cliechti7d448562014-08-03 21:57:45 +0000187 """\
188 Clear output buffer, aborting the current output and
189 discarding all that is in the buffer.
190 """
cliechti41973a92009-08-06 02:18:21 +0000191 if not self._isOpen: raise portNotOpenError
cliechti6a300772009-08-12 02:28:56 +0000192 if self.logger:
193 self.logger.info('flushOutput()')
Chris Liechtia469cde2015-08-11 23:05:24 +0200194 try:
195 while self.queue.qsize():
196 self.queue.get_nowait()
197 except queue.Empty:
198 pass
cliechti41973a92009-08-06 02:18:21 +0000199
200 def sendBreak(self, duration=0.25):
cliechti7d448562014-08-03 21:57:45 +0000201 """\
202 Send break condition. Timed, returns to idle state after given
203 duration.
204 """
cliechti41973a92009-08-06 02:18:21 +0000205 if not self._isOpen: raise portNotOpenError
Chris Liechtia469cde2015-08-11 23:05:24 +0200206 time.sleep(duration)
cliechti41973a92009-08-06 02:18:21 +0000207
208 def setBreak(self, level=True):
cliechti7d448562014-08-03 21:57:45 +0000209 """\
210 Set break: Controls TXD. When active, to transmitting is
211 possible.
212 """
cliechti41973a92009-08-06 02:18:21 +0000213 if not self._isOpen: raise portNotOpenError
cliechti6a300772009-08-12 02:28:56 +0000214 if self.logger:
215 self.logger.info('setBreak(%r)' % (level,))
cliechti41973a92009-08-06 02:18:21 +0000216
217 def setRTS(self, level=True):
218 """Set terminal status line: Request To Send"""
219 if not self._isOpen: raise portNotOpenError
cliechti6a300772009-08-12 02:28:56 +0000220 if self.logger:
221 self.logger.info('setRTS(%r) -> state of CTS' % (level,))
cliechti41973a92009-08-06 02:18:21 +0000222 self.cts = level
223
224 def setDTR(self, level=True):
225 """Set terminal status line: Data Terminal Ready"""
226 if not self._isOpen: raise portNotOpenError
cliechti6a300772009-08-12 02:28:56 +0000227 if self.logger:
228 self.logger.info('setDTR(%r) -> state of DSR' % (level,))
cliechti41973a92009-08-06 02:18:21 +0000229 self.dsr = level
230
231 def getCTS(self):
232 """Read terminal status line: Clear To Send"""
233 if not self._isOpen: raise portNotOpenError
cliechti6a300772009-08-12 02:28:56 +0000234 if self.logger:
235 self.logger.info('getCTS() -> state of RTS (%r)' % (self.cts,))
cliechti41973a92009-08-06 02:18:21 +0000236 return self.cts
237
238 def getDSR(self):
239 """Read terminal status line: Data Set Ready"""
240 if not self._isOpen: raise portNotOpenError
cliechti6a300772009-08-12 02:28:56 +0000241 if self.logger:
242 self.logger.info('getDSR() -> state of DTR (%r)' % (self.dsr,))
cliechti41973a92009-08-06 02:18:21 +0000243 return self.dsr
244
245 def getRI(self):
246 """Read terminal status line: Ring Indicator"""
247 if not self._isOpen: raise portNotOpenError
cliechti6a300772009-08-12 02:28:56 +0000248 if self.logger:
249 self.logger.info('returning dummy for getRI()')
cliechti41973a92009-08-06 02:18:21 +0000250 return False
251
252 def getCD(self):
253 """Read terminal status line: Carrier Detect"""
254 if not self._isOpen: raise portNotOpenError
cliechti6a300772009-08-12 02:28:56 +0000255 if self.logger:
256 self.logger.info('returning dummy for getCD()')
cliechti41973a92009-08-06 02:18:21 +0000257 return True
258
259 # - - - platform specific - - -
260 # None so far
261
262
cliechti41973a92009-08-06 02:18:21 +0000263# simple client test
264if __name__ == '__main__':
265 import sys
cliechtiab3d4282011-08-19 01:52:46 +0000266 s = Serial('loop://')
cliechti41973a92009-08-06 02:18:21 +0000267 sys.stdout.write('%s\n' % s)
268
269 sys.stdout.write("write...\n")
270 s.write("hello\n")
271 s.flush()
272 sys.stdout.write("read: %s\n" % s.read(5))
273
274 s.close()