#include <WiFi.h>
#include <PubSubClient.h>
#include <ArduinoJson.h>
#include <NTPClient.h>
#include <WiFiUdp.h>
#define RELAYPIN 2
const char *ssid = "Wokwi-GUEST"; // Enter your WiFi name
const char *password = ""; // Enter WiFi password
WiFiClient espClient;
PubSubClient mqttClient(espClient);
WiFiUDP ntpUDP;
NTPClient timeClient(ntpUDP);
char powerAr[6];
bool isSheduled = false;
unsigned long scheduledOnTime;
void setup() {
Serial.begin(115200);
delay(5000);
setupWifi();
setupMqtt();
setupRelay();
setupTime();
randomSeed(analogRead(0));
}
void loop() {
if (!mqttClient.connected()) {
connetToBroker();
}
mqttClient.loop();
updatePower();
mqttClient.publish("UOM-SC-POW", powerAr);
checkSchedule();
delay(1000);
}
void setupMqtt() {
mqttClient.setServer("test.mosquitto.org", 1883);
mqttClient.setCallback(receiveCallback);
}
void receiveCallback(char* topic, byte*payload, unsigned int length) {
Serial.print("Got a Message : ");
Serial.println(topic);
char payloadCharAr[length];
for (int i = 0 ; i < length; i++) {
Serial.print((char)payload[i]);
payloadCharAr[i] = (char)payload[i];
}
Serial.println();
if (strcmp(topic, "UOM-SC-MS") == 0) {
switchRelay((char)payload[0] == '1');
}
else if (strcmp(topic, "UOM-SC-SS-ON") == 0) {
if ((char)payload[0] == 'N') {
isSheduled = false;
} else {
isSheduled = true;
scheduledOnTime = atol(payloadCharAr);
}
}
}
void connetToBroker() {
while (!mqttClient.connected()) {
Serial.println("Attempting MQTT Connection...");
if (mqttClient.connect("ESP32-379843959873")) {
Serial.println("MQTT Connected!!!");
mqttClient.subscribe("UOM-SC-MS");
mqttClient.subscribe("UOM-SC-SS-ON");
} else {
Serial.println("MQTT Failed!!!");
Serial.println(mqttClient.state());
delay(5000);
}
}
}
void updatePower() {
double power = 100 + random(4000) / 10.0;
dtostrf(power, 6, 1, powerAr);
}
void switchRelay(boolean statusRelay){
if(statusRelay){
digitalWrite(RELAYPIN,HIGH);
}else{
digitalWrite(RELAYPIN,LOW);
}
}
void setupRelay(){
pinMode(RELAYPIN, OUTPUT);
pinMode(RELAYPIN, LOW);
}
void setupTime() {
timeClient.begin();
timeClient.setTimeOffset(5.5 * 3600);
}
unsigned long getTime(){
timeClient.update();
return timeClient.getEpochTime();
}
void checkSchedule(){
if(isSheduled){
unsigned long currentTime =getTime();
if(isSheduled && currentTime>scheduledOnTime){
switchRelay(true);
isSheduled = false;
mqttClient.publish("UOM-SC-MS-AUTO", "1");
mqttClient.publish("UOM-SC-SS-AUTO", "0");
Serial.println("Scedule On!!!");
}
}
}
void setupWifi() {
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.println("Connecting to WiFi..");
}
Serial.println("Connected to the WiFi network");
}