/*When we publish a command in the MQTT Lens application,
based on the command LED will turn ON and OFF in the Wokwi platform.*/
#include "WiFi.h"
#include "PubSubClient.h" //library for MQTT connection
int led_pin = 5;
char clientId[50]; //define client-id with size=50 to store random-id in it
WiFiClient espClient; // for establishing a connection for the network
PubSubClient client(espClient); //client() used for requesting to publish or subscribe messages by the client.
void setup()
{
Serial.begin(115200); //starts communication
pinMode(led_pin, OUTPUT);
WiFi.mode(WIFI_STA); //check WiFi station where ESP32 will connect.
WiFi.begin("Wokwi-GUEST", ""); //used to initialize the SSID and password.
client.setServer("broker.emqx.io", 1883); //set server hostname and port
client.setCallback(callback); //function written below
}
void loop()
{
delay(10000); //10 sec
if (!client.connected()) //if not connected
{
mqttReconnect();
}
client.loop();
}
void mqttReconnect()
{
while (!client.connected()) //repeat till its not connected to MQTT
{
Serial.print("Attempting MQTT connection...");
if (client.connect(clientId))
{
Serial.println("Connected");
client.subscribe("topicName");//means every message coming from MQTT should be reflected here
}
else
{
Serial.print("Connection failed try again in 5 seconds");
delay(5000); //5 sec
}
}
}
void callback(char* topic, byte* message, unsigned int length)
{
// published message is coming from the MQTTLens and it is stored in stMessage variable
String stMessage; //variable
for (int i = 0; i < length; i++)
{
stMessage += (char)message[i]; //take complete input character
}
if(stMessage == "off")
{
digitalWrite(led_pin, LOW);
Serial.print("LIGHT OFF!!");
}
else if (stMessage == "on")
{
digitalWrite(led_pin, HIGH);
Serial.print("LIGHT ON!!");
}
else
{
Serial.print("INVALID COMMAND!!");
}
}
//OUTPUT- when you write on or off on MQTTX then light should switch on or off.