MQTT client

We will create two client applications, one for Raspberry Pi, which will act as the sender (publisher), and one at the server, which will act as the receiver (subscriber). This will help us to implement and better understand the architecture of MQTT. Our implementation will look like the diagram shown in Figure 3.12:

Figure 3.12

Let's write the desktop client application first. We will straight away write the code and not get into the Node.js setup, which we have already done in an earlier part of this chapter:

  1. Create a file with the name desktop_client.js under any folder of your choice; just make sure you have Node.js and its modules installed there locally (refer to Step 6 of the HTTP server section in this chapter).
  2. Add the following code to include the (import) MQTT client module. You can check the link for more details about this module: https://www.npmjs.com/package/mqtt:
const mqtt = require('mqtt')
  1. Provide connection details like port on which broker is running (default port: 1883) and the public IP address of our server:
const options={
port:'1883',
host:'ip_address_of_broker_server'
}
  1. Using the MQTT connect method, we will establish a connection with broker:
const client = mqtt.connect(options)
  1. We will use the client object of the connect method to listen for a connect event, which gets fired on successful connection with the broker. As soon as we connect, we will subscribe to a topic as well, on which our Raspberry Pi client will publish. We also print to the console for our reference when we execute our code:
client.on('connect', () => 
{
client.subscribe('pub/data');
console.log(" desktop mqtt client connected to broker ");
})

Here, the pub/data topic will be created when the Raspberry client publishes on it. Check the code section of the Raspberry client.

  1. Once we subscribe to a topic, we listen for a message event of the client object to retrieve the actual data from the received message packet through a callback function. The callback function returns two values; one is the topic to which the client has subscribed and data/message received:
client.on('message', (topic, message) => 
{
if (topic=='pub/data')
{
console.log('Data received from Rpi client on topic:
pub/data '+ message.toString());
client.publish('sub/ack','Ack: Success..!!');
console.log("Acknowledgement sent to Rpi client ==>
Ack: Success..!! ")
}
})
  1. Using an if condition, we check whether we have received messages from the topic we have subscribed to. For our reference, we print the data received.
  2. To send an acknowledgment, we publish a message on the topic 'sub/ack', which our Raspberry Pi client will subscribe to.
  3. To check the successful implementation of our code, let's just run it using this command in the same sequence mentioned. Open the Command Prompt and move to the folder where we have our code file.
  1. This will install the MQTT module:
npm install mqtt --save
  1. To execute the code run following command. On success, we will have output in our console as shown here:
node desktop_client.js
  1. Now, we will create the Raspberry Pi client application.
  2. Connect to the Pi using SSH/PuTTY, as shown in an earlier part of the chapter.
  3. Create a file with the name rpi_client.js, using the nano editor, under any folder of your choice; just make sure you have Node.js and its modules installed there locally.
  4. Execute this command to create and open the file in edit mode:
sudo nano rpi_client.js
  1. Add this code to include/import the MQTT client module:
const mqtt = require('mqtt')
  1. Provide connection details like port on which broker is running (default port: 1883) and public IP address of our server:
const options={
port:'1883',
host:'ip_address_of_broker_server'
}
  1. Using the MQTT connect method, we will establish a connection with the broker:
const client = mqtt.connect(options) 
  1. We will use the client object of the connect method to listen for a connect event, which gets fired on successful connection with the broker. As soon as we connect, we will subscribe to a topic on which will receive acknowledgment from our desktop client. We already defined the topic as 'sub/ack' in the desktop client code:
client.on('connect', () => {
console.log("Rpi mqtt client connected to brokerrn")
client.subscribe('sub/ack')
})
  1. Now, let's publish the data from the Raspberry client to the desktop client. This will publish the message 'pi_data' every five seconds on the topic 'pub/data':
setInterval(function () {
console.log('Data pushed from Pi client on topic: pub/data ==> pi_data')
client.publish('pub/data','pi_data')
},5000)
  1. As we publish the data, listen for the 'message' message of the client object to receive acknowledgement from the desktop client:
client.on('message', (topic, message) => {
if (topic=='sub/ack'){
console.log('Acknowledgement received on topic: '+topic+' ==>
'+message.toString()+'rn')
}
  1. Using an if condition, we check whether we have received messages from the topic we have subscribed to, and for our reference, we print the data received from the desktop client.
  2. To check the successful implementation of our code, let's just run it using the following command in the same sequence mentioned. Open the Command Prompt and move to the folder where we have our code file.
  1. This will install the MQTT module:
sudo npm install mqtt -save
  1. To execute the code run following command. On success, we will have output on our console as shown here:
sudo nano rpi_client.js
  1. Now, it is time to run both clients simultaneously and see the MQTT protocol working.
  1. The Raspberry client publishes data every five seconds and receives an acknowledgment:
  1. The desktop client receives data every five second and sends an acknowledgement as a response:

The following figure shows the architecture of our implementation of MQTT protocol:

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.12.36.30