// Autor: DjEdu28 <GitHub.com/DjEdu28>

// projetos WOKWI
// https://wokwi.com/projects/397207107109591041
// https://wokwi.com/projects/397128466983540737

#include <WiFi.h>
#include <PubSubClient.h>
#include <DHT.h>

// Substitua com suas credenciais de WiFi
const char* ssid = "Wokwi-GUEST";
const char* password = "";

// Substitua com o endereço do seu broker MQTT
const char* mqtt_server = "test.mosquitto.org";
const char* clientId = "esp32_djedu28_397207107109591041";

WiFiClient espClient;
PubSubClient client(espClient);

// Substitua o pino do LED
#define LED_PIN 15

// Substitua o pino do sensor DHT
#define DHTPIN 4
// DHTTYPE DHT22 ou DHT11
#define DHTTYPE DHT22

DHT dht(DHTPIN, DHTTYPE);

void setup() {
  pinMode(LED_PIN, OUTPUT);
  digitalWrite(LED_PIN, HIGH);
  Serial.begin(115200);
  setup_wifi();
  client.setServer(mqtt_server, 1883);
  dht.begin();
  digitalWrite(LED_PIN, LOW);
}

void setup_wifi() {
  delay(10);
  Serial.println("");
  Serial.print("Conectando... ");
  Serial.println(ssid);

  WiFi.begin(ssid, password, 6);

  while (WiFi.status() != WL_CONNECTED) {
    delay(100);
    Serial.print(".");
  }

  Serial.println("");
  Serial.print(" WiFi Conectado!");
  Serial.print(" IP: ");
  Serial.println(WiFi.localIP());
}
void reconnect() {
 while (!client.connected()) {
    Serial.print("Tentando conectar MQTT ... ");
    if (client.connect(clientId)) {
      Serial.println("conectado");
      client.subscribe("ledControl");
    } else {
      Serial.print("falhou, rc =");
      Serial.print(client.state());
      Serial.println(" Tente novamente em 5 segundos");
      delay(5000);
    }
 }
}
void loop() {
  if (!client.connected()) {
    reconnect();
 }
  client.loop();

  // Publica os dados de temperatura e umidade
  client.publish("temperature", "80");
  client.publish("humidity", "30");

  
  delay(1000);
}

void callback(char* topic, byte* message, unsigned int length) {
  String messageTemp;

  for (int i = 0; i < length; i++) {
    messageTemp += (char)message[i];
  }
  Serial.print("Mensagem recebida[");
  Serial.print(topic);
  Serial.print("]: ");
  Serial.println(messageTemp);

  if (String(topic) == "ledControl") {
    if (messageTemp == "ON") {
      digitalWrite(LED_PIN, HIGH);
    } else if (messageTemp == "OFF") {
      digitalWrite(LED_PIN, LOW);
    }
  }
}
NOCOMNCVCCGNDINLED1PWRRelay Module