eclipse / paho.mqtt.python

paho.mqtt.python
Other
2.19k stars 722 forks source link

Make AsyncioHelper part of the library proper #455

Open micolous opened 4 years ago

micolous commented 4 years ago

The AsyncioHelper class is really helpful in using this library with asyncio.

As asyncio and async def are part of the Python v3.5+, it would be helpful if this was a proper part of paho.mqtt.python (minus print statements), rather than merely a standalone example. That way, software using this library doesn't need to ship its own copy of that class.

For compatibility with older versions of Python, this should be in its own module.

newAM commented 4 years ago

Additionally, it would be nice to get native asyncio support to use coroutine functions for callback (async def on_connect(self, client, userdata, flags, rc):)

frederikaalund commented 4 years ago

asyncio-mqtt provides an idiomatic asyncio-based interface. It's a tiny wrapper (250 lines of code) around paho-mqtt. asyncio-mqtt replaces callbacks with async with and async for statements.

This enables you to write code like this:

async with Client('test.mosquitto.org') as client:
    await client.subscribe('floors/#')

    async with client.filtered_messages('floors/+/humidity') as messages:
        async for message in messages:
            print(message.decode())

It's all paho-mqtt underneath, so you still have the time-proven stability and large feature set of paho-mqtt.

Full disclosure: I'm the author of asyncio-mqtt. :) Feel free to take inspiration from the design and implementation of asyncio-mqtt. I'd also be happy to see asyncio-mqtt directly integrated into paho-mqtt.