MQTT with RUST and NodeJs
Pre-requisite
You need to make sure that these are installed in your environment :
What is MQTT ?
MQTT (Message Queuing Telemetry Transport) is another messaging protocol designed to be lightweight so it can be used in IOT devices.
The basic idea is pub-sub, devices connected to a message broker and they exchange data by subscribing (to receive) or publishing (to broadcast).
You can read a more detailed info on what is MQTT in this link.
We are now going to simulate a MQTT connection, we will build 2 clients in RUST & NodeJs and a broker in NodeJs.
Message Broker
A message broker’s job is to coordinate who gets what message.
Start by creating a node js project
1 | yarn init -y #or |
now add aedes
dependency who is going to be our MQTT message broker
1 | yarn add aedes |
now create src/index.js
1 | const aedes = require("aedes") |
Client
Our clients will act as a subscriber and a publisher, we’ll build a subscriber in Rust and a publisher in NodeJs.
One of MQTT’s features is to be able to define a topic
on the fly, so you don’t need to configure it in the broker to be able to send messages back and forth.
Rust
1 | cargo new mqtt-client-subscriber |
in src/main.rs
1 | use rumqttc::{MqttOptions, Client, QoS}; |
Nodejs
Create a new NodeJs project
1 | yarn init -y |
in src/index.js
1 | const mqtt = require("mqtt"); |
now run the broker first then the NodeJs subscriber by running node src/index.js
in each project & lastly the Publisher in Rust by running cargo run
.
Conclusion
MQTT is lightweight, and it’s widely implemented in many programming languages and building apps for MQTT requires minimal effort.