peterhinch / micropython-mqtt

A 'resilient' asynchronous MQTT driver. Recovers from WiFi and broker outages.
MIT License
549 stars 116 forks source link

How to subscribe in subs_cb? #67

Closed Narsskrarc closed 2 years ago

Narsskrarc commented 2 years ago

Hi all,

I try to setup an ESP32 which get its config from a mqtt topic. So I subscribe the topic in the connect_coro. When the message comes I want to subscribe other topics according to this message. But how can I subscribe something in the subs_cb? It is no coroutine and when I try to await mqtt.subscribe() inside the subs_cb it isn't called at all.

What would be the right way to do that?

peterhinch commented 2 years ago

I've never tried that arrangement but I think it should work fine. I would do something like this. In the callback:

if condition_is_met:
    asyncio.create_task(subscribe_to, topic, qos)

And then

async def subscribe_to(topic, qos):
    await client.subscribe(topic, qos)
Narsskrarc commented 2 years ago

That sounds as a good idea. I will test it asap. Thanks!

Narsskrarc commented 2 years ago

Well, I tested it now. ;-) A little change: it has to be asyncio.create_task(subscribe_to(topic, qos)) ...and then this works. Thanks again!

peterhinch commented 2 years ago

Yes. Brain-fade there on my part :)