#include "WiFi.h"
#include "PubSubClient.h"
#include <FastLED.h>
// Define variables
char ClientID[50];
WiFiClient espClient;
PubSubClient client(espClient);
CRGB leds[1];
// Define setup() function
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, 3>(leds, 1);
}
// Define mqttReconnect() function
void mqttReconnect()
{
while (!client.connected()){
Serial.print("Attempting MQTT Connection....");
if (client.connect(ClientID)){
Serial.print("Connected");
client.subscribe("topicName");
}
else{
Serial.println("Connection Failed. Trying 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::FireBrick;
FastLED.show();
Serial.println("Out!");
}
else if (stMessage == "Not Out"){
leds[0]= CRGB::GreenYellow;
FastLED.show();
Serial.println("Not Out!");
}
else {
leds[0]= CRGB::DeepSkyBlue;
FastLED.show();
Serial.println("Decision Pending");
}
}
void loop()
{
delay(100);
if (!client.connected())
{
mqttReconnect();
}
client.loop();
}