MQTT-Aedes Broker
MQTT is a lightweight publish/subscribe messaging protocol designed for constrained devices with low bandwidth. so it’s the perfect solution to exchange data between multiple IoT devices.
MQTT Basic Concepts
In MQTT there are four basic concepts that you need to understand:
- MQTT - Publish/Subscribe
- MQTT - Message
- MQTT - Topics
- MQTT - Broker
MQTT - Publish/Subscribe
In a publish and subscribe system, a device can publish a message on a topic, or it can be subscribed to a particular topic to receive messages
- for example, Device 1 publishes on a Topic, and Device 2 is subscribed to the same Topic that Device 1 is publishing. So, Device 2 will receive the message.
MQTT - Message
Messages are the information that you want to exchange between your devices. It can be a message like a command or data like sensor readings.
MQTT - Topics
Another important concept is the Topics. Topics are the way you register interest for incoming messages or how you specify where you want to publish the message.
Note: topics are case-sensitive, which makes these two topics different:
MQTT - Broker
The MQTT broker is responsible for receiving all messages, filtering the messages, deciding who is interested in them, and then publishing the message to all subscribed clients.
- Aedes - MQTT Broker : Aedes is a Barebone MQTT broker that can run on any stream server.
Installation
we can easily install the Aedes - MQTT Broker using npm
npm i aedes
Let's take an example of the basic code for setting the Aedes Broker in NodeJS.
first, we need to require aedes module and create aedes server in broker.js file:
const aedes = require('aedes')()
const server = require('net').createServer(aedes.handle)
MQTT_Port = 1884server.listen(MQTT_Port, function () {
console.log('Aedes MQTT server started and listening on port ', MQTT_Port)
})
Starts your server by running the command node broker.js
from the above code, the server will create and starts on MQTT port number 1884, but if you want to use both MQTT over Web-sockets and native MQTT you will need to configure the broker to listen on two separate ports:
npm i websocket-stream
after installing websocket-stream npm, add the below code to your broker.js file:
const aedes = require('aedes')()
const server = require('net').createServer(aedes.handle)
const httpServer = require('http').createServer()
const ws = require('websocket-stream')
MQTT_Port = 1884
const wsPort = 8884server.listen(MQTT_Port, function () {
console.log('Aedes MQTT server started and listening on port', MQTT_Port)
}),ws.createServer({ server: httpServer }, aedes.handle)httpServer.listen(wsPort, function () {
console.log('websocket server listening on port ', wsPort)
})
you can also use aedes-server-factory npm to create stream on TCP, HTTP, HTTP2, WS, and PROXY decoders. for more information click here.
Aedes Broker also has many handler functions such as:
- preConnect
- authenticate
- authorizePublish
- authorizeSubscribe
Let's take an example of authenticate and authorizePublish handlers, add below code to your broker.js file:
// authenticationaedes.authenticate = (client, username, password, callback) => {
password = Buffer.from(password, 'base64').toString();
if (username === 'xyz' && password === 'xyz123') {
return callback(null, true);
}
const error = new Error('Authentication Failed!! Please enter valid credentials.');
console.log('Authentication failed.')
return callback(error, false)
}// authorising client topic to publish a messageaedes.authorizePublish = (client, packet, callback) => {
if (packet.topic === 'abc') {
return callback(new Error('wrong topic'));
}
if (packet.topic === 'charcha') {
packet.payload = Buffer.from('overwrite packet payload')
}
callback(null)
}
There are various events that can be triggered in the broker, few of some common events are:
- client: This event will be triggered when a client will connect to the broker.
- clientDisconnect: This event will be triggered when a client will disconnect from the broker.
- publish: This event will be triggered when a client publishes a message.
- subscribe: This event will be triggered when a client subscribes to a topic on the broker.
- unsubscribe: This event will be triggered when a client unsubscribes to a topic on the broker.
Below are some of the events triggered on the broker server on interactions with a client. Add these codes to your broker.js file :
// emitted when a client connects to the brokeraedes.on('client', function (client) {
console.log(`CLIENT_CONNECTED : MQTT Client ${(client ? client.id : client)} connected to aedes broker ${aedes.id}`)
})// emitted when a client disconnects from the brokeraedes.on('clientDisconnect', function (client) {
console.log(`CLIENT_DISCONNECTED : MQTT Client ${(client ? client.id : client)} disconnected from the aedes broker ${aedes.id}`)
})// emitted when a client subscribes to a message topicaedes.on('subscribe', function (subscriptions, client) {
console.log(`TOPIC_SUBSCRIBED : MQTT Client ${(client ? client.id : client)} subscribed to topic: ${subscriptions.map(s => s.topic).join(',')} on aedes broker ${aedes.id}`)
})// emitted when a client unsubscribes from a message topicaedes.on('unsubscribe', function (subscriptions, client) {
console.log(`TOPIC_UNSUBSCRIBED : MQTT Client ${(client ? client.id : client)} unsubscribed to topic: ${subscriptions.join(',')} from aedes broker ${aedes.id}`)
})// emitted when a client publishes a message packet on the topicaedes.on('publish', function (packet, client) {if (client) {
console.log(`MESSAGE_PUBLISHED : MQTT Client ${(client ? client.id : 'AEDES BROKER_' + aedes.id)} has published message "${packet.payload}" on ${packet.topic} to aedes broker ${aedes.id}`)}
})
Now, to manually test the broker, make sure your server is up and running, then try connecting your MQTT client to the broker. You may use MQTT Box Google chrome extension to test your broker.
You did it…..
That’s it from my side, for any queries please comment below.
Please give a round of applause if you liked it….. 👏
Special Thanks to Random Nerd Tutorials 😇
“Many will start fast, few will finish strong.” — Gary Ryan Blair