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