//Sematec_2023 - Pratica ESP32 - nov/2023
//chave e push-button em D5 Comanda o Led Vermelho em D4 (modo LOCAL).
//Led Azul em D18 controlado via MQTT
//Potenciometro em D34 simula tensao de 0 a 100 V
//DHT22 simula temperatura e umidade
//Instalar as bibliotecas: (instalação na aba "Library Manager")
   //PubSubClient
   //Adafruit Unified Sensor
   //DHT sensor library
 
//Adaptado a partir de RandomNerdTutorials (Rui Santos)
#include "DHT.h"
#define DHTPIN 21         // Digital pin connected to the DHT sensor
//#define DHTTYPE DHT11   // DHT 11
#define DHTTYPE DHT22     // DHT 22   
//#define DHTTYPE DHT21   // DHT 21 
DHT dht(DHTPIN, DHTTYPE);
#include <WiFi.h>
#include <PubSubClient.h>
// Replace the next variables with your SSID/Password combination
const char* ssid = "Wokwi-GUEST";
const char* password = "";
const char* mqtt_server = "test.mosquitto.org";
WiFiClient espClient;
PubSubClient client(espClient);
long lastMsg = 0;
long scanSensores = 0;
char msg[50];
int value = 0;
float temperature;
float humidity;
// LED Pin
const int ledRedPin = 4;
const int ledRedChave = 5;
const int ledBlueMqttPin = 18;
bool statusChaveLedRed;
float voltage34;

void setup() {
  Serial.begin(115200);
  setup_wifi();
  client.setServer(mqtt_server, 1883);
  client.setCallback(callback);
  pinMode(ledRedPin, OUTPUT);
  pinMode(ledRedChave, INPUT);
  pinMode(ledBlueMqttPin, OUTPUT);
  Serial.println(F("DHTxx test!"));
  dht.begin();
  delay(500);
}

void setup_wifi() {
  delay(10);
  // We start by connecting to a WiFi network
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);
  WiFi.begin(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 callback(char* topic, byte* message, unsigned int length) {
  Serial.print("Message arrived on topic: ");
  Serial.print(topic);
  Serial.print(". Message: ");
  String messageTemp;
  for (int i = 0; i < length; i++) {
    Serial.print((char)message[i]);
    messageTemp += (char)message[i];
  }
  Serial.println();
  if (String(topic) == "sematec23/ledBlueX") {
    Serial.print("Changing output to ");
    if(messageTemp == "on"){
      Serial.println("on");
      digitalWrite(ledBlueMqttPin, HIGH);
    }
    else if(messageTemp == "off"){
      Serial.println("off");
      digitalWrite(ledBlueMqttPin, LOW);
    }
  }
}

void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    // Attempt to connect
    if (client.connect("sematec23ClientX1")) {
      Serial.println("connected");
      // Subscribe
      client.subscribe("sematec23/ledBlueX");
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      // Wait 5 seconds before retrying
      delay(5000);
    }
  }
}

void leSensores(){
  if(digitalRead(ledRedChave) == HIGH){
    statusChaveLedRed=1;
    digitalWrite(ledRedPin,HIGH);
  } else{
    statusChaveLedRed=0;
    digitalWrite(ledRedPin,LOW);
  }
  int v34 = analogRead(34);
  voltage34 = map(v34,0,4095,0,100)/1.0;
  Serial.println(voltage34);
  humidity = dht.readHumidity();
  // Read temperature as Celsius (the default)
  temperature = dht.readTemperature();
  // Read temperature as Fahrenheit (isFahrenheit = true)
  float f = dht.readTemperature(true);

  // Check if any reads failed and exit early (to try again).
  if (isnan(humidity) || isnan(temperature) || isnan(f)) {
    Serial.println(F("Failed to read from DHT sensor!"));
    return;
  }
}

void loop() {
  if (!client.connected()) {
    reconnect();
  }
  client.loop();
  long now = millis();
  if(now - scanSensores > 450){
    scanSensores = now;
    leSensores();
  }
  if (now - lastMsg > 1000) {
    lastMsg = now;
    // Convert the value to a char array
    char tempString[8];
    dtostrf(temperature, 1, 2, tempString);
    Serial.print("Temperature: ");
    Serial.println(tempString);
    client.publish("sematec23/tempX", tempString);
    // Convert the value to a char array
    char humString[8];
    dtostrf(humidity, 1, 2, humString);
    Serial.print("Humidity: ");
    Serial.println(humString);
    client.publish("sematec23/umidX", humString);
    // Convert the value to a char array
    char cvoltage[8];
    dtostrf(voltage34, 1, 2, cvoltage);
    Serial.print("voltage34: ");
    Serial.println(cvoltage);
    client.publish("sematec23/voltage34X", cvoltage);
    //myString.toCharArray(buf, len)
    char s_temp[]={};
    unsigned int len = 10;
    String s_Chave="";
    if(statusChaveLedRed){
      s_Chave = "Ligada";
      } else {
      s_Chave = "Desligada";
    }
    s_Chave.toCharArray(s_temp,len);
    client.publish("sematec23/chaveX",s_temp);
    Serial.print("Status_chave: ");
    Serial.println(s_temp);
  }
}