cliechti | 0d6029a | 2008-06-21 01:28:46 +0000 | [diff] [blame] | 1 | #! python |
cliechti | ff0c379 | 2008-06-22 01:01:21 +0000 | [diff] [blame] | 2 | # Python Serial Port Extension for Win32, Linux, BSD, Jython and .NET/Mono |
| 3 | # serial driver for .NET/Mono (IronPython), .NET >= 2 |
| 4 | # see __init__.py |
cliechti | 0d6029a | 2008-06-21 01:28:46 +0000 | [diff] [blame] | 5 | # |
cliechti | ff0c379 | 2008-06-22 01:01:21 +0000 | [diff] [blame] | 6 | # (C) 2008 Chris Liechti <cliechti@gmx.net> |
cliechti | 0d6029a | 2008-06-21 01:28:46 +0000 | [diff] [blame] | 7 | # this is distributed under a free software license, see license.txt |
| 8 | |
cliechti | 761fd6e | 2008-06-24 11:32:43 +0000 | [diff] [blame] | 9 | import clr |
| 10 | import System |
cliechti | 0d6029a | 2008-06-21 01:28:46 +0000 | [diff] [blame] | 11 | import System.IO.Ports |
cliechti | 39cfb7b | 2011-08-22 00:30:07 +0000 | [diff] [blame] | 12 | from serial.serialutil import * |
cliechti | 0d6029a | 2008-06-21 01:28:46 +0000 | [diff] [blame] | 13 | |
cliechti | 4a567a0 | 2009-07-27 22:09:31 +0000 | [diff] [blame] | 14 | |
cliechti | 0d6029a | 2008-06-21 01:28:46 +0000 | [diff] [blame] | 15 | def device(portnum): |
| 16 | """Turn a port number into a device name""" |
| 17 | return System.IO.Ports.SerialPort.GetPortNames()[portnum] |
| 18 | |
cliechti | 4a567a0 | 2009-07-27 22:09:31 +0000 | [diff] [blame] | 19 | |
cliechti | 761fd6e | 2008-06-24 11:32:43 +0000 | [diff] [blame] | 20 | # must invoke function with byte array, make a helper to convert strings |
| 21 | # to byte arrays |
| 22 | sab = System.Array[System.Byte] |
| 23 | def as_byte_array(string): |
cliechti | 4a567a0 | 2009-07-27 22:09:31 +0000 | [diff] [blame] | 24 | return sab([ord(x) for x in string]) # XXX will require adaption when run with a 3.x compatible IronPython |
cliechti | 761fd6e | 2008-06-24 11:32:43 +0000 | [diff] [blame] | 25 | |
Chris Liechti | ef6b7b4 | 2015-08-06 22:19:26 +0200 | [diff] [blame] | 26 | class Serial(SerialBase): |
cliechti | 771278b | 2013-10-17 03:19:00 +0000 | [diff] [blame] | 27 | """Serial port implementation for .NET/Mono.""" |
cliechti | 0d6029a | 2008-06-21 01:28:46 +0000 | [diff] [blame] | 28 | |
cliechti | 4a567a0 | 2009-07-27 22:09:31 +0000 | [diff] [blame] | 29 | BAUDRATES = (50, 75, 110, 134, 150, 200, 300, 600, 1200, 1800, 2400, 4800, |
| 30 | 9600, 19200, 38400, 57600, 115200) |
cliechti | 0d6029a | 2008-06-21 01:28:46 +0000 | [diff] [blame] | 31 | |
| 32 | def open(self): |
cliechti | 00df970 | 2014-08-04 10:12:48 +0000 | [diff] [blame] | 33 | """\ |
| 34 | Open port with current settings. This may throw a SerialException |
| 35 | if the port cannot be opened. |
| 36 | """ |
cliechti | 0d6029a | 2008-06-21 01:28:46 +0000 | [diff] [blame] | 37 | if self._port is None: |
| 38 | raise SerialException("Port must be configured before it can be used.") |
cliechti | 8f69e70 | 2011-03-19 00:22:32 +0000 | [diff] [blame] | 39 | if self._isOpen: |
| 40 | raise SerialException("Port is already open.") |
cliechti | 0d6029a | 2008-06-21 01:28:46 +0000 | [diff] [blame] | 41 | try: |
| 42 | self._port_handle = System.IO.Ports.SerialPort(self.portstr) |
| 43 | except Exception, msg: |
cliechti | ff0c379 | 2008-06-22 01:01:21 +0000 | [diff] [blame] | 44 | self._port_handle = None |
cliechti | 0d6029a | 2008-06-21 01:28:46 +0000 | [diff] [blame] | 45 | raise SerialException("could not open port %s: %s" % (self.portstr, msg)) |
| 46 | |
| 47 | self._reconfigurePort() |
| 48 | self._port_handle.Open() |
| 49 | self._isOpen = True |
cliechti | 761fd6e | 2008-06-24 11:32:43 +0000 | [diff] [blame] | 50 | if not self._rtscts: |
| 51 | self.setRTS(True) |
| 52 | self.setDTR(True) |
cliechti | ff0c379 | 2008-06-22 01:01:21 +0000 | [diff] [blame] | 53 | self.flushInput() |
| 54 | self.flushOutput() |
cliechti | 0d6029a | 2008-06-21 01:28:46 +0000 | [diff] [blame] | 55 | |
| 56 | def _reconfigurePort(self): |
cliechti | ff0c379 | 2008-06-22 01:01:21 +0000 | [diff] [blame] | 57 | """Set communication parameters on opened port.""" |
cliechti | 0d6029a | 2008-06-21 01:28:46 +0000 | [diff] [blame] | 58 | if not self._port_handle: |
| 59 | raise SerialException("Can only operate on a valid port handle") |
cliechti | 58b481c | 2009-02-16 20:42:32 +0000 | [diff] [blame] | 60 | |
cliechti | edfba4e | 2009-02-07 00:29:47 +0000 | [diff] [blame] | 61 | #~ self._port_handle.ReceivedBytesThreshold = 1 |
cliechti | 58b481c | 2009-02-16 20:42:32 +0000 | [diff] [blame] | 62 | |
cliechti | 0d6029a | 2008-06-21 01:28:46 +0000 | [diff] [blame] | 63 | if self._timeout is None: |
| 64 | self._port_handle.ReadTimeout = System.IO.Ports.SerialPort.InfiniteTimeout |
| 65 | else: |
| 66 | self._port_handle.ReadTimeout = int(self._timeout*1000) |
cliechti | 58b481c | 2009-02-16 20:42:32 +0000 | [diff] [blame] | 67 | |
cliechti | 0d6029a | 2008-06-21 01:28:46 +0000 | [diff] [blame] | 68 | # if self._timeout != 0 and self._interCharTimeout is not None: |
| 69 | # timeouts = (int(self._interCharTimeout * 1000),) + timeouts[1:] |
cliechti | 58b481c | 2009-02-16 20:42:32 +0000 | [diff] [blame] | 70 | |
cliechti | 0d6029a | 2008-06-21 01:28:46 +0000 | [diff] [blame] | 71 | if self._writeTimeout is None: |
cliechti | ff0c379 | 2008-06-22 01:01:21 +0000 | [diff] [blame] | 72 | self._port_handle.WriteTimeout = System.IO.Ports.SerialPort.InfiniteTimeout |
cliechti | 0d6029a | 2008-06-21 01:28:46 +0000 | [diff] [blame] | 73 | else: |
| 74 | self._port_handle.WriteTimeout = int(self._writeTimeout*1000) |
| 75 | |
| 76 | |
| 77 | # Setup the connection info. |
cliechti | c53a8ca | 2008-06-24 11:57:32 +0000 | [diff] [blame] | 78 | try: |
| 79 | self._port_handle.BaudRate = self._baudrate |
| 80 | except IOError, e: |
| 81 | # catch errors from illegal baudrate settings |
| 82 | raise ValueError(str(e)) |
cliechti | 0d6029a | 2008-06-21 01:28:46 +0000 | [diff] [blame] | 83 | |
| 84 | if self._bytesize == FIVEBITS: |
| 85 | self._port_handle.DataBits = 5 |
| 86 | elif self._bytesize == SIXBITS: |
| 87 | self._port_handle.DataBits = 6 |
| 88 | elif self._bytesize == SEVENBITS: |
| 89 | self._port_handle.DataBits = 7 |
| 90 | elif self._bytesize == EIGHTBITS: |
| 91 | self._port_handle.DataBits = 8 |
| 92 | else: |
| 93 | raise ValueError("Unsupported number of data bits: %r" % self._bytesize) |
| 94 | |
| 95 | if self._parity == PARITY_NONE: |
cliechti | 91d247d | 2009-07-25 00:42:57 +0000 | [diff] [blame] | 96 | self._port_handle.Parity = getattr(System.IO.Ports.Parity, 'None') # reserved keyword in Py3k |
cliechti | 0d6029a | 2008-06-21 01:28:46 +0000 | [diff] [blame] | 97 | elif self._parity == PARITY_EVEN: |
| 98 | self._port_handle.Parity = System.IO.Ports.Parity.Even |
| 99 | elif self._parity == PARITY_ODD: |
| 100 | self._port_handle.Parity = System.IO.Ports.Parity.Odd |
| 101 | elif self._parity == PARITY_MARK: |
| 102 | self._port_handle.Parity = System.IO.Ports.Parity.Mark |
| 103 | elif self._parity == PARITY_SPACE: |
| 104 | self._port_handle.Parity = System.IO.Ports.Parity.Space |
| 105 | else: |
| 106 | raise ValueError("Unsupported parity mode: %r" % self._parity) |
| 107 | |
| 108 | if self._stopbits == STOPBITS_ONE: |
| 109 | self._port_handle.StopBits = System.IO.Ports.StopBits.One |
cliechti | 58b481c | 2009-02-16 20:42:32 +0000 | [diff] [blame] | 110 | elif self._stopbits == STOPBITS_ONE_POINT_FIVE: |
| 111 | self._port_handle.StopBits = System.IO.Ports.StopBits.OnePointFive |
cliechti | 0d6029a | 2008-06-21 01:28:46 +0000 | [diff] [blame] | 112 | elif self._stopbits == STOPBITS_TWO: |
| 113 | self._port_handle.StopBits = System.IO.Ports.StopBits.Two |
| 114 | else: |
| 115 | raise ValueError("Unsupported number of stop bits: %r" % self._stopbits) |
cliechti | 58b481c | 2009-02-16 20:42:32 +0000 | [diff] [blame] | 116 | |
cliechti | 0d6029a | 2008-06-21 01:28:46 +0000 | [diff] [blame] | 117 | if self._rtscts and self._xonxoff: |
| 118 | self._port_handle.Handshake = System.IO.Ports.Handshake.RequestToSendXOnXOff |
| 119 | elif self._rtscts: |
| 120 | self._port_handle.Handshake = System.IO.Ports.Handshake.RequestToSend |
| 121 | elif self._xonxoff: |
| 122 | self._port_handle.Handshake = System.IO.Ports.Handshake.XOnXOff |
| 123 | else: |
cliechti | 91d247d | 2009-07-25 00:42:57 +0000 | [diff] [blame] | 124 | self._port_handle.Handshake = getattr(System.IO.Ports.Handshake, 'None') # reserved keyword in Py3k |
cliechti | 0d6029a | 2008-06-21 01:28:46 +0000 | [diff] [blame] | 125 | |
| 126 | #~ def __del__(self): |
| 127 | #~ self.close() |
| 128 | |
| 129 | def close(self): |
| 130 | """Close port""" |
| 131 | if self._isOpen: |
| 132 | if self._port_handle: |
| 133 | try: |
cliechti | ff0c379 | 2008-06-22 01:01:21 +0000 | [diff] [blame] | 134 | self._port_handle.Close() |
cliechti | 0d6029a | 2008-06-21 01:28:46 +0000 | [diff] [blame] | 135 | except System.IO.Ports.InvalidOperationException: |
| 136 | # ignore errors. can happen for unplugged USB serial devices |
| 137 | pass |
| 138 | self._port_handle = None |
| 139 | self._isOpen = False |
| 140 | |
| 141 | def makeDeviceName(self, port): |
cliechti | c53a8ca | 2008-06-24 11:57:32 +0000 | [diff] [blame] | 142 | try: |
| 143 | return device(port) |
| 144 | except TypeError, e: |
| 145 | raise SerialException(str(e)) |
cliechti | 0d6029a | 2008-06-21 01:28:46 +0000 | [diff] [blame] | 146 | |
| 147 | # - - - - - - - - - - - - - - - - - - - - - - - - |
cliechti | 58b481c | 2009-02-16 20:42:32 +0000 | [diff] [blame] | 148 | |
cliechti | 0d6029a | 2008-06-21 01:28:46 +0000 | [diff] [blame] | 149 | def inWaiting(self): |
| 150 | """Return the number of characters currently in the input buffer.""" |
| 151 | if not self._port_handle: raise portNotOpenError |
| 152 | return self._port_handle.BytesToRead |
| 153 | |
cliechti | 4a567a0 | 2009-07-27 22:09:31 +0000 | [diff] [blame] | 154 | def read(self, size=1): |
cliechti | 00df970 | 2014-08-04 10:12:48 +0000 | [diff] [blame] | 155 | """\ |
| 156 | Read size bytes from the serial port. If a timeout is set it may |
| 157 | return less characters as requested. With no timeout it will block |
| 158 | until the requested number of bytes is read. |
| 159 | """ |
cliechti | 0d6029a | 2008-06-21 01:28:46 +0000 | [diff] [blame] | 160 | if not self._port_handle: raise portNotOpenError |
cliechti | 4a567a0 | 2009-07-27 22:09:31 +0000 | [diff] [blame] | 161 | # must use single byte reads as this is the only way to read |
| 162 | # without applying encodings |
| 163 | data = bytearray() |
cliechti | 0d6029a | 2008-06-21 01:28:46 +0000 | [diff] [blame] | 164 | while size: |
cliechti | ff0c379 | 2008-06-22 01:01:21 +0000 | [diff] [blame] | 165 | try: |
cliechti | 4a567a0 | 2009-07-27 22:09:31 +0000 | [diff] [blame] | 166 | data.append(self._port_handle.ReadByte()) |
cliechti | ff0c379 | 2008-06-22 01:01:21 +0000 | [diff] [blame] | 167 | except System.TimeoutException, e: |
| 168 | break |
| 169 | else: |
| 170 | size -= 1 |
cliechti | 4a567a0 | 2009-07-27 22:09:31 +0000 | [diff] [blame] | 171 | return bytes(data) |
cliechti | 0d6029a | 2008-06-21 01:28:46 +0000 | [diff] [blame] | 172 | |
cliechti | 4a567a0 | 2009-07-27 22:09:31 +0000 | [diff] [blame] | 173 | def write(self, data): |
cliechti | 0d6029a | 2008-06-21 01:28:46 +0000 | [diff] [blame] | 174 | """Output the given string over the serial port.""" |
| 175 | if not self._port_handle: raise portNotOpenError |
cliechti | 00df970 | 2014-08-04 10:12:48 +0000 | [diff] [blame] | 176 | #~ if not isinstance(data, (bytes, bytearray)): |
| 177 | #~ raise TypeError('expected %s or bytearray, got %s' % (bytes, type(data))) |
cliechti | ff0c379 | 2008-06-22 01:01:21 +0000 | [diff] [blame] | 178 | try: |
cliechti | 761fd6e | 2008-06-24 11:32:43 +0000 | [diff] [blame] | 179 | # must call overloaded method with byte array argument |
| 180 | # as this is the only one not applying encodings |
| 181 | self._port_handle.Write(as_byte_array(data), 0, len(data)) |
cliechti | ff0c379 | 2008-06-22 01:01:21 +0000 | [diff] [blame] | 182 | except System.TimeoutException, e: |
| 183 | raise writeTimeoutError |
cliechti | f81362e | 2009-07-25 03:44:33 +0000 | [diff] [blame] | 184 | return len(data) |
cliechti | 0d6029a | 2008-06-21 01:28:46 +0000 | [diff] [blame] | 185 | |
| 186 | def flushInput(self): |
| 187 | """Clear input buffer, discarding all that is in the buffer.""" |
| 188 | if not self._port_handle: raise portNotOpenError |
| 189 | self._port_handle.DiscardInBuffer() |
| 190 | |
| 191 | def flushOutput(self): |
cliechti | 00df970 | 2014-08-04 10:12:48 +0000 | [diff] [blame] | 192 | """\ |
| 193 | Clear output buffer, aborting the current output and |
| 194 | discarding all that is in the buffer. |
| 195 | """ |
cliechti | 0d6029a | 2008-06-21 01:28:46 +0000 | [diff] [blame] | 196 | if not self._port_handle: raise portNotOpenError |
| 197 | self._port_handle.DiscardOutBuffer() |
| 198 | |
| 199 | def sendBreak(self, duration=0.25): |
cliechti | 00df970 | 2014-08-04 10:12:48 +0000 | [diff] [blame] | 200 | """\ |
| 201 | Send break condition. Timed, returns to idle state after given |
| 202 | duration. |
| 203 | """ |
cliechti | 0d6029a | 2008-06-21 01:28:46 +0000 | [diff] [blame] | 204 | if not self._port_handle: raise portNotOpenError |
| 205 | import time |
| 206 | self._port_handle.BreakState = True |
| 207 | time.sleep(duration) |
| 208 | self._port_handle.BreakState = False |
| 209 | |
cliechti | ff0c379 | 2008-06-22 01:01:21 +0000 | [diff] [blame] | 210 | def setBreak(self, level=True): |
cliechti | 00df970 | 2014-08-04 10:12:48 +0000 | [diff] [blame] | 211 | """ |
| 212 | Set break: Controls TXD. When active, to transmitting is possible. |
| 213 | """ |
cliechti | 0d6029a | 2008-06-21 01:28:46 +0000 | [diff] [blame] | 214 | if not self._port_handle: raise portNotOpenError |
cliechti | ff0c379 | 2008-06-22 01:01:21 +0000 | [diff] [blame] | 215 | self._port_handle.BreakState = bool(level) |
cliechti | 0d6029a | 2008-06-21 01:28:46 +0000 | [diff] [blame] | 216 | |
cliechti | ff0c379 | 2008-06-22 01:01:21 +0000 | [diff] [blame] | 217 | def setRTS(self, level=True): |
cliechti | 0d6029a | 2008-06-21 01:28:46 +0000 | [diff] [blame] | 218 | """Set terminal status line: Request To Send""" |
| 219 | if not self._port_handle: raise portNotOpenError |
cliechti | ff0c379 | 2008-06-22 01:01:21 +0000 | [diff] [blame] | 220 | self._port_handle.RtsEnable = bool(level) |
cliechti | 0d6029a | 2008-06-21 01:28:46 +0000 | [diff] [blame] | 221 | |
cliechti | ff0c379 | 2008-06-22 01:01:21 +0000 | [diff] [blame] | 222 | def setDTR(self, level=True): |
cliechti | 0d6029a | 2008-06-21 01:28:46 +0000 | [diff] [blame] | 223 | """Set terminal status line: Data Terminal Ready""" |
| 224 | if not self._port_handle: raise portNotOpenError |
cliechti | ff0c379 | 2008-06-22 01:01:21 +0000 | [diff] [blame] | 225 | self._port_handle.DtrEnable = bool(level) |
cliechti | 0d6029a | 2008-06-21 01:28:46 +0000 | [diff] [blame] | 226 | |
| 227 | def getCTS(self): |
| 228 | """Read terminal status line: Clear To Send""" |
| 229 | if not self._port_handle: raise portNotOpenError |
| 230 | return self._port_handle.CtsHolding |
| 231 | |
| 232 | def getDSR(self): |
| 233 | """Read terminal status line: Data Set Ready""" |
| 234 | if not self._port_handle: raise portNotOpenError |
| 235 | return self._port_handle.DsrHolding |
| 236 | |
cliechti | ff0c379 | 2008-06-22 01:01:21 +0000 | [diff] [blame] | 237 | def getRI(self): |
| 238 | """Read terminal status line: Ring Indicator""" |
| 239 | if not self._port_handle: raise portNotOpenError |
cliechti | 0d6029a | 2008-06-21 01:28:46 +0000 | [diff] [blame] | 240 | #~ return self._port_handle.XXX |
cliechti | ff0c379 | 2008-06-22 01:01:21 +0000 | [diff] [blame] | 241 | return False #XXX an error would be better |
cliechti | 0d6029a | 2008-06-21 01:28:46 +0000 | [diff] [blame] | 242 | |
| 243 | def getCD(self): |
| 244 | """Read terminal status line: Carrier Detect""" |
| 245 | if not self._port_handle: raise portNotOpenError |
| 246 | return self._port_handle.CDHolding |
| 247 | |
| 248 | # - - platform specific - - - - |
cliechti | f81362e | 2009-07-25 03:44:33 +0000 | [diff] [blame] | 249 | # none |
| 250 | |
| 251 | |
cliechti | 4a567a0 | 2009-07-27 22:09:31 +0000 | [diff] [blame] | 252 | # Nur Testfunktion!! |
cliechti | 0d6029a | 2008-06-21 01:28:46 +0000 | [diff] [blame] | 253 | if __name__ == '__main__': |
cliechti | 7aaead3 | 2009-07-23 14:02:41 +0000 | [diff] [blame] | 254 | import sys |
| 255 | |
cliechti | 0d6029a | 2008-06-21 01:28:46 +0000 | [diff] [blame] | 256 | s = Serial(0) |
cliechti | 7aaead3 | 2009-07-23 14:02:41 +0000 | [diff] [blame] | 257 | sys.stdio.write('%s\n' % s) |
| 258 | |
cliechti | 0d6029a | 2008-06-21 01:28:46 +0000 | [diff] [blame] | 259 | s = Serial() |
cliechti | 7aaead3 | 2009-07-23 14:02:41 +0000 | [diff] [blame] | 260 | sys.stdio.write('%s\n' % s) |
| 261 | |
| 262 | |
cliechti | 0d6029a | 2008-06-21 01:28:46 +0000 | [diff] [blame] | 263 | s.baudrate = 19200 |
| 264 | s.databits = 7 |
| 265 | s.close() |
| 266 | s.port = 0 |
| 267 | s.open() |
cliechti | 7aaead3 | 2009-07-23 14:02:41 +0000 | [diff] [blame] | 268 | sys.stdio.write('%s\n' % s) |
cliechti | 0d6029a | 2008-06-21 01:28:46 +0000 | [diff] [blame] | 269 | |