//*Circuit Diagram #2 - LDR Brightness & Darkness Sensor
//**" The coding and solfware process of LDR Brightness & Darkness Sensors in smart home automation system "**//
//Smart Home Automation -> " SHA " (variable)
#include <PubSubClient.h> //Library Contact MQTT
#include <WiFi.h>         //Library Contact WiFi

#define LDR_Pin       34  //GPIO-34 to LDR
#define Relay_LED002  14  //GPIO-14 to 2nd-LEDin 

#define TOPIC_SUBSCRIBE_LEDin_002   "SHA_on_off_LEDin002"
#define TOPIC_PUBLISH_LDR           "SHA/LDR"

#define PUBLISH_DELAY 2000  // Delay time for publish data to MQTT Broker
                            // millis() -> loop 2 second
#define ID_MQTT "ESP32_LDR" // Device ID for connect to MQTT Broker

const char SSID[] = "Wokwi-GUEST";   //Enter WiFi SSID
const char PASSWORD[] = "";   //Enter WiFi Password

//URL for MQTT broker
const char *BROKER_MQTT = "broker.hivemq.com";
int BROKER_PORT = 1883; //Port of Broker MQTT

unsigned long Publish_Update;

static char strBrightDark[10] = {0};

WiFiClient espClient;
PubSubClient MQTT(espClient);

void Initial_WiFi(void);
void Initial_MQTT(void);
void Callback_MQTT(char *topic, byte *payload, unsigned int length);
void Reconnect_MQTT(void);
void Reconnect_WiFi(void);
void Check_WiFiAndMQTT(void);

/*Start Beginning of WiFi*/
void Initial_WiFi(void) 
{
  delay(10);
  Serial.println("------Connect to WI-FI------");
  Serial.print("Connecting to : ");
  Serial.println(SSID);

  Reconnect_WiFi();
}

/*Start Beginning of MQTT*/
void Initial_MQTT(void) 
{
  MQTT.setServer(BROKER_MQTT, BROKER_PORT); 
  MQTT.setCallback(Callback_MQTT);
}

// Function Callback: Receive Message from another MQTT Client publish message pass through the MQTT Broker
void Callback_MQTT(char *topic, byte *payload, unsigned int length) 
{
  String msg;

  //Obtem a string do payload recebido
  for (int i = 0; i < length; i++) {
    char c = (char)payload[i];
    msg += c;
  }

  Serial.printf("Receive string via MQTT : %s on topic : %s\n", msg, topic);

    if (msg.equals("1")) {
      digitalWrite(Relay_LED002, HIGH);
      Serial.println("LEDin 2nd status : 'ON'");
    }
    if (msg.equals("0")) {
      digitalWrite(Relay_LED002, LOW);
      Serial.println("LEDin 2nd status : 'OFF'");
    }
}
//Function Reconnect MQTT Broker
void Reconnect_MQTT(void) 
{
  while (!MQTT.connected()) {
    Serial.print("Connecting MQTT Broker : ");
    Serial.println(BROKER_MQTT);
    if (MQTT.connect(ID_MQTT)) {
      Serial.println("Connecting the MQTT Broker success!\n");

      MQTT.subscribe(TOPIC_SUBSCRIBE_LEDin_002);

    }
    else {
      Serial.println("Fail! to connect then reconnect MQTT Broker again in 2 seconds.\n");
      delay(2000);
    }
  }
}
//Function Reconnect WiFi Router
void Reconnect_WiFi(void) 
{
  if (WiFi.status() == WL_CONNECTED)
    return;
  
  WiFi.begin(SSID, PASSWORD); 
  
  while (WiFi.status() != WL_CONNECTED) {
    delay(100);
    Serial.print("#.....#\n");
  }
  Serial.print("Connected WiFi success!\n");
  Serial.print(SSID);
  Serial.println("IP Address : ");
  Serial.println(WiFi.localIP());
}
// Function checking connected to WiFi Router and MQTT Broker */
void Check_WiFiAndMQTT(void) 
{
  if (!MQTT.connected())
    Reconnect_MQTT();
  Reconnect_WiFi();
}
//-------------------------------------------------------------------------------------//

int LDR_Sensor = 34 ;

int LEDin_2nd = 14 ;

int LDR_Limit_Criterion = 40;

int DarkNess_LDR = 0;

unsigned long BeginLoop_Delay = 0;

//-------------------------------------------------------------------------------------//

void setup() 
{
  Serial.begin(115200); //Initialize Serial Moniter
  Serial.println("Get Started!!!");

  pinMode(LDR_Sensor, INPUT);
  pinMode(LEDin_2nd, OUTPUT);

  Initial_WiFi();
  Initial_MQTT();
}

void loop() 
{
//-----------------------------------------------------//
  Serial.print("******************************\n");
  Serial.print("Check LDR Status : ");
  Serial.println(analogRead(LDR_Sensor));

//-----------------------------------------------------//
BeginLoop_Delay = millis();
if ((BeginLoop_Delay - Publish_Update) >= PUBLISH_DELAY) {
    Publish_Update = millis();
    //Verify the operation of the WiFi connection and go to the MQTT broker
    Check_WiFiAndMQTT();
    
    DarkNess_LDR = analogRead(LDR_Sensor);
    DarkNess_LDR = map(DarkNess_LDR, 0, 4095, 0, 100);
    Serial.print("LDR Sensor Value : ");
    Serial.println(DarkNess_LDR);

    if(DarkNess_LDR <= LDR_Limit_Criterion) {
    String text_3 = "Darkness in LDR Detected!!!" ;
    Serial.println(text_3);
    digitalWrite(LEDin_2nd, HIGH);
    } else {
    String text_4 = "Darkness in LDR Stopped!!!" ;
    Serial.println(text_4);
    digitalWrite(LEDin_2nd, LOW);
  }

    //Change format of the Data as String for send it via MQTT protocol
    sprintf(strBrightDark, "%d",analogRead(LDR_Sensor));
    delay(1000);

    //Send data string to MQTT Broker
    MQTT.publish(TOPIC_PUBLISH_LDR, strBrightDark);

    // Keep-alive for connected MQTT broker
    MQTT.loop();
  }
}
$abcdeabcde151015202530fghijfghij
NOCOMNCVCCGNDINLED1PWRRelay Module