Getting started with MQTT and Node-RED
What is MQTT
MQTT is an OASIS standard messaging protocol for the Internet of Things (IoT). It is designed as an extremely lightweight publish/subscribe messaging transport that is ideal for connecting remote devices with a small code footprint and minimal network bandwidth.
What is Node-RED
Node-RED is a programming tool for wiring together hardware devices, APIs and online services in new and interesting ways. It provides a browser-based editor that makes it easy to wire together flows using the wide range of nodes in the palette that can be deployed to its runtime in a single-click.
NOTE: This tutorial is written and tested on MacOS
We will be using:
- Docker version 20.10.10
- Eclipse Mosquitto version 2.0.14
- Node-RED version 2.1.3
Setup and run Mosquitto
Create a new folder called mosquitto
and inside this folder, create a config file mosquitto.conf
listener 1883
allow_anonymous true
persistence true
persistence_location /mosquitto/data/
log_dest file /mosquitto/log/mosquitto.log
Create a docker network
docker network create local
Run Mosquitto
docker run --name mosquitto --net local --rm -d -it -p 1883:1883 -p 9001:9001 -v `pwd`/mosquitto.conf:/mosquitto/config/mosquitto.conf -v `pwd`/data:/mosquitto/data -v `pwd`/log:/mosquitto/log eclipse-mosquitto:2.0.14
Your MQTT server is now up and running.
Run Node-Red
Get out of the mosquitto
folder, create a new folder nodered
and from inside of this folder run Node-RED
docker run --name node-red --net local --rm -d -it -p 1880:1880 -v `pwd`/data:/data nodered/node-red:2.1.3
Node-RED should now be running. Open your browser and go to http://localhost:1880
Add the following nodes to your flow. You can drag them from the palette onto the workspace:
- inject (timestamp) with properties (double-click to edit the properties):
- msg.payload = timestamp
- msg.topic = heartbeat
- repeat = interval, every 5 seconds
- mqtt out:
- server = Add new mttt-broker with properties:
- server = mosquitto (this should be the name of the mosquitto docker container)
- port = 1883
- server = Add new mttt-broker with properties:
- mqtt in:
- server = mosquitto:1883
- topic = heartbeat
- debug
Connect the inject
node to the mqqt out
node and the mqtt in
node to the debug
node
Click “Deploy” in the upper right corner and then click show debug messages (Menu - View - Debug messages)
Done! Our Node-RED is now publishing a heartbeat message to our Mosquitto MQTT server for every 5 seconds.