In this blog we will see how to connect to a MQTT broker from nodeMCU and exchange messages.
We will just subscribe to the channel and display the data published to the channel on the console. whenever message is posted in the subscribed channel , we will post the status of the IO’s to the specified channel.
First we need a MQTT broker you can install the broker on your local machine and connect to it or use a cloud provider. I will use cluodmqtt. coludmqtt provides a free instance which is good for exploring purpose.
Setting up cloudmqtt :
- Go to plans , and select the Cute Cat plan, signup if not already done
- Go to control panel
- Create a instance
- Click on details of the created instance and note down server address and port, we need them to connect to the broker.
- Create a user with name “nodemcu” and give a password
- Save the new user, now we need to provide the ACL to the new user. Please note that I am giving full access to the “nodemcu” user, in production you should use more find grained ACLs
- Now your MQTT instance is ready to accept connections.
There are four files that you need to flash to the module.
config.lua : this file contains the information about the MQTT server ,WiFi details. You need to place your wifi name password,MQTT server name,MQTT user name (that you just created in step 5) and password in this file
setup.lua: This file contains the code to connect to your WiFi
app.lua : This is where you will place your application logic, like controlling the IO pins based on the information received , and sending the messages to the desired channels
init.lua : NodeMCU will execute this file on startup, we will bootstrap the application using this file.
All the files are available on github.
Once you changed the parameters in config.lua , you need to flash all the four files to nodeMCU and reset the board.
You should see something like this on your console.
Note down the chip id, you need it to send messages to the nodeMCU.
You need a MQTT client application to send messages to nodeMCU form your laptop, I am using mqtt-spy.
First you need to subscribe to the nodeMCU publishing channel to receive the messages from nodeMCU.
Channel name: /nodemcu/10652610/fromnode
10652610 is my node chip id, replace it with yours. To send messages to the nodeMCU you can use the following channel,
Channel Name: /nodemcu/10652610/tonode
Again you need to replace the chip id with yours, what ever you post will appear in your console.