MQTT Subscribe

In this chapter we will connect your microcontroller board to the MQTT broker already running on your Raspberry Pi.

For this to work the microcontroller has to know where to connect to to reach the broker. So the first steps will be creating a new project folder for this chapter and adding the connection informations to it.

First create the project folder:

[user@computer ~]$ cd projects
[user@computer ~]$ cp -rv /usr/src/nodemcu_base projects/chapter_3_sub
[user@computer ~]$ cd projects/chapter_3_sub

now you should edit the credentials.lua like you did in the previous chapter and in addition to that add the following three lines to the bottom of the file:


These set the ip address and port number of the broker and the identification the microcontroller should use.

The next step is to replace the content of the application.lua with the following:

function mqtt_on_message(mc, topic, data)
   print("Topic "..topic..": "

function mqtt_on_connect(mc)
   print("MQTT connection successful")

   mc:subscribe("/led", 0)

function mqtt_on_failure(mc, reason)
   print("MQTT connection failed: "..reason)

function mqtt_setup()
   local mc= mqtt.Client(MQTT_ID)

   mc:on("message", mqtt_on_message)
   mc:connect(MQTT_HOST, MQTT_PORT, 0, mqtt_on_connect, mqtt_on_failure)


Then you are ready to upload the files, connect picocom and reset the microcontroller.

If everything went well the output should look something like the following:

[user@computer ~]$ picocom -b 115200 /dev/ttyUSB0
init: connected to AP: nota_1
init: got IP address via DHCP
init: startup will continue in 3s
init: handing over to application
MQTT connection successful

To send messages to the topic the microcontroller is subscribed to we use the mosquitto_pub commandline program.

The following command will send the message “MyMessage” to the topic “/mytopic”.

[user@computer ~]$ mosquitto_pub -h localhost -t /mytopic -m MyMessage

Task: find the topic that the application subscribed to and send a message to that topic.

Task: make the topic actually controll the state of the LED.