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> |
Chris Liechti | fbdd8a0 | 2015-08-09 02:37:45 +0200 | [diff] [blame] | 12 | # |
| 13 | # SPDX-License-Identifier: BSD-3-Clause |
cliechti | 41973a9 | 2009-08-06 02:18:21 +0000 | [diff] [blame] | 14 | # |
| 15 | # URL format: loop://[option[/option...]] |
| 16 | # options: |
| 17 | # - "debug" print diagnostic messages |
Chris Liechti | c4bca9e | 2015-08-07 14:40:41 +0200 | [diff] [blame] | 18 | import logging |
| 19 | import numbers |
cliechti | 41973a9 | 2009-08-06 02:18:21 +0000 | [diff] [blame] | 20 | import threading |
| 21 | import time |
Chris Liechti | c4bca9e | 2015-08-07 14:40:41 +0200 | [diff] [blame] | 22 | try: |
| 23 | import urlparse |
| 24 | except ImportError: |
| 25 | import urllib.parse as urlparse |
Chris Liechti | a469cde | 2015-08-11 23:05:24 +0200 | [diff] [blame^] | 26 | try: |
| 27 | import queue |
| 28 | except ImportError: |
| 29 | import Queue as queue |
Chris Liechti | c4bca9e | 2015-08-07 14:40:41 +0200 | [diff] [blame] | 30 | |
| 31 | from serial.serialutil import * |
cliechti | c64ba69 | 2009-08-12 00:32:47 +0000 | [diff] [blame] | 32 | |
| 33 | # map log level names to constants. used in fromURL() |
| 34 | LOGGER_LEVELS = { |
Chris Liechti | c4bca9e | 2015-08-07 14:40:41 +0200 | [diff] [blame] | 35 | 'debug': logging.DEBUG, |
| 36 | 'info': logging.INFO, |
| 37 | 'warning': logging.WARNING, |
| 38 | 'error': logging.ERROR, |
| 39 | } |
cliechti | c64ba69 | 2009-08-12 00:32:47 +0000 | [diff] [blame] | 40 | |
cliechti | 41973a9 | 2009-08-06 02:18:21 +0000 | [diff] [blame] | 41 | |
Chris Liechti | ef6b7b4 | 2015-08-06 22:19:26 +0200 | [diff] [blame] | 42 | class Serial(SerialBase): |
cliechti | ab3d428 | 2011-08-19 01:52:46 +0000 | [diff] [blame] | 43 | """Serial port implementation that simulates a loop back connection in plain software.""" |
cliechti | 41973a9 | 2009-08-06 02:18:21 +0000 | [diff] [blame] | 44 | |
| 45 | BAUDRATES = (50, 75, 110, 134, 150, 200, 300, 600, 1200, 1800, 2400, 4800, |
| 46 | 9600, 19200, 38400, 57600, 115200) |
| 47 | |
Chris Liechti | a469cde | 2015-08-11 23:05:24 +0200 | [diff] [blame^] | 48 | def __init__(self, *args, **kwargs): |
| 49 | super(Serial, self).__init__(*args, **kwargs) |
| 50 | self.buffer_size = 4096 |
| 51 | |
cliechti | 41973a9 | 2009-08-06 02:18:21 +0000 | [diff] [blame] | 52 | def open(self): |
cliechti | 7d44856 | 2014-08-03 21:57:45 +0000 | [diff] [blame] | 53 | """\ |
| 54 | Open port with current settings. This may throw a SerialException |
| 55 | if the port cannot be opened. |
| 56 | """ |
cliechti | 8f69e70 | 2011-03-19 00:22:32 +0000 | [diff] [blame] | 57 | if self._isOpen: |
| 58 | raise SerialException("Port is already open.") |
cliechti | 6a30077 | 2009-08-12 02:28:56 +0000 | [diff] [blame] | 59 | self.logger = None |
Chris Liechti | a469cde | 2015-08-11 23:05:24 +0200 | [diff] [blame^] | 60 | self.queue = queue.Queue(self.buffer_size) |
cliechti | 41973a9 | 2009-08-06 02:18:21 +0000 | [diff] [blame] | 61 | self.cts = False |
| 62 | self.dsr = False |
| 63 | |
| 64 | if self._port is None: |
| 65 | raise SerialException("Port must be configured before it can be used.") |
| 66 | # not that there is anything to open, but the function applies the |
| 67 | # options found in the URL |
| 68 | self.fromURL(self.port) |
| 69 | |
| 70 | # not that there anything to configure... |
| 71 | self._reconfigurePort() |
| 72 | # all things set up get, now a clean start |
| 73 | self._isOpen = True |
| 74 | if not self._rtscts: |
| 75 | self.setRTS(True) |
| 76 | self.setDTR(True) |
| 77 | self.flushInput() |
| 78 | self.flushOutput() |
| 79 | |
Chris Liechti | a469cde | 2015-08-11 23:05:24 +0200 | [diff] [blame^] | 80 | def close(self): |
| 81 | self.queue.put(None) |
| 82 | super(Serial, self).close() |
| 83 | |
cliechti | 41973a9 | 2009-08-06 02:18:21 +0000 | [diff] [blame] | 84 | def _reconfigurePort(self): |
cliechti | 7d44856 | 2014-08-03 21:57:45 +0000 | [diff] [blame] | 85 | """\ |
| 86 | Set communication parameters on opened port. For the loop:// |
| 87 | protocol all settings are ignored! |
| 88 | """ |
cliechti | 41973a9 | 2009-08-06 02:18:21 +0000 | [diff] [blame] | 89 | # 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] | 90 | 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] | 91 | raise ValueError("invalid baudrate: %r" % (self._baudrate)) |
cliechti | 6a30077 | 2009-08-12 02:28:56 +0000 | [diff] [blame] | 92 | if self.logger: |
| 93 | self.logger.info('_reconfigurePort()') |
cliechti | 41973a9 | 2009-08-06 02:18:21 +0000 | [diff] [blame] | 94 | |
| 95 | def close(self): |
| 96 | """Close port""" |
| 97 | if self._isOpen: |
| 98 | self._isOpen = False |
| 99 | # in case of quick reconnects, give the server some time |
| 100 | time.sleep(0.3) |
| 101 | |
cliechti | 41973a9 | 2009-08-06 02:18:21 +0000 | [diff] [blame] | 102 | def fromURL(self, url): |
| 103 | """extract host and port from an URL string""" |
Chris Liechti | c4bca9e | 2015-08-07 14:40:41 +0200 | [diff] [blame] | 104 | parts = urlparse.urlsplit(url) |
| 105 | if parts.scheme.lower() != "loop": |
| 106 | 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] | 107 | try: |
| 108 | # process options now, directly altering self |
Chris Liechti | c4bca9e | 2015-08-07 14:40:41 +0200 | [diff] [blame] | 109 | for option in parts.path.split('/'): |
cliechti | c64ba69 | 2009-08-12 00:32:47 +0000 | [diff] [blame] | 110 | if '=' in option: |
| 111 | option, value = option.split('=', 1) |
| 112 | else: |
| 113 | value = None |
cliechti | 641c4bb | 2009-08-12 02:34:19 +0000 | [diff] [blame] | 114 | if not option: |
| 115 | pass |
| 116 | elif option == 'logging': |
cliechti | c64ba69 | 2009-08-12 00:32:47 +0000 | [diff] [blame] | 117 | logging.basicConfig() # XXX is that good to call it here? |
cliechti | 6a30077 | 2009-08-12 02:28:56 +0000 | [diff] [blame] | 118 | self.logger = logging.getLogger('pySerial.loop') |
| 119 | self.logger.setLevel(LOGGER_LEVELS[value]) |
| 120 | self.logger.debug('enabled logging') |
cliechti | 41973a9 | 2009-08-06 02:18:21 +0000 | [diff] [blame] | 121 | else: |
| 122 | raise ValueError('unknown option: %r' % (option,)) |
Chris Liechti | 68340d7 | 2015-08-03 14:15:48 +0200 | [diff] [blame] | 123 | except ValueError as e: |
cliechti | 41973a9 | 2009-08-06 02:18:21 +0000 | [diff] [blame] | 124 | raise SerialException('expected a string in the form "[loop://][option[/option...]]": %s' % e) |
| 125 | |
| 126 | # - - - - - - - - - - - - - - - - - - - - - - - - |
| 127 | |
| 128 | def inWaiting(self): |
| 129 | """Return the number of characters currently in the input buffer.""" |
| 130 | if not self._isOpen: raise portNotOpenError |
cliechti | 6a30077 | 2009-08-12 02:28:56 +0000 | [diff] [blame] | 131 | if self.logger: |
cliechti | c64ba69 | 2009-08-12 00:32:47 +0000 | [diff] [blame] | 132 | # attention the logged value can differ from return value in |
| 133 | # threaded environments... |
Chris Liechti | a469cde | 2015-08-11 23:05:24 +0200 | [diff] [blame^] | 134 | self.logger.debug('inWaiting() -> %d' % (self.queue.qsize(),)) |
| 135 | return self.queue.qsize() |
cliechti | 41973a9 | 2009-08-06 02:18:21 +0000 | [diff] [blame] | 136 | |
| 137 | def read(self, size=1): |
cliechti | 7d44856 | 2014-08-03 21:57:45 +0000 | [diff] [blame] | 138 | """\ |
| 139 | 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] | 140 | return less characters as requested. With no timeout it will block |
cliechti | 7d44856 | 2014-08-03 21:57:45 +0000 | [diff] [blame] | 141 | until the requested number of bytes is read. |
| 142 | """ |
cliechti | 41973a9 | 2009-08-06 02:18:21 +0000 | [diff] [blame] | 143 | if not self._isOpen: raise portNotOpenError |
cliechti | 41973a9 | 2009-08-06 02:18:21 +0000 | [diff] [blame] | 144 | if self._timeout is not None: |
| 145 | timeout = time.time() + self._timeout |
| 146 | else: |
cliechti | 024b4f4 | 2009-08-07 18:43:05 +0000 | [diff] [blame] | 147 | timeout = None |
cliechti | 1de32cd | 2009-08-07 19:05:09 +0000 | [diff] [blame] | 148 | data = bytearray() |
Chris Liechti | a469cde | 2015-08-11 23:05:24 +0200 | [diff] [blame^] | 149 | while size > 0 and self._isOpen: |
| 150 | try: |
| 151 | data += self.queue.get(timeout=self._timeout) # XXX inter char timeout |
| 152 | except queue.Empty: |
| 153 | break |
| 154 | else: |
| 155 | size -= 1 |
cliechti | 41973a9 | 2009-08-06 02:18:21 +0000 | [diff] [blame] | 156 | # check for timeout now, after data has been read. |
| 157 | # useful for timeout = 0 (non blocking) read |
cliechti | 024b4f4 | 2009-08-07 18:43:05 +0000 | [diff] [blame] | 158 | if timeout and time.time() > timeout: |
cliechti | 41973a9 | 2009-08-06 02:18:21 +0000 | [diff] [blame] | 159 | break |
| 160 | return bytes(data) |
| 161 | |
| 162 | def write(self, data): |
cliechti | 7d44856 | 2014-08-03 21:57:45 +0000 | [diff] [blame] | 163 | """\ |
| 164 | Output the given string over the serial port. Can block if the |
cliechti | 41973a9 | 2009-08-06 02:18:21 +0000 | [diff] [blame] | 165 | connection is blocked. May raise SerialException if the connection is |
cliechti | 7d44856 | 2014-08-03 21:57:45 +0000 | [diff] [blame] | 166 | closed. |
| 167 | """ |
cliechti | 41973a9 | 2009-08-06 02:18:21 +0000 | [diff] [blame] | 168 | if not self._isOpen: raise portNotOpenError |
cliechti | 3807712 | 2013-10-16 02:57:27 +0000 | [diff] [blame] | 169 | data = to_bytes(data) |
cliechti | 66957bf | 2009-08-06 23:25:37 +0000 | [diff] [blame] | 170 | # calculate aprox time that would be used to send the data |
| 171 | time_used_to_send = 10.0*len(data) / self._baudrate |
| 172 | # when a write timeout is configured check if we would be successful |
| 173 | # (not sending anything, not even the part that would have time) |
| 174 | if self._writeTimeout is not None and time_used_to_send > self._writeTimeout: |
| 175 | time.sleep(self._writeTimeout) # must wait so that unit test succeeds |
| 176 | raise writeTimeoutError |
Chris Liechti | a469cde | 2015-08-11 23:05:24 +0200 | [diff] [blame^] | 177 | #~ for byte in data: # fails for python3 as it returns ints instead of b'' |
| 178 | for x in range(len(data)): |
| 179 | byte = data[x:x+1] |
| 180 | self.queue.put(byte, timeout=self._writeTimeout) |
cliechti | 41973a9 | 2009-08-06 02:18:21 +0000 | [diff] [blame] | 181 | return len(data) |
| 182 | |
| 183 | def flushInput(self): |
| 184 | """Clear input buffer, discarding all that is in the buffer.""" |
| 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('flushInput()') |
Chris Liechti | a469cde | 2015-08-11 23:05:24 +0200 | [diff] [blame^] | 188 | try: |
| 189 | while self.queue.qsize(): |
| 190 | self.queue.get_nowait() |
| 191 | except queue.Empty: |
| 192 | pass |
cliechti | 41973a9 | 2009-08-06 02:18:21 +0000 | [diff] [blame] | 193 | |
| 194 | def flushOutput(self): |
cliechti | 7d44856 | 2014-08-03 21:57:45 +0000 | [diff] [blame] | 195 | """\ |
| 196 | Clear output buffer, aborting the current output and |
| 197 | discarding all that is in the buffer. |
| 198 | """ |
cliechti | 41973a9 | 2009-08-06 02:18:21 +0000 | [diff] [blame] | 199 | if not self._isOpen: raise portNotOpenError |
cliechti | 6a30077 | 2009-08-12 02:28:56 +0000 | [diff] [blame] | 200 | if self.logger: |
| 201 | self.logger.info('flushOutput()') |
Chris Liechti | a469cde | 2015-08-11 23:05:24 +0200 | [diff] [blame^] | 202 | try: |
| 203 | while self.queue.qsize(): |
| 204 | self.queue.get_nowait() |
| 205 | except queue.Empty: |
| 206 | pass |
cliechti | 41973a9 | 2009-08-06 02:18:21 +0000 | [diff] [blame] | 207 | |
| 208 | def sendBreak(self, duration=0.25): |
cliechti | 7d44856 | 2014-08-03 21:57:45 +0000 | [diff] [blame] | 209 | """\ |
| 210 | Send break condition. Timed, returns to idle state after given |
| 211 | duration. |
| 212 | """ |
cliechti | 41973a9 | 2009-08-06 02:18:21 +0000 | [diff] [blame] | 213 | if not self._isOpen: raise portNotOpenError |
Chris Liechti | a469cde | 2015-08-11 23:05:24 +0200 | [diff] [blame^] | 214 | time.sleep(duration) |
cliechti | 41973a9 | 2009-08-06 02:18:21 +0000 | [diff] [blame] | 215 | |
| 216 | def setBreak(self, level=True): |
cliechti | 7d44856 | 2014-08-03 21:57:45 +0000 | [diff] [blame] | 217 | """\ |
| 218 | Set break: Controls TXD. When active, to transmitting is |
| 219 | possible. |
| 220 | """ |
cliechti | 41973a9 | 2009-08-06 02:18:21 +0000 | [diff] [blame] | 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('setBreak(%r)' % (level,)) |
cliechti | 41973a9 | 2009-08-06 02:18:21 +0000 | [diff] [blame] | 224 | |
| 225 | def setRTS(self, level=True): |
| 226 | """Set terminal status line: Request To Send""" |
| 227 | if not self._isOpen: raise portNotOpenError |
cliechti | 6a30077 | 2009-08-12 02:28:56 +0000 | [diff] [blame] | 228 | if self.logger: |
| 229 | self.logger.info('setRTS(%r) -> state of CTS' % (level,)) |
cliechti | 41973a9 | 2009-08-06 02:18:21 +0000 | [diff] [blame] | 230 | self.cts = level |
| 231 | |
| 232 | def setDTR(self, level=True): |
| 233 | """Set terminal status line: Data Terminal Ready""" |
| 234 | if not self._isOpen: raise portNotOpenError |
cliechti | 6a30077 | 2009-08-12 02:28:56 +0000 | [diff] [blame] | 235 | if self.logger: |
| 236 | self.logger.info('setDTR(%r) -> state of DSR' % (level,)) |
cliechti | 41973a9 | 2009-08-06 02:18:21 +0000 | [diff] [blame] | 237 | self.dsr = level |
| 238 | |
| 239 | def getCTS(self): |
| 240 | """Read terminal status line: Clear To Send""" |
| 241 | if not self._isOpen: raise portNotOpenError |
cliechti | 6a30077 | 2009-08-12 02:28:56 +0000 | [diff] [blame] | 242 | if self.logger: |
| 243 | self.logger.info('getCTS() -> state of RTS (%r)' % (self.cts,)) |
cliechti | 41973a9 | 2009-08-06 02:18:21 +0000 | [diff] [blame] | 244 | return self.cts |
| 245 | |
| 246 | def getDSR(self): |
| 247 | """Read terminal status line: Data Set Ready""" |
| 248 | if not self._isOpen: raise portNotOpenError |
cliechti | 6a30077 | 2009-08-12 02:28:56 +0000 | [diff] [blame] | 249 | if self.logger: |
| 250 | self.logger.info('getDSR() -> state of DTR (%r)' % (self.dsr,)) |
cliechti | 41973a9 | 2009-08-06 02:18:21 +0000 | [diff] [blame] | 251 | return self.dsr |
| 252 | |
| 253 | def getRI(self): |
| 254 | """Read terminal status line: Ring Indicator""" |
| 255 | if not self._isOpen: raise portNotOpenError |
cliechti | 6a30077 | 2009-08-12 02:28:56 +0000 | [diff] [blame] | 256 | if self.logger: |
| 257 | self.logger.info('returning dummy for getRI()') |
cliechti | 41973a9 | 2009-08-06 02:18:21 +0000 | [diff] [blame] | 258 | return False |
| 259 | |
| 260 | def getCD(self): |
| 261 | """Read terminal status line: Carrier Detect""" |
| 262 | if not self._isOpen: raise portNotOpenError |
cliechti | 6a30077 | 2009-08-12 02:28:56 +0000 | [diff] [blame] | 263 | if self.logger: |
| 264 | self.logger.info('returning dummy for getCD()') |
cliechti | 41973a9 | 2009-08-06 02:18:21 +0000 | [diff] [blame] | 265 | return True |
| 266 | |
| 267 | # - - - platform specific - - - |
| 268 | # None so far |
| 269 | |
| 270 | |
cliechti | 41973a9 | 2009-08-06 02:18:21 +0000 | [diff] [blame] | 271 | # simple client test |
| 272 | if __name__ == '__main__': |
| 273 | import sys |
cliechti | ab3d428 | 2011-08-19 01:52:46 +0000 | [diff] [blame] | 274 | s = Serial('loop://') |
cliechti | 41973a9 | 2009-08-06 02:18:21 +0000 | [diff] [blame] | 275 | sys.stdout.write('%s\n' % s) |
| 276 | |
| 277 | sys.stdout.write("write...\n") |
| 278 | s.write("hello\n") |
| 279 | s.flush() |
| 280 | sys.stdout.write("read: %s\n" % s.read(5)) |
| 281 | |
| 282 | s.close() |