You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

478 lines
20KB

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