MQTT Subscribe and Post

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
User avatar
pythoncoder
Posts: 5956
Joined: Fri Jul 18, 2014 8:01 am
Location: UK
Contact:

Re: MQTT Subscribe and Post

Post by pythoncoder » Thu Dec 28, 2017 9:41 am

c.wait_msg() is a blocking function: this means it won't return until a message is received. This prevents you from publishing while waiting for a message. The way to proceed is to use c.check_msg(). This returns immediately. If a message has been received the callback will run as before. So your main loop might look like

Code: Select all

try:
    while 1:
        c.check_msg()
        if door_has_opened():  # Detect change of state
            c.publish(b"door", b"open")
        if door_has_closed():
            c.publish(b"door", b"closed")
        time.sleep(0.2)  # Avoid 100% CPU usage
    finally:
        c.disconnect()
Peter Hinch
Index to my micropython libraries.

Post Reply