blob: 6883b4c0a896537169021191cae6474dab4ffd79 [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>
cliechti41973a92009-08-06 02:18:21 +000012# this is distributed under a free software license, see license.txt
13#
14# URL format: loop://[option[/option...]]
15# options:
16# - "debug" print diagnostic messages
Chris Liechtic4bca9e2015-08-07 14:40:41 +020017import logging
18import numbers
cliechti41973a92009-08-06 02:18:21 +000019import threading
20import time
Chris Liechtic4bca9e2015-08-07 14:40:41 +020021try:
22 import urlparse
23except ImportError:
24 import urllib.parse as urlparse
25
26from serial.serialutil import *
cliechtic64ba692009-08-12 00:32:47 +000027
28# map log level names to constants. used in fromURL()
29LOGGER_LEVELS = {
Chris Liechtic4bca9e2015-08-07 14:40:41 +020030 'debug': logging.DEBUG,
31 'info': logging.INFO,
32 'warning': logging.WARNING,
33 'error': logging.ERROR,
34 }
cliechtic64ba692009-08-12 00:32:47 +000035
cliechti41973a92009-08-06 02:18:21 +000036
Chris Liechtief6b7b42015-08-06 22:19:26 +020037class Serial(SerialBase):
cliechtiab3d4282011-08-19 01:52:46 +000038 """Serial port implementation that simulates a loop back connection in plain software."""
cliechti41973a92009-08-06 02:18:21 +000039
40 BAUDRATES = (50, 75, 110, 134, 150, 200, 300, 600, 1200, 1800, 2400, 4800,
41 9600, 19200, 38400, 57600, 115200)
42
43 def open(self):
cliechti7d448562014-08-03 21:57:45 +000044 """\
45 Open port with current settings. This may throw a SerialException
46 if the port cannot be opened.
47 """
cliechti8f69e702011-03-19 00:22:32 +000048 if self._isOpen:
49 raise SerialException("Port is already open.")
cliechti6a300772009-08-12 02:28:56 +000050 self.logger = None
cliechti41973a92009-08-06 02:18:21 +000051 self.buffer_lock = threading.Lock()
52 self.loop_buffer = bytearray()
53 self.cts = False
54 self.dsr = False
55
56 if self._port is None:
57 raise SerialException("Port must be configured before it can be used.")
58 # not that there is anything to open, but the function applies the
59 # options found in the URL
60 self.fromURL(self.port)
61
62 # not that there anything to configure...
63 self._reconfigurePort()
64 # all things set up get, now a clean start
65 self._isOpen = True
66 if not self._rtscts:
67 self.setRTS(True)
68 self.setDTR(True)
69 self.flushInput()
70 self.flushOutput()
71
72 def _reconfigurePort(self):
cliechti7d448562014-08-03 21:57:45 +000073 """\
74 Set communication parameters on opened port. For the loop://
75 protocol all settings are ignored!
76 """
cliechti41973a92009-08-06 02:18:21 +000077 # not that's it of any real use, but it helps in the unit tests
Chris Liechtic4bca9e2015-08-07 14:40:41 +020078 if not isinstance(self._baudrate, numbers.Integral) or not 0 < self._baudrate < 2**32:
cliechti41973a92009-08-06 02:18:21 +000079 raise ValueError("invalid baudrate: %r" % (self._baudrate))
cliechti6a300772009-08-12 02:28:56 +000080 if self.logger:
81 self.logger.info('_reconfigurePort()')
cliechti41973a92009-08-06 02:18:21 +000082
83 def close(self):
84 """Close port"""
85 if self._isOpen:
86 self._isOpen = False
87 # in case of quick reconnects, give the server some time
88 time.sleep(0.3)
89
90 def makeDeviceName(self, port):
91 raise SerialException("there is no sensible way to turn numbers into URLs")
92
93 def fromURL(self, url):
94 """extract host and port from an URL string"""
Chris Liechtic4bca9e2015-08-07 14:40:41 +020095 parts = urlparse.urlsplit(url)
96 if parts.scheme.lower() != "loop":
97 raise SerialException('expected a string in the form "loop://[option[/option...]]": not starting with loop:// (%r)' % (parts.scheme,))
cliechti41973a92009-08-06 02:18:21 +000098 try:
99 # process options now, directly altering self
Chris Liechtic4bca9e2015-08-07 14:40:41 +0200100 for option in parts.path.split('/'):
cliechtic64ba692009-08-12 00:32:47 +0000101 if '=' in option:
102 option, value = option.split('=', 1)
103 else:
104 value = None
cliechti641c4bb2009-08-12 02:34:19 +0000105 if not option:
106 pass
107 elif option == 'logging':
cliechtic64ba692009-08-12 00:32:47 +0000108 logging.basicConfig() # XXX is that good to call it here?
cliechti6a300772009-08-12 02:28:56 +0000109 self.logger = logging.getLogger('pySerial.loop')
110 self.logger.setLevel(LOGGER_LEVELS[value])
111 self.logger.debug('enabled logging')
cliechti41973a92009-08-06 02:18:21 +0000112 else:
113 raise ValueError('unknown option: %r' % (option,))
Chris Liechti68340d72015-08-03 14:15:48 +0200114 except ValueError as e:
cliechti41973a92009-08-06 02:18:21 +0000115 raise SerialException('expected a string in the form "[loop://][option[/option...]]": %s' % e)
116
117 # - - - - - - - - - - - - - - - - - - - - - - - -
118
119 def inWaiting(self):
120 """Return the number of characters currently in the input buffer."""
121 if not self._isOpen: raise portNotOpenError
cliechti6a300772009-08-12 02:28:56 +0000122 if self.logger:
cliechtic64ba692009-08-12 00:32:47 +0000123 # attention the logged value can differ from return value in
124 # threaded environments...
cliechti6a300772009-08-12 02:28:56 +0000125 self.logger.debug('inWaiting() -> %d' % (len(self.loop_buffer),))
cliechti41973a92009-08-06 02:18:21 +0000126 return len(self.loop_buffer)
127
128 def read(self, size=1):
cliechti7d448562014-08-03 21:57:45 +0000129 """\
130 Read size bytes from the serial port. If a timeout is set it may
cliechti41973a92009-08-06 02:18:21 +0000131 return less characters as requested. With no timeout it will block
cliechti7d448562014-08-03 21:57:45 +0000132 until the requested number of bytes is read.
133 """
cliechti41973a92009-08-06 02:18:21 +0000134 if not self._isOpen: raise portNotOpenError
cliechti41973a92009-08-06 02:18:21 +0000135 if self._timeout is not None:
136 timeout = time.time() + self._timeout
137 else:
cliechti024b4f42009-08-07 18:43:05 +0000138 timeout = None
cliechti1de32cd2009-08-07 19:05:09 +0000139 data = bytearray()
cliechtifb2306b2011-08-18 22:46:57 +0000140 while size > 0:
Chris Liechtic4bca9e2015-08-07 14:40:41 +0200141 with self.buffer_lock:
cliechti1de32cd2009-08-07 19:05:09 +0000142 block = to_bytes(self.loop_buffer[:size])
cliechti41973a92009-08-06 02:18:21 +0000143 del self.loop_buffer[:size]
cliechti41973a92009-08-06 02:18:21 +0000144 data += block
cliechtifb2306b2011-08-18 22:46:57 +0000145 size -= len(block)
cliechti41973a92009-08-06 02:18:21 +0000146 # check for timeout now, after data has been read.
147 # useful for timeout = 0 (non blocking) read
cliechti024b4f42009-08-07 18:43:05 +0000148 if timeout and time.time() > timeout:
cliechti41973a92009-08-06 02:18:21 +0000149 break
150 return bytes(data)
151
152 def write(self, data):
cliechti7d448562014-08-03 21:57:45 +0000153 """\
154 Output the given string over the serial port. Can block if the
cliechti41973a92009-08-06 02:18:21 +0000155 connection is blocked. May raise SerialException if the connection is
cliechti7d448562014-08-03 21:57:45 +0000156 closed.
157 """
cliechti41973a92009-08-06 02:18:21 +0000158 if not self._isOpen: raise portNotOpenError
cliechtifb2306b2011-08-18 22:46:57 +0000159 # ensure we're working with bytes
cliechti38077122013-10-16 02:57:27 +0000160 data = to_bytes(data)
cliechti66957bf2009-08-06 23:25:37 +0000161 # calculate aprox time that would be used to send the data
162 time_used_to_send = 10.0*len(data) / self._baudrate
163 # when a write timeout is configured check if we would be successful
164 # (not sending anything, not even the part that would have time)
165 if self._writeTimeout is not None and time_used_to_send > self._writeTimeout:
166 time.sleep(self._writeTimeout) # must wait so that unit test succeeds
167 raise writeTimeoutError
Chris Liechtic4bca9e2015-08-07 14:40:41 +0200168 with self.buffer_lock:
cliechtifb2306b2011-08-18 22:46:57 +0000169 self.loop_buffer += data
cliechti41973a92009-08-06 02:18:21 +0000170 return len(data)
171
172 def flushInput(self):
173 """Clear input buffer, discarding all that is in the buffer."""
174 if not self._isOpen: raise portNotOpenError
cliechti6a300772009-08-12 02:28:56 +0000175 if self.logger:
176 self.logger.info('flushInput()')
Chris Liechtic4bca9e2015-08-07 14:40:41 +0200177 with self.buffer_lock:
cliechti41973a92009-08-06 02:18:21 +0000178 del self.loop_buffer[:]
cliechti41973a92009-08-06 02:18:21 +0000179
180 def flushOutput(self):
cliechti7d448562014-08-03 21:57:45 +0000181 """\
182 Clear output buffer, aborting the current output and
183 discarding all that is in the buffer.
184 """
cliechti41973a92009-08-06 02:18:21 +0000185 if not self._isOpen: raise portNotOpenError
cliechti6a300772009-08-12 02:28:56 +0000186 if self.logger:
187 self.logger.info('flushOutput()')
cliechti41973a92009-08-06 02:18:21 +0000188
189 def sendBreak(self, duration=0.25):
cliechti7d448562014-08-03 21:57:45 +0000190 """\
191 Send break condition. Timed, returns to idle state after given
192 duration.
193 """
cliechti41973a92009-08-06 02:18:21 +0000194 if not self._isOpen: raise portNotOpenError
195
196 def setBreak(self, level=True):
cliechti7d448562014-08-03 21:57:45 +0000197 """\
198 Set break: Controls TXD. When active, to transmitting is
199 possible.
200 """
cliechti41973a92009-08-06 02:18:21 +0000201 if not self._isOpen: raise portNotOpenError
cliechti6a300772009-08-12 02:28:56 +0000202 if self.logger:
203 self.logger.info('setBreak(%r)' % (level,))
cliechti41973a92009-08-06 02:18:21 +0000204
205 def setRTS(self, level=True):
206 """Set terminal status line: Request To Send"""
207 if not self._isOpen: raise portNotOpenError
cliechti6a300772009-08-12 02:28:56 +0000208 if self.logger:
209 self.logger.info('setRTS(%r) -> state of CTS' % (level,))
cliechti41973a92009-08-06 02:18:21 +0000210 self.cts = level
211
212 def setDTR(self, level=True):
213 """Set terminal status line: Data Terminal Ready"""
214 if not self._isOpen: raise portNotOpenError
cliechti6a300772009-08-12 02:28:56 +0000215 if self.logger:
216 self.logger.info('setDTR(%r) -> state of DSR' % (level,))
cliechti41973a92009-08-06 02:18:21 +0000217 self.dsr = level
218
219 def getCTS(self):
220 """Read terminal status line: Clear To Send"""
221 if not self._isOpen: raise portNotOpenError
cliechti6a300772009-08-12 02:28:56 +0000222 if self.logger:
223 self.logger.info('getCTS() -> state of RTS (%r)' % (self.cts,))
cliechti41973a92009-08-06 02:18:21 +0000224 return self.cts
225
226 def getDSR(self):
227 """Read terminal status line: Data Set Ready"""
228 if not self._isOpen: raise portNotOpenError
cliechti6a300772009-08-12 02:28:56 +0000229 if self.logger:
230 self.logger.info('getDSR() -> state of DTR (%r)' % (self.dsr,))
cliechti41973a92009-08-06 02:18:21 +0000231 return self.dsr
232
233 def getRI(self):
234 """Read terminal status line: Ring Indicator"""
235 if not self._isOpen: raise portNotOpenError
cliechti6a300772009-08-12 02:28:56 +0000236 if self.logger:
237 self.logger.info('returning dummy for getRI()')
cliechti41973a92009-08-06 02:18:21 +0000238 return False
239
240 def getCD(self):
241 """Read terminal status line: Carrier Detect"""
242 if not self._isOpen: raise portNotOpenError
cliechti6a300772009-08-12 02:28:56 +0000243 if self.logger:
244 self.logger.info('returning dummy for getCD()')
cliechti41973a92009-08-06 02:18:21 +0000245 return True
246
247 # - - - platform specific - - -
248 # None so far
249
250
cliechti41973a92009-08-06 02:18:21 +0000251# simple client test
252if __name__ == '__main__':
253 import sys
cliechtiab3d4282011-08-19 01:52:46 +0000254 s = Serial('loop://')
cliechti41973a92009-08-06 02:18:21 +0000255 sys.stdout.write('%s\n' % s)
256
257 sys.stdout.write("write...\n")
258 s.write("hello\n")
259 s.flush()
260 sys.stdout.write("read: %s\n" % s.read(5))
261
262 s.close()