Page 1 of 1

Understanding uasyncio and mqtt_as

Posted: Thu Nov 07, 2019 8:12 am
by nickehallgren
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 ;)

Re: Understanding uasyncio and mqtt_as

Posted: Thu Nov 07, 2019 11:11 am
by kevinkk525
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.