serialcli.py 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270
  1. #! python
  2. #
  3. # Backend for .NET/Mono (IronPython), .NET >= 2
  4. #
  5. # This file is part of pySerial. https://github.com/pyserial/pyserial
  6. # (C) 2008-2015 Chris Liechti <cliechti@gmx.net>
  7. #
  8. # SPDX-License-Identifier: BSD-3-Clause
  9. import clr
  10. import System
  11. import System.IO.Ports
  12. from serial.serialutil import *
  13. #~ def device(portnum):
  14. #~ """Turn a port number into a device name"""
  15. #~ return System.IO.Ports.SerialPort.GetPortNames()[portnum]
  16. # must invoke function with byte array, make a helper to convert strings
  17. # to byte arrays
  18. sab = System.Array[System.Byte]
  19. def as_byte_array(string):
  20. return sab([ord(x) for x in string]) # XXX will require adaption when run with a 3.x compatible IronPython
  21. class Serial(SerialBase):
  22. """Serial port implementation for .NET/Mono."""
  23. BAUDRATES = (50, 75, 110, 134, 150, 200, 300, 600, 1200, 1800, 2400, 4800,
  24. 9600, 19200, 38400, 57600, 115200)
  25. def open(self):
  26. """\
  27. Open port with current settings. This may throw a SerialException
  28. if the port cannot be opened.
  29. """
  30. if self._port is None:
  31. raise SerialException("Port must be configured before it can be used.")
  32. if self.is_open:
  33. raise SerialException("Port is already open.")
  34. try:
  35. self._port_handle = System.IO.Ports.SerialPort(self.portstr)
  36. except Exception as msg:
  37. self._port_handle = None
  38. raise SerialException("could not open port %s: %s" % (self.portstr, msg))
  39. self._reconfigurePort()
  40. self._port_handle.Open()
  41. self.is_open = True
  42. if not self._dsrdtr:
  43. self._update_dtr_state()
  44. if not self._rtscts:
  45. self._update_rts_state()
  46. self.reset_input_buffer()
  47. def _reconfigurePort(self):
  48. """Set communication parameters on opened port."""
  49. if not self._port_handle:
  50. raise SerialException("Can only operate on a valid port handle")
  51. #~ self._port_handle.ReceivedBytesThreshold = 1
  52. if self._timeout is None:
  53. self._port_handle.ReadTimeout = System.IO.Ports.SerialPort.InfiniteTimeout
  54. else:
  55. self._port_handle.ReadTimeout = int(self._timeout*1000)
  56. # if self._timeout != 0 and self._interCharTimeout is not None:
  57. # timeouts = (int(self._interCharTimeout * 1000),) + timeouts[1:]
  58. if self._write_timeout is None:
  59. self._port_handle.WriteTimeout = System.IO.Ports.SerialPort.InfiniteTimeout
  60. else:
  61. self._port_handle.WriteTimeout = int(self._write_timeout*1000)
  62. # Setup the connection info.
  63. try:
  64. self._port_handle.BaudRate = self._baudrate
  65. except IOError as e:
  66. # catch errors from illegal baudrate settings
  67. raise ValueError(str(e))
  68. if self._bytesize == FIVEBITS:
  69. self._port_handle.DataBits = 5
  70. elif self._bytesize == SIXBITS:
  71. self._port_handle.DataBits = 6
  72. elif self._bytesize == SEVENBITS:
  73. self._port_handle.DataBits = 7
  74. elif self._bytesize == EIGHTBITS:
  75. self._port_handle.DataBits = 8
  76. else:
  77. raise ValueError("Unsupported number of data bits: %r" % self._bytesize)
  78. if self._parity == PARITY_NONE:
  79. self._port_handle.Parity = getattr(System.IO.Ports.Parity, 'None') # reserved keyword in Py3k
  80. elif self._parity == PARITY_EVEN:
  81. self._port_handle.Parity = System.IO.Ports.Parity.Even
  82. elif self._parity == PARITY_ODD:
  83. self._port_handle.Parity = System.IO.Ports.Parity.Odd
  84. elif self._parity == PARITY_MARK:
  85. self._port_handle.Parity = System.IO.Ports.Parity.Mark
  86. elif self._parity == PARITY_SPACE:
  87. self._port_handle.Parity = System.IO.Ports.Parity.Space
  88. else:
  89. raise ValueError("Unsupported parity mode: %r" % self._parity)
  90. if self._stopbits == STOPBITS_ONE:
  91. self._port_handle.StopBits = System.IO.Ports.StopBits.One
  92. elif self._stopbits == STOPBITS_ONE_POINT_FIVE:
  93. self._port_handle.StopBits = System.IO.Ports.StopBits.OnePointFive
  94. elif self._stopbits == STOPBITS_TWO:
  95. self._port_handle.StopBits = System.IO.Ports.StopBits.Two
  96. else:
  97. raise ValueError("Unsupported number of stop bits: %r" % self._stopbits)
  98. if self._rtscts and self._xonxoff:
  99. self._port_handle.Handshake = System.IO.Ports.Handshake.RequestToSendXOnXOff
  100. elif self._rtscts:
  101. self._port_handle.Handshake = System.IO.Ports.Handshake.RequestToSend
  102. elif self._xonxoff:
  103. self._port_handle.Handshake = System.IO.Ports.Handshake.XOnXOff
  104. else:
  105. self._port_handle.Handshake = getattr(System.IO.Ports.Handshake, 'None') # reserved keyword in Py3k
  106. #~ def __del__(self):
  107. #~ self.close()
  108. def close(self):
  109. """Close port"""
  110. if self.is_open:
  111. if self._port_handle:
  112. try:
  113. self._port_handle.Close()
  114. except System.IO.Ports.InvalidOperationException:
  115. # ignore errors. can happen for unplugged USB serial devices
  116. pass
  117. self._port_handle = None
  118. self.is_open = False
  119. # - - - - - - - - - - - - - - - - - - - - - - - -
  120. @property
  121. def in_waiting(self):
  122. """Return the number of characters currently in the input buffer."""
  123. if not self._port_handle:
  124. raise portNotOpenError
  125. return self._port_handle.BytesToRead
  126. def read(self, size=1):
  127. """\
  128. Read size bytes from the serial port. If a timeout is set it may
  129. return less characters as requested. With no timeout it will block
  130. until the requested number of bytes is read.
  131. """
  132. if not self._port_handle:
  133. raise portNotOpenError
  134. # must use single byte reads as this is the only way to read
  135. # without applying encodings
  136. data = bytearray()
  137. while size:
  138. try:
  139. data.append(self._port_handle.ReadByte())
  140. except System.TimeoutException as e:
  141. break
  142. else:
  143. size -= 1
  144. return bytes(data)
  145. def write(self, data):
  146. """Output the given string over the serial port."""
  147. if not self._port_handle:
  148. raise portNotOpenError
  149. #~ if not isinstance(data, (bytes, bytearray)):
  150. #~ raise TypeError('expected %s or bytearray, got %s' % (bytes, type(data)))
  151. try:
  152. # must call overloaded method with byte array argument
  153. # as this is the only one not applying encodings
  154. self._port_handle.Write(as_byte_array(data), 0, len(data))
  155. except System.TimeoutException as e:
  156. raise writeTimeoutError
  157. return len(data)
  158. def reset_input_buffer(self):
  159. """Clear input buffer, discarding all that is in the buffer."""
  160. if not self._port_handle:
  161. raise portNotOpenError
  162. self._port_handle.DiscardInBuffer()
  163. def reset_output_buffer(self):
  164. """\
  165. Clear output buffer, aborting the current output and
  166. discarding all that is in the buffer.
  167. """
  168. if not self._port_handle:
  169. raise portNotOpenError
  170. self._port_handle.DiscardOutBuffer()
  171. def _update_break_state(self):
  172. """
  173. Set break: Controls TXD. When active, to transmitting is possible.
  174. """
  175. if not self._port_handle:
  176. raise portNotOpenError
  177. self._port_handle.BreakState = bool(self._break_state)
  178. def _update_rts_state(self):
  179. """Set terminal status line: Request To Send"""
  180. if not self._port_handle:
  181. raise portNotOpenError
  182. self._port_handle.RtsEnable = bool(self._rts_state)
  183. def _update_dtr_state(self):
  184. """Set terminal status line: Data Terminal Ready"""
  185. if not self._port_handle:
  186. raise portNotOpenError
  187. self._port_handle.DtrEnable = bool(self._dtr_state)
  188. @property
  189. def cts(self):
  190. """Read terminal status line: Clear To Send"""
  191. if not self._port_handle:
  192. raise portNotOpenError
  193. return self._port_handle.CtsHolding
  194. @property
  195. def dsr(self):
  196. """Read terminal status line: Data Set Ready"""
  197. if not self._port_handle:
  198. raise portNotOpenError
  199. return self._port_handle.DsrHolding
  200. @property
  201. def ri(self):
  202. """Read terminal status line: Ring Indicator"""
  203. if not self._port_handle:
  204. raise portNotOpenError
  205. #~ return self._port_handle.XXX
  206. return False #XXX an error would be better
  207. @property
  208. def cd(self):
  209. """Read terminal status line: Carrier Detect"""
  210. if not self._port_handle:
  211. raise portNotOpenError
  212. return self._port_handle.CDHolding
  213. # - - platform specific - - - -
  214. # none
  215. # Nur Testfunktion!!
  216. if __name__ == '__main__':
  217. import sys
  218. s = Serial(0)
  219. sys.stdio.write('%s\n' % s)
  220. s = Serial()
  221. sys.stdio.write('%s\n' % s)
  222. s.baudrate = 19200
  223. s.databits = 7
  224. s.close()
  225. s.port = 0
  226. s.open()
  227. sys.stdio.write('%s\n' % s)