serialwin32.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443
  1. #! python
  2. #
  3. # backend for Windows ("win32" incl. 32/64 bit support)
  4. #
  5. # (C) 2001-2015 Chris Liechti <cliechti@gmx.net>
  6. #
  7. # This file is part of pySerial. https://github.com/pyserial/pyserial
  8. # SPDX-License-Identifier: BSD-3-Clause
  9. #
  10. # Initial patch to use ctypes by Giovanni Bajo <rasky@develer.com>
  11. import ctypes
  12. import time
  13. from serial import win32
  14. import serial
  15. from serial.serialutil import SerialBase, SerialException, to_bytes, portNotOpenError, writeTimeoutError
  16. class Serial(SerialBase):
  17. """Serial port implementation for Win32 based on ctypes."""
  18. BAUDRATES = (50, 75, 110, 134, 150, 200, 300, 600, 1200, 1800, 2400, 4800,
  19. 9600, 19200, 38400, 57600, 115200)
  20. def __init__(self, *args, **kwargs):
  21. super(SerialBase, self).__init__()
  22. self._port_handle = None
  23. self._overlapped_read = None
  24. self._overlapped_write = None
  25. SerialBase.__init__(self, *args, **kwargs)
  26. def open(self):
  27. """\
  28. Open port with current settings. This may throw a SerialException
  29. if the port cannot be opened.
  30. """
  31. if self._port is None:
  32. raise SerialException("Port must be configured before it can be used.")
  33. if self.is_open:
  34. raise SerialException("Port is already open.")
  35. # the "\\.\COMx" format is required for devices other than COM1-COM8
  36. # not all versions of windows seem to support this properly
  37. # so that the first few ports are used with the DOS device name
  38. port = self.name
  39. try:
  40. if port.upper().startswith('COM') and int(port[3:]) > 8:
  41. port = '\\\\.\\' + port
  42. except ValueError:
  43. # for like COMnotanumber
  44. pass
  45. self._port_handle = win32.CreateFile(
  46. port,
  47. win32.GENERIC_READ | win32.GENERIC_WRITE,
  48. 0, # exclusive access
  49. None, # no security
  50. win32.OPEN_EXISTING,
  51. win32.FILE_ATTRIBUTE_NORMAL | win32.FILE_FLAG_OVERLAPPED,
  52. 0)
  53. if self._port_handle == win32.INVALID_HANDLE_VALUE:
  54. self._port_handle = None # 'cause __del__ is called anyway
  55. raise SerialException("could not open port %r: %r" % (self.portstr, ctypes.WinError()))
  56. try:
  57. self._overlapped_read = win32.OVERLAPPED()
  58. self._overlapped_read.hEvent = win32.CreateEvent(None, 1, 0, None)
  59. self._overlapped_write = win32.OVERLAPPED()
  60. #~ self._overlapped_write.hEvent = win32.CreateEvent(None, 1, 0, None)
  61. self._overlapped_write.hEvent = win32.CreateEvent(None, 0, 0, None)
  62. # Setup a 4k buffer
  63. win32.SetupComm(self._port_handle, 4096, 4096)
  64. # Save original timeout values:
  65. self._orgTimeouts = win32.COMMTIMEOUTS()
  66. win32.GetCommTimeouts(self._port_handle, ctypes.byref(self._orgTimeouts))
  67. self._reconfigure_port()
  68. # Clear buffers:
  69. # Remove anything that was there
  70. win32.PurgeComm(
  71. self._port_handle,
  72. win32.PURGE_TXCLEAR | win32.PURGE_TXABORT |
  73. win32.PURGE_RXCLEAR | win32.PURGE_RXABORT)
  74. except:
  75. try:
  76. self._close()
  77. except:
  78. # ignore any exception when closing the port
  79. # also to keep original exception that happened when setting up
  80. pass
  81. self._port_handle = None
  82. raise
  83. else:
  84. self.is_open = True
  85. def _reconfigure_port(self):
  86. """Set communication parameters on opened port."""
  87. if not self._port_handle:
  88. raise SerialException("Can only operate on a valid port handle")
  89. # Set Windows timeout values
  90. # timeouts is a tuple with the following items:
  91. # (ReadIntervalTimeout,ReadTotalTimeoutMultiplier,
  92. # ReadTotalTimeoutConstant,WriteTotalTimeoutMultiplier,
  93. # WriteTotalTimeoutConstant)
  94. timeouts = win32.COMMTIMEOUTS()
  95. if self._timeout is None:
  96. pass # default of all zeros is OK
  97. elif self._timeout == 0:
  98. timeouts.ReadIntervalTimeout = win32.MAXDWORD
  99. else:
  100. timeouts.ReadTotalTimeoutConstant = max(int(self._timeout * 1000), 1)
  101. if self._timeout != 0 and self._inter_byte_timeout is not None:
  102. timeouts.ReadIntervalTimeout = max(int(self._inter_byte_timeout * 1000), 1)
  103. if self._write_timeout is None:
  104. pass
  105. elif self._write_timeout == 0:
  106. timeouts.WriteTotalTimeoutConstant = win32.MAXDWORD
  107. else:
  108. timeouts.WriteTotalTimeoutConstant = max(int(self._write_timeout * 1000), 1)
  109. win32.SetCommTimeouts(self._port_handle, ctypes.byref(timeouts))
  110. win32.SetCommMask(self._port_handle, win32.EV_ERR)
  111. # Setup the connection info.
  112. # Get state and modify it:
  113. comDCB = win32.DCB()
  114. win32.GetCommState(self._port_handle, ctypes.byref(comDCB))
  115. comDCB.BaudRate = self._baudrate
  116. if self._bytesize == serial.FIVEBITS:
  117. comDCB.ByteSize = 5
  118. elif self._bytesize == serial.SIXBITS:
  119. comDCB.ByteSize = 6
  120. elif self._bytesize == serial.SEVENBITS:
  121. comDCB.ByteSize = 7
  122. elif self._bytesize == serial.EIGHTBITS:
  123. comDCB.ByteSize = 8
  124. else:
  125. raise ValueError("Unsupported number of data bits: %r" % self._bytesize)
  126. if self._parity == serial.PARITY_NONE:
  127. comDCB.Parity = win32.NOPARITY
  128. comDCB.fParity = 0 # Disable Parity Check
  129. elif self._parity == serial.PARITY_EVEN:
  130. comDCB.Parity = win32.EVENPARITY
  131. comDCB.fParity = 1 # Enable Parity Check
  132. elif self._parity == serial.PARITY_ODD:
  133. comDCB.Parity = win32.ODDPARITY
  134. comDCB.fParity = 1 # Enable Parity Check
  135. elif self._parity == serial.PARITY_MARK:
  136. comDCB.Parity = win32.MARKPARITY
  137. comDCB.fParity = 1 # Enable Parity Check
  138. elif self._parity == serial.PARITY_SPACE:
  139. comDCB.Parity = win32.SPACEPARITY
  140. comDCB.fParity = 1 # Enable Parity Check
  141. else:
  142. raise ValueError("Unsupported parity mode: %r" % self._parity)
  143. if self._stopbits == serial.STOPBITS_ONE:
  144. comDCB.StopBits = win32.ONESTOPBIT
  145. elif self._stopbits == serial.STOPBITS_ONE_POINT_FIVE:
  146. comDCB.StopBits = win32.ONE5STOPBITS
  147. elif self._stopbits == serial.STOPBITS_TWO:
  148. comDCB.StopBits = win32.TWOSTOPBITS
  149. else:
  150. raise ValueError("Unsupported number of stop bits: %r" % self._stopbits)
  151. comDCB.fBinary = 1 # Enable Binary Transmission
  152. # Char. w/ Parity-Err are replaced with 0xff (if fErrorChar is set to TRUE)
  153. if self._rs485_mode is None:
  154. if self._rtscts:
  155. comDCB.fRtsControl = win32.RTS_CONTROL_HANDSHAKE
  156. else:
  157. comDCB.fRtsControl = win32.RTS_CONTROL_ENABLE if self._rts_state else win32.RTS_CONTROL_DISABLE
  158. comDCB.fOutxCtsFlow = self._rtscts
  159. else:
  160. # checks for unsupported settings
  161. # XXX verify if platform really does not have a setting for those
  162. if not self._rs485_mode.rts_level_for_tx:
  163. raise ValueError(
  164. 'Unsupported value for RS485Settings.rts_level_for_tx: %r' % (
  165. self._rs485_mode.rts_level_for_tx,))
  166. if self._rs485_mode.rts_level_for_rx:
  167. raise ValueError(
  168. 'Unsupported value for RS485Settings.rts_level_for_rx: %r' % (
  169. self._rs485_mode.rts_level_for_rx,))
  170. if self._rs485_mode.delay_before_tx is not None:
  171. raise ValueError(
  172. 'Unsupported value for RS485Settings.delay_before_tx: %r' % (
  173. self._rs485_mode.delay_before_tx,))
  174. if self._rs485_mode.delay_before_rx is not None:
  175. raise ValueError(
  176. 'Unsupported value for RS485Settings.delay_before_rx: %r' % (
  177. self._rs485_mode.delay_before_rx,))
  178. if self._rs485_mode.loopback:
  179. raise ValueError(
  180. 'Unsupported value for RS485Settings.loopback: %r' % (
  181. self._rs485_mode.loopback,))
  182. comDCB.fRtsControl = win32.RTS_CONTROL_TOGGLE
  183. comDCB.fOutxCtsFlow = 0
  184. if self._dsrdtr:
  185. comDCB.fDtrControl = win32.DTR_CONTROL_HANDSHAKE
  186. else:
  187. comDCB.fDtrControl = win32.DTR_CONTROL_ENABLE if self._dtr_state else win32.DTR_CONTROL_DISABLE
  188. comDCB.fOutxDsrFlow = self._dsrdtr
  189. comDCB.fOutX = self._xonxoff
  190. comDCB.fInX = self._xonxoff
  191. comDCB.fNull = 0
  192. comDCB.fErrorChar = 0
  193. comDCB.fAbortOnError = 0
  194. comDCB.XonChar = serial.XON
  195. comDCB.XoffChar = serial.XOFF
  196. if not win32.SetCommState(self._port_handle, ctypes.byref(comDCB)):
  197. raise SerialException("Cannot configure port, something went wrong. Original message: %r" % ctypes.WinError())
  198. #~ def __del__(self):
  199. #~ self.close()
  200. def _close(self):
  201. """internal close port helper"""
  202. if self._port_handle:
  203. # Restore original timeout values:
  204. win32.SetCommTimeouts(self._port_handle, self._orgTimeouts)
  205. # Close COM-Port:
  206. win32.CloseHandle(self._port_handle)
  207. if self._overlapped_read is not None:
  208. win32.CloseHandle(self._overlapped_read.hEvent)
  209. self._overlapped_read = None
  210. if self._overlapped_write is not None:
  211. win32.CloseHandle(self._overlapped_write.hEvent)
  212. self._overlapped_write = None
  213. self._port_handle = None
  214. def close(self):
  215. """Close port"""
  216. if self.is_open:
  217. self._close()
  218. self.is_open = False
  219. # - - - - - - - - - - - - - - - - - - - - - - - -
  220. @property
  221. def in_waiting(self):
  222. """Return the number of bytes currently in the input buffer."""
  223. flags = win32.DWORD()
  224. comstat = win32.COMSTAT()
  225. if not win32.ClearCommError(self._port_handle, ctypes.byref(flags), ctypes.byref(comstat)):
  226. raise SerialException('call to ClearCommError failed')
  227. return comstat.cbInQue
  228. def read(self, size=1):
  229. """\
  230. Read size bytes from the serial port. If a timeout is set it may
  231. return less characters as requested. With no timeout it will block
  232. until the requested number of bytes is read."""
  233. if not self._port_handle:
  234. raise portNotOpenError
  235. if size > 0:
  236. win32.ResetEvent(self._overlapped_read.hEvent)
  237. flags = win32.DWORD()
  238. comstat = win32.COMSTAT()
  239. if not win32.ClearCommError(self._port_handle, ctypes.byref(flags), ctypes.byref(comstat)):
  240. raise SerialException('call to ClearCommError failed')
  241. if self.timeout == 0:
  242. n = min(comstat.cbInQue, size)
  243. if n > 0:
  244. buf = ctypes.create_string_buffer(n)
  245. rc = win32.DWORD()
  246. read_ok = win32.ReadFile(self._port_handle, buf, n, ctypes.byref(rc), ctypes.byref(self._overlapped_read))
  247. if not read_ok and win32.GetLastError() not in (win32.ERROR_SUCCESS, win32.ERROR_IO_PENDING):
  248. raise SerialException("ReadFile failed (%r)" % ctypes.WinError())
  249. win32.GetOverlappedResult(self._port_handle, ctypes.byref(self._overlapped_read), ctypes.byref(rc), True)
  250. read = buf.raw[:rc.value]
  251. else:
  252. read = bytes()
  253. else:
  254. buf = ctypes.create_string_buffer(size)
  255. rc = win32.DWORD()
  256. read_ok = win32.ReadFile(self._port_handle, buf, size, ctypes.byref(rc), ctypes.byref(self._overlapped_read))
  257. if not read_ok and win32.GetLastError() not in (win32.ERROR_SUCCESS, win32.ERROR_IO_PENDING):
  258. raise SerialException("ReadFile failed (%r)" % ctypes.WinError())
  259. win32.GetOverlappedResult(self._port_handle, ctypes.byref(self._overlapped_read), ctypes.byref(rc), True)
  260. read = buf.raw[:rc.value]
  261. else:
  262. read = bytes()
  263. return bytes(read)
  264. def write(self, data):
  265. """Output the given byte string over the serial port."""
  266. if not self._port_handle:
  267. raise portNotOpenError
  268. #~ if not isinstance(data, (bytes, bytearray)):
  269. #~ raise TypeError('expected %s or bytearray, got %s' % (bytes, type(data)))
  270. # convert data (needed in case of memoryview instance: Py 3.1 io lib), ctypes doesn't like memoryview
  271. data = to_bytes(data)
  272. if data:
  273. #~ win32event.ResetEvent(self._overlapped_write.hEvent)
  274. n = win32.DWORD()
  275. err = win32.WriteFile(self._port_handle, data, len(data), ctypes.byref(n), self._overlapped_write)
  276. if not err and win32.GetLastError() != win32.ERROR_IO_PENDING:
  277. raise SerialException("WriteFile failed (%r)" % ctypes.WinError())
  278. if self._write_timeout != 0: # if blocking (None) or w/ write timeout (>0)
  279. # Wait for the write to complete.
  280. #~ win32.WaitForSingleObject(self._overlapped_write.hEvent, win32.INFINITE)
  281. err = win32.GetOverlappedResult(self._port_handle, self._overlapped_write, ctypes.byref(n), True)
  282. if n.value != len(data):
  283. raise writeTimeoutError
  284. return n.value
  285. else:
  286. return 0
  287. def flush(self):
  288. """\
  289. Flush of file like objects. In this case, wait until all data
  290. is written.
  291. """
  292. while self.out_waiting:
  293. time.sleep(0.05)
  294. # XXX could also use WaitCommEvent with mask EV_TXEMPTY, but it would
  295. # require overlapped IO and its also only possible to set a single mask
  296. # on the port---
  297. def reset_input_buffer(self):
  298. """Clear input buffer, discarding all that is in the buffer."""
  299. if not self._port_handle:
  300. raise portNotOpenError
  301. win32.PurgeComm(self._port_handle, win32.PURGE_RXCLEAR | win32.PURGE_RXABORT)
  302. def reset_output_buffer(self):
  303. """\
  304. Clear output buffer, aborting the current output and discarding all
  305. that is in the buffer.
  306. """
  307. if not self._port_handle:
  308. raise portNotOpenError
  309. win32.PurgeComm(self._port_handle, win32.PURGE_TXCLEAR | win32.PURGE_TXABORT)
  310. def _update_break_state(self):
  311. """Set break: Controls TXD. When active, to transmitting is possible."""
  312. if not self._port_handle:
  313. raise portNotOpenError
  314. if self._break_state:
  315. win32.SetCommBreak(self._port_handle)
  316. else:
  317. win32.ClearCommBreak(self._port_handle)
  318. def _update_rts_state(self):
  319. """Set terminal status line: Request To Send"""
  320. if self._rts_state:
  321. win32.EscapeCommFunction(self._port_handle, win32.SETRTS)
  322. else:
  323. win32.EscapeCommFunction(self._port_handle, win32.CLRRTS)
  324. def _update_dtr_state(self):
  325. """Set terminal status line: Data Terminal Ready"""
  326. if self._dtr_state:
  327. win32.EscapeCommFunction(self._port_handle, win32.SETDTR)
  328. else:
  329. win32.EscapeCommFunction(self._port_handle, win32.CLRDTR)
  330. def _GetCommModemStatus(self):
  331. if not self._port_handle:
  332. raise portNotOpenError
  333. stat = win32.DWORD()
  334. win32.GetCommModemStatus(self._port_handle, ctypes.byref(stat))
  335. return stat.value
  336. @property
  337. def cts(self):
  338. """Read terminal status line: Clear To Send"""
  339. return win32.MS_CTS_ON & self._GetCommModemStatus() != 0
  340. @property
  341. def dsr(self):
  342. """Read terminal status line: Data Set Ready"""
  343. return win32.MS_DSR_ON & self._GetCommModemStatus() != 0
  344. @property
  345. def ri(self):
  346. """Read terminal status line: Ring Indicator"""
  347. return win32.MS_RING_ON & self._GetCommModemStatus() != 0
  348. @property
  349. def cd(self):
  350. """Read terminal status line: Carrier Detect"""
  351. return win32.MS_RLSD_ON & self._GetCommModemStatus() != 0
  352. # - - platform specific - - - -
  353. def set_buffer_size(self, rx_size=4096, tx_size=None):
  354. """\
  355. Recommend a buffer size to the driver (device driver can ignore this
  356. value). Must be called before the port is opended.
  357. """
  358. if tx_size is None:
  359. tx_size = rx_size
  360. win32.SetupComm(self._port_handle, rx_size, tx_size)
  361. def set_output_flow_control(self, enable=True):
  362. """\
  363. Manually control flow - when software flow control is enabled.
  364. This will do the same as if XON (true) or XOFF (false) are received
  365. from the other device and control the transmission accordingly.
  366. WARNING: this function is not portable to different platforms!
  367. """
  368. if not self._port_handle:
  369. raise portNotOpenError
  370. if enable:
  371. win32.EscapeCommFunction(self._port_handle, win32.SETXON)
  372. else:
  373. win32.EscapeCommFunction(self._port_handle, win32.SETXOFF)
  374. @property
  375. def out_waiting(self):
  376. """Return how many bytes the in the outgoing buffer"""
  377. flags = win32.DWORD()
  378. comstat = win32.COMSTAT()
  379. if not win32.ClearCommError(self._port_handle, ctypes.byref(flags), ctypes.byref(comstat)):
  380. raise SerialException('call to ClearCommError failed')
  381. return comstat.cbOutQue
  382. # Nur Testfunktion!!
  383. if __name__ == '__main__':
  384. import sys
  385. s = Serial(0)
  386. sys.stdout.write("%s\n" % s)
  387. s = Serial()
  388. sys.stdout.write("%s\n" % s)
  389. s.baudrate = 19200
  390. s.databits = 7
  391. s.close()
  392. s.port = 0
  393. s.open()
  394. sys.stdout.write("%s\n" % s)