#include <WiFi.h>
#include <PubSubClient.h>
#include <OneWire.h>
#include <DallasTemperature.h>
#include <ArduinoJson.h>

#include "DHTesp.h"
const char* ssid = "Wokwi-GUEST";
const char* password = "";
const char* mqtt_server = "broker.hivemq.com";
const char* stopic = "ledpark";
const char* ptopic = "temperature1";
//const int oneWireBus = 4;  // dùng pin GPIO4

const int DHT_PIN = 15; // DHT22
char result_temp[10]; // Buffer big enough for 7-character float
char result_hum[10]; // Buffer big enough for 7-character float

WiFiClient espClient;
PubSubClient client(espClient);
unsigned long lastMsg = 0;

DHTesp dhtSensor;

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 button () {
  // btn1
  if (digitalRead(2) == 1 && btn_1lock == 1){
    if(state1 == 0){
      state1 = 1 ;
    }else{
      state1 = 0;
    }
    btn_1lock = 0;
    delay(100);
  }
  if (digitalRead(2) == 0){
    btn_1lock = 1;
  }
  // btn2
  if (digitalRead(4) == 1 && btn_2lock == 1){
    if(state2 == 0){
      state2 = 1 ;
    }else{
      state2 = 0;
    }
    btn_2lock = 0;
    delay(100);
  }
  if (digitalRead(4) == 0){
    btn_2lock = 1;
  }
  // btn3
  if (digitalRead(5) == 1 && btn_3lock == 1){
    if(state3 == 0){
      state3 = 1 ;
    }else{
      state3 = 0;
    }
    btn_3lock = 0;
    delay(100);
  }
  if (digitalRead(5) == 0){
    btn_3lock = 1;
  }
  if(state1 == 1 ) {
      digitalWrite(12,LOW);
    }else{
      digitalWrite(12,HIGH);
    }
  if(state2 == 1 ) {
      digitalWrite(14,LOW);
  }else{
      digitalWrite(14,HIGH);
  }
    if(state3 == 1 ) {
      digitalWrite(13,LOW);
    }else{
      digitalWrite(13,HIGH);
    }
}


void ReceivedMessage(char* topic, byte* payload, unsigned int length) {
  // Output the first character of the message to serial (debug)
  StaticJsonDocument<200> doc;
  deserializeJson(doc, payload, length);
  
  // Extract values from the JSON data
  String id = doc["id"];
  String data = doc["data"];

  Serial.print(id);
  Serial.print(":");
  Serial.println(data);
   if(id == "12"){
     if(data == "LOW"){
       state1 = 1 ;     
      }
      else{
        state1 = 0 ;       
      }
   }
    if(id == "13"){
      if(data == "LOW"){
        state2 = 1 ; 
      }
      else{
        state2 = 0 ; 
      }
    }
    if(id == "14"){
      if(data == "LOW"){
        state3 = 1 ; 
      }
      else{
        state3 = 0 ; 
      }  
    }
}


void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    // Create a random client ID
    String clientId = "ESP8266Client-";
    clientId += String(random(0xffff), HEX);
    // Attempt to connect
    if (client.connect(clientId.c_str())) {
      Serial.println("connected");
      
      // Once connected, publish an announcement...
      client.publish(ptopic, "hello world");
       // ... and resubscribe
      client.subscribe(stopic);
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      // Wait 5 seconds before retrying
      delay(5000);
    }
  }
}

void publish_temp()
{
      TempAndHumidity  data_temp = dhtSensor.getTempAndHumidity();
      dtostrf(data_temp.temperature, 6, 2, result_temp); // Leave room for too large numbers!
      dtostrf(data_temp.humidity, 6, 2, result_hum); // Leave room for too large numbers!
      DynamicJsonDocument json(100);
      json["temp"] = result_temp;
      json["humi"] = result_hum;
      
       
      String jsonString;
      serializeJson(json, jsonString);
      
      const char* payload = jsonString.c_str();
     // Serial.print("Publishing: ");
      ///Serial.println(payload);
      client.publish(ptopic, payload);
      //Serial.print("Done!");

}

void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);
  Serial.println("Hello, ESP32!");
  Serial.begin(115200);
  dhtSensor.setup(DHT_PIN, DHTesp::DHT22);
  pinMode(34, INPUT);
  pinMode(35, INPUT);
  pinMode(2, OUTPUT);
  pinMode(4, OUTPUT);
  pinMode(5, OUTPUT);

  btn_1lock = 1 ;
  btn_2lock = 1 ;
  btn_3lock = 1 ;
  
  setup_wifi();
  client.setServer(mqtt_server, 1883);
  client.setCallback(ReceivedMessage);
  
}

void loop() {
  
   
  if (!client.connected()) {
    reconnect();
  }
  client.loop();
  publish_temp();
  button();

delay(1000);
}

esp:VIN
esp:GND.2
esp:D13
esp:D12
esp:D14
esp:D27
esp:D26
esp:D25
esp:D33
esp:D32
esp:D35
esp:D34
esp:VN
esp:VP
esp:EN
esp:3V3
esp:GND.1
esp:D15
esp:D2
esp:D4
esp:RX2
esp:TX2
esp:D5
esp:D18
esp:D19
esp:D21
esp:RX0
esp:TX0
esp:D22
esp:D23
dht1:VCC
dht1:SDA
dht1:NC
dht1:GND
btn1:1.l
btn1:2.l
btn1:1.r
btn1:2.r
r1:1
r1:2
btn2:1.l
btn2:2.l
btn2:1.r
btn2:2.r
r2:1
r2:2
led1:A
led1:C
led2:A
led2:C
r4:1
r4:2
r5:1
r5:2
led4:A
led4:C
r3:1
r3:2