Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Async-with API #69

Open
liamdiprose opened this issue Nov 14, 2019 · 4 comments
Open

Async-with API #69

liamdiprose opened this issue Nov 14, 2019 · 4 comments

Comments

@liamdiprose
Copy link

liamdiprose commented Nov 14, 2019

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)

@liamdiprose liamdiprose changed the title Pythonic API Async-with API Nov 14, 2019
@Lenka42
Copy link
Collaborator

Lenka42 commented Nov 14, 2019

@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
Copy link
Author

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

This comment has been minimized.

@eerimoq

This comment has been minimized.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants