#include <DHTesp.h>
#include <WiFi.h> // Library for connecting the ESP32 to a Wi-Fi network.
#include <PubSubClient.h> // Publish and subscribe to messages on an MQTT broker.
#include <NTPClient.h> // Provides access to NTP servers for synchronizing the ESP32's internal clock.
#include <WiFiUdp.h> // Used by NTPClient for communication with NTP servers.
// Define connection pins
#define DHT_PIN 15
#define BUZZER 12
// Initializing objects related to WiFi, MQTT communication, and time synchronization.
WiFiClient espClient; // A WiFiClient object for establishing a connection to the Wi-Fi network.
PubSubClient mqttClient(espClient); // A PubSubClient object used to interact with the MQTT broker using espClient connection
WiFiUDP ntpUDP; // A WiFiUdp object used by NTPClient for communication with NTP servers.
NTPClient timeClient(ntpUDP); // An NTPClient object for synchronizing the ESP32's clock with an NTP server.
DHTesp dhtSensor; // A DHTesp object representing the DHT sensor.
// Variable for temperature
char tempAr[6]; // A character array of size 6 to store the temperature reading as a string.
// Variables for scheduling alarm
bool isScheduledON = false;
unsigned long scheduledOnTime;
/********************************************************************************/
/********************************************************************************/
void setup() {
Serial.begin(115200);
setupWifi();
setupMqtt();
dhtSensor.setup(DHT_PIN, DHTesp :: DHT22); // Initializes the DHT sensor object (dhtSensor).
timeClient.begin(); // Initializing the NTP client for communication with NTP servers.
timeClient.setTimeOffset(5.5 * 3600); // Adjust the retrieved NTP time to match your local time zone.
// Sets the buzzer pin as output and sets it to LOW initially.
pinMode(BUZZER, OUTPUT);
digitalWrite(BUZZER, LOW);
}
/********************************************************************************/
/********************************************************************************/
void loop() {
if (!mqttClient.connected()) { // Checks if the connection to the MQTT broker is lost.
connectToBroker(); // Reconnects if necessary using connectToBroker().
}
mqttClient.loop(); // Keeps the MQTT client connection active and manages message exchange.
updateTemperature();
Serial.println(tempAr);
mqttClient.publish("EE-Arjun-TEMP", tempAr); // Publishes tempAr to the MQTT broker.
checkSchedule();
delay(500);
}
/********************************************************************************/
void updateTemperature() {
TempAndHumidity data = dhtSensor.getTempAndHumidity();
String(data. temperature, 2).toCharArray(tempAr, 6);
}
/********************************************************************************/
void setupWifi() {
Serial.println();
Serial.print("Connecting to ");
Serial.println("Wokwi-GUEST");
WiFi.begin("Wokwi-GUEST", ""); // Connects the ESP32 to a WiFi network (SSID, Password).
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println();
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}
/********************************************************************************/
void setupMqtt() {
mqttClient.setServer("test.mosquitto.org", 1883); // Sets the MQTT broker server.
mqttClient.setCallback(receiveCallback);
// setCallback function allows you to specify a function that will be called
// whenever a message is received on a topic the client is subscribed to.
}
/********************************************************************************/
// This function gets called whenever a message is received on a topic the ESP32 is subscribed to.
void receiveCallback(char* topic, byte* payload, unsigned int length) {
Serial.print("Message arrived [");
Serial.print(topic);
Serial.print("] ");
char payloadCharAr[length];
for (int i = 0; i < length; i++) {
Serial.print((char)payload[i]); // Prints each byte of the payload data as a character.
payloadCharAr[i] = (char)payload[i]; // Copies each byte of the payload data into the payloadCharAr character array
}
Serial.println();
// strcmp - String compare
// If topic and EE-ARJUN-MAIN-ON-OFF matches, strcmp returns 0
if (strcmp(topic, "EE-ARJUN-MAIN-ON-OFF") == 0) {
buzzerOn(payloadCharAr[0] == 't');
} else if (strcmp(topic, "EE-ARJUN-SCH-ON-OFF") == 0) {
if (payloadCharAr[0] == 'N') {
isScheduledON = false;
} else {
isScheduledON = true;
scheduledOnTime = atol(payloadCharAr);
}
}
}
/********************************************************************************/
void connectToBroker() {
while (!mqttClient.connected()) {
Serial.println("Attempting MQTT connection ... ");
if (mqttClient.connect("ESP32-56465653791")) { // The connect() method returns true if the connection is successful
Serial.println("Connected to MQTT broker");
mqttClient.subscribe("EE-ARJUN-MAIN-ON-OFF");
mqttClient.subscribe("EE-ARJUN-SCH-ON-OFF");
} else {
Serial.print("failed ");
Serial.println(mqttClient.state()); // To get the connection error code.
delay(2000);
}
}
}
/********************************************************************************/
void buzzerOn(bool on) {
if (on) {
tone(BUZZER, 256);
} else {
noTone(BUZZER);
}
}
/********************************************************************************/
unsigned long getTime() {
timeClient.update();
return timeClient.getEpochTime();
}
/********************************************************************************/
void checkSchedule() {
if (isScheduledON) {
unsigned long currentTime = getTime();
if (currentTime > scheduledOnTime) {
buzzerOn(true);
isScheduledON = false;
mqttClient. publish("EE-ARJUN-MAIN-ON-OFF-ESP", "1");
mqttClient. publish("EE-ARJUN-SCH-ESP-ON", "0");
Serial.println("Scheduled On");
}
}
}