How can we use MQTT protocol to send messages over micropython(esp32) board?

Concepts

Basically, you got two actions available.
One is publish.
Another is subscribe.
If we want to send some message out to others, we need to use publish.
If we want to just receive messages from others, we use subscribe.

publish 

from umqtt.simple import MQTTClient

c = MQTTClient("clients/a", SERVICE_IP)
c.connect()
c.publish(b"a_topic", b"hello")
c.disconnect()

subscribe

import time
from umqtt.simple import MQTTClient

# Received messages from subscriptions will be delivered to this callback
def callback(topic, msg):
    print((topic, msg))

c = MQTTClient("clients/b", SERVICE_IP)
c.set_callback(callback)
c.connect()
c.subscribe(b"a_topic")
while True:
    if True:
        # Blocking wait for message
        c.wait_msg()
    else:
        # Non-blocking wait for message
        c.check_msg()
        # Then need to sleep to avoid 100% CPU usage (in a real
        # app other useful actions would be performed instead)
        time.sleep(1)

c.disconnect()
  • You can’t receive a topic before you subscribe to it.
  • You won’t receive anything if you don’t call client.check_msg() or client.wait_msg().
  • You may need a timer to execute the check_msg() function since you can’t use threading in micropython.

The author and more info

https://yingshaoxo.blogspot.com
https://mpython.readthedocs.io/en/master/library/mPython/umqtt.simple.html