Understanding uasyncio and mqtt_as

Discussion about programs, libraries and tools that work with MicroPython. Mostly these are provided by a third party.
Target audience: All users and developers of MicroPython.
Post Reply
nickehallgren
Posts: 4
Joined: Thu Nov 07, 2019 7:18 am

Understanding uasyncio and mqtt_as

Post by nickehallgren » Thu Nov 07, 2019 8:12 am

Hi,

I've been playing around with a ESP32 and the mqtt_as library (had a lot of stability problems with the umqtttsimple). I want to turn on/off a led with a mqtt message. Then publish a message that confirms the state of the led. The code below works but is this the right way to do it?

Code: Select all

# Subscription callback
def sub_cb(topic, msg, retained):
    print((topic, msg, retained))
    if topic == b'led/1/state/set' and msg == b'0' :
      print('Turn off')
      led.value(0)
      print(led.value())
      loop = asyncio.get_event_loop()
      loop.create_task(client.publish('led/1/state', '{}'.format(led.value()), True, qos=1))
    elif topic == b'led/1/state/set' and msg == b'1' :
      print('Turn on')
      led.value(1)
      print(led.value())
      loop = asyncio.get_event_loop()
      loop.create_task(client.publish('led/1/state', '{}'.format(led.value()), True, qos=1))
      
Thanks in advance and yes I'm a newbie ;)

kevinkk525
Posts: 969
Joined: Sat Feb 03, 2018 7:02 pm

Re: Understanding uasyncio and mqtt_as

Post by kevinkk525 » Thu Nov 07, 2019 11:11 am

Yes that would be the most basic approach to your case.
Should you plan on doing something more complicated (which calls asyncio.sleep()) than just toggling a LED, you should create a task for that operation and include the publish. Otherwise you will block mqtt.

I use a very similar mechanism at the core of my Smarthome framework https://github.com/kevinkk525/pysmartnode
Every controllable component uses a topic ending with "/set" and after the request was handled by the component, the new state is automatically published to the topic without "/set" at the end.
Kevin Köck
Micropython Smarthome Firmware (with Home-Assistant integration): https://github.com/kevinkk525/pysmartnode

Post Reply