Page 1 of 1

mqtt_as: how to reply to a message?

Posted: Sun Jan 19, 2020 9:29 pm
by tve
This is probably something really dumb... but how do I reply to an incoming message? A subscription callback is a `def` but `MTTClient.publish` is an `async def`. So in a subscription handler I can't simply process the message and call publish to send a reply back... Or am I missing the obvious?

Re: mqtt_as: how to reply to a message?

Posted: Mon Jan 20, 2020 9:08 am
by pythoncoder
Something along these lines:

Code: Select all

def callback(topic, msg, retained):
    loop.create_task(link.publish('my_topic', 'my_message')
I suggest you look at the tutorial in this repo to learn how to combine synchronous and asynchronous code.

Re: mqtt_as: how to reply to a message?

Posted: Mon Jan 20, 2020 5:47 pm
by tve
Good point, I should re-read that, lots of good examples! By the way, do you have any plans to incorporate all the docs you have there into the main micropython docs? They would be easier to find. Or do you like having them separate?

uasyncio tutorial

Posted: Mon Jan 20, 2020 6:27 pm
by pythoncoder
In general the official docs are not intended as a Python tutorial: they are written to enable experienced Python coders to use MicroPython. I therefore think it's unlikely that the maintainers would want to incorporate my tutorial into the official docs.

I wrote it for a number of reasons. Cooperative multi tasking is a core feature of many professional firmware applications and I wanted to promote its use, including for beginners. There are also some specific issues.

Firstly Python's asyncio has gone through a number of iterations resulting in a confusing API which took me a while to understand. Secondly uasyncio V2.0 is a subset of the asyncio shipped with Python 3.5: that warranted some explanation. Finally there are issues associated with writing firmware applications, notably how to do stream I/O with uarts, handling short delays with sleep_ms and suchlike. And I wanted to present a consistent way of using uasyncio which facilitated writing code portable to CPython.

This material will need some amendment when the new uasyncio comes out. In particular I don't know whether all the CPython synchronisation primitives will be included or whether I will still need to provide some of these - hopefully in a more efficient form. I have submitted a suggestion for providing the necessary hooks to facilitate task suspension and resume. My hope is that the new uasyncio will render most of my async code obsolete - in particular the fast_io version and the primitives.