Using MicroPython on a NodeMCU as a MQTT publisher

Scenario

We will be setting up

  • The Mosquitto MQTT Broker running inside a Docker conatiner on a laptop.
  • MicroPython on a NodeMCU to send data to the Mosquitto MQTT Broker

Local MQTT Broker Docker container for testing

Pull the MQTT Docker container

docker pull toke/mosquitto

Start local MQTT Broker Docker container for testing

docker run -d -p 1883:1883 -p 9001:9001 --name mqtt toke/mosquitto

Enter the container and subscribe to the topic

docker exec -ti mqtt mosquitto_sub -t foo_topic

From Normal Python

Use pip to instal paho-mqtt

pip install paho-mqtt

Use the Paho MQTT Client to publish to the MQTT test server.

import paho.mqtt.client as mqtt


client_name = "macbook-air"
mqtt_broker = "10.10.10.124"


# Client(client_id="", clean_session=True, userdata=None, protocol=MQTTv311, transport="tcp")
client =mqtt.Client(client_name)

# connect(host, port=1883, keepalive=60, bind_address="")
client.connect(mqtt_broker)

# publish(topic, payload=None, qos=0, retain=False)
client.publish("foo_topic","hello")

From MicroPython

from umqtt.simple import MQTTClient

def main(mqtt_broker="localhost", clientid="umqtt_client"):
  c = MQTTClient(clientid, mqtt_broker)
  c.connect()
  c.publish(b"foo_topic", b"hello")
  c.disconnect()

if __name__ == "__main__":
  mqtt_broker = "10.10.10.124"
  clientid    = "nodemcu-rocks"
  main(mqtt_broker, clientid)
categories: micropython | esp8266 | nodemcu |