#include <WiFi.h>
#include <PubSubClient.h>
#include "DHTesp.h"

#define DHTPIN 15
#define L1 18
#define L2 19

DHTesp dhtSensor;

const char* ssid = "Wokwi-GUEST";
const char* password = "";
const char* mqtt_server = "test.mosquitto.org";
const char* topic_in = "In03319403290";
const char* topic_out_temp = "Out03319403290/Temperatura";
const char* topic_out_hum = "Out03319403290/Umidade";

WiFiClient espClient;
PubSubClient client(espClient);
unsigned long lastMsg = 0;
#define MSG_BUFFER_SIZE	(50)
char msg[MSG_BUFFER_SIZE];
int value = 0;

String recv_msg = "";

void setup_wifi() {
  delay(10);
  // We start by connecting to a WiFi network
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);

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

  randomSeed(micros());

  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}

void callback(char* topic, byte* payload, unsigned int length) {
  Serial.print("Message arrived [");
  Serial.print(topic);
  Serial.print("] ");
  for (int i = 0; i < length; i++) {
    // Serial.print((char)payload[i]);
    recv_msg += (char)payload[i];
  }
  Serial.print(recv_msg);
  Serial.println();


  if(recv_msg == "1L"){
      digitalWrite(L1, HIGH);
      Serial.print("LED1 On \n");
  }else if (recv_msg == "1D"){
      digitalWrite(L1, LOW);
      Serial.print("LED1 O ff\n");
  }else if (recv_msg == "2L"){
      digitalWrite(L2, HIGH);
      Serial.print("LED2 On \n");
  } else if(recv_msg == "2D") {
      digitalWrite(L2, LOW);
      Serial.print("LED1 Off \n");
  } else {
    Serial.print("Comando não reconhecindo ! \n");
  }
  
  recv_msg = "";
}

void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    // Create a random client ID
    String clientId = "ESP32Client-";
    clientId += String(random(0xffff), HEX);
    // Attempt to connect
    if (client.connect(clientId.c_str())) {
      Serial.println("connected");
      // Once connected, publish an announcement...
      client.publish(topic_out_temp, "starting Temperatura Sensor....");
      client.publish(topic_out_hum, "starting Humidade Sensor....");
      // ... and resubscribe
      client.subscribe(topic_in);
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      delay(5000);
    }
  }
}

void setup() {
  pinMode(L1, OUTPUT);
  pinMode(L2, OUTPUT);
  pinMode(BUILTIN_LED, OUTPUT);     // Initialize the LED pin as an output
  Serial.begin(115200);
  setup_wifi();
  client.setServer(mqtt_server, 1883);
  client.setCallback(callback);

  dhtSensor.setup(DHTPIN, DHTesp::DHT22);

}

void loop() {
  if (!client.connected()) {
    reconnect();
  }
  client.loop();
  unsigned long now = millis();
  if (now - lastMsg > 5000) {
    lastMsg = now;
    TempAndHumidity data = dhtSensor.getTempAndHumidity();

    snprintf (msg, MSG_BUFFER_SIZE, "%f", data.temperature);
    client.publish(topic_out_temp, msg);

    //Limpando msg para colocar a umidade
    snprintf (msg, MSG_BUFFER_SIZE, "");

    snprintf (msg, MSG_BUFFER_SIZE, "%f", data.humidity);
    client.publish(topic_out_hum, msg);

    Serial.print("Umidade: " + String(data.humidity, 1) + "% ");
    Serial.print("Temperatura: " + String(data.temperature, 2) + " graus \n");
  }

  
}