#include "WiFi.h"
#include "PubSubclient.h"
#include <FastLED.h>
char clientId[50];
WiFiClient espClient;
PubSubClient client(espClient);
CRGB leds[1];
void setup() {
// put your setup code here, to run once:
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.connect()){
Serial.print("Attempting MQTT connection.....");
if(client.connect(clientId)){
Serial.print("Connected");
client.subscribe('topicName');
}
else{
Serial.println("Connection failed try again in 5 seconds");
delay(5000);
}
}
}
void callback(char* topic, byte* message, unsigned int length)
{
String stMessage;
for (int i = 0; i < length; i++)
{
stMessage += (char)message[i];
}
// Add codes to control NeoPixel LED
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!!");
}
}
void loop()
{
delay(100);
if (!client.connected())
{
mqttReconnect();
}
client.loop();
}