aio.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428
  1. #!/usr/bin/env python3
  2. #
  3. # Experimental implementation of asyncio support.
  4. #
  5. # This file is part of pySerial. https://github.com/pyserial/pyserial
  6. # (C) 2015 Chris Liechti <cliechti@gmx.net>
  7. #
  8. # SPDX-License-Identifier: BSD-3-Clause
  9. """\
  10. Support asyncio with serial ports. EXPERIMENTAL
  11. Posix platforms only, Python 3.4+ only.
  12. Windows event loops can not wait for serial ports with the current
  13. implementation. It should be possible to get that working though.
  14. """
  15. import asyncio
  16. import serial
  17. class SerialTransport(asyncio.Transport):
  18. """An asyncio transport model of a serial communication channel.
  19. A transport class is an abstraction of a communication channel.
  20. This allows protocol implementations to be developed against the
  21. transport abstraction without needing to know the details of the
  22. underlying channel, such as whether it is a pipe, a socket, or
  23. indeed a serial port.
  24. You generally won’t instantiate a transport yourself; instead, you
  25. will call `create_serial_connection` which will create the
  26. transport and try to initiate the underlying communication channel,
  27. calling you back when it succeeds.
  28. """
  29. def __init__(self, loop, protocol, serial_instance):
  30. super().__init__()
  31. self._loop = loop
  32. self._protocol = protocol
  33. self._serial = serial_instance
  34. self._closing = False
  35. self._protocol_paused = False
  36. self._max_read_size = 1024
  37. self._write_buffer = []
  38. self._set_write_buffer_limits()
  39. self._has_reader = False
  40. self._has_writer = False
  41. # XXX how to support url handlers too
  42. # Asynchronous I/O requires non-blocking devices
  43. self._serial.timeout = 0
  44. self._serial.write_timeout = 0
  45. # These two callbacks will be enqueued in a FIFO queue by asyncio
  46. loop.call_soon(protocol.connection_made, self)
  47. loop.call_soon(self._ensure_reader)
  48. @property
  49. def serial(self):
  50. """The underlying Serial instance."""
  51. return self._serial
  52. def __repr__(self):
  53. return '{self.__class__.__name__}({self._loop}, {self._protocol}, {self.serial})'.format(self=self)
  54. def is_closing(self):
  55. """Return True if the transport is closing or closed."""
  56. return self._closing
  57. def close(self):
  58. """Close the transport gracefully.
  59. Any buffered data will be written asynchronously. No more data
  60. will be received and further writes will be silently ignored.
  61. After all buffered data is flushed, the protocol's
  62. connection_lost() method will be called with None as its
  63. argument.
  64. """
  65. if not self._closing:
  66. self._close(None)
  67. def _read_ready(self):
  68. try:
  69. data = self._serial.read(self._max_read_size)
  70. except serial.SerialException as e:
  71. self._close(exc=e)
  72. else:
  73. if data:
  74. self._protocol.data_received(data)
  75. def write(self, data):
  76. """Write some data to the transport.
  77. This method does not block; it buffers the data and arranges
  78. for it to be sent out asynchronously. Writes made after the
  79. transport has been closed will be ignored."""
  80. if self._closing:
  81. return
  82. if self.get_write_buffer_size() == 0:
  83. # Attempt to send it right away first
  84. try:
  85. n = self._serial.write(data)
  86. except serial.SerialException as exc:
  87. self._fatal_error(exc, 'Fatal write error on serial transport')
  88. return
  89. if n == len(data):
  90. return # Whole request satisfied
  91. assert n > 0
  92. data = data[n:]
  93. self._ensure_writer()
  94. self._write_buffer.append(data)
  95. self._maybe_pause_protocol()
  96. def can_write_eof(self):
  97. """Serial ports do not support the concept of end-of-file.
  98. Always returns False.
  99. """
  100. return False
  101. def pause_reading(self):
  102. """Pause the receiving end of the transport.
  103. No data will be passed to the protocol’s data_received() method
  104. until resume_reading() is called.
  105. """
  106. self._remove_reader()
  107. def resume_reading(self):
  108. """Resume the receiving end of the transport.
  109. Incoming data will be passed to the protocol's data_received()
  110. method until pause_reading() is called.
  111. """
  112. self._ensure_reader()
  113. def set_write_buffer_limits(self, high=None, low=None):
  114. """Set the high- and low-water limits for write flow control.
  115. These two values control when call the protocol’s
  116. pause_writing()and resume_writing() methods are called. If
  117. specified, the low-water limit must be less than or equal to
  118. the high-water limit. Neither high nor low can be negative.
  119. """
  120. self._set_write_buffer_limits(high=high, low=low)
  121. self._maybe_pause_protocol()
  122. def get_write_buffer_size(self):
  123. """The number of bytes in the write buffer.
  124. This buffer is unbounded, so the result may be larger than the
  125. the high water mark.
  126. """
  127. return sum(map(len, self._write_buffer))
  128. def write_eof(self):
  129. raise NotImplementedError("Serial connections do not support end-of-file")
  130. def abort(self):
  131. """Close the transport immediately.
  132. Pending operations will not be given opportunity to complete,
  133. and buffered data will be lost. No more data will be received
  134. and further writes will be ignored. The protocol's
  135. connection_lost() method will eventually be called.
  136. """
  137. self._abort(None)
  138. def _maybe_pause_protocol(self):
  139. """To be called whenever the write-buffer size increases.
  140. Tests the current write-buffer size against the high water
  141. mark configured for this transport. If the high water mark is
  142. exceeded, the protocol is instructed to pause_writing().
  143. """
  144. if self.get_write_buffer_size() <= self._high_water:
  145. return
  146. if not self._protocol_paused:
  147. self._protocol_paused = True
  148. try:
  149. self._protocol.pause_writing()
  150. except Exception as exc:
  151. self._loop.call_exception_handler({
  152. 'message': 'protocol.pause_writing() failed',
  153. 'exception': exc,
  154. 'transport': self,
  155. 'protocol': self._protocol,
  156. })
  157. def _maybe_resume_protocol(self):
  158. """To be called whenever the write-buffer size decreases.
  159. Tests the current write-buffer size against the low water
  160. mark configured for this transport. If the write-buffer
  161. size is below the low water mark, the protocol is
  162. instructed that is can resume_writing().
  163. """
  164. if (self._protocol_paused and
  165. self.get_write_buffer_size() <= self._low_water):
  166. self._protocol_paused = False
  167. try:
  168. self._protocol.resume_writing()
  169. except Exception as exc:
  170. self._loop.call_exception_handler({
  171. 'message': 'protocol.resume_writing() failed',
  172. 'exception': exc,
  173. 'transport': self,
  174. 'protocol': self._protocol,
  175. })
  176. def _write_ready(self):
  177. """Asynchronously write buffered data.
  178. This method is called back asynchronously as a writer
  179. registered with the asyncio event-loop against the
  180. underlying file descriptor for the serial port.
  181. Should the write-buffer become empty if this method
  182. is invoked while the transport is closing, the protocol's
  183. connection_lost() method will be called with None as its
  184. argument.
  185. """
  186. data = b''.join(self._write_buffer)
  187. num_bytes = len(data)
  188. assert data, 'Write buffer should not be empty'
  189. self._write_buffer.clear()
  190. try:
  191. n = self._serial.write(data)
  192. except (BlockingIOError, InterruptedError):
  193. self._write_buffer.append(data)
  194. except serial.SerialException as exc:
  195. self._fatal_error(exc, 'Fatal write error on serial transport')
  196. else:
  197. if n == len(data):
  198. assert self._flushed()
  199. self._remove_writer()
  200. self._maybe_resume_protocol() # May cause further writes
  201. # _write_ready may have been invoked by the event loop
  202. # after the transport was closed, as part of the ongoing
  203. # process of flushing buffered data. If the buffer
  204. # is now empty, we can close the connection
  205. if self._closing and self._flushed():
  206. self._close()
  207. return
  208. assert n > 0
  209. data = data[n:]
  210. self._write_buffer.append(data) # Try again later
  211. self._maybe_resume_protocol()
  212. assert self._has_writer
  213. def _ensure_reader(self):
  214. if (not self._has_reader) and (not self._closing):
  215. self._loop.add_reader(self._serial.fd, self._read_ready)
  216. self._has_reader = True
  217. def _remove_reader(self):
  218. if self._has_reader:
  219. self._loop.remove_reader(self._serial.fd)
  220. self._has_reader = False
  221. def _ensure_writer(self):
  222. if (not self._has_writer) and (not self._closing):
  223. self._loop.add_writer(self._serial.fd, self._write_ready)
  224. self._has_writer = True
  225. def _remove_writer(self):
  226. if self._has_writer:
  227. self._loop.remove_writer(self._serial.fd)
  228. self._has_writer = False
  229. def _set_write_buffer_limits(self, high=None, low=None):
  230. """Ensure consistent write-buffer limits."""
  231. if high is None:
  232. high = 64 * 1024 if low is None else 4 * low
  233. if low is None:
  234. low = high // 4
  235. if not high >= low >= 0:
  236. raise ValueError('high (%r) must be >= low (%r) must be >= 0' %
  237. (high, low))
  238. self._high_water = high
  239. self._low_water = low
  240. def _fatal_error(self, exc, message='Fatal error on serial transport'):
  241. """Report a fatal error to the event-loop and abort the transport."""
  242. self._loop.call_exception_handler({
  243. 'message': message,
  244. 'exception': exc,
  245. 'transport': self,
  246. 'protocol': self._protocol,
  247. })
  248. self._abort(exc)
  249. def _flushed(self):
  250. """True if the write buffer is empty, otherwise False."""
  251. return self.get_write_buffer_size() == 0
  252. def _close(self, exc=None):
  253. """Close the transport gracefully.
  254. If the write buffer is already empty, writing will be
  255. stopped immediately and a call to the protocol's
  256. connection_lost() method scheduled.
  257. If the write buffer is not already empty, the
  258. asynchronous writing will continue, and the _write_ready
  259. method will call this _close method again when the
  260. buffer has been flushed completely.
  261. """
  262. self._closing = True
  263. self._remove_reader()
  264. if self._flushed():
  265. self._remove_writer()
  266. self._loop.call_soon(self._call_connection_lost, exc)
  267. def _abort(self, exc):
  268. """Close the transport immediately.
  269. Pending operations will not be given opportunity to complete,
  270. and buffered data will be lost. No more data will be received
  271. and further writes will be ignored. The protocol's
  272. connection_lost() method will eventually be called with the
  273. passed exception.
  274. """
  275. self._closing = True
  276. self._remove_reader()
  277. self._remove_writer() # Pending buffered data will not be written
  278. self._loop.call_soon(self._call_connection_lost, exc)
  279. def _call_connection_lost(self, exc):
  280. """Close the connection.
  281. Informs the protocol through connection_lost() and clears
  282. pending buffers and closes the serial connection.
  283. """
  284. assert self._closing
  285. assert not self._has_writer
  286. assert not self._has_reader
  287. self._serial.flush()
  288. try:
  289. self._protocol.connection_lost(exc)
  290. finally:
  291. self._write_buffer.clear()
  292. self._serial.close()
  293. self._serial = None
  294. self._protocol = None
  295. self._loop = None
  296. @asyncio.coroutine
  297. def create_serial_connection(loop, protocol_factory, *args, **kwargs):
  298. ser = serial.serial_for_url(*args, **kwargs)
  299. protocol = protocol_factory()
  300. transport = SerialTransport(loop, protocol, ser)
  301. return (transport, protocol)
  302. @asyncio.coroutine
  303. def open_serial_connection(**kwargs):
  304. """A wrapper for create_serial_connection() returning a (reader,
  305. writer) pair.
  306. The reader returned is a StreamReader instance; the writer is a
  307. StreamWriter instance.
  308. The arguments are all the usual arguments to Serial(). Additional
  309. optional keyword arguments are loop (to set the event loop instance
  310. to use) and limit (to set the buffer limit passed to the
  311. StreamReader.
  312. This function is a coroutine.
  313. """
  314. # in order to avoid errors when pySerial is installed under Python 2,
  315. # avoid Pyhthon 3 syntax here. So do not use this function as a good
  316. # example!
  317. loop = kwargs.get('loop', asyncio.get_event_loop())
  318. limit = kwargs.get('limit', asyncio.streams._DEFAULT_LIMIT)
  319. reader = asyncio.StreamReader(limit=limit, loop=loop)
  320. protocol = asyncio.StreamReaderProtocol(reader, loop=loop)
  321. # in Python 3 we would write "yield transport, _ from c()"
  322. for transport, _ in create_serial_connection(
  323. loop=loop,
  324. protocol_factory=lambda: protocol,
  325. **kwargs):
  326. yield transport, _
  327. writer = asyncio.StreamWriter(transport, protocol, reader, loop)
  328. # in Python 3 we would write "return reader, writer"
  329. raise StopIteration(reader, writer)
  330. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  331. # test
  332. if __name__ == '__main__':
  333. class Output(asyncio.Protocol):
  334. def connection_made(self, transport):
  335. self.transport = transport
  336. print('port opened', transport)
  337. transport.serial.rts = False
  338. transport.write(b'hello world\n')
  339. def data_received(self, data):
  340. print('data received', repr(data))
  341. if b'\n' in data:
  342. self.transport.close()
  343. def connection_lost(self, exc):
  344. print('port closed')
  345. asyncio.get_event_loop().stop()
  346. def pause_writing(self):
  347. print('pause writing')
  348. print(self.transport.get_write_buffer_size())
  349. def resume_writing(self):
  350. print(self.transport.get_write_buffer_size())
  351. print('resume writing')
  352. loop = asyncio.get_event_loop()
  353. coro = create_serial_connection(loop, Output, '/dev/ttyUSB0', baudrate=115200)
  354. loop.run_until_complete(coro)
  355. loop.run_forever()
  356. loop.close()