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:

MQTT_HOST= "192.168.94.1"
MQTT_PORT= 1883
MQTT_ID= "ESP1"

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..": "..data)
end

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

   mc:subscribe("/led", 0)
end

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

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)
end

mqtt_setup()

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 192.168.94.158 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.