wialon / gmqtt

Python MQTT v5.0 async client
MIT License
395 stars 53 forks source link

Async-with API #69

Open liamdiprose opened 4 years ago

liamdiprose commented 4 years ago

Hi there, Thanks for sharing this project, I'm very excited to see MQTT and asyncio coming together.

I was surprised by the callback-style API in the basic example. I expected the example to use the async-with pattern like the aiohttp or websockets clients. My recreation:

async with gmqtt.connect('mqtt.flespi.io') as client:
    print('Connected')
    await client.publish('TEST/TIME', str(time.time()), qos=1)

    async for message in client.subscribe('TEST/#', qos=0):
        print('RECV MSG:', message)
        break  # print one message only

Do you have any ideas how to implement this? (I'll be looking into it myself)

Lenka42 commented 4 years ago

@liamdiprose we do not support such behaviour and do not plan to implement it. I guess you can implement behaviour similar to async with gmqtt.connect('mqtt.flespi.io') as client: on your own creating context-manager class which will do connect on enter and disconnect on exit.

But implementation of behaviour similar to this one: async for message in client.subscribe('TEST/#', qos=0): is hardly possible now. But I think it might be related to issue #60

liamdiprose commented 4 years ago

Hi @Lenka42, Thanks for the tips, I might have a go at the context manager class this week.

The async for line is closer to question I was trying to ask: Using an awaitable object instead of callbacks.

message = await client.subscribe(...)

Asyncio has the Future class, which was made to "bridge low-level callback-based code with high-level async/await code". I'll have a go at wrapping gmqtt's on_connect and on_message callbacks and see how it goes.

With the global callbacks (#60), the Future implementation probably won't work for more than one subscription at a time.

Would you be open to a Pull Request?

frederikaalund commented 4 years ago

I've written an idiomatic asyncio-based interface around paho-mqtt: asyncio-mqtt

It replaces the callback-based interface with async with and async for statements. Feel free to take inspiration from asyncio-mqtt's interface and implementation. :)

70

eerimoq commented 4 years ago

Another alternative is mqttools. However, it only implements MQTT version 5.0, and not the older 3.x versions.