Publishing and subscribing to cloudMQTT using IoT development board ESP8266-12.

 Publishing and  subscribing to cloudMQTT  using IoT development board ESP8266-12.

In this article, we are going to publish and to subscribe to cloudMQTT a simple text message to cloudMQTT.

If you are reading my article for the first time, I recommend my previous article to you Demystifying the MQTT maze: clients, servers, connection, publish, subscribe and its applications. to understand what follows.

Without wasting time, I am going down into the programming aspect. If you don't know how to setup the ESP8266-12 IoT development board, I recommend my article to you Sending sensor data to localhost using IoT development board esp8266-12 to get it done.

To achieve the scope of this article you need to have arduino IDE and connect ESP8266 to your computer or desktop


The full code is provided at the end of this article but before reaching there, let me break each part down.

What is PubSubClient?

PubSubClient is a client library for MQTT messaging. It allows you to send and to receive MQTT messages

Step 1: Launch the arduino IDE and install  PubSubClient library .


Step 2: Enter your mqtt server configurations

const char* mqttServer = "postman.cloudmqtt.com";  
const int mqttPort = 12311;  
const char* mqttUser = "rrwezuls";
const char mqttPassword = "BcLVHDg5YgI";

Step 3: Write a method to connect to the cloudmqtt, publish and subscribe to a topic


void mqttConnect(){
  while (!client.connected()) {
  Serial.println("Connecting to MQTT...");
  if (client.connect("ESP8266", mqttUser, mqttPassword )) {
   Serial.println("connected");   
  }
 else {
   Serial.print("failed with state ");
   Serial.println(client.state()); //If you get state 5: mismatch in configuration
   delay(2000);
  }
 client.publish("maxtek/iot_startup", "mqtt is fun");
 client.subscribe("maxtek/iot_startup");
}

In this method we first initiate a connection to the broker by invoking the method client.connect() which take three parameters, the device name, the mqttUser and the password.

To publish to the broker, you call the method client.publish() which takes two parameters namely the topic of the message in our case maxtek/iot_startup and the data to be publised "mqtt is fun".

To subscribe to the topic, we invoke the method client.subscribe() which takes as parameter the topic of the the message in which you want to receive.

From this code, we program the device to publish and to receive a message from the broker.

Step 4: Write a method MQTTcallback() that enables the program to be notified when asynchronous events related to the client occur.

  • the MQTTcallback() takes three parameters namely:
  • the topic to publish to (const char[])
  • payload - the message to publish (byte[])
  • length - the length of the message int)

void MQTTcallback(char* topic, byte* payload, unsigned int length) {
 Serial.print("Message arrived in topic: ");
 Serial.println(topic);
 Serial.print("Message:");
 String message;
 for (int i = 0; i < length; i++) {
  message = message + (char)payload[i]; //Convert *byte to String
 }
  Serial.print(message);  
}


step 5: Create a method wifiConnect() to connect to the Wireless network.


void Wificonnect(){
 WiFi.begin(ssid, password);
 while (WiFi.status() != WL_CONNECTED) {
  delay(500);
  Serial.println("Connecting to WiFi..");
 }
 Serial.print("Connected to WiFi :");
 Serial.println(WiFi.SSID());
}


Below is the complete sketch of the program

#include <ESP8266WiFi.h>
#include <PubSubClient.h>
//Enter your wifi credentials
const char* ssid = "MelleB";  
const char* password = "refj4497";
//Enter your mqtt server configurations
const char* mqttServer = "postman.cloudmqtt.com";  //Enter Your mqttServer address
const int mqttPort = 12311;    //Port number
const char* mqttUser = "rrwezuls"; //User
const char* mqttPassword = "BcL_VHDg5YgI"; //Password
WiFiClient espClient;
PubSubClient client(espClient); 
void setup() {
 delay(1000);
 pinMode(LED,OUTPUT);
 Serial.begin(115200);
  Wificonnect();
 client.setServer(mqttServer, mqttPort);
 client.setCallback(MQTTcallback);
 } 
void MQTTcallback(char* topic, byte* payload, unsigned int length) { 
 Serial.print("Message arrived in topic: ");
 Serial.println(topic);
 Serial.print("Message:");
 String message;
 for (int i = 0; i < length; i++) {
  message = message + (char)payload[i]; //Conver *byte to String
 }
  Serial.print(message);  
}
void mqttConnect(){
  while (!client.connected()) {
  Serial.println("Connecting to MQTT...");
  if (client.connect("ESP8266", mqttUser, mqttPassword )) {
   Serial.println("connected");   
  } 
 else {
   Serial.print("failed with state ");
   Serial.println(client.state()); //If you get state 5: mismatch in configuration
   delay(2000);
  }
 client.publish("maxtek/iot_startup", "mqtt is fun");
 client.subscribe("maxtek/iot_startup");
}
void loop() {
 if (! client.connected() ){
  mqttConnect();
 }
 client.loop();
 delay(300);
}
void Wificonnect(){  
 WiFi.begin(ssid, password);
 while (WiFi.status() != WL_CONNECTED) {
  delay(500);
  Serial.println("Connecting to WiFi..");
 }
 Serial.print("Connected to WiFi :");
 Serial.println(WiFi.SSID());
}


Step 6: Testing

Open the serial monitor you will see

Wrapping Up

In summary, we’ve shown you the basic concepts that allow you to publish and to subscribe to cloudMQTT using MQTT. In my next article, we are going to program a smart house to control the light and other sensor anywhere around the world

cloud

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

Multi-cloud Spending: 8 Tips To Lower Cost

Mismanagement of multi-cloud expense costs an arm and leg to business and its management has become a major pain point. Here we break down some crucial tips to take some of the management challenges off your plate and help you optimize your cloud spend.

What are the benefits of cloud migration? Reasons you should migrate

To move or not to move? Benefits are multifold when you are migrating to the cloud. Get the correct information to make your decision, with our cloud engineering expertise.

Multi-Cloud: Worst Practice or the Future of Public Cloud?

Corey Quinn, cloud economist at The Duckbill Group, recently argued that multi-cloud is "the worst practice to be avoided by default”.The author of the Last Week in AWS newsletter defines multi-cloud as running the same workload across multiple cloud providers in an agnostic way.

Cloud Migration Strategy

Before dipping that first toe in the cloud migration, think of devising the transition plan. 6Rs Migration Technique has become a staple of cloud migration strategy.

How Cloud Optimisation Helps Reduce Total Cost of Infrastructure Ownership

As the whole world is slowly awakening from several months of complete lockdown as a result of the COVID-19 outbreak, Cloud computing has started gaining even more steam it had before the pandemic.