serialwin32.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475
  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. # pylint: disable=invalid-name,too-few-public-methods
  12. import ctypes
  13. import time
  14. from serial import win32
  15. import serial
  16. from serial.serialutil import SerialBase, SerialException, to_bytes, portNotOpenError, writeTimeoutError
  17. class Serial(SerialBase):
  18. """Serial port implementation for Win32 based on ctypes."""
  19. BAUDRATES = (50, 75, 110, 134, 150, 200, 300, 600, 1200, 1800, 2400, 4800,
  20. 9600, 19200, 38400, 57600, 115200)
  21. def __init__(self, *args, **kwargs):
  22. self._port_handle = None
  23. self._overlapped_read = None
  24. self._overlapped_write = None
  25. super(Serial, self).__init__(*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}".format(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}".format(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}".format(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}".format(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}'.format(
  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}'.format(
  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}'.format(
  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}'.format(
  177. self._rs485_mode.delay_before_rx,))
  178. if self._rs485_mode.loopback:
  179. raise ValueError(
  180. 'Unsupported value for RS485Settings.loopback: {!r}'.format(
  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(
  198. 'Cannot configure port, something went wrong. '
  199. 'Original message: {!r}'.format(ctypes.WinError()))
  200. #~ def __del__(self):
  201. #~ self.close()
  202. def _close(self):
  203. """internal close port helper"""
  204. if self._port_handle is not None:
  205. # Restore original timeout values:
  206. win32.SetCommTimeouts(self._port_handle, self._orgTimeouts)
  207. if self._overlapped_read is not None:
  208. self.cancel_read()
  209. win32.CloseHandle(self._overlapped_read.hEvent)
  210. self._overlapped_read = None
  211. if self._overlapped_write is not None:
  212. self.cancel_write()
  213. win32.CloseHandle(self._overlapped_write.hEvent)
  214. self._overlapped_write = None
  215. win32.CloseHandle(self._port_handle)
  216. self._port_handle = None
  217. def close(self):
  218. """Close port"""
  219. if self.is_open:
  220. self._close()
  221. self.is_open = False
  222. # - - - - - - - - - - - - - - - - - - - - - - - -
  223. @property
  224. def in_waiting(self):
  225. """Return the number of bytes currently in the input buffer."""
  226. flags = win32.DWORD()
  227. comstat = win32.COMSTAT()
  228. if not win32.ClearCommError(self._port_handle, ctypes.byref(flags), ctypes.byref(comstat)):
  229. raise SerialException("ClearCommError failed ({!r})".format(ctypes.WinError()))
  230. return comstat.cbInQue
  231. def read(self, size=1):
  232. """\
  233. Read size bytes from the serial port. If a timeout is set it may
  234. return less characters as requested. With no timeout it will block
  235. until the requested number of bytes is read.
  236. """
  237. if not self.is_open:
  238. raise portNotOpenError
  239. if size > 0:
  240. win32.ResetEvent(self._overlapped_read.hEvent)
  241. flags = win32.DWORD()
  242. comstat = win32.COMSTAT()
  243. if not win32.ClearCommError(self._port_handle, ctypes.byref(flags), ctypes.byref(comstat)):
  244. raise SerialException("ClearCommError failed ({!r})".format(ctypes.WinError()))
  245. n = min(comstat.cbInQue, size) if self.timeout == 0 else size
  246. if n > 0:
  247. buf = ctypes.create_string_buffer(n)
  248. rc = win32.DWORD()
  249. read_ok = win32.ReadFile(
  250. self._port_handle,
  251. buf,
  252. n,
  253. ctypes.byref(rc),
  254. ctypes.byref(self._overlapped_read))
  255. if not read_ok and win32.GetLastError() not in (win32.ERROR_SUCCESS, win32.ERROR_IO_PENDING):
  256. raise SerialException("ReadFile failed ({!r})".format(ctypes.WinError()))
  257. result_ok = win32.GetOverlappedResult(
  258. self._port_handle,
  259. ctypes.byref(self._overlapped_read),
  260. ctypes.byref(rc),
  261. True)
  262. if not result_ok:
  263. if win32.GetLastError() != win32.ERROR_OPERATION_ABORTED:
  264. raise SerialException("GetOverlappedResult failed ({!r})".format(ctypes.WinError()))
  265. read = buf.raw[:rc.value]
  266. else:
  267. read = bytes()
  268. else:
  269. read = bytes()
  270. return bytes(read)
  271. def write(self, data):
  272. """Output the given byte string over the serial port."""
  273. if not self.is_open:
  274. raise portNotOpenError
  275. #~ if not isinstance(data, (bytes, bytearray)):
  276. #~ raise TypeError('expected %s or bytearray, got %s' % (bytes, type(data)))
  277. # convert data (needed in case of memoryview instance: Py 3.1 io lib), ctypes doesn't like memoryview
  278. data = to_bytes(data)
  279. if data:
  280. #~ win32event.ResetEvent(self._overlapped_write.hEvent)
  281. n = win32.DWORD()
  282. success = win32.WriteFile(self._port_handle, data, len(data), ctypes.byref(n), self._overlapped_write)
  283. if self._write_timeout != 0: # if blocking (None) or w/ write timeout (>0)
  284. if not success and win32.GetLastError() not in (win32.ERROR_SUCCESS, win32.ERROR_IO_PENDING):
  285. raise SerialException("WriteFile failed ({!r})".format(ctypes.WinError()))
  286. # Wait for the write to complete.
  287. #~ win32.WaitForSingleObject(self._overlapped_write.hEvent, win32.INFINITE)
  288. win32.GetOverlappedResult(self._port_handle, self._overlapped_write, ctypes.byref(n), True)
  289. if win32.GetLastError() == win32.ERROR_OPERATION_ABORTED:
  290. return n.value # canceled IO is no error
  291. if n.value != len(data):
  292. raise writeTimeoutError
  293. return n.value
  294. else:
  295. errorcode = win32.ERROR_SUCCESS if success else win32.GetLastError()
  296. if errorcode in (win32.ERROR_INVALID_USER_BUFFER, win32.ERROR_NOT_ENOUGH_MEMORY,
  297. win32.ERROR_OPERATION_ABORTED):
  298. return 0
  299. elif errorcode in (win32.ERROR_SUCCESS, win32.ERROR_IO_PENDING):
  300. # no info on true length provided by OS function in async mode
  301. return len(data)
  302. else:
  303. raise SerialException("WriteFile failed ({!r})".format(ctypes.WinError()))
  304. else:
  305. return 0
  306. def flush(self):
  307. """\
  308. Flush of file like objects. In this case, wait until all data
  309. is written.
  310. """
  311. while self.out_waiting:
  312. time.sleep(0.05)
  313. # XXX could also use WaitCommEvent with mask EV_TXEMPTY, but it would
  314. # require overlapped IO and it's also only possible to set a single mask
  315. # on the port---
  316. def reset_input_buffer(self):
  317. """Clear input buffer, discarding all that is in the buffer."""
  318. if not self.is_open:
  319. raise portNotOpenError
  320. win32.PurgeComm(self._port_handle, win32.PURGE_RXCLEAR | win32.PURGE_RXABORT)
  321. def reset_output_buffer(self):
  322. """\
  323. Clear output buffer, aborting the current output and discarding all
  324. that is in the buffer.
  325. """
  326. if not self.is_open:
  327. raise portNotOpenError
  328. win32.PurgeComm(self._port_handle, win32.PURGE_TXCLEAR | win32.PURGE_TXABORT)
  329. def _update_break_state(self):
  330. """Set break: Controls TXD. When active, to transmitting is possible."""
  331. if not self.is_open:
  332. raise portNotOpenError
  333. if self._break_state:
  334. win32.SetCommBreak(self._port_handle)
  335. else:
  336. win32.ClearCommBreak(self._port_handle)
  337. def _update_rts_state(self):
  338. """Set terminal status line: Request To Send"""
  339. if self._rts_state:
  340. win32.EscapeCommFunction(self._port_handle, win32.SETRTS)
  341. else:
  342. win32.EscapeCommFunction(self._port_handle, win32.CLRRTS)
  343. def _update_dtr_state(self):
  344. """Set terminal status line: Data Terminal Ready"""
  345. if self._dtr_state:
  346. win32.EscapeCommFunction(self._port_handle, win32.SETDTR)
  347. else:
  348. win32.EscapeCommFunction(self._port_handle, win32.CLRDTR)
  349. def _GetCommModemStatus(self):
  350. if not self.is_open:
  351. raise portNotOpenError
  352. stat = win32.DWORD()
  353. win32.GetCommModemStatus(self._port_handle, ctypes.byref(stat))
  354. return stat.value
  355. @property
  356. def cts(self):
  357. """Read terminal status line: Clear To Send"""
  358. return win32.MS_CTS_ON & self._GetCommModemStatus() != 0
  359. @property
  360. def dsr(self):
  361. """Read terminal status line: Data Set Ready"""
  362. return win32.MS_DSR_ON & self._GetCommModemStatus() != 0
  363. @property
  364. def ri(self):
  365. """Read terminal status line: Ring Indicator"""
  366. return win32.MS_RING_ON & self._GetCommModemStatus() != 0
  367. @property
  368. def cd(self):
  369. """Read terminal status line: Carrier Detect"""
  370. return win32.MS_RLSD_ON & self._GetCommModemStatus() != 0
  371. # - - platform specific - - - -
  372. def set_buffer_size(self, rx_size=4096, tx_size=None):
  373. """\
  374. Recommend a buffer size to the driver (device driver can ignore this
  375. value). Must be called before the port is opened.
  376. """
  377. if tx_size is None:
  378. tx_size = rx_size
  379. win32.SetupComm(self._port_handle, rx_size, tx_size)
  380. def set_output_flow_control(self, enable=True):
  381. """\
  382. Manually control flow - when software flow control is enabled.
  383. This will do the same as if XON (true) or XOFF (false) are received
  384. from the other device and control the transmission accordingly.
  385. WARNING: this function is not portable to different platforms!
  386. """
  387. if not self.is_open:
  388. raise portNotOpenError
  389. if enable:
  390. win32.EscapeCommFunction(self._port_handle, win32.SETXON)
  391. else:
  392. win32.EscapeCommFunction(self._port_handle, win32.SETXOFF)
  393. @property
  394. def out_waiting(self):
  395. """Return how many bytes the in the outgoing buffer"""
  396. flags = win32.DWORD()
  397. comstat = win32.COMSTAT()
  398. if not win32.ClearCommError(self._port_handle, ctypes.byref(flags), ctypes.byref(comstat)):
  399. raise SerialException("ClearCommError failed ({!r})".format(ctypes.WinError()))
  400. return comstat.cbOutQue
  401. def _cancel_overlapped_io(self, overlapped):
  402. """Cancel a blocking read operation, may be called from other thread"""
  403. # check if read operation is pending
  404. rc = win32.DWORD()
  405. err = win32.GetOverlappedResult(
  406. self._port_handle,
  407. ctypes.byref(overlapped),
  408. ctypes.byref(rc),
  409. False)
  410. if not err and win32.GetLastError() in (win32.ERROR_IO_PENDING, win32.ERROR_IO_INCOMPLETE):
  411. # cancel, ignoring any errors (e.g. it may just have finished on its own)
  412. win32.CancelIoEx(self._port_handle, overlapped)
  413. def cancel_read(self):
  414. """Cancel a blocking read operation, may be called from other thread"""
  415. self._cancel_overlapped_io(self._overlapped_read)
  416. def cancel_write(self):
  417. """Cancel a blocking write operation, may be called from other thread"""
  418. self._cancel_overlapped_io(self._overlapped_write)
  419. @SerialBase.exclusive.setter
  420. def exclusive(self, exclusive):
  421. """Change the exclusive access setting."""
  422. if exclusive is not None and not exclusive:
  423. raise ValueError('win32 only supports exclusive access (not: {})'.format(exclusive))
  424. else:
  425. serial.SerialBase.exclusive.__set__(self, exclusive)