blob: 756704bcdabe47741df3a99be277c07f963ddfef [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
26
27from serial.serialutil import *
cliechtic64ba692009-08-12 00:32:47 +000028
29# map log level names to constants. used in fromURL()
30LOGGER_LEVELS = {
Chris Liechtic4bca9e2015-08-07 14:40:41 +020031 'debug': logging.DEBUG,
32 'info': logging.INFO,
33 'warning': logging.WARNING,
34 'error': logging.ERROR,
35 }
cliechtic64ba692009-08-12 00:32:47 +000036
cliechti41973a92009-08-06 02:18:21 +000037
Chris Liechtief6b7b42015-08-06 22:19:26 +020038class Serial(SerialBase):
cliechtiab3d4282011-08-19 01:52:46 +000039 """Serial port implementation that simulates a loop back connection in plain software."""
cliechti41973a92009-08-06 02:18:21 +000040
41 BAUDRATES = (50, 75, 110, 134, 150, 200, 300, 600, 1200, 1800, 2400, 4800,
42 9600, 19200, 38400, 57600, 115200)
43
44 def open(self):
cliechti7d448562014-08-03 21:57:45 +000045 """\
46 Open port with current settings. This may throw a SerialException
47 if the port cannot be opened.
48 """
cliechti8f69e702011-03-19 00:22:32 +000049 if self._isOpen:
50 raise SerialException("Port is already open.")
cliechti6a300772009-08-12 02:28:56 +000051 self.logger = None
cliechti41973a92009-08-06 02:18:21 +000052 self.buffer_lock = threading.Lock()
53 self.loop_buffer = bytearray()
54 self.cts = False
55 self.dsr = False
56
57 if self._port is None:
58 raise SerialException("Port must be configured before it can be used.")
59 # not that there is anything to open, but the function applies the
60 # options found in the URL
61 self.fromURL(self.port)
62
63 # not that there anything to configure...
64 self._reconfigurePort()
65 # all things set up get, now a clean start
66 self._isOpen = True
67 if not self._rtscts:
68 self.setRTS(True)
69 self.setDTR(True)
70 self.flushInput()
71 self.flushOutput()
72
73 def _reconfigurePort(self):
cliechti7d448562014-08-03 21:57:45 +000074 """\
75 Set communication parameters on opened port. For the loop://
76 protocol all settings are ignored!
77 """
cliechti41973a92009-08-06 02:18:21 +000078 # not that's it of any real use, but it helps in the unit tests
Chris Liechtic4bca9e2015-08-07 14:40:41 +020079 if not isinstance(self._baudrate, numbers.Integral) or not 0 < self._baudrate < 2**32:
cliechti41973a92009-08-06 02:18:21 +000080 raise ValueError("invalid baudrate: %r" % (self._baudrate))
cliechti6a300772009-08-12 02:28:56 +000081 if self.logger:
82 self.logger.info('_reconfigurePort()')
cliechti41973a92009-08-06 02:18:21 +000083
84 def close(self):
85 """Close port"""
86 if self._isOpen:
87 self._isOpen = False
88 # in case of quick reconnects, give the server some time
89 time.sleep(0.3)
90
91 def makeDeviceName(self, port):
92 raise SerialException("there is no sensible way to turn numbers into URLs")
93
94 def fromURL(self, url):
95 """extract host and port from an URL string"""
Chris Liechtic4bca9e2015-08-07 14:40:41 +020096 parts = urlparse.urlsplit(url)
97 if parts.scheme.lower() != "loop":
98 raise SerialException('expected a string in the form "loop://[option[/option...]]": not starting with loop:// (%r)' % (parts.scheme,))
cliechti41973a92009-08-06 02:18:21 +000099 try:
100 # process options now, directly altering self
Chris Liechtic4bca9e2015-08-07 14:40:41 +0200101 for option in parts.path.split('/'):
cliechtic64ba692009-08-12 00:32:47 +0000102 if '=' in option:
103 option, value = option.split('=', 1)
104 else:
105 value = None
cliechti641c4bb2009-08-12 02:34:19 +0000106 if not option:
107 pass
108 elif 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')
111 self.logger.setLevel(LOGGER_LEVELS[value])
112 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:
cliechti41973a92009-08-06 02:18:21 +0000116 raise SerialException('expected a string in the form "[loop://][option[/option...]]": %s' % e)
117
118 # - - - - - - - - - - - - - - - - - - - - - - - -
119
120 def inWaiting(self):
121 """Return the number of characters currently in the input buffer."""
122 if not self._isOpen: 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...
cliechti6a300772009-08-12 02:28:56 +0000126 self.logger.debug('inWaiting() -> %d' % (len(self.loop_buffer),))
cliechti41973a92009-08-06 02:18:21 +0000127 return len(self.loop_buffer)
128
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 """
cliechti41973a92009-08-06 02:18:21 +0000135 if not self._isOpen: raise portNotOpenError
cliechti41973a92009-08-06 02:18:21 +0000136 if self._timeout is not None:
137 timeout = time.time() + self._timeout
138 else:
cliechti024b4f42009-08-07 18:43:05 +0000139 timeout = None
cliechti1de32cd2009-08-07 19:05:09 +0000140 data = bytearray()
cliechtifb2306b2011-08-18 22:46:57 +0000141 while size > 0:
Chris Liechtic4bca9e2015-08-07 14:40:41 +0200142 with self.buffer_lock:
cliechti1de32cd2009-08-07 19:05:09 +0000143 block = to_bytes(self.loop_buffer[:size])
cliechti41973a92009-08-06 02:18:21 +0000144 del self.loop_buffer[:size]
cliechti41973a92009-08-06 02:18:21 +0000145 data += block
cliechtifb2306b2011-08-18 22:46:57 +0000146 size -= len(block)
cliechti41973a92009-08-06 02:18:21 +0000147 # check for timeout now, after data has been read.
148 # useful for timeout = 0 (non blocking) read
cliechti024b4f42009-08-07 18:43:05 +0000149 if timeout and time.time() > timeout:
cliechti41973a92009-08-06 02:18:21 +0000150 break
151 return bytes(data)
152
153 def write(self, data):
cliechti7d448562014-08-03 21:57:45 +0000154 """\
155 Output the given string over the serial port. Can block if the
cliechti41973a92009-08-06 02:18:21 +0000156 connection is blocked. May raise SerialException if the connection is
cliechti7d448562014-08-03 21:57:45 +0000157 closed.
158 """
cliechti41973a92009-08-06 02:18:21 +0000159 if not self._isOpen: raise portNotOpenError
cliechtifb2306b2011-08-18 22:46:57 +0000160 # ensure we're working with bytes
cliechti38077122013-10-16 02:57:27 +0000161 data = to_bytes(data)
cliechti66957bf2009-08-06 23:25:37 +0000162 # calculate aprox time that would be used to send the data
163 time_used_to_send = 10.0*len(data) / self._baudrate
164 # when a write timeout is configured check if we would be successful
165 # (not sending anything, not even the part that would have time)
166 if self._writeTimeout is not None and time_used_to_send > self._writeTimeout:
167 time.sleep(self._writeTimeout) # must wait so that unit test succeeds
168 raise writeTimeoutError
Chris Liechtic4bca9e2015-08-07 14:40:41 +0200169 with self.buffer_lock:
cliechtifb2306b2011-08-18 22:46:57 +0000170 self.loop_buffer += data
cliechti41973a92009-08-06 02:18:21 +0000171 return len(data)
172
173 def flushInput(self):
174 """Clear input buffer, discarding all that is in the buffer."""
175 if not self._isOpen: raise portNotOpenError
cliechti6a300772009-08-12 02:28:56 +0000176 if self.logger:
177 self.logger.info('flushInput()')
Chris Liechtic4bca9e2015-08-07 14:40:41 +0200178 with self.buffer_lock:
cliechti41973a92009-08-06 02:18:21 +0000179 del self.loop_buffer[:]
cliechti41973a92009-08-06 02:18:21 +0000180
181 def flushOutput(self):
cliechti7d448562014-08-03 21:57:45 +0000182 """\
183 Clear output buffer, aborting the current output and
184 discarding all that is in the buffer.
185 """
cliechti41973a92009-08-06 02:18:21 +0000186 if not self._isOpen: raise portNotOpenError
cliechti6a300772009-08-12 02:28:56 +0000187 if self.logger:
188 self.logger.info('flushOutput()')
cliechti41973a92009-08-06 02:18:21 +0000189
190 def sendBreak(self, duration=0.25):
cliechti7d448562014-08-03 21:57:45 +0000191 """\
192 Send break condition. Timed, returns to idle state after given
193 duration.
194 """
cliechti41973a92009-08-06 02:18:21 +0000195 if not self._isOpen: raise portNotOpenError
196
197 def setBreak(self, level=True):
cliechti7d448562014-08-03 21:57:45 +0000198 """\
199 Set break: Controls TXD. When active, to transmitting is
200 possible.
201 """
cliechti41973a92009-08-06 02:18:21 +0000202 if not self._isOpen: raise portNotOpenError
cliechti6a300772009-08-12 02:28:56 +0000203 if self.logger:
204 self.logger.info('setBreak(%r)' % (level,))
cliechti41973a92009-08-06 02:18:21 +0000205
206 def setRTS(self, level=True):
207 """Set terminal status line: Request To Send"""
208 if not self._isOpen: raise portNotOpenError
cliechti6a300772009-08-12 02:28:56 +0000209 if self.logger:
210 self.logger.info('setRTS(%r) -> state of CTS' % (level,))
cliechti41973a92009-08-06 02:18:21 +0000211 self.cts = level
212
213 def setDTR(self, level=True):
214 """Set terminal status line: Data Terminal Ready"""
215 if not self._isOpen: raise portNotOpenError
cliechti6a300772009-08-12 02:28:56 +0000216 if self.logger:
217 self.logger.info('setDTR(%r) -> state of DSR' % (level,))
cliechti41973a92009-08-06 02:18:21 +0000218 self.dsr = level
219
220 def getCTS(self):
221 """Read terminal status line: Clear To Send"""
222 if not self._isOpen: raise portNotOpenError
cliechti6a300772009-08-12 02:28:56 +0000223 if self.logger:
224 self.logger.info('getCTS() -> state of RTS (%r)' % (self.cts,))
cliechti41973a92009-08-06 02:18:21 +0000225 return self.cts
226
227 def getDSR(self):
228 """Read terminal status line: Data Set Ready"""
229 if not self._isOpen: raise portNotOpenError
cliechti6a300772009-08-12 02:28:56 +0000230 if self.logger:
231 self.logger.info('getDSR() -> state of DTR (%r)' % (self.dsr,))
cliechti41973a92009-08-06 02:18:21 +0000232 return self.dsr
233
234 def getRI(self):
235 """Read terminal status line: Ring Indicator"""
236 if not self._isOpen: raise portNotOpenError
cliechti6a300772009-08-12 02:28:56 +0000237 if self.logger:
238 self.logger.info('returning dummy for getRI()')
cliechti41973a92009-08-06 02:18:21 +0000239 return False
240
241 def getCD(self):
242 """Read terminal status line: Carrier Detect"""
243 if not self._isOpen: raise portNotOpenError
cliechti6a300772009-08-12 02:28:56 +0000244 if self.logger:
245 self.logger.info('returning dummy for getCD()')
cliechti41973a92009-08-06 02:18:21 +0000246 return True
247
248 # - - - platform specific - - -
249 # None so far
250
251
cliechti41973a92009-08-06 02:18:21 +0000252# simple client test
253if __name__ == '__main__':
254 import sys
cliechtiab3d4282011-08-19 01:52:46 +0000255 s = Serial('loop://')
cliechti41973a92009-08-06 02:18:21 +0000256 sys.stdout.write('%s\n' % s)
257
258 sys.stdout.write("write...\n")
259 s.write("hello\n")
260 s.flush()
261 sys.stdout.write("read: %s\n" % s.read(5))
262
263 s.close()