#include "WiFi.h"
#include "PubSubClient.h"
#include <FastLED>
char clientId[50];
WiFiClient espClient;
PubSubClient client(espClient);
CRGB leds[1];
void callback(char* topic, byte* message, unsigned int length)
{
String stMessage;
for (int i = 0; i < length; i++)
{
stMessage += (char)message[i];
}
if(stMessage == "Out")
{
leds[0] = CRGB::Red;
FastLED.show();
Serial.println("Out!!");
}
else if(stMessage == "Not Out")
{
leds[0] = CRGB::Green;
FastLED.show();
Serial.println("Not Out !!");
}
else{
leds[0] = CRGB::Blue;
FastLED.show();
Serial.println("Decision Pending !!")
}
// Add codes to control NeoPixel LED
}
void loop()
{
delay(100);
if (!client.connected())
{
mqttReconnect();
}
client.loop();
}
void setup(){
Serial.begin(115200);
WiFi.mode(WIFI_STA);
WiFi.begin("Wokwi-GUEST", " ");
client.setServer("broker.emqx.io", 1883);
client.setCallback(callback);
FastLED.addLeds <NEOPIXEL, 5> (leds, 1);
}
void mqttReconnect()
{
while(!client.connected()){
Serial.print("Attempting MQTT Connection ........ ");
if(client.connect(clientId)){
Serial.println("Connected");
client.subscribe("topicName");
}
else{
Serial.println("Connection Failed. Try Agian In 5 Seconds");
delay(5000);
}
}
}