cliechti | 41973a9 | 2009-08-06 02:18:21 +0000 | [diff] [blame] | 1 | #! 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 Liechti | c4bca9e | 2015-08-07 14:40:41 +0200 | [diff] [blame^] | 11 | # (C) 2001-2015 Chris Liechti <cliechti@gmx.net> |
cliechti | 41973a9 | 2009-08-06 02:18:21 +0000 | [diff] [blame] | 12 | # 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 Liechti | c4bca9e | 2015-08-07 14:40:41 +0200 | [diff] [blame^] | 17 | import logging |
| 18 | import numbers |
cliechti | 41973a9 | 2009-08-06 02:18:21 +0000 | [diff] [blame] | 19 | import threading |
| 20 | import time |
Chris Liechti | c4bca9e | 2015-08-07 14:40:41 +0200 | [diff] [blame^] | 21 | try: |
| 22 | import urlparse |
| 23 | except ImportError: |
| 24 | import urllib.parse as urlparse |
| 25 | |
| 26 | from serial.serialutil import * |
cliechti | c64ba69 | 2009-08-12 00:32:47 +0000 | [diff] [blame] | 27 | |
| 28 | # map log level names to constants. used in fromURL() |
| 29 | LOGGER_LEVELS = { |
Chris Liechti | c4bca9e | 2015-08-07 14:40:41 +0200 | [diff] [blame^] | 30 | 'debug': logging.DEBUG, |
| 31 | 'info': logging.INFO, |
| 32 | 'warning': logging.WARNING, |
| 33 | 'error': logging.ERROR, |
| 34 | } |
cliechti | c64ba69 | 2009-08-12 00:32:47 +0000 | [diff] [blame] | 35 | |
cliechti | 41973a9 | 2009-08-06 02:18:21 +0000 | [diff] [blame] | 36 | |
Chris Liechti | ef6b7b4 | 2015-08-06 22:19:26 +0200 | [diff] [blame] | 37 | class Serial(SerialBase): |
cliechti | ab3d428 | 2011-08-19 01:52:46 +0000 | [diff] [blame] | 38 | """Serial port implementation that simulates a loop back connection in plain software.""" |
cliechti | 41973a9 | 2009-08-06 02:18:21 +0000 | [diff] [blame] | 39 | |
| 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): |
cliechti | 7d44856 | 2014-08-03 21:57:45 +0000 | [diff] [blame] | 44 | """\ |
| 45 | Open port with current settings. This may throw a SerialException |
| 46 | if the port cannot be opened. |
| 47 | """ |
cliechti | 8f69e70 | 2011-03-19 00:22:32 +0000 | [diff] [blame] | 48 | if self._isOpen: |
| 49 | raise SerialException("Port is already open.") |
cliechti | 6a30077 | 2009-08-12 02:28:56 +0000 | [diff] [blame] | 50 | self.logger = None |
cliechti | 41973a9 | 2009-08-06 02:18:21 +0000 | [diff] [blame] | 51 | 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): |
cliechti | 7d44856 | 2014-08-03 21:57:45 +0000 | [diff] [blame] | 73 | """\ |
| 74 | Set communication parameters on opened port. For the loop:// |
| 75 | protocol all settings are ignored! |
| 76 | """ |
cliechti | 41973a9 | 2009-08-06 02:18:21 +0000 | [diff] [blame] | 77 | # not that's it of any real use, but it helps in the unit tests |
Chris Liechti | c4bca9e | 2015-08-07 14:40:41 +0200 | [diff] [blame^] | 78 | if not isinstance(self._baudrate, numbers.Integral) or not 0 < self._baudrate < 2**32: |
cliechti | 41973a9 | 2009-08-06 02:18:21 +0000 | [diff] [blame] | 79 | raise ValueError("invalid baudrate: %r" % (self._baudrate)) |
cliechti | 6a30077 | 2009-08-12 02:28:56 +0000 | [diff] [blame] | 80 | if self.logger: |
| 81 | self.logger.info('_reconfigurePort()') |
cliechti | 41973a9 | 2009-08-06 02:18:21 +0000 | [diff] [blame] | 82 | |
| 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 Liechti | c4bca9e | 2015-08-07 14:40:41 +0200 | [diff] [blame^] | 95 | 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,)) |
cliechti | 41973a9 | 2009-08-06 02:18:21 +0000 | [diff] [blame] | 98 | try: |
| 99 | # process options now, directly altering self |
Chris Liechti | c4bca9e | 2015-08-07 14:40:41 +0200 | [diff] [blame^] | 100 | for option in parts.path.split('/'): |
cliechti | c64ba69 | 2009-08-12 00:32:47 +0000 | [diff] [blame] | 101 | if '=' in option: |
| 102 | option, value = option.split('=', 1) |
| 103 | else: |
| 104 | value = None |
cliechti | 641c4bb | 2009-08-12 02:34:19 +0000 | [diff] [blame] | 105 | if not option: |
| 106 | pass |
| 107 | elif option == 'logging': |
cliechti | c64ba69 | 2009-08-12 00:32:47 +0000 | [diff] [blame] | 108 | logging.basicConfig() # XXX is that good to call it here? |
cliechti | 6a30077 | 2009-08-12 02:28:56 +0000 | [diff] [blame] | 109 | self.logger = logging.getLogger('pySerial.loop') |
| 110 | self.logger.setLevel(LOGGER_LEVELS[value]) |
| 111 | self.logger.debug('enabled logging') |
cliechti | 41973a9 | 2009-08-06 02:18:21 +0000 | [diff] [blame] | 112 | else: |
| 113 | raise ValueError('unknown option: %r' % (option,)) |
Chris Liechti | 68340d7 | 2015-08-03 14:15:48 +0200 | [diff] [blame] | 114 | except ValueError as e: |
cliechti | 41973a9 | 2009-08-06 02:18:21 +0000 | [diff] [blame] | 115 | 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 |
cliechti | 6a30077 | 2009-08-12 02:28:56 +0000 | [diff] [blame] | 122 | if self.logger: |
cliechti | c64ba69 | 2009-08-12 00:32:47 +0000 | [diff] [blame] | 123 | # attention the logged value can differ from return value in |
| 124 | # threaded environments... |
cliechti | 6a30077 | 2009-08-12 02:28:56 +0000 | [diff] [blame] | 125 | self.logger.debug('inWaiting() -> %d' % (len(self.loop_buffer),)) |
cliechti | 41973a9 | 2009-08-06 02:18:21 +0000 | [diff] [blame] | 126 | return len(self.loop_buffer) |
| 127 | |
| 128 | def read(self, size=1): |
cliechti | 7d44856 | 2014-08-03 21:57:45 +0000 | [diff] [blame] | 129 | """\ |
| 130 | Read size bytes from the serial port. If a timeout is set it may |
cliechti | 41973a9 | 2009-08-06 02:18:21 +0000 | [diff] [blame] | 131 | return less characters as requested. With no timeout it will block |
cliechti | 7d44856 | 2014-08-03 21:57:45 +0000 | [diff] [blame] | 132 | until the requested number of bytes is read. |
| 133 | """ |
cliechti | 41973a9 | 2009-08-06 02:18:21 +0000 | [diff] [blame] | 134 | if not self._isOpen: raise portNotOpenError |
cliechti | 41973a9 | 2009-08-06 02:18:21 +0000 | [diff] [blame] | 135 | if self._timeout is not None: |
| 136 | timeout = time.time() + self._timeout |
| 137 | else: |
cliechti | 024b4f4 | 2009-08-07 18:43:05 +0000 | [diff] [blame] | 138 | timeout = None |
cliechti | 1de32cd | 2009-08-07 19:05:09 +0000 | [diff] [blame] | 139 | data = bytearray() |
cliechti | fb2306b | 2011-08-18 22:46:57 +0000 | [diff] [blame] | 140 | while size > 0: |
Chris Liechti | c4bca9e | 2015-08-07 14:40:41 +0200 | [diff] [blame^] | 141 | with self.buffer_lock: |
cliechti | 1de32cd | 2009-08-07 19:05:09 +0000 | [diff] [blame] | 142 | block = to_bytes(self.loop_buffer[:size]) |
cliechti | 41973a9 | 2009-08-06 02:18:21 +0000 | [diff] [blame] | 143 | del self.loop_buffer[:size] |
cliechti | 41973a9 | 2009-08-06 02:18:21 +0000 | [diff] [blame] | 144 | data += block |
cliechti | fb2306b | 2011-08-18 22:46:57 +0000 | [diff] [blame] | 145 | size -= len(block) |
cliechti | 41973a9 | 2009-08-06 02:18:21 +0000 | [diff] [blame] | 146 | # check for timeout now, after data has been read. |
| 147 | # useful for timeout = 0 (non blocking) read |
cliechti | 024b4f4 | 2009-08-07 18:43:05 +0000 | [diff] [blame] | 148 | if timeout and time.time() > timeout: |
cliechti | 41973a9 | 2009-08-06 02:18:21 +0000 | [diff] [blame] | 149 | break |
| 150 | return bytes(data) |
| 151 | |
| 152 | def write(self, data): |
cliechti | 7d44856 | 2014-08-03 21:57:45 +0000 | [diff] [blame] | 153 | """\ |
| 154 | Output the given string over the serial port. Can block if the |
cliechti | 41973a9 | 2009-08-06 02:18:21 +0000 | [diff] [blame] | 155 | connection is blocked. May raise SerialException if the connection is |
cliechti | 7d44856 | 2014-08-03 21:57:45 +0000 | [diff] [blame] | 156 | closed. |
| 157 | """ |
cliechti | 41973a9 | 2009-08-06 02:18:21 +0000 | [diff] [blame] | 158 | if not self._isOpen: raise portNotOpenError |
cliechti | fb2306b | 2011-08-18 22:46:57 +0000 | [diff] [blame] | 159 | # ensure we're working with bytes |
cliechti | 3807712 | 2013-10-16 02:57:27 +0000 | [diff] [blame] | 160 | data = to_bytes(data) |
cliechti | 66957bf | 2009-08-06 23:25:37 +0000 | [diff] [blame] | 161 | # 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 Liechti | c4bca9e | 2015-08-07 14:40:41 +0200 | [diff] [blame^] | 168 | with self.buffer_lock: |
cliechti | fb2306b | 2011-08-18 22:46:57 +0000 | [diff] [blame] | 169 | self.loop_buffer += data |
cliechti | 41973a9 | 2009-08-06 02:18:21 +0000 | [diff] [blame] | 170 | 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 |
cliechti | 6a30077 | 2009-08-12 02:28:56 +0000 | [diff] [blame] | 175 | if self.logger: |
| 176 | self.logger.info('flushInput()') |
Chris Liechti | c4bca9e | 2015-08-07 14:40:41 +0200 | [diff] [blame^] | 177 | with self.buffer_lock: |
cliechti | 41973a9 | 2009-08-06 02:18:21 +0000 | [diff] [blame] | 178 | del self.loop_buffer[:] |
cliechti | 41973a9 | 2009-08-06 02:18:21 +0000 | [diff] [blame] | 179 | |
| 180 | def flushOutput(self): |
cliechti | 7d44856 | 2014-08-03 21:57:45 +0000 | [diff] [blame] | 181 | """\ |
| 182 | Clear output buffer, aborting the current output and |
| 183 | discarding all that is in the buffer. |
| 184 | """ |
cliechti | 41973a9 | 2009-08-06 02:18:21 +0000 | [diff] [blame] | 185 | if not self._isOpen: raise portNotOpenError |
cliechti | 6a30077 | 2009-08-12 02:28:56 +0000 | [diff] [blame] | 186 | if self.logger: |
| 187 | self.logger.info('flushOutput()') |
cliechti | 41973a9 | 2009-08-06 02:18:21 +0000 | [diff] [blame] | 188 | |
| 189 | def sendBreak(self, duration=0.25): |
cliechti | 7d44856 | 2014-08-03 21:57:45 +0000 | [diff] [blame] | 190 | """\ |
| 191 | Send break condition. Timed, returns to idle state after given |
| 192 | duration. |
| 193 | """ |
cliechti | 41973a9 | 2009-08-06 02:18:21 +0000 | [diff] [blame] | 194 | if not self._isOpen: raise portNotOpenError |
| 195 | |
| 196 | def setBreak(self, level=True): |
cliechti | 7d44856 | 2014-08-03 21:57:45 +0000 | [diff] [blame] | 197 | """\ |
| 198 | Set break: Controls TXD. When active, to transmitting is |
| 199 | possible. |
| 200 | """ |
cliechti | 41973a9 | 2009-08-06 02:18:21 +0000 | [diff] [blame] | 201 | if not self._isOpen: raise portNotOpenError |
cliechti | 6a30077 | 2009-08-12 02:28:56 +0000 | [diff] [blame] | 202 | if self.logger: |
| 203 | self.logger.info('setBreak(%r)' % (level,)) |
cliechti | 41973a9 | 2009-08-06 02:18:21 +0000 | [diff] [blame] | 204 | |
| 205 | def setRTS(self, level=True): |
| 206 | """Set terminal status line: Request To Send""" |
| 207 | if not self._isOpen: raise portNotOpenError |
cliechti | 6a30077 | 2009-08-12 02:28:56 +0000 | [diff] [blame] | 208 | if self.logger: |
| 209 | self.logger.info('setRTS(%r) -> state of CTS' % (level,)) |
cliechti | 41973a9 | 2009-08-06 02:18:21 +0000 | [diff] [blame] | 210 | 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 |
cliechti | 6a30077 | 2009-08-12 02:28:56 +0000 | [diff] [blame] | 215 | if self.logger: |
| 216 | self.logger.info('setDTR(%r) -> state of DSR' % (level,)) |
cliechti | 41973a9 | 2009-08-06 02:18:21 +0000 | [diff] [blame] | 217 | self.dsr = level |
| 218 | |
| 219 | def getCTS(self): |
| 220 | """Read terminal status line: Clear To Send""" |
| 221 | if not self._isOpen: raise portNotOpenError |
cliechti | 6a30077 | 2009-08-12 02:28:56 +0000 | [diff] [blame] | 222 | if self.logger: |
| 223 | self.logger.info('getCTS() -> state of RTS (%r)' % (self.cts,)) |
cliechti | 41973a9 | 2009-08-06 02:18:21 +0000 | [diff] [blame] | 224 | return self.cts |
| 225 | |
| 226 | def getDSR(self): |
| 227 | """Read terminal status line: Data Set Ready""" |
| 228 | if not self._isOpen: raise portNotOpenError |
cliechti | 6a30077 | 2009-08-12 02:28:56 +0000 | [diff] [blame] | 229 | if self.logger: |
| 230 | self.logger.info('getDSR() -> state of DTR (%r)' % (self.dsr,)) |
cliechti | 41973a9 | 2009-08-06 02:18:21 +0000 | [diff] [blame] | 231 | return self.dsr |
| 232 | |
| 233 | def getRI(self): |
| 234 | """Read terminal status line: Ring Indicator""" |
| 235 | if not self._isOpen: raise portNotOpenError |
cliechti | 6a30077 | 2009-08-12 02:28:56 +0000 | [diff] [blame] | 236 | if self.logger: |
| 237 | self.logger.info('returning dummy for getRI()') |
cliechti | 41973a9 | 2009-08-06 02:18:21 +0000 | [diff] [blame] | 238 | return False |
| 239 | |
| 240 | def getCD(self): |
| 241 | """Read terminal status line: Carrier Detect""" |
| 242 | if not self._isOpen: raise portNotOpenError |
cliechti | 6a30077 | 2009-08-12 02:28:56 +0000 | [diff] [blame] | 243 | if self.logger: |
| 244 | self.logger.info('returning dummy for getCD()') |
cliechti | 41973a9 | 2009-08-06 02:18:21 +0000 | [diff] [blame] | 245 | return True |
| 246 | |
| 247 | # - - - platform specific - - - |
| 248 | # None so far |
| 249 | |
| 250 | |
cliechti | 41973a9 | 2009-08-06 02:18:21 +0000 | [diff] [blame] | 251 | # simple client test |
| 252 | if __name__ == '__main__': |
| 253 | import sys |
cliechti | ab3d428 | 2011-08-19 01:52:46 +0000 | [diff] [blame] | 254 | s = Serial('loop://') |
cliechti | 41973a9 | 2009-08-06 02:18:21 +0000 | [diff] [blame] | 255 | 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() |