aio.py 3.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114
  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. import logging
  18. class SerialTransport(asyncio.Transport):
  19. def __init__(self, loop, protocol, serial_instance):
  20. self._loop = loop
  21. self._protocol = protocol
  22. self.serial = serial_instance
  23. self._closing = False
  24. self._paused = False
  25. # XXX how to support url handlers too
  26. self.serial.timeout = 0
  27. self.serial.nonblocking()
  28. loop.call_soon(protocol.connection_made, self)
  29. # only start reading when connection_made() has been called
  30. loop.call_soon(loop.add_reader, self.serial.fd, self._read_ready)
  31. def __repr__(self):
  32. return '{self.__class__.__name__}({self._loop}, {self._protocol}, {self.serial})'.format(self=self)
  33. def close(self):
  34. if self._closing:
  35. return
  36. self._closing = True
  37. self._loop.remove_reader(self.serial.fd)
  38. self.serial.close()
  39. self._loop.call_soon(self._protocol.connection_lost, None)
  40. def _read_ready(self):
  41. data = self.serial.read(1024)
  42. if data:
  43. self._protocol.data_received(data)
  44. def write(self, data):
  45. self.serial.write(data)
  46. def can_write_eof(self):
  47. return False
  48. def pause_reading(self):
  49. if self._closing:
  50. raise RuntimeError('Cannot pause_reading() when closing')
  51. if self._paused:
  52. raise RuntimeError('Already paused')
  53. self._paused = True
  54. self._loop.remove_reader(self._sock_fd)
  55. if self._loop.get_debug():
  56. logging.debug("%r pauses reading", self)
  57. def resume_reading(self):
  58. if not self._paused:
  59. raise RuntimeError('Not paused')
  60. self._paused = False
  61. if self._closing:
  62. return
  63. self._loop.add_reader(self._sock_fd, self._read_ready)
  64. if self._loop.get_debug():
  65. logging.debug("%r resumes reading", self)
  66. #~ def set_write_buffer_limits(self, high=None, low=None):
  67. #~ def get_write_buffer_size(self):
  68. #~ def writelines(self, list_of_data):
  69. #~ def write_eof(self):
  70. #~ def abort(self):
  71. @asyncio.coroutine
  72. def create_serial_connection(loop, protocol_factory, *args, **kwargs):
  73. ser = serial.Serial(*args, **kwargs)
  74. protocol = protocol_factory()
  75. transport = SerialTransport(loop, protocol, ser)
  76. return (transport, protocol)
  77. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  78. # test
  79. if __name__ == '__main__':
  80. class Output(asyncio.Protocol):
  81. def connection_made(self, transport):
  82. self.transport = transport
  83. print('port opened', transport)
  84. transport.serial.rts = False
  85. transport.write(b'hello world\n')
  86. def data_received(self, data):
  87. print('data received', repr(data))
  88. self.transport.close()
  89. def connection_lost(self, exc):
  90. print('port closed')
  91. asyncio.get_event_loop().stop()
  92. loop = asyncio.get_event_loop()
  93. coro = create_serial_connection(loop, Output, '/dev/ttyUSB0', baudrate=115200)
  94. loop.run_until_complete(coro)
  95. loop.run_forever()
  96. loop.close()