blob: 05a21cdd8f98b7825622c45c8d172e408efbc53b [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#
cliechti2a6d5332011-03-04 02:08:32 +000011# (C) 2001-2011 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
17
cliechti2a6d5332011-03-04 02:08:32 +000018from serial.serialutil import *
cliechti41973a92009-08-06 02:18:21 +000019import threading
20import time
cliechtic64ba692009-08-12 00:32:47 +000021import logging
22
23# map log level names to constants. used in fromURL()
24LOGGER_LEVELS = {
25 'debug': logging.DEBUG,
26 'info': logging.INFO,
27 'warning': logging.WARNING,
28 'error': logging.ERROR,
29 }
30
cliechti41973a92009-08-06 02:18:21 +000031
Chris Liechtief6b7b42015-08-06 22:19:26 +020032class Serial(SerialBase):
cliechtiab3d4282011-08-19 01:52:46 +000033 """Serial port implementation that simulates a loop back connection in plain software."""
cliechti41973a92009-08-06 02:18:21 +000034
35 BAUDRATES = (50, 75, 110, 134, 150, 200, 300, 600, 1200, 1800, 2400, 4800,
36 9600, 19200, 38400, 57600, 115200)
37
38 def open(self):
cliechti7d448562014-08-03 21:57:45 +000039 """\
40 Open port with current settings. This may throw a SerialException
41 if the port cannot be opened.
42 """
cliechti8f69e702011-03-19 00:22:32 +000043 if self._isOpen:
44 raise SerialException("Port is already open.")
cliechti6a300772009-08-12 02:28:56 +000045 self.logger = None
cliechti41973a92009-08-06 02:18:21 +000046 self.buffer_lock = threading.Lock()
47 self.loop_buffer = bytearray()
48 self.cts = False
49 self.dsr = False
50
51 if self._port is None:
52 raise SerialException("Port must be configured before it can be used.")
53 # not that there is anything to open, but the function applies the
54 # options found in the URL
55 self.fromURL(self.port)
56
57 # not that there anything to configure...
58 self._reconfigurePort()
59 # all things set up get, now a clean start
60 self._isOpen = True
61 if not self._rtscts:
62 self.setRTS(True)
63 self.setDTR(True)
64 self.flushInput()
65 self.flushOutput()
66
67 def _reconfigurePort(self):
cliechti7d448562014-08-03 21:57:45 +000068 """\
69 Set communication parameters on opened port. For the loop://
70 protocol all settings are ignored!
71 """
cliechti41973a92009-08-06 02:18:21 +000072 # not that's it of any real use, but it helps in the unit tests
73 if not isinstance(self._baudrate, (int, long)) or not 0 < self._baudrate < 2**32:
74 raise ValueError("invalid baudrate: %r" % (self._baudrate))
cliechti6a300772009-08-12 02:28:56 +000075 if self.logger:
76 self.logger.info('_reconfigurePort()')
cliechti41973a92009-08-06 02:18:21 +000077
78 def close(self):
79 """Close port"""
80 if self._isOpen:
81 self._isOpen = False
82 # in case of quick reconnects, give the server some time
83 time.sleep(0.3)
84
85 def makeDeviceName(self, port):
86 raise SerialException("there is no sensible way to turn numbers into URLs")
87
88 def fromURL(self, url):
89 """extract host and port from an URL string"""
90 if url.lower().startswith("loop://"): url = url[7:]
91 try:
92 # process options now, directly altering self
93 for option in url.split('/'):
cliechtic64ba692009-08-12 00:32:47 +000094 if '=' in option:
95 option, value = option.split('=', 1)
96 else:
97 value = None
cliechti641c4bb2009-08-12 02:34:19 +000098 if not option:
99 pass
100 elif option == 'logging':
cliechtic64ba692009-08-12 00:32:47 +0000101 logging.basicConfig() # XXX is that good to call it here?
cliechti6a300772009-08-12 02:28:56 +0000102 self.logger = logging.getLogger('pySerial.loop')
103 self.logger.setLevel(LOGGER_LEVELS[value])
104 self.logger.debug('enabled logging')
cliechti41973a92009-08-06 02:18:21 +0000105 else:
106 raise ValueError('unknown option: %r' % (option,))
Chris Liechti68340d72015-08-03 14:15:48 +0200107 except ValueError as e:
cliechti41973a92009-08-06 02:18:21 +0000108 raise SerialException('expected a string in the form "[loop://][option[/option...]]": %s' % e)
109
110 # - - - - - - - - - - - - - - - - - - - - - - - -
111
112 def inWaiting(self):
113 """Return the number of characters currently in the input buffer."""
114 if not self._isOpen: raise portNotOpenError
cliechti6a300772009-08-12 02:28:56 +0000115 if self.logger:
cliechtic64ba692009-08-12 00:32:47 +0000116 # attention the logged value can differ from return value in
117 # threaded environments...
cliechti6a300772009-08-12 02:28:56 +0000118 self.logger.debug('inWaiting() -> %d' % (len(self.loop_buffer),))
cliechti41973a92009-08-06 02:18:21 +0000119 return len(self.loop_buffer)
120
121 def read(self, size=1):
cliechti7d448562014-08-03 21:57:45 +0000122 """\
123 Read size bytes from the serial port. If a timeout is set it may
cliechti41973a92009-08-06 02:18:21 +0000124 return less characters as requested. With no timeout it will block
cliechti7d448562014-08-03 21:57:45 +0000125 until the requested number of bytes is read.
126 """
cliechti41973a92009-08-06 02:18:21 +0000127 if not self._isOpen: raise portNotOpenError
cliechti41973a92009-08-06 02:18:21 +0000128 if self._timeout is not None:
129 timeout = time.time() + self._timeout
130 else:
cliechti024b4f42009-08-07 18:43:05 +0000131 timeout = None
cliechti1de32cd2009-08-07 19:05:09 +0000132 data = bytearray()
cliechtifb2306b2011-08-18 22:46:57 +0000133 while size > 0:
cliechti41973a92009-08-06 02:18:21 +0000134 self.buffer_lock.acquire()
135 try:
cliechti1de32cd2009-08-07 19:05:09 +0000136 block = to_bytes(self.loop_buffer[:size])
cliechti41973a92009-08-06 02:18:21 +0000137 del self.loop_buffer[:size]
138 finally:
139 self.buffer_lock.release()
140 data += block
cliechtifb2306b2011-08-18 22:46:57 +0000141 size -= len(block)
cliechti41973a92009-08-06 02:18:21 +0000142 # check for timeout now, after data has been read.
143 # useful for timeout = 0 (non blocking) read
cliechti024b4f42009-08-07 18:43:05 +0000144 if timeout and time.time() > timeout:
cliechti41973a92009-08-06 02:18:21 +0000145 break
146 return bytes(data)
147
148 def write(self, data):
cliechti7d448562014-08-03 21:57:45 +0000149 """\
150 Output the given string over the serial port. Can block if the
cliechti41973a92009-08-06 02:18:21 +0000151 connection is blocked. May raise SerialException if the connection is
cliechti7d448562014-08-03 21:57:45 +0000152 closed.
153 """
cliechti41973a92009-08-06 02:18:21 +0000154 if not self._isOpen: raise portNotOpenError
cliechtifb2306b2011-08-18 22:46:57 +0000155 # ensure we're working with bytes
cliechti38077122013-10-16 02:57:27 +0000156 data = to_bytes(data)
cliechti66957bf2009-08-06 23:25:37 +0000157 # calculate aprox time that would be used to send the data
158 time_used_to_send = 10.0*len(data) / self._baudrate
159 # when a write timeout is configured check if we would be successful
160 # (not sending anything, not even the part that would have time)
161 if self._writeTimeout is not None and time_used_to_send > self._writeTimeout:
162 time.sleep(self._writeTimeout) # must wait so that unit test succeeds
163 raise writeTimeoutError
cliechti41973a92009-08-06 02:18:21 +0000164 self.buffer_lock.acquire()
165 try:
cliechtifb2306b2011-08-18 22:46:57 +0000166 self.loop_buffer += data
cliechti41973a92009-08-06 02:18:21 +0000167 finally:
168 self.buffer_lock.release()
169 return len(data)
170
171 def flushInput(self):
172 """Clear input buffer, discarding all that is in the buffer."""
173 if not self._isOpen: raise portNotOpenError
cliechti6a300772009-08-12 02:28:56 +0000174 if self.logger:
175 self.logger.info('flushInput()')
cliechti41973a92009-08-06 02:18:21 +0000176 self.buffer_lock.acquire()
177 try:
178 del self.loop_buffer[:]
179 finally:
180 self.buffer_lock.release()
181
182 def flushOutput(self):
cliechti7d448562014-08-03 21:57:45 +0000183 """\
184 Clear output buffer, aborting the current output and
185 discarding all that is in the buffer.
186 """
cliechti41973a92009-08-06 02:18:21 +0000187 if not self._isOpen: raise portNotOpenError
cliechti6a300772009-08-12 02:28:56 +0000188 if self.logger:
189 self.logger.info('flushOutput()')
cliechti41973a92009-08-06 02:18:21 +0000190
191 def sendBreak(self, duration=0.25):
cliechti7d448562014-08-03 21:57:45 +0000192 """\
193 Send break condition. Timed, returns to idle state after given
194 duration.
195 """
cliechti41973a92009-08-06 02:18:21 +0000196 if not self._isOpen: raise portNotOpenError
197
198 def setBreak(self, level=True):
cliechti7d448562014-08-03 21:57:45 +0000199 """\
200 Set break: Controls TXD. When active, to transmitting is
201 possible.
202 """
cliechti41973a92009-08-06 02:18:21 +0000203 if not self._isOpen: raise portNotOpenError
cliechti6a300772009-08-12 02:28:56 +0000204 if self.logger:
205 self.logger.info('setBreak(%r)' % (level,))
cliechti41973a92009-08-06 02:18:21 +0000206
207 def setRTS(self, level=True):
208 """Set terminal status line: Request To Send"""
209 if not self._isOpen: raise portNotOpenError
cliechti6a300772009-08-12 02:28:56 +0000210 if self.logger:
211 self.logger.info('setRTS(%r) -> state of CTS' % (level,))
cliechti41973a92009-08-06 02:18:21 +0000212 self.cts = level
213
214 def setDTR(self, level=True):
215 """Set terminal status line: Data Terminal Ready"""
216 if not self._isOpen: raise portNotOpenError
cliechti6a300772009-08-12 02:28:56 +0000217 if self.logger:
218 self.logger.info('setDTR(%r) -> state of DSR' % (level,))
cliechti41973a92009-08-06 02:18:21 +0000219 self.dsr = level
220
221 def getCTS(self):
222 """Read terminal status line: Clear To Send"""
223 if not self._isOpen: raise portNotOpenError
cliechti6a300772009-08-12 02:28:56 +0000224 if self.logger:
225 self.logger.info('getCTS() -> state of RTS (%r)' % (self.cts,))
cliechti41973a92009-08-06 02:18:21 +0000226 return self.cts
227
228 def getDSR(self):
229 """Read terminal status line: Data Set Ready"""
230 if not self._isOpen: raise portNotOpenError
cliechti6a300772009-08-12 02:28:56 +0000231 if self.logger:
232 self.logger.info('getDSR() -> state of DTR (%r)' % (self.dsr,))
cliechti41973a92009-08-06 02:18:21 +0000233 return self.dsr
234
235 def getRI(self):
236 """Read terminal status line: Ring Indicator"""
237 if not self._isOpen: raise portNotOpenError
cliechti6a300772009-08-12 02:28:56 +0000238 if self.logger:
239 self.logger.info('returning dummy for getRI()')
cliechti41973a92009-08-06 02:18:21 +0000240 return False
241
242 def getCD(self):
243 """Read terminal status line: Carrier Detect"""
244 if not self._isOpen: raise portNotOpenError
cliechti6a300772009-08-12 02:28:56 +0000245 if self.logger:
246 self.logger.info('returning dummy for getCD()')
cliechti41973a92009-08-06 02:18:21 +0000247 return True
248
249 # - - - platform specific - - -
250 # None so far
251
252
cliechti41973a92009-08-06 02:18:21 +0000253# simple client test
254if __name__ == '__main__':
255 import sys
cliechtiab3d4282011-08-19 01:52:46 +0000256 s = Serial('loop://')
cliechti41973a92009-08-06 02:18:21 +0000257 sys.stdout.write('%s\n' % s)
258
259 sys.stdout.write("write...\n")
260 s.write("hello\n")
261 s.flush()
262 sys.stdout.write("read: %s\n" % s.read(5))
263
264 s.close()