/README.md

https://github.com/mossblaser/aiomqtt · Markdown · 88 lines · 65 code · 23 blank · 0 comment · 0 complexity · 5ad6cdd8f90a3d88570de19d9854346f MD5 · raw file

  1. `aiomqtt`: An asyncio Wrapper for paho-mqtt
  2. ===========================================
  3. This library implements a minimal Python 3
  4. [asyncio](https://docs.python.org/3/library/asyncio.html) wrapper around the
  5. MQTT client in [paho-mqtt](https://github.com/eclipse/paho.mqtt.python).
  6. Installation:
  7. pip install aiomqtt
  8. API
  9. ---
  10. This library is as thin as possible, exposing the exact same API as the
  11. original paho-mqtt `Client` object with blocking calls replaced with coroutines
  12. and all callbacks being scheduled into the asyncio main event loop. It does not
  13. attempt to introduce a more idiomatic asyncio API.
  14. When using aiomqtt, refer to the [paho-mqtt
  15. documentation](https://pypi.python.org/pypi/paho-mqtt/1.1) which applies
  16. verbatim with the exception of the above rules. An example use of the library
  17. is shown below:
  18. ```python
  19. import asyncio
  20. import aiomqtt
  21. loop = asyncio.get_event_loop()
  22. async def demo():
  23. c = aiomqtt.Client(loop)
  24. c.loop_start() # See "About that loop..." below.
  25. connected = asyncio.Event(loop=loop)
  26. def on_connect(client, userdata, flags, rc):
  27. connected.set()
  28. c.on_connect = on_connect
  29. await c.connect("localhost")
  30. await connected.wait()
  31. print("Connected!")
  32. subscribed = asyncio.Event(loop=loop)
  33. def on_subscribe(client, userdata, mid, granted_qos):
  34. subscribed.set()
  35. c.on_subscribe = on_subscribe
  36. c.subscribe("my/test/path")
  37. await subscribed.wait()
  38. print("Subscribed to my/test/path")
  39. def on_message(client, userdata, message):
  40. print("Got message:", message.topic, message.payload)
  41. c.on_message = on_message
  42. message_info = c.publish("my/test/path", "Hello, world")
  43. await message_info.wait_for_publish()
  44. print("Message published!")
  45. await asyncio.sleep(1, loop=loop)
  46. print("Disconnecting...")
  47. disconnected = asyncio.Event(loop=loop)
  48. def on_disconnect(client, userdata, rc):
  49. disconnected.set()
  50. c.on_disconnect = on_disconnect
  51. c.disconnect()
  52. await disconnected.wait()
  53. print("Disconnected")
  54. await c.loop_stop()
  55. print("MQTT loop stopped!")
  56. loop.run_until_complete(demo())
  57. ```
  58. About that loop...
  59. ------------------
  60. Unfortunately the author was unable to work out how to integrate paho-mqtt's
  61. event loop into asyncio, despite the best efforts of the paho-mqtt authors to
  62. make this possible. (Patches are welcome.)
  63. Instead, `loop_start()` and `loop_stop()` may be used as normal (and aiomqtt
  64. will ensure callbacks arrive in the correct thread) or `loop_forever()` may be
  65. used which in aiomqtt is a coroutine.