__init__.py 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  1. #!/usr/bin/env python3
  2. #
  3. # Working with threading and pySerial
  4. #
  5. # This file is part of pySerial. https://github.com/pyserial/pyserial
  6. # (C) 2015-2016 Chris Liechti <cliechti@gmx.net>
  7. #
  8. # SPDX-License-Identifier: BSD-3-Clause
  9. """\
  10. Support threading with serial ports.
  11. """
  12. from __future__ import absolute_import
  13. import serial
  14. import threading
  15. class Protocol(object):
  16. """\
  17. Protocol as used by the ReaderThread. This base class provides empty
  18. implementations of all methods.
  19. """
  20. def connection_made(self, transport):
  21. """Called when reader thread is started"""
  22. def data_received(self, data):
  23. """Called with snippets received from the serial port"""
  24. def connection_lost(self, exc):
  25. """\
  26. Called when the serial port is closed or the reader loop terminated
  27. otherwise.
  28. """
  29. if isinstance(exc, Exception):
  30. raise exc
  31. class Packetizer(Protocol):
  32. """
  33. Read binary packets from serial port. Packets are expected to be terminated
  34. with a TERMINATOR byte (null byte by default).
  35. The class also keeps track of the transport.
  36. """
  37. TERMINATOR = b'\0'
  38. def __init__(self):
  39. self.buffer = bytearray()
  40. self.transport = None
  41. def connection_made(self, transport):
  42. """Store transport"""
  43. self.transport = transport
  44. def connection_lost(self, exc):
  45. """Forget transport"""
  46. self.transport = None
  47. super(Packetizer, self).connection_lost(exc)
  48. def data_received(self, data):
  49. """Buffer received data, find TERMINATOR, call handle_packet"""
  50. self.buffer.extend(data)
  51. while self.TERMINATOR in self.buffer:
  52. packet, self.buffer = self.buffer.split(self.TERMINATOR, 1)
  53. self.handle_packet(packet)
  54. def handle_packet(self, packet):
  55. """Process packets - to be overridden by subclassing"""
  56. raise NotImplementedError('please implement functionality in handle_packet')
  57. class FramedPacket(Protocol):
  58. """
  59. Read binary packets. Packets are expected to have a start and stop marker.
  60. The class also keeps track of the transport.
  61. """
  62. START = b'('
  63. STOP = b')'
  64. def __init__(self):
  65. self.packet = bytearray()
  66. self.in_packet = False
  67. self.transport = None
  68. def connection_made(self, transport):
  69. """Store transport"""
  70. self.transport = transport
  71. def connection_lost(self, exc):
  72. """Forget transport"""
  73. self.transport = None
  74. self.in_packet = False
  75. del self.packet[:]
  76. super(FramedPacket, self).connection_lost(exc)
  77. def data_received(self, data):
  78. """Find data enclosed in START/STOP, call handle_packet"""
  79. for byte in serial.iterbytes(data):
  80. if byte == self.START:
  81. self.in_packet = True
  82. elif byte == self.STOP:
  83. self.in_packet = False
  84. self.handle_packet(bytes(self.packet)) # make read-only copy
  85. del self.packet[:]
  86. elif self.in_packet:
  87. self.packet.extend(byte)
  88. else:
  89. self.handle_out_of_packet_data(byte)
  90. def handle_packet(self, packet):
  91. """Process packets - to be overridden by subclassing"""
  92. raise NotImplementedError('please implement functionality in handle_packet')
  93. def handle_out_of_packet_data(self, data):
  94. """Process data that is received outside of packets"""
  95. pass
  96. class LineReader(Packetizer):
  97. """
  98. Read and write (Unicode) lines from/to serial port.
  99. The encoding is applied.
  100. """
  101. TERMINATOR = b'\r\n'
  102. ENCODING = 'utf-8'
  103. UNICODE_HANDLING = 'replace'
  104. def handle_packet(self, packet):
  105. self.handle_line(packet.decode(self.ENCODING, self.UNICODE_HANDLING))
  106. def handle_line(self, line):
  107. """Process one line - to be overridden by subclassing"""
  108. raise NotImplementedError('please implement functionality in handle_line')
  109. def write_line(self, text):
  110. """
  111. Write text to the transport. ``text`` is a Unicode string and the encoding
  112. is applied before sending ans also the newline is append.
  113. """
  114. # + is not the best choice but bytes does not support % or .format in py3 and we want a single write call
  115. self.transport.write(text.encode(self.ENCODING, self.UNICODE_HANDLING) + self.TERMINATOR)
  116. class ReaderThread(threading.Thread):
  117. """\
  118. Implement a serial port read loop and dispatch to a Protocol instance (like
  119. the asyncio.Protocol) but do it with threads.
  120. Calls to close() will close the serial port but it is also possible to just
  121. stop() this thread and continue the serial port instance otherwise.
  122. """
  123. def __init__(self, serial_instance, protocol_factory):
  124. """\
  125. Initialize thread.
  126. Note that the serial_instance' timeout is set to one second!
  127. Other settings are not changed.
  128. """
  129. super(ReaderThread, self).__init__()
  130. self.daemon = True
  131. self.serial = serial_instance
  132. self.protocol_factory = protocol_factory
  133. self.alive = True
  134. self._lock = threading.Lock()
  135. self._connection_made = threading.Event()
  136. self.protocol = None
  137. def stop(self):
  138. """Stop the reader thread"""
  139. self.alive = False
  140. if hasattr(self.serial, 'cancel_read'):
  141. self.serial.cancel_read()
  142. self.join(2)
  143. def run(self):
  144. """Reader loop"""
  145. if not hasattr(self.serial, 'cancel_read'):
  146. self.serial.timeout = 1
  147. self.protocol = self.protocol_factory()
  148. try:
  149. self.protocol.connection_made(self)
  150. except Exception as e:
  151. self.alive = False
  152. self.protocol.connection_lost(e)
  153. self._connection_made.set()
  154. return
  155. error = None
  156. self._connection_made.set()
  157. while self.alive and self.serial.is_open:
  158. try:
  159. # read all that is there or wait for one byte (blocking)
  160. data = self.serial.read(self.serial.in_waiting or 1)
  161. except serial.SerialException as e:
  162. # probably some I/O problem such as disconnected USB serial
  163. # adapters -> exit
  164. error = e
  165. break
  166. else:
  167. if data:
  168. # make a separated try-except for called user code
  169. try:
  170. self.protocol.data_received(data)
  171. except Exception as e:
  172. error = e
  173. break
  174. self.alive = False
  175. self.protocol.connection_lost(error)
  176. self.protocol = None
  177. def write(self, data):
  178. """Thread safe writing (uses lock)"""
  179. with self._lock:
  180. return self.serial.write(data)
  181. def close(self):
  182. """Close the serial port and exit reader thread (uses lock)"""
  183. # use the lock to let other threads finish writing
  184. with self._lock:
  185. # first stop reading, so that closing can be done on idle port
  186. self.stop()
  187. self.serial.close()
  188. def connect(self):
  189. """
  190. Wait until connection is set up and return the transport and protocol
  191. instances.
  192. """
  193. if self.alive:
  194. self._connection_made.wait()
  195. if not self.alive:
  196. raise RuntimeError('connection_lost already called')
  197. return (self, self.protocol)
  198. else:
  199. raise RuntimeError('already stopped')
  200. # - - context manager, returns protocol
  201. def __enter__(self):
  202. """\
  203. Enter context handler. May raise RuntimeError in case the connection
  204. could not be created.
  205. """
  206. self.start()
  207. self._connection_made.wait()
  208. if not self.alive:
  209. raise RuntimeError('connection_lost already called')
  210. return self.protocol
  211. def __exit__(self, exc_type, exc_val, exc_tb):
  212. """Leave context: close port"""
  213. self.close()
  214. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  215. # test
  216. if __name__ == '__main__':
  217. # pylint: disable=wrong-import-position
  218. import sys
  219. import time
  220. import traceback
  221. #~ PORT = 'spy:///dev/ttyUSB0'
  222. PORT = 'loop://'
  223. class PrintLines(LineReader):
  224. def connection_made(self, transport):
  225. super(PrintLines, self).connection_made(transport)
  226. sys.stdout.write('port opened\n')
  227. self.write_line('hello world')
  228. def handle_line(self, data):
  229. sys.stdout.write('line received: {!r}\n'.format(data))
  230. def connection_lost(self, exc):
  231. if exc:
  232. traceback.print_exc(exc)
  233. sys.stdout.write('port closed\n')
  234. ser = serial.serial_for_url(PORT, baudrate=115200, timeout=1)
  235. with ReaderThread(ser, PrintLines) as protocol:
  236. protocol.write_line('hello')
  237. time.sleep(2)
  238. # alternative usage
  239. ser = serial.serial_for_url(PORT, baudrate=115200, timeout=1)
  240. t = ReaderThread(ser, PrintLines)
  241. t.start()
  242. transport, protocol = t.connect()
  243. protocol.write_line('hello')
  244. time.sleep(2)
  245. t.close()