blob: e50cae7adc59c2ade0ae5d4d50e2c62117746ab0 [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
Chris Liechtiaf6d0462015-08-03 17:21:14 +020012import io
cliechti39cfb7b2011-08-22 00:30:07 +000013from serial import win32
cliechti183d4ae2009-07-23 22:03:51 +000014
cliechti39cfb7b2011-08-22 00:30:07 +000015from serial.serialutil import *
cliechti89b4af12002-02-12 23:24:41 +000016
cliechti4a567a02009-07-27 22:09:31 +000017
cliechti4e838702003-08-28 22:18:02 +000018def device(portnum):
cliechtid6bf52c2003-10-01 02:28:12 +000019 """Turn a port number into a device name"""
cliechti4a567a02009-07-27 22:09:31 +000020 return 'COM%d' % (portnum+1) # numbers are transformed to a string
21
cliechti4e838702003-08-28 22:18:02 +000022
Chris Liechtiaf6d0462015-08-03 17:21:14 +020023class Serial(SerialBase, io.RawIOBase):
cliechti1e2a6df2009-07-24 02:00:50 +000024 """Serial port implementation for Win32 based on ctypes."""
cliechti89b4af12002-02-12 23:24:41 +000025
cliechti4a567a02009-07-27 22:09:31 +000026 BAUDRATES = (50, 75, 110, 134, 150, 200, 300, 600, 1200, 1800, 2400, 4800,
27 9600, 19200, 38400, 57600, 115200)
cliechti80a0ed12003-10-03 23:53:42 +000028
cliechti5735a072009-10-26 23:57:48 +000029 def __init__(self, *args, **kwargs):
30 self.hComPort = None
cliechti1ae5ab02013-10-11 01:08:02 +000031 self._overlappedRead = None
32 self._overlappedWrite = None
cliechti1f89a0a2011-08-05 02:53:24 +000033 self._rtsToggle = False
cliechti22175a72011-12-29 00:17:53 +000034
35 self._rtsState = win32.RTS_CONTROL_ENABLE
36 self._dtrState = win32.DTR_CONTROL_ENABLE
37
cliechti1ae5ab02013-10-11 01:08:02 +000038
cliechti5735a072009-10-26 23:57:48 +000039 SerialBase.__init__(self, *args, **kwargs)
40
cliechtid6bf52c2003-10-01 02:28:12 +000041 def open(self):
cliechti7d448562014-08-03 21:57:45 +000042 """\
43 Open port with current settings. This may throw a SerialException
44 if the port cannot be opened.
45 """
cliechtid6bf52c2003-10-01 02:28:12 +000046 if self._port is None:
47 raise SerialException("Port must be configured before it can be used.")
cliechti8f69e702011-03-19 00:22:32 +000048 if self._isOpen:
49 raise SerialException("Port is already open.")
cliechti8b7cff02008-06-24 12:11:57 +000050 # the "\\.\COMx" format is required for devices other than COM1-COM8
51 # not all versions of windows seem to support this properly
52 # so that the first few ports are used with the DOS device name
53 port = self.portstr
cliechti4a567a02009-07-27 22:09:31 +000054 try:
55 if port.upper().startswith('COM') and int(port[3:]) > 8:
56 port = '\\\\.\\' + port
57 except ValueError:
58 # for like COMnotanumber
59 pass
cliechtie37b6a82009-07-24 12:19:50 +000060 self.hComPort = win32.CreateFile(port,
61 win32.GENERIC_READ | win32.GENERIC_WRITE,
62 0, # exclusive access
63 None, # no security
64 win32.OPEN_EXISTING,
65 win32.FILE_ATTRIBUTE_NORMAL | win32.FILE_FLAG_OVERLAPPED,
66 0)
67 if self.hComPort == win32.INVALID_HANDLE_VALUE:
cliechti4a567a02009-07-27 22:09:31 +000068 self.hComPort = None # 'cause __del__ is called anyway
cliechti1083be72011-12-28 20:45:30 +000069 raise SerialException("could not open port %r: %r" % (self.portstr, ctypes.WinError()))
cliechtie37b6a82009-07-24 12:19:50 +000070
cliechti1ae5ab02013-10-11 01:08:02 +000071 try:
72 self._overlappedRead = win32.OVERLAPPED()
73 self._overlappedRead.hEvent = win32.CreateEvent(None, 1, 0, None)
74 self._overlappedWrite = win32.OVERLAPPED()
75 #~ self._overlappedWrite.hEvent = win32.CreateEvent(None, 1, 0, None)
76 self._overlappedWrite.hEvent = win32.CreateEvent(None, 0, 0, None)
cliechti89b4af12002-02-12 23:24:41 +000077
cliechti1ae5ab02013-10-11 01:08:02 +000078 # Setup a 4k buffer
79 win32.SetupComm(self.hComPort, 4096, 4096)
cliechti89b4af12002-02-12 23:24:41 +000080
cliechti1ae5ab02013-10-11 01:08:02 +000081 # Save original timeout values:
82 self._orgTimeouts = win32.COMMTIMEOUTS()
83 win32.GetCommTimeouts(self.hComPort, ctypes.byref(self._orgTimeouts))
cliechtiedfba4e2009-02-07 00:29:47 +000084
cliechti1ae5ab02013-10-11 01:08:02 +000085 self._reconfigurePort()
cliechti89b4af12002-02-12 23:24:41 +000086
cliechti1ae5ab02013-10-11 01:08:02 +000087 # Clear buffers:
88 # Remove anything that was there
89 win32.PurgeComm(self.hComPort,
90 win32.PURGE_TXCLEAR | win32.PURGE_TXABORT |
91 win32.PURGE_RXCLEAR | win32.PURGE_RXABORT)
92 except:
93 try:
94 self._close()
95 except:
96 # ignore any exception when closing the port
97 # also to keep original exception that happened when setting up
98 pass
99 self.hComPort = None
100 raise
101 else:
102 self._isOpen = True
103
cliechti89b4af12002-02-12 23:24:41 +0000104
cliechtid6bf52c2003-10-01 02:28:12 +0000105 def _reconfigurePort(self):
cliechticc8d9d22008-07-06 22:42:44 +0000106 """Set communication parameters on opened port."""
cliechtid6bf52c2003-10-01 02:28:12 +0000107 if not self.hComPort:
108 raise SerialException("Can only operate on a valid port handle")
cliechtiedfba4e2009-02-07 00:29:47 +0000109
110 # Set Windows timeout values
111 # timeouts is a tuple with the following items:
112 # (ReadIntervalTimeout,ReadTotalTimeoutMultiplier,
113 # ReadTotalTimeoutConstant,WriteTotalTimeoutMultiplier,
114 # WriteTotalTimeoutConstant)
cliechtid6bf52c2003-10-01 02:28:12 +0000115 if self._timeout is None:
116 timeouts = (0, 0, 0, 0, 0)
117 elif self._timeout == 0:
cliechti183d4ae2009-07-23 22:03:51 +0000118 timeouts = (win32.MAXDWORD, 0, 0, 0, 0)
cliechtid6bf52c2003-10-01 02:28:12 +0000119 else:
120 timeouts = (0, 0, int(self._timeout*1000), 0, 0)
cliechti679bfa62008-06-20 23:58:15 +0000121 if self._timeout != 0 and self._interCharTimeout is not None:
122 timeouts = (int(self._interCharTimeout * 1000),) + timeouts[1:]
cliechtiedfba4e2009-02-07 00:29:47 +0000123
cliechti62611612004-04-20 01:55:43 +0000124 if self._writeTimeout is None:
125 pass
126 elif self._writeTimeout == 0:
cliechti183d4ae2009-07-23 22:03:51 +0000127 timeouts = timeouts[:-2] + (0, win32.MAXDWORD)
cliechti62611612004-04-20 01:55:43 +0000128 else:
129 timeouts = timeouts[:-2] + (0, int(self._writeTimeout*1000))
cliechti183d4ae2009-07-23 22:03:51 +0000130 win32.SetCommTimeouts(self.hComPort, ctypes.byref(win32.COMMTIMEOUTS(*timeouts)))
cliechti89b4af12002-02-12 23:24:41 +0000131
cliechti183d4ae2009-07-23 22:03:51 +0000132 win32.SetCommMask(self.hComPort, win32.EV_ERR)
cliechti89b4af12002-02-12 23:24:41 +0000133
cliechti95c62212002-03-04 22:17:53 +0000134 # Setup the connection info.
135 # Get state and modify it:
cliechti183d4ae2009-07-23 22:03:51 +0000136 comDCB = win32.DCB()
137 win32.GetCommState(self.hComPort, ctypes.byref(comDCB))
cliechtid6bf52c2003-10-01 02:28:12 +0000138 comDCB.BaudRate = self._baudrate
139
140 if self._bytesize == FIVEBITS:
141 comDCB.ByteSize = 5
142 elif self._bytesize == SIXBITS:
143 comDCB.ByteSize = 6
144 elif self._bytesize == SEVENBITS:
145 comDCB.ByteSize = 7
146 elif self._bytesize == EIGHTBITS:
147 comDCB.ByteSize = 8
148 else:
149 raise ValueError("Unsupported number of data bits: %r" % self._bytesize)
150
151 if self._parity == PARITY_NONE:
cliechti183d4ae2009-07-23 22:03:51 +0000152 comDCB.Parity = win32.NOPARITY
153 comDCB.fParity = 0 # Disable Parity Check
cliechtid6bf52c2003-10-01 02:28:12 +0000154 elif self._parity == PARITY_EVEN:
cliechti183d4ae2009-07-23 22:03:51 +0000155 comDCB.Parity = win32.EVENPARITY
156 comDCB.fParity = 1 # Enable Parity Check
cliechtid6bf52c2003-10-01 02:28:12 +0000157 elif self._parity == PARITY_ODD:
cliechti183d4ae2009-07-23 22:03:51 +0000158 comDCB.Parity = win32.ODDPARITY
159 comDCB.fParity = 1 # Enable Parity Check
cliechtic54b2c82008-06-21 01:59:08 +0000160 elif self._parity == PARITY_MARK:
cliechti183d4ae2009-07-23 22:03:51 +0000161 comDCB.Parity = win32.MARKPARITY
162 comDCB.fParity = 1 # Enable Parity Check
cliechtic54b2c82008-06-21 01:59:08 +0000163 elif self._parity == PARITY_SPACE:
cliechti183d4ae2009-07-23 22:03:51 +0000164 comDCB.Parity = win32.SPACEPARITY
165 comDCB.fParity = 1 # Enable Parity Check
cliechtid6bf52c2003-10-01 02:28:12 +0000166 else:
167 raise ValueError("Unsupported parity mode: %r" % self._parity)
168
169 if self._stopbits == STOPBITS_ONE:
cliechti183d4ae2009-07-23 22:03:51 +0000170 comDCB.StopBits = win32.ONESTOPBIT
cliechti58b481c2009-02-16 20:42:32 +0000171 elif self._stopbits == STOPBITS_ONE_POINT_FIVE:
cliechti183d4ae2009-07-23 22:03:51 +0000172 comDCB.StopBits = win32.ONE5STOPBITS
cliechtid6bf52c2003-10-01 02:28:12 +0000173 elif self._stopbits == STOPBITS_TWO:
cliechti183d4ae2009-07-23 22:03:51 +0000174 comDCB.StopBits = win32.TWOSTOPBITS
cliechtid6bf52c2003-10-01 02:28:12 +0000175 else:
176 raise ValueError("Unsupported number of stop bits: %r" % self._stopbits)
cliechtiedfba4e2009-02-07 00:29:47 +0000177
cliechtid6bf52c2003-10-01 02:28:12 +0000178 comDCB.fBinary = 1 # Enable Binary Transmission
179 # Char. w/ Parity-Err are replaced with 0xff (if fErrorChar is set to TRUE)
180 if self._rtscts:
cliechti183d4ae2009-07-23 22:03:51 +0000181 comDCB.fRtsControl = win32.RTS_CONTROL_HANDSHAKE
cliechti1f89a0a2011-08-05 02:53:24 +0000182 elif self._rtsToggle:
183 comDCB.fRtsControl = win32.RTS_CONTROL_TOGGLE
cliechtid6bf52c2003-10-01 02:28:12 +0000184 else:
cliechti7ffcfef2004-07-28 01:08:25 +0000185 comDCB.fRtsControl = self._rtsState
cliechtif46e0a82005-05-19 15:24:57 +0000186 if self._dsrdtr:
cliechti183d4ae2009-07-23 22:03:51 +0000187 comDCB.fDtrControl = win32.DTR_CONTROL_HANDSHAKE
cliechtif46e0a82005-05-19 15:24:57 +0000188 else:
cliechti7ffcfef2004-07-28 01:08:25 +0000189 comDCB.fDtrControl = self._dtrState
cliechti1f89a0a2011-08-05 02:53:24 +0000190
191 if self._rtsToggle:
192 comDCB.fOutxCtsFlow = 0
193 else:
194 comDCB.fOutxCtsFlow = self._rtscts
cliechtif46e0a82005-05-19 15:24:57 +0000195 comDCB.fOutxDsrFlow = self._dsrdtr
cliechtid6bf52c2003-10-01 02:28:12 +0000196 comDCB.fOutX = self._xonxoff
197 comDCB.fInX = self._xonxoff
198 comDCB.fNull = 0
199 comDCB.fErrorChar = 0
200 comDCB.fAbortOnError = 0
cliechti62611612004-04-20 01:55:43 +0000201 comDCB.XonChar = XON
202 comDCB.XoffChar = XOFF
cliechtid6bf52c2003-10-01 02:28:12 +0000203
cliechti183d4ae2009-07-23 22:03:51 +0000204 if not win32.SetCommState(self.hComPort, ctypes.byref(comDCB)):
cliechti1083be72011-12-28 20:45:30 +0000205 raise ValueError("Cannot configure port, some setting was wrong. Original message: %r" % ctypes.WinError())
cliechti95c62212002-03-04 22:17:53 +0000206
cliechtid6bf52c2003-10-01 02:28:12 +0000207 #~ def __del__(self):
208 #~ self.close()
209
cliechti1ae5ab02013-10-11 01:08:02 +0000210
211 def _close(self):
212 """internal close port helper"""
213 if self.hComPort:
214 # Restore original timeout values:
215 win32.SetCommTimeouts(self.hComPort, self._orgTimeouts)
216 # Close COM-Port:
217 win32.CloseHandle(self.hComPort)
218 if self._overlappedRead is not None:
219 win32.CloseHandle(self._overlappedRead.hEvent)
220 self._overlappedRead = None
221 if self._overlappedWrite is not None:
222 win32.CloseHandle(self._overlappedWrite.hEvent)
223 self._overlappedWrite = None
224 self.hComPort = None
225
cliechtid6bf52c2003-10-01 02:28:12 +0000226 def close(self):
227 """Close port"""
228 if self._isOpen:
cliechti1ae5ab02013-10-11 01:08:02 +0000229 self._close()
cliechtid6bf52c2003-10-01 02:28:12 +0000230 self._isOpen = False
231
232 def makeDeviceName(self, port):
cliechti8b7cff02008-06-24 12:11:57 +0000233 return device(port)
cliechtid6bf52c2003-10-01 02:28:12 +0000234
235 # - - - - - - - - - - - - - - - - - - - - - - - -
cliechtiedfba4e2009-02-07 00:29:47 +0000236
cliechti89b4af12002-02-12 23:24:41 +0000237 def inWaiting(self):
cliechtid6bf52c2003-10-01 02:28:12 +0000238 """Return the number of characters currently in the input buffer."""
cliechti183d4ae2009-07-23 22:03:51 +0000239 flags = win32.DWORD()
240 comstat = win32.COMSTAT()
241 if not win32.ClearCommError(self.hComPort, ctypes.byref(flags), ctypes.byref(comstat)):
242 raise SerialException('call to ClearCommError failed')
cliechti89b4af12002-02-12 23:24:41 +0000243 return comstat.cbInQue
244
cliechti4a567a02009-07-27 22:09:31 +0000245 def read(self, size=1):
cliechti7d448562014-08-03 21:57:45 +0000246 """\
247 Read size bytes from the serial port. If a timeout is set it may
248 return less characters as requested. With no timeout it will block
249 until the requested number of bytes is read."""
cliechti89b4af12002-02-12 23:24:41 +0000250 if not self.hComPort: raise portNotOpenError
cliechti89b4af12002-02-12 23:24:41 +0000251 if size > 0:
cliechti183d4ae2009-07-23 22:03:51 +0000252 win32.ResetEvent(self._overlappedRead.hEvent)
253 flags = win32.DWORD()
254 comstat = win32.COMSTAT()
255 if not win32.ClearCommError(self.hComPort, ctypes.byref(flags), ctypes.byref(comstat)):
256 raise SerialException('call to ClearCommError failed')
cliechti5c39e702002-06-04 14:56:34 +0000257 if self.timeout == 0:
cliechti17f177f2002-06-07 22:33:37 +0000258 n = min(comstat.cbInQue, size)
259 if n > 0:
cliechti183d4ae2009-07-23 22:03:51 +0000260 buf = ctypes.create_string_buffer(n)
261 rc = win32.DWORD()
cliechti14213e12010-05-20 22:31:18 +0000262 err = win32.ReadFile(self.hComPort, buf, n, ctypes.byref(rc), ctypes.byref(self._overlappedRead))
cliechti183d4ae2009-07-23 22:03:51 +0000263 if not err and win32.GetLastError() != win32.ERROR_IO_PENDING:
cliechti1083be72011-12-28 20:45:30 +0000264 raise SerialException("ReadFile failed (%r)" % ctypes.WinError())
cliechti183d4ae2009-07-23 22:03:51 +0000265 err = win32.WaitForSingleObject(self._overlappedRead.hEvent, win32.INFINITE)
266 read = buf.raw[:rc.value]
cliechtif622faf2003-07-12 23:41:43 +0000267 else:
cliechti4a567a02009-07-27 22:09:31 +0000268 read = bytes()
cliechti5c39e702002-06-04 14:56:34 +0000269 else:
cliechti183d4ae2009-07-23 22:03:51 +0000270 buf = ctypes.create_string_buffer(size)
271 rc = win32.DWORD()
272 err = win32.ReadFile(self.hComPort, buf, size, ctypes.byref(rc), ctypes.byref(self._overlappedRead))
273 if not err and win32.GetLastError() != win32.ERROR_IO_PENDING:
cliechti1083be72011-12-28 20:45:30 +0000274 raise SerialException("ReadFile failed (%r)" % ctypes.WinError())
cliechti183d4ae2009-07-23 22:03:51 +0000275 err = win32.GetOverlappedResult(self.hComPort, ctypes.byref(self._overlappedRead), ctypes.byref(rc), True)
276 read = buf.raw[:rc.value]
cliechtif622faf2003-07-12 23:41:43 +0000277 else:
cliechti4a567a02009-07-27 22:09:31 +0000278 read = bytes()
279 return bytes(read)
cliechti89b4af12002-02-12 23:24:41 +0000280
cliechti4a567a02009-07-27 22:09:31 +0000281 def write(self, data):
cliechtid6bf52c2003-10-01 02:28:12 +0000282 """Output the given string over the serial port."""
cliechti89b4af12002-02-12 23:24:41 +0000283 if not self.hComPort: raise portNotOpenError
cliechti23dc2a02009-07-30 17:25:09 +0000284 #~ if not isinstance(data, (bytes, bytearray)):
285 #~ raise TypeError('expected %s or bytearray, got %s' % (bytes, type(data)))
286 # convert data (needed in case of memoryview instance: Py 3.1 io lib), ctypes doesn't like memoryview
cliechti38077122013-10-16 02:57:27 +0000287 data = to_bytes(data)
cliechtib2f5fc82006-10-20 00:09:07 +0000288 if data:
cliechti107db8d2004-01-15 01:20:23 +0000289 #~ win32event.ResetEvent(self._overlappedWrite.hEvent)
cliechti183d4ae2009-07-23 22:03:51 +0000290 n = win32.DWORD()
cliechtie37b6a82009-07-24 12:19:50 +0000291 err = win32.WriteFile(self.hComPort, data, len(data), ctypes.byref(n), self._overlappedWrite)
cliechti183d4ae2009-07-23 22:03:51 +0000292 if not err and win32.GetLastError() != win32.ERROR_IO_PENDING:
cliechti1083be72011-12-28 20:45:30 +0000293 raise SerialException("WriteFile failed (%r)" % ctypes.WinError())
cliechti31000fc2011-08-05 01:47:26 +0000294 if self._writeTimeout != 0: # if blocking (None) or w/ write timeout (>0)
295 # Wait for the write to complete.
296 #~ win32.WaitForSingleObject(self._overlappedWrite.hEvent, win32.INFINITE)
297 err = win32.GetOverlappedResult(self.hComPort, self._overlappedWrite, ctypes.byref(n), True)
298 if n.value != len(data):
299 raise writeTimeoutError
cliechti23dc2a02009-07-30 17:25:09 +0000300 return n.value
301 else:
302 return 0
cliechtiedfba4e2009-02-07 00:29:47 +0000303
cliechti26409782013-05-31 00:47:16 +0000304 def flush(self):
cliechti7d448562014-08-03 21:57:45 +0000305 """\
306 Flush of file like objects. In this case, wait until all data
307 is written.
308 """
cliechti26409782013-05-31 00:47:16 +0000309 while self.outWaiting():
310 time.sleep(0.05)
311 # XXX could also use WaitCommEvent with mask EV_TXEMPTY, but it would
312 # require overlapped IO and its also only possible to set a single mask
313 # on the port---
cliechti89b4af12002-02-12 23:24:41 +0000314
315 def flushInput(self):
cliechtid6bf52c2003-10-01 02:28:12 +0000316 """Clear input buffer, discarding all that is in the buffer."""
cliechti89b4af12002-02-12 23:24:41 +0000317 if not self.hComPort: raise portNotOpenError
cliechti183d4ae2009-07-23 22:03:51 +0000318 win32.PurgeComm(self.hComPort, win32.PURGE_RXCLEAR | win32.PURGE_RXABORT)
cliechti89b4af12002-02-12 23:24:41 +0000319
320 def flushOutput(self):
cliechti7d448562014-08-03 21:57:45 +0000321 """\
322 Clear output buffer, aborting the current output and discarding all
323 that is in the buffer.
324 """
cliechti89b4af12002-02-12 23:24:41 +0000325 if not self.hComPort: raise portNotOpenError
cliechti183d4ae2009-07-23 22:03:51 +0000326 win32.PurgeComm(self.hComPort, win32.PURGE_TXCLEAR | win32.PURGE_TXABORT)
cliechti89b4af12002-02-12 23:24:41 +0000327
cliechtiaaa04602006-02-05 23:02:46 +0000328 def sendBreak(self, duration=0.25):
cliechti7d448562014-08-03 21:57:45 +0000329 """\
330 Send break condition. Timed, returns to idle state after given duration.
331 """
cliechti89b4af12002-02-12 23:24:41 +0000332 if not self.hComPort: raise portNotOpenError
cliechti1b327022002-02-13 22:26:06 +0000333 import time
cliechti183d4ae2009-07-23 22:03:51 +0000334 win32.SetCommBreak(self.hComPort)
cliechtiaaa04602006-02-05 23:02:46 +0000335 time.sleep(duration)
cliechti183d4ae2009-07-23 22:03:51 +0000336 win32.ClearCommBreak(self.hComPort)
cliechti89b4af12002-02-12 23:24:41 +0000337
cliechti997b63c2008-06-21 00:09:31 +0000338 def setBreak(self, level=1):
339 """Set break: Controls TXD. When active, to transmitting is possible."""
340 if not self.hComPort: raise portNotOpenError
341 if level:
cliechti183d4ae2009-07-23 22:03:51 +0000342 win32.SetCommBreak(self.hComPort)
cliechti997b63c2008-06-21 00:09:31 +0000343 else:
cliechti183d4ae2009-07-23 22:03:51 +0000344 win32.ClearCommBreak(self.hComPort)
cliechti997b63c2008-06-21 00:09:31 +0000345
cliechti93db61b2006-08-26 19:16:18 +0000346 def setRTS(self, level=1):
cliechtid6bf52c2003-10-01 02:28:12 +0000347 """Set terminal status line: Request To Send"""
cliechti22175a72011-12-29 00:17:53 +0000348 # remember level for reconfigure
cliechti89b4af12002-02-12 23:24:41 +0000349 if level:
cliechtie37b6a82009-07-24 12:19:50 +0000350 self._rtsState = win32.RTS_CONTROL_ENABLE
cliechti89b4af12002-02-12 23:24:41 +0000351 else:
cliechtie37b6a82009-07-24 12:19:50 +0000352 self._rtsState = win32.RTS_CONTROL_DISABLE
cliechti22175a72011-12-29 00:17:53 +0000353 # also apply now if port is open
354 if self.hComPort:
355 if level:
356 win32.EscapeCommFunction(self.hComPort, win32.SETRTS)
357 else:
358 win32.EscapeCommFunction(self.hComPort, win32.CLRRTS)
cliechti89b4af12002-02-12 23:24:41 +0000359
cliechti93db61b2006-08-26 19:16:18 +0000360 def setDTR(self, level=1):
cliechtid6bf52c2003-10-01 02:28:12 +0000361 """Set terminal status line: Data Terminal Ready"""
cliechti22175a72011-12-29 00:17:53 +0000362 # remember level for reconfigure
cliechti89b4af12002-02-12 23:24:41 +0000363 if level:
cliechtie37b6a82009-07-24 12:19:50 +0000364 self._dtrState = win32.DTR_CONTROL_ENABLE
cliechti89b4af12002-02-12 23:24:41 +0000365 else:
cliechtie37b6a82009-07-24 12:19:50 +0000366 self._dtrState = win32.DTR_CONTROL_DISABLE
cliechti22175a72011-12-29 00:17:53 +0000367 # also apply now if port is open
368 if self.hComPort:
369 if level:
370 win32.EscapeCommFunction(self.hComPort, win32.SETDTR)
371 else:
372 win32.EscapeCommFunction(self.hComPort, win32.CLRDTR)
cliechti183d4ae2009-07-23 22:03:51 +0000373
374 def _GetCommModemStatus(self):
375 stat = win32.DWORD()
376 win32.GetCommModemStatus(self.hComPort, ctypes.byref(stat))
377 return stat.value
cliechti89b4af12002-02-12 23:24:41 +0000378
379 def getCTS(self):
cliechtid6bf52c2003-10-01 02:28:12 +0000380 """Read terminal status line: Clear To Send"""
cliechti89b4af12002-02-12 23:24:41 +0000381 if not self.hComPort: raise portNotOpenError
cliechti183d4ae2009-07-23 22:03:51 +0000382 return win32.MS_CTS_ON & self._GetCommModemStatus() != 0
cliechti89b4af12002-02-12 23:24:41 +0000383
384 def getDSR(self):
cliechtid6bf52c2003-10-01 02:28:12 +0000385 """Read terminal status line: Data Set Ready"""
cliechti89b4af12002-02-12 23:24:41 +0000386 if not self.hComPort: raise portNotOpenError
cliechti183d4ae2009-07-23 22:03:51 +0000387 return win32.MS_DSR_ON & self._GetCommModemStatus() != 0
cliechti89b4af12002-02-12 23:24:41 +0000388
cliechtid0b8b272002-02-14 01:33:08 +0000389 def getRI(self):
cliechtid6bf52c2003-10-01 02:28:12 +0000390 """Read terminal status line: Ring Indicator"""
cliechtid0b8b272002-02-14 01:33:08 +0000391 if not self.hComPort: raise portNotOpenError
cliechti183d4ae2009-07-23 22:03:51 +0000392 return win32.MS_RING_ON & self._GetCommModemStatus() != 0
cliechti89b4af12002-02-12 23:24:41 +0000393
cliechtid0b8b272002-02-14 01:33:08 +0000394 def getCD(self):
cliechtid6bf52c2003-10-01 02:28:12 +0000395 """Read terminal status line: Carrier Detect"""
cliechtid0b8b272002-02-14 01:33:08 +0000396 if not self.hComPort: raise portNotOpenError
cliechti183d4ae2009-07-23 22:03:51 +0000397 return win32.MS_RLSD_ON & self._GetCommModemStatus() != 0
cliechti89b4af12002-02-12 23:24:41 +0000398
cliechtia30a8a02003-10-05 12:28:13 +0000399 # - - platform specific - - - -
400
cliechti59199642011-12-28 20:54:30 +0000401 def setBufferSize(self, rx_size=4096, tx_size=None):
402 """\
403 Recommend a buffer size to the driver (device driver can ignore this
404 vlaue). Must be called before the port is opended.
405 """
406 if tx_size is None: tx_size = rx_size
407 win32.SetupComm(self.hComPort, rx_size, tx_size)
408
cliechtia30a8a02003-10-05 12:28:13 +0000409 def setXON(self, level=True):
cliechti2f0f8a32011-12-28 22:10:00 +0000410 """\
411 Manually control flow - when software flow control is enabled.
412 This will send XON (true) and XOFF (false) to the other device.
413 WARNING: this function is not portable to different platforms!
414 """
cliechtia30a8a02003-10-05 12:28:13 +0000415 if not self.hComPort: raise portNotOpenError
416 if level:
cliechti183d4ae2009-07-23 22:03:51 +0000417 win32.EscapeCommFunction(self.hComPort, win32.SETXON)
cliechtia30a8a02003-10-05 12:28:13 +0000418 else:
cliechti183d4ae2009-07-23 22:03:51 +0000419 win32.EscapeCommFunction(self.hComPort, win32.SETXOFF)
cliechtia30a8a02003-10-05 12:28:13 +0000420
cliechtic8e83d82009-07-21 21:34:05 +0000421 def outWaiting(self):
cliechti7d448562014-08-03 21:57:45 +0000422 """Return how many characters the in the outgoing buffer"""
cliechti183d4ae2009-07-23 22:03:51 +0000423 flags = win32.DWORD()
424 comstat = win32.COMSTAT()
425 if not win32.ClearCommError(self.hComPort, ctypes.byref(flags), ctypes.byref(comstat)):
426 raise SerialException('call to ClearCommError failed')
cliechtic8e83d82009-07-21 21:34:05 +0000427 return comstat.cbOutQue
428
cliechti1f89a0a2011-08-05 02:53:24 +0000429 # functions useful for RS-485 adapters
430 def setRtsToggle(self, rtsToggle):
431 """Change RTS toggle control setting."""
432 self._rtsToggle = rtsToggle
433 if self._isOpen: self._reconfigurePort()
434
435 def getRtsToggle(self):
436 """Get the current RTS toggle control setting."""
437 return self._rtsToggle
438
439 rtsToggle = property(getRtsToggle, setRtsToggle, doc="RTS toggle control setting")
440
cliechtif81362e2009-07-25 03:44:33 +0000441
Chris Liechtiaf6d0462015-08-03 17:21:14 +0200442t
cliechtiedfba4e2009-02-07 00:29:47 +0000443# Nur Testfunktion!!
cliechti89b4af12002-02-12 23:24:41 +0000444if __name__ == '__main__':
cliechti93db61b2006-08-26 19:16:18 +0000445 s = Serial(0)
cliechti7aaead32009-07-23 14:02:41 +0000446 sys.stdout.write("%s\n" % s)
cliechtiedfba4e2009-02-07 00:29:47 +0000447
cliechtid6bf52c2003-10-01 02:28:12 +0000448 s = Serial()
cliechti7aaead32009-07-23 14:02:41 +0000449 sys.stdout.write("%s\n" % s)
cliechtiedfba4e2009-02-07 00:29:47 +0000450
cliechtid6bf52c2003-10-01 02:28:12 +0000451 s.baudrate = 19200
452 s.databits = 7
453 s.close()
cliechti93db61b2006-08-26 19:16:18 +0000454 s.port = 0
cliechtid6bf52c2003-10-01 02:28:12 +0000455 s.open()
cliechti7aaead32009-07-23 14:02:41 +0000456 sys.stdout.write("%s\n" % s)
cliechti89b4af12002-02-12 23:24:41 +0000457