peterhinch / micropython-mqtt

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

How to publish an mqtt message from the subscribe callback? #69

Closed roipoussiere closed 2 years ago

roipoussiere commented 2 years ago

config['subs_cb'] is a supposed to be function but publish() is asynchronous, so I don't understand how to publish inside the callback.

Use case: the board subscribes to a topic in order to execute a function when received. This function does something then send a mqtt message when it is completed or if an error happened.

peterhinch commented 2 years ago

You can start an asynchronous function from synchronous code using uasyncio.create_task():

import uasyncio as asyncio

async def bar():
    # do something

def foo():
    asyncio.create_task(bar())

If necessary you can save the task instance in case you want to await it or cancel it:

bar_task = None
def foo():
    global bar_task
    bar_task = ayncio.create_task(bar())

You may want to look at my uasyncio tutorial.