blob: 785f6d46cbbceb06bb7eadf88b6435205e33bb5e [file] [log] [blame]
cliechti89b4af12002-02-12 23:24:41 +00001#! python
cliechtic54b2c82008-06-21 01:59:08 +00002# Python Serial Port Extension for Win32, Linux, BSD, Jython
3# serial driver for win32
4# see __init__.py
cliechti89b4af12002-02-12 23:24:41 +00005#
Chris Liechti68340d72015-08-03 14:15:48 +02006# (C) 2001-2015 Chris Liechti <cliechti@gmx.net>
cliechti89b4af12002-02-12 23:24:41 +00007# this is distributed under a free software license, see license.txt
cliechti183d4ae2009-07-23 22:03:51 +00008#
9# Initial patch to use ctypes by Giovanni Bajo <rasky@develer.com>
cliechti89b4af12002-02-12 23:24:41 +000010
cliechti183d4ae2009-07-23 22:03:51 +000011import ctypes
cliechti39cfb7b2011-08-22 00:30:07 +000012from serial import win32
cliechti183d4ae2009-07-23 22:03:51 +000013
cliechti39cfb7b2011-08-22 00:30:07 +000014from serial.serialutil import *
cliechti89b4af12002-02-12 23:24:41 +000015
cliechti4a567a02009-07-27 22:09:31 +000016
cliechti4e838702003-08-28 22:18:02 +000017def device(portnum):
cliechtid6bf52c2003-10-01 02:28:12 +000018 """Turn a port number into a device name"""
cliechti4a567a02009-07-27 22:09:31 +000019 return 'COM%d' % (portnum+1) # numbers are transformed to a string
20
cliechti4e838702003-08-28 22:18:02 +000021
cliechtif81362e2009-07-25 03:44:33 +000022class Win32Serial(SerialBase):
cliechti1e2a6df2009-07-24 02:00:50 +000023 """Serial port implementation for Win32 based on ctypes."""
cliechti89b4af12002-02-12 23:24:41 +000024
cliechti4a567a02009-07-27 22:09:31 +000025 BAUDRATES = (50, 75, 110, 134, 150, 200, 300, 600, 1200, 1800, 2400, 4800,
26 9600, 19200, 38400, 57600, 115200)
cliechti80a0ed12003-10-03 23:53:42 +000027
cliechti5735a072009-10-26 23:57:48 +000028 def __init__(self, *args, **kwargs):
29 self.hComPort = None
cliechti1ae5ab02013-10-11 01:08:02 +000030 self._overlappedRead = None
31 self._overlappedWrite = None
cliechti1f89a0a2011-08-05 02:53:24 +000032 self._rtsToggle = False
cliechti22175a72011-12-29 00:17:53 +000033
34 self._rtsState = win32.RTS_CONTROL_ENABLE
35 self._dtrState = win32.DTR_CONTROL_ENABLE
36
cliechti1ae5ab02013-10-11 01:08:02 +000037
cliechti5735a072009-10-26 23:57:48 +000038 SerialBase.__init__(self, *args, **kwargs)
39
cliechtid6bf52c2003-10-01 02:28:12 +000040 def open(self):
cliechti7d448562014-08-03 21:57:45 +000041 """\
42 Open port with current settings. This may throw a SerialException
43 if the port cannot be opened.
44 """
cliechtid6bf52c2003-10-01 02:28:12 +000045 if self._port is None:
46 raise SerialException("Port must be configured before it can be used.")
cliechti8f69e702011-03-19 00:22:32 +000047 if self._isOpen:
48 raise SerialException("Port is already open.")
cliechti8b7cff02008-06-24 12:11:57 +000049 # the "\\.\COMx" format is required for devices other than COM1-COM8
50 # not all versions of windows seem to support this properly
51 # so that the first few ports are used with the DOS device name
52 port = self.portstr
cliechti4a567a02009-07-27 22:09:31 +000053 try:
54 if port.upper().startswith('COM') and int(port[3:]) > 8:
55 port = '\\\\.\\' + port
56 except ValueError:
57 # for like COMnotanumber
58 pass
cliechtie37b6a82009-07-24 12:19:50 +000059 self.hComPort = win32.CreateFile(port,
60 win32.GENERIC_READ | win32.GENERIC_WRITE,
61 0, # exclusive access
62 None, # no security
63 win32.OPEN_EXISTING,
64 win32.FILE_ATTRIBUTE_NORMAL | win32.FILE_FLAG_OVERLAPPED,
65 0)
66 if self.hComPort == win32.INVALID_HANDLE_VALUE:
cliechti4a567a02009-07-27 22:09:31 +000067 self.hComPort = None # 'cause __del__ is called anyway
cliechti1083be72011-12-28 20:45:30 +000068 raise SerialException("could not open port %r: %r" % (self.portstr, ctypes.WinError()))
cliechtie37b6a82009-07-24 12:19:50 +000069
cliechti1ae5ab02013-10-11 01:08:02 +000070 try:
71 self._overlappedRead = win32.OVERLAPPED()
72 self._overlappedRead.hEvent = win32.CreateEvent(None, 1, 0, None)
73 self._overlappedWrite = win32.OVERLAPPED()
74 #~ self._overlappedWrite.hEvent = win32.CreateEvent(None, 1, 0, None)
75 self._overlappedWrite.hEvent = win32.CreateEvent(None, 0, 0, None)
cliechti89b4af12002-02-12 23:24:41 +000076
cliechti1ae5ab02013-10-11 01:08:02 +000077 # Setup a 4k buffer
78 win32.SetupComm(self.hComPort, 4096, 4096)
cliechti89b4af12002-02-12 23:24:41 +000079
cliechti1ae5ab02013-10-11 01:08:02 +000080 # Save original timeout values:
81 self._orgTimeouts = win32.COMMTIMEOUTS()
82 win32.GetCommTimeouts(self.hComPort, ctypes.byref(self._orgTimeouts))
cliechtiedfba4e2009-02-07 00:29:47 +000083
cliechti1ae5ab02013-10-11 01:08:02 +000084 self._reconfigurePort()
cliechti89b4af12002-02-12 23:24:41 +000085
cliechti1ae5ab02013-10-11 01:08:02 +000086 # Clear buffers:
87 # Remove anything that was there
88 win32.PurgeComm(self.hComPort,
89 win32.PURGE_TXCLEAR | win32.PURGE_TXABORT |
90 win32.PURGE_RXCLEAR | win32.PURGE_RXABORT)
91 except:
92 try:
93 self._close()
94 except:
95 # ignore any exception when closing the port
96 # also to keep original exception that happened when setting up
97 pass
98 self.hComPort = None
99 raise
100 else:
101 self._isOpen = True
102
cliechti89b4af12002-02-12 23:24:41 +0000103
cliechtid6bf52c2003-10-01 02:28:12 +0000104 def _reconfigurePort(self):
cliechticc8d9d22008-07-06 22:42:44 +0000105 """Set communication parameters on opened port."""
cliechtid6bf52c2003-10-01 02:28:12 +0000106 if not self.hComPort:
107 raise SerialException("Can only operate on a valid port handle")
cliechtiedfba4e2009-02-07 00:29:47 +0000108
109 # Set Windows timeout values
110 # timeouts is a tuple with the following items:
111 # (ReadIntervalTimeout,ReadTotalTimeoutMultiplier,
112 # ReadTotalTimeoutConstant,WriteTotalTimeoutMultiplier,
113 # WriteTotalTimeoutConstant)
cliechtid6bf52c2003-10-01 02:28:12 +0000114 if self._timeout is None:
115 timeouts = (0, 0, 0, 0, 0)
116 elif self._timeout == 0:
cliechti183d4ae2009-07-23 22:03:51 +0000117 timeouts = (win32.MAXDWORD, 0, 0, 0, 0)
cliechtid6bf52c2003-10-01 02:28:12 +0000118 else:
119 timeouts = (0, 0, int(self._timeout*1000), 0, 0)
cliechti679bfa62008-06-20 23:58:15 +0000120 if self._timeout != 0 and self._interCharTimeout is not None:
121 timeouts = (int(self._interCharTimeout * 1000),) + timeouts[1:]
cliechtiedfba4e2009-02-07 00:29:47 +0000122
cliechti62611612004-04-20 01:55:43 +0000123 if self._writeTimeout is None:
124 pass
125 elif self._writeTimeout == 0:
cliechti183d4ae2009-07-23 22:03:51 +0000126 timeouts = timeouts[:-2] + (0, win32.MAXDWORD)
cliechti62611612004-04-20 01:55:43 +0000127 else:
128 timeouts = timeouts[:-2] + (0, int(self._writeTimeout*1000))
cliechti183d4ae2009-07-23 22:03:51 +0000129 win32.SetCommTimeouts(self.hComPort, ctypes.byref(win32.COMMTIMEOUTS(*timeouts)))
cliechti89b4af12002-02-12 23:24:41 +0000130
cliechti183d4ae2009-07-23 22:03:51 +0000131 win32.SetCommMask(self.hComPort, win32.EV_ERR)
cliechti89b4af12002-02-12 23:24:41 +0000132
cliechti95c62212002-03-04 22:17:53 +0000133 # Setup the connection info.
134 # Get state and modify it:
cliechti183d4ae2009-07-23 22:03:51 +0000135 comDCB = win32.DCB()
136 win32.GetCommState(self.hComPort, ctypes.byref(comDCB))
cliechtid6bf52c2003-10-01 02:28:12 +0000137 comDCB.BaudRate = self._baudrate
138
139 if self._bytesize == FIVEBITS:
140 comDCB.ByteSize = 5
141 elif self._bytesize == SIXBITS:
142 comDCB.ByteSize = 6
143 elif self._bytesize == SEVENBITS:
144 comDCB.ByteSize = 7
145 elif self._bytesize == EIGHTBITS:
146 comDCB.ByteSize = 8
147 else:
148 raise ValueError("Unsupported number of data bits: %r" % self._bytesize)
149
150 if self._parity == PARITY_NONE:
cliechti183d4ae2009-07-23 22:03:51 +0000151 comDCB.Parity = win32.NOPARITY
152 comDCB.fParity = 0 # Disable Parity Check
cliechtid6bf52c2003-10-01 02:28:12 +0000153 elif self._parity == PARITY_EVEN:
cliechti183d4ae2009-07-23 22:03:51 +0000154 comDCB.Parity = win32.EVENPARITY
155 comDCB.fParity = 1 # Enable Parity Check
cliechtid6bf52c2003-10-01 02:28:12 +0000156 elif self._parity == PARITY_ODD:
cliechti183d4ae2009-07-23 22:03:51 +0000157 comDCB.Parity = win32.ODDPARITY
158 comDCB.fParity = 1 # Enable Parity Check
cliechtic54b2c82008-06-21 01:59:08 +0000159 elif self._parity == PARITY_MARK:
cliechti183d4ae2009-07-23 22:03:51 +0000160 comDCB.Parity = win32.MARKPARITY
161 comDCB.fParity = 1 # Enable Parity Check
cliechtic54b2c82008-06-21 01:59:08 +0000162 elif self._parity == PARITY_SPACE:
cliechti183d4ae2009-07-23 22:03:51 +0000163 comDCB.Parity = win32.SPACEPARITY
164 comDCB.fParity = 1 # Enable Parity Check
cliechtid6bf52c2003-10-01 02:28:12 +0000165 else:
166 raise ValueError("Unsupported parity mode: %r" % self._parity)
167
168 if self._stopbits == STOPBITS_ONE:
cliechti183d4ae2009-07-23 22:03:51 +0000169 comDCB.StopBits = win32.ONESTOPBIT
cliechti58b481c2009-02-16 20:42:32 +0000170 elif self._stopbits == STOPBITS_ONE_POINT_FIVE:
cliechti183d4ae2009-07-23 22:03:51 +0000171 comDCB.StopBits = win32.ONE5STOPBITS
cliechtid6bf52c2003-10-01 02:28:12 +0000172 elif self._stopbits == STOPBITS_TWO:
cliechti183d4ae2009-07-23 22:03:51 +0000173 comDCB.StopBits = win32.TWOSTOPBITS
cliechtid6bf52c2003-10-01 02:28:12 +0000174 else:
175 raise ValueError("Unsupported number of stop bits: %r" % self._stopbits)
cliechtiedfba4e2009-02-07 00:29:47 +0000176
cliechtid6bf52c2003-10-01 02:28:12 +0000177 comDCB.fBinary = 1 # Enable Binary Transmission
178 # Char. w/ Parity-Err are replaced with 0xff (if fErrorChar is set to TRUE)
179 if self._rtscts:
cliechti183d4ae2009-07-23 22:03:51 +0000180 comDCB.fRtsControl = win32.RTS_CONTROL_HANDSHAKE
cliechti1f89a0a2011-08-05 02:53:24 +0000181 elif self._rtsToggle:
182 comDCB.fRtsControl = win32.RTS_CONTROL_TOGGLE
cliechtid6bf52c2003-10-01 02:28:12 +0000183 else:
cliechti7ffcfef2004-07-28 01:08:25 +0000184 comDCB.fRtsControl = self._rtsState
cliechtif46e0a82005-05-19 15:24:57 +0000185 if self._dsrdtr:
cliechti183d4ae2009-07-23 22:03:51 +0000186 comDCB.fDtrControl = win32.DTR_CONTROL_HANDSHAKE
cliechtif46e0a82005-05-19 15:24:57 +0000187 else:
cliechti7ffcfef2004-07-28 01:08:25 +0000188 comDCB.fDtrControl = self._dtrState
cliechti1f89a0a2011-08-05 02:53:24 +0000189
190 if self._rtsToggle:
191 comDCB.fOutxCtsFlow = 0
192 else:
193 comDCB.fOutxCtsFlow = self._rtscts
cliechtif46e0a82005-05-19 15:24:57 +0000194 comDCB.fOutxDsrFlow = self._dsrdtr
cliechtid6bf52c2003-10-01 02:28:12 +0000195 comDCB.fOutX = self._xonxoff
196 comDCB.fInX = self._xonxoff
197 comDCB.fNull = 0
198 comDCB.fErrorChar = 0
199 comDCB.fAbortOnError = 0
cliechti62611612004-04-20 01:55:43 +0000200 comDCB.XonChar = XON
201 comDCB.XoffChar = XOFF
cliechtid6bf52c2003-10-01 02:28:12 +0000202
cliechti183d4ae2009-07-23 22:03:51 +0000203 if not win32.SetCommState(self.hComPort, ctypes.byref(comDCB)):
cliechti1083be72011-12-28 20:45:30 +0000204 raise ValueError("Cannot configure port, some setting was wrong. Original message: %r" % ctypes.WinError())
cliechti95c62212002-03-04 22:17:53 +0000205
cliechtid6bf52c2003-10-01 02:28:12 +0000206 #~ def __del__(self):
207 #~ self.close()
208
cliechti1ae5ab02013-10-11 01:08:02 +0000209
210 def _close(self):
211 """internal close port helper"""
212 if self.hComPort:
213 # Restore original timeout values:
214 win32.SetCommTimeouts(self.hComPort, self._orgTimeouts)
215 # Close COM-Port:
216 win32.CloseHandle(self.hComPort)
217 if self._overlappedRead is not None:
218 win32.CloseHandle(self._overlappedRead.hEvent)
219 self._overlappedRead = None
220 if self._overlappedWrite is not None:
221 win32.CloseHandle(self._overlappedWrite.hEvent)
222 self._overlappedWrite = None
223 self.hComPort = None
224
cliechtid6bf52c2003-10-01 02:28:12 +0000225 def close(self):
226 """Close port"""
227 if self._isOpen:
cliechti1ae5ab02013-10-11 01:08:02 +0000228 self._close()
cliechtid6bf52c2003-10-01 02:28:12 +0000229 self._isOpen = False
230
231 def makeDeviceName(self, port):
cliechti8b7cff02008-06-24 12:11:57 +0000232 return device(port)
cliechtid6bf52c2003-10-01 02:28:12 +0000233
234 # - - - - - - - - - - - - - - - - - - - - - - - -
cliechtiedfba4e2009-02-07 00:29:47 +0000235
cliechti89b4af12002-02-12 23:24:41 +0000236 def inWaiting(self):
cliechtid6bf52c2003-10-01 02:28:12 +0000237 """Return the number of characters currently in the input buffer."""
cliechti183d4ae2009-07-23 22:03:51 +0000238 flags = win32.DWORD()
239 comstat = win32.COMSTAT()
240 if not win32.ClearCommError(self.hComPort, ctypes.byref(flags), ctypes.byref(comstat)):
241 raise SerialException('call to ClearCommError failed')
cliechti89b4af12002-02-12 23:24:41 +0000242 return comstat.cbInQue
243
cliechti4a567a02009-07-27 22:09:31 +0000244 def read(self, size=1):
cliechti7d448562014-08-03 21:57:45 +0000245 """\
246 Read size bytes from the serial port. If a timeout is set it may
247 return less characters as requested. With no timeout it will block
248 until the requested number of bytes is read."""
cliechti89b4af12002-02-12 23:24:41 +0000249 if not self.hComPort: raise portNotOpenError
cliechti89b4af12002-02-12 23:24:41 +0000250 if size > 0:
cliechti183d4ae2009-07-23 22:03:51 +0000251 win32.ResetEvent(self._overlappedRead.hEvent)
252 flags = win32.DWORD()
253 comstat = win32.COMSTAT()
254 if not win32.ClearCommError(self.hComPort, ctypes.byref(flags), ctypes.byref(comstat)):
255 raise SerialException('call to ClearCommError failed')
cliechti5c39e702002-06-04 14:56:34 +0000256 if self.timeout == 0:
cliechti17f177f2002-06-07 22:33:37 +0000257 n = min(comstat.cbInQue, size)
258 if n > 0:
cliechti183d4ae2009-07-23 22:03:51 +0000259 buf = ctypes.create_string_buffer(n)
260 rc = win32.DWORD()
cliechti14213e12010-05-20 22:31:18 +0000261 err = win32.ReadFile(self.hComPort, buf, n, ctypes.byref(rc), ctypes.byref(self._overlappedRead))
cliechti183d4ae2009-07-23 22:03:51 +0000262 if not err and win32.GetLastError() != win32.ERROR_IO_PENDING:
cliechti1083be72011-12-28 20:45:30 +0000263 raise SerialException("ReadFile failed (%r)" % ctypes.WinError())
cliechti183d4ae2009-07-23 22:03:51 +0000264 err = win32.WaitForSingleObject(self._overlappedRead.hEvent, win32.INFINITE)
265 read = buf.raw[:rc.value]
cliechtif622faf2003-07-12 23:41:43 +0000266 else:
cliechti4a567a02009-07-27 22:09:31 +0000267 read = bytes()
cliechti5c39e702002-06-04 14:56:34 +0000268 else:
cliechti183d4ae2009-07-23 22:03:51 +0000269 buf = ctypes.create_string_buffer(size)
270 rc = win32.DWORD()
271 err = win32.ReadFile(self.hComPort, buf, size, ctypes.byref(rc), ctypes.byref(self._overlappedRead))
272 if not err and win32.GetLastError() != win32.ERROR_IO_PENDING:
cliechti1083be72011-12-28 20:45:30 +0000273 raise SerialException("ReadFile failed (%r)" % ctypes.WinError())
cliechti183d4ae2009-07-23 22:03:51 +0000274 err = win32.GetOverlappedResult(self.hComPort, ctypes.byref(self._overlappedRead), ctypes.byref(rc), True)
275 read = buf.raw[:rc.value]
cliechtif622faf2003-07-12 23:41:43 +0000276 else:
cliechti4a567a02009-07-27 22:09:31 +0000277 read = bytes()
278 return bytes(read)
cliechti89b4af12002-02-12 23:24:41 +0000279
cliechti4a567a02009-07-27 22:09:31 +0000280 def write(self, data):
cliechtid6bf52c2003-10-01 02:28:12 +0000281 """Output the given string over the serial port."""
cliechti89b4af12002-02-12 23:24:41 +0000282 if not self.hComPort: raise portNotOpenError
cliechti23dc2a02009-07-30 17:25:09 +0000283 #~ if not isinstance(data, (bytes, bytearray)):
284 #~ raise TypeError('expected %s or bytearray, got %s' % (bytes, type(data)))
285 # convert data (needed in case of memoryview instance: Py 3.1 io lib), ctypes doesn't like memoryview
cliechti38077122013-10-16 02:57:27 +0000286 data = to_bytes(data)
cliechtib2f5fc82006-10-20 00:09:07 +0000287 if data:
cliechti107db8d2004-01-15 01:20:23 +0000288 #~ win32event.ResetEvent(self._overlappedWrite.hEvent)
cliechti183d4ae2009-07-23 22:03:51 +0000289 n = win32.DWORD()
cliechtie37b6a82009-07-24 12:19:50 +0000290 err = win32.WriteFile(self.hComPort, data, len(data), ctypes.byref(n), self._overlappedWrite)
cliechti183d4ae2009-07-23 22:03:51 +0000291 if not err and win32.GetLastError() != win32.ERROR_IO_PENDING:
cliechti1083be72011-12-28 20:45:30 +0000292 raise SerialException("WriteFile failed (%r)" % ctypes.WinError())
cliechti31000fc2011-08-05 01:47:26 +0000293 if self._writeTimeout != 0: # if blocking (None) or w/ write timeout (>0)
294 # Wait for the write to complete.
295 #~ win32.WaitForSingleObject(self._overlappedWrite.hEvent, win32.INFINITE)
296 err = win32.GetOverlappedResult(self.hComPort, self._overlappedWrite, ctypes.byref(n), True)
297 if n.value != len(data):
298 raise writeTimeoutError
cliechti23dc2a02009-07-30 17:25:09 +0000299 return n.value
300 else:
301 return 0
cliechtiedfba4e2009-02-07 00:29:47 +0000302
cliechti26409782013-05-31 00:47:16 +0000303 def flush(self):
cliechti7d448562014-08-03 21:57:45 +0000304 """\
305 Flush of file like objects. In this case, wait until all data
306 is written.
307 """
cliechti26409782013-05-31 00:47:16 +0000308 while self.outWaiting():
309 time.sleep(0.05)
310 # XXX could also use WaitCommEvent with mask EV_TXEMPTY, but it would
311 # require overlapped IO and its also only possible to set a single mask
312 # on the port---
cliechti89b4af12002-02-12 23:24:41 +0000313
314 def flushInput(self):
cliechtid6bf52c2003-10-01 02:28:12 +0000315 """Clear input buffer, discarding all that is in the buffer."""
cliechti89b4af12002-02-12 23:24:41 +0000316 if not self.hComPort: raise portNotOpenError
cliechti183d4ae2009-07-23 22:03:51 +0000317 win32.PurgeComm(self.hComPort, win32.PURGE_RXCLEAR | win32.PURGE_RXABORT)
cliechti89b4af12002-02-12 23:24:41 +0000318
319 def flushOutput(self):
cliechti7d448562014-08-03 21:57:45 +0000320 """\
321 Clear output buffer, aborting the current output and discarding all
322 that is in the buffer.
323 """
cliechti89b4af12002-02-12 23:24:41 +0000324 if not self.hComPort: raise portNotOpenError
cliechti183d4ae2009-07-23 22:03:51 +0000325 win32.PurgeComm(self.hComPort, win32.PURGE_TXCLEAR | win32.PURGE_TXABORT)
cliechti89b4af12002-02-12 23:24:41 +0000326
cliechtiaaa04602006-02-05 23:02:46 +0000327 def sendBreak(self, duration=0.25):
cliechti7d448562014-08-03 21:57:45 +0000328 """\
329 Send break condition. Timed, returns to idle state after given duration.
330 """
cliechti89b4af12002-02-12 23:24:41 +0000331 if not self.hComPort: raise portNotOpenError
cliechti1b327022002-02-13 22:26:06 +0000332 import time
cliechti183d4ae2009-07-23 22:03:51 +0000333 win32.SetCommBreak(self.hComPort)
cliechtiaaa04602006-02-05 23:02:46 +0000334 time.sleep(duration)
cliechti183d4ae2009-07-23 22:03:51 +0000335 win32.ClearCommBreak(self.hComPort)
cliechti89b4af12002-02-12 23:24:41 +0000336
cliechti997b63c2008-06-21 00:09:31 +0000337 def setBreak(self, level=1):
338 """Set break: Controls TXD. When active, to transmitting is possible."""
339 if not self.hComPort: raise portNotOpenError
340 if level:
cliechti183d4ae2009-07-23 22:03:51 +0000341 win32.SetCommBreak(self.hComPort)
cliechti997b63c2008-06-21 00:09:31 +0000342 else:
cliechti183d4ae2009-07-23 22:03:51 +0000343 win32.ClearCommBreak(self.hComPort)
cliechti997b63c2008-06-21 00:09:31 +0000344
cliechti93db61b2006-08-26 19:16:18 +0000345 def setRTS(self, level=1):
cliechtid6bf52c2003-10-01 02:28:12 +0000346 """Set terminal status line: Request To Send"""
cliechti22175a72011-12-29 00:17:53 +0000347 # remember level for reconfigure
cliechti89b4af12002-02-12 23:24:41 +0000348 if level:
cliechtie37b6a82009-07-24 12:19:50 +0000349 self._rtsState = win32.RTS_CONTROL_ENABLE
cliechti89b4af12002-02-12 23:24:41 +0000350 else:
cliechtie37b6a82009-07-24 12:19:50 +0000351 self._rtsState = win32.RTS_CONTROL_DISABLE
cliechti22175a72011-12-29 00:17:53 +0000352 # also apply now if port is open
353 if self.hComPort:
354 if level:
355 win32.EscapeCommFunction(self.hComPort, win32.SETRTS)
356 else:
357 win32.EscapeCommFunction(self.hComPort, win32.CLRRTS)
cliechti89b4af12002-02-12 23:24:41 +0000358
cliechti93db61b2006-08-26 19:16:18 +0000359 def setDTR(self, level=1):
cliechtid6bf52c2003-10-01 02:28:12 +0000360 """Set terminal status line: Data Terminal Ready"""
cliechti22175a72011-12-29 00:17:53 +0000361 # remember level for reconfigure
cliechti89b4af12002-02-12 23:24:41 +0000362 if level:
cliechtie37b6a82009-07-24 12:19:50 +0000363 self._dtrState = win32.DTR_CONTROL_ENABLE
cliechti89b4af12002-02-12 23:24:41 +0000364 else:
cliechtie37b6a82009-07-24 12:19:50 +0000365 self._dtrState = win32.DTR_CONTROL_DISABLE
cliechti22175a72011-12-29 00:17:53 +0000366 # also apply now if port is open
367 if self.hComPort:
368 if level:
369 win32.EscapeCommFunction(self.hComPort, win32.SETDTR)
370 else:
371 win32.EscapeCommFunction(self.hComPort, win32.CLRDTR)
cliechti183d4ae2009-07-23 22:03:51 +0000372
373 def _GetCommModemStatus(self):
374 stat = win32.DWORD()
375 win32.GetCommModemStatus(self.hComPort, ctypes.byref(stat))
376 return stat.value
cliechti89b4af12002-02-12 23:24:41 +0000377
378 def getCTS(self):
cliechtid6bf52c2003-10-01 02:28:12 +0000379 """Read terminal status line: Clear To Send"""
cliechti89b4af12002-02-12 23:24:41 +0000380 if not self.hComPort: raise portNotOpenError
cliechti183d4ae2009-07-23 22:03:51 +0000381 return win32.MS_CTS_ON & self._GetCommModemStatus() != 0
cliechti89b4af12002-02-12 23:24:41 +0000382
383 def getDSR(self):
cliechtid6bf52c2003-10-01 02:28:12 +0000384 """Read terminal status line: Data Set Ready"""
cliechti89b4af12002-02-12 23:24:41 +0000385 if not self.hComPort: raise portNotOpenError
cliechti183d4ae2009-07-23 22:03:51 +0000386 return win32.MS_DSR_ON & self._GetCommModemStatus() != 0
cliechti89b4af12002-02-12 23:24:41 +0000387
cliechtid0b8b272002-02-14 01:33:08 +0000388 def getRI(self):
cliechtid6bf52c2003-10-01 02:28:12 +0000389 """Read terminal status line: Ring Indicator"""
cliechtid0b8b272002-02-14 01:33:08 +0000390 if not self.hComPort: raise portNotOpenError
cliechti183d4ae2009-07-23 22:03:51 +0000391 return win32.MS_RING_ON & self._GetCommModemStatus() != 0
cliechti89b4af12002-02-12 23:24:41 +0000392
cliechtid0b8b272002-02-14 01:33:08 +0000393 def getCD(self):
cliechtid6bf52c2003-10-01 02:28:12 +0000394 """Read terminal status line: Carrier Detect"""
cliechtid0b8b272002-02-14 01:33:08 +0000395 if not self.hComPort: raise portNotOpenError
cliechti183d4ae2009-07-23 22:03:51 +0000396 return win32.MS_RLSD_ON & self._GetCommModemStatus() != 0
cliechti89b4af12002-02-12 23:24:41 +0000397
cliechtia30a8a02003-10-05 12:28:13 +0000398 # - - platform specific - - - -
399
cliechti59199642011-12-28 20:54:30 +0000400 def setBufferSize(self, rx_size=4096, tx_size=None):
401 """\
402 Recommend a buffer size to the driver (device driver can ignore this
403 vlaue). Must be called before the port is opended.
404 """
405 if tx_size is None: tx_size = rx_size
406 win32.SetupComm(self.hComPort, rx_size, tx_size)
407
cliechtia30a8a02003-10-05 12:28:13 +0000408 def setXON(self, level=True):
cliechti2f0f8a32011-12-28 22:10:00 +0000409 """\
410 Manually control flow - when software flow control is enabled.
411 This will send XON (true) and XOFF (false) to the other device.
412 WARNING: this function is not portable to different platforms!
413 """
cliechtia30a8a02003-10-05 12:28:13 +0000414 if not self.hComPort: raise portNotOpenError
415 if level:
cliechti183d4ae2009-07-23 22:03:51 +0000416 win32.EscapeCommFunction(self.hComPort, win32.SETXON)
cliechtia30a8a02003-10-05 12:28:13 +0000417 else:
cliechti183d4ae2009-07-23 22:03:51 +0000418 win32.EscapeCommFunction(self.hComPort, win32.SETXOFF)
cliechtia30a8a02003-10-05 12:28:13 +0000419
cliechtic8e83d82009-07-21 21:34:05 +0000420 def outWaiting(self):
cliechti7d448562014-08-03 21:57:45 +0000421 """Return how many characters the in the outgoing buffer"""
cliechti183d4ae2009-07-23 22:03:51 +0000422 flags = win32.DWORD()
423 comstat = win32.COMSTAT()
424 if not win32.ClearCommError(self.hComPort, ctypes.byref(flags), ctypes.byref(comstat)):
425 raise SerialException('call to ClearCommError failed')
cliechtic8e83d82009-07-21 21:34:05 +0000426 return comstat.cbOutQue
427
cliechti1f89a0a2011-08-05 02:53:24 +0000428 # functions useful for RS-485 adapters
429 def setRtsToggle(self, rtsToggle):
430 """Change RTS toggle control setting."""
431 self._rtsToggle = rtsToggle
432 if self._isOpen: self._reconfigurePort()
433
434 def getRtsToggle(self):
435 """Get the current RTS toggle control setting."""
436 return self._rtsToggle
437
438 rtsToggle = property(getRtsToggle, setRtsToggle, doc="RTS toggle control setting")
439
cliechtif81362e2009-07-25 03:44:33 +0000440
cliechti4a567a02009-07-27 22:09:31 +0000441# assemble Serial class with the platform specific implementation and the base
442# for file-like behavior. for Python 2.6 and newer, that provide the new I/O
443# library, derive from io.RawIOBase
444try:
445 import io
446except ImportError:
447 # classic version with our own file-like emulation
448 class Serial(Win32Serial, FileLike):
cliechtif81362e2009-07-25 03:44:33 +0000449 pass
cliechti4a567a02009-07-27 22:09:31 +0000450else:
451 # io library present
452 class Serial(Win32Serial, io.RawIOBase):
453 pass
cliechtif81362e2009-07-25 03:44:33 +0000454
cliechtic8e83d82009-07-21 21:34:05 +0000455
cliechtiedfba4e2009-02-07 00:29:47 +0000456# Nur Testfunktion!!
cliechti89b4af12002-02-12 23:24:41 +0000457if __name__ == '__main__':
cliechti93db61b2006-08-26 19:16:18 +0000458 s = Serial(0)
cliechti7aaead32009-07-23 14:02:41 +0000459 sys.stdout.write("%s\n" % s)
cliechtiedfba4e2009-02-07 00:29:47 +0000460
cliechtid6bf52c2003-10-01 02:28:12 +0000461 s = Serial()
cliechti7aaead32009-07-23 14:02:41 +0000462 sys.stdout.write("%s\n" % s)
cliechtiedfba4e2009-02-07 00:29:47 +0000463
cliechtid6bf52c2003-10-01 02:28:12 +0000464 s.baudrate = 19200
465 s.databits = 7
466 s.close()
cliechti93db61b2006-08-26 19:16:18 +0000467 s.port = 0
cliechtid6bf52c2003-10-01 02:28:12 +0000468 s.open()
cliechti7aaead32009-07-23 14:02:41 +0000469 sys.stdout.write("%s\n" % s)
cliechti89b4af12002-02-12 23:24:41 +0000470