#if defined(ESP8266)
#include <ESP8266WiFi.h>
#elif defined(ESP32)
#include <WiFi.h>
#endif

#include "ThingsBoard.h"
#include "DHTesp.h"

#define CURRENT_FIRMWARE_TITLE    "TEST"
#define CURRENT_FIRMWARE_VERSION  "1.0.0"

#define WIFI_SSID           "Wokwi-GUEST"
#define WIFI_PASSWORD       ""

#define TOKEN               "weQLuuPuvapOYILBbp8i"
#define THINGSBOARD_SERVER  "thingsboard.cloud"

//oled
#include <SPI.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>

#define SCREEN_WIDTH 128 // OLED display width, in pixels
#define SCREEN_HEIGHT 64 

#define OLED_RESET     4 // Reset pin # (or -1 if sharing Arduino reset pin)
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);

#define SERIAL_DEBUG_BAUD   115200

const int DHT_PIN = 15;

DHTesp dhtSensor;

// Initialize ThingsBoard client
WiFiClient espClient;
// Initialize ThingsBoard instance
ThingsBoard tb(espClient);
// the Wifi radio's status
int status = WL_IDLE_STATUS;

void InitWiFi()
{
  Serial.println("Connecting to AP ...");
  // attempt to connect to WiFi network

  WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
  while (WiFi.status() != WL_CONNECTED) {

    delay(500);
    Serial.print(".");
    
  }
  Serial.println("Connected to AP");
}

void reconnect() {
  // Loop until we're reconnected
  status = WiFi.status();
  if ( status != WL_CONNECTED) {
    WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
    while (WiFi.status() != WL_CONNECTED) {
      delay(500);
      Serial.print(".");
    }
    Serial.println("Connected to AP");
   
  }
}

int buzzerPin = 4;

void setup() 
{
   Serial.begin(SERIAL_DEBUG_BAUD);
  Serial.println();
  InitWiFi();
  dhtSensor.setup(DHT_PIN, DHTesp::DHT22);
  pinMode(33, OUTPUT);//led_merah
  pinMode(25, OUTPUT);//led_hijau
  pinMode(26, OUTPUT);//led_biru
  pinMode(27, OUTPUT);//aktuator pemanas
  pinMode(14, OUTPUT);//aktuator pendingin
  pinMode(12, OUTPUT);//aktuator sirkulasi udara
  pinMode(buzzerPin, OUTPUT);

  if(!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) { // Address 0x3D for 128x64
    Serial.println(("SSD1306 allocation failed"));
    for(;;);

     display.display();
  delay(2000);
  display.clearDisplay();

  }
    /// pembukaan sistem
    display.clearDisplay();

  display.setTextSize(2); // Draw 2X-scale text
  display.setTextColor(SSD1306_WHITE);
  display.setCursor(10, 0);
  display.println(("Selamat Datang"));
  display.display();      // Show initial text
  delay(100);

  //efek font
  display.startscrollright(0x00, 0x0F);
  delay(2000);
  display.stopscroll();
  delay(1000);
  display.startscrollleft(0x00, 0x0F);
  delay(2000);
  display.stopscroll();
  delay(1000);
  

}

void loop() {
  // put your main code here, to run repeatedly:
  delay(1000); // this speeds up the simulation
    if (WiFi.status() != WL_CONNECTED) {
    
    reconnect();
  }

   if (!tb.connected()) {
    display.clearDisplay();

  display.setTextSize(2); // Draw 2X-scale text
  display.setTextColor(SSD1306_WHITE);
  display.setCursor(10, 0);
  display.println("Connect Server");
  display.display();      // Show initial text
  delay(100);
  
    display.clearDisplay();

  display.setTextSize(2); // Draw 2X-scale text
  display.setTextColor(SSD1306_WHITE);
  display.setCursor(10, 0);
  display.println("Thingsboard.cloud");
  display.display();      // Show initial text
  delay(100);

     display.clearDisplay();
    // Connect to the ThingsBoard
    Serial.print("Connecting to: ");
    Serial.print(THINGSBOARD_SERVER);
    Serial.print(" with token ");
    Serial.println(TOKEN);
    if (!tb.connect(THINGSBOARD_SERVER, TOKEN)) {
      Serial.println("Failed to connect");
       display.clearDisplay();

  display.setTextSize(2); // Draw 2X-scale text
  display.setTextColor(SSD1306_WHITE);
  display.setCursor(10, 0);
  display.println("Failed to connect");
  display.display();      // Show initial text
  delay(100);
      return;
    }
  }
  Serial.println("Sending data...");
   display.clearDisplay();

  display.setTextSize(2); // Draw 2X-scale text
  display.setTextColor(SSD1306_WHITE);
  display.setCursor(10, 0);
  display.println(("Sending data"));
  display.display();      // Show initial text
  delay(100);
  // Uploads new telemetry to ThingsBoard using MQTT.
  // See https://thingsboard.io/docs/reference/mqtt-api/#telemetry-upload-api
  // for more details

  TempAndHumidity  data = dhtSensor.getTempAndHumidity();
  tb.sendTelemetryInt("temperature", data.temperature);
  tb.sendTelemetryFloat("humidity", data.humidity);
  Serial.print("Suhu : ");
  Serial.print(data.temperature);
  Serial.print(" Kelembaban : ");
  Serial.println(data.humidity);

  if(data.temperature < 26){
    Serial.println("suhu rendah");
    led_dingin();
    tampil_oled();
    tone_dingin();
    
    display.clearDisplay();

  display.setTextSize(2); // Draw 2X-scale text
  display.setTextColor(SSD1306_WHITE);
  display.setCursor(10, 0);
  display.println(("Suhu Rendah/Dingin"));
  display.display();      // Show initial text
  delay(100);
  }
  else if ((data.temperature >=26)&&(data.temperature<=34)){
    Serial.println("normal");
    led_normal();
    tampil_oled();

    display.clearDisplay();

  display.setTextSize(2); // Draw 2X-scale text
  display.setTextColor(SSD1306_WHITE);
  display.setCursor(10, 0);
  display.println(("Suhu Normal"));
  display.display();      // Show initial text
  delay(100);
  }
  else if (data.temperature > 34) {
    Serial.println("panas");
    led_panas();
    tampil_oled();
    tone_panas();

    display.clearDisplay();

  display.setTextSize(2); // Draw 2X-scale text
  display.setTextColor(SSD1306_WHITE);
  display.setCursor(10, 0);
  display.println(("Suhu Tinggi!"));
  display.display();      // Show initial text
  delay(100);
  }


  tb.loop();

  tb.loop();
}
}


void tone_panas(){
    tone(buzzerPin, 1000);
    delay(1000);
    tone(buzzerPin, 0);
    delay(50);
    tone(buzzerPin, 1000);
    delay(500);
    tone(buzzerPin, 0);
    delay(20);
}

void tone_dingin(){
  tone(buzzerPin, 300);
    delay(800);
    tone(buzzerPin, 0);
    delay(50);
    tone(buzzerPin, 300);
    delay(500);
    tone(buzzerPin, 0);
    delay(50);
}
///// fungsi led
void led_dingin(){
    digitalWrite(26, HIGH);
    digitalWrite(25, LOW);
    digitalWrite(33, LOW);
    //aktuator pemanas
    digitalWrite(27, HIGH);
}
void led_normal(){
    digitalWrite(26, LOW);
    digitalWrite(25, HIGH);
    digitalWrite(33, LOW);
    //aktuator sirkulasi
    digitalWrite(12, HIGH);
}
void led_panas(){
    digitalWrite(26, LOW);
    digitalWrite(25, LOW);
    digitalWrite(33, HIGH);
    //aktuator pendingin
    digitalWrite(14, HIGH);
}

void tampil_oled(){
  //kirim data real time langsung dari sensor ke interface
   TempAndHumidity  data = dhtSensor.getTempAndHumidity();
  tb.sendTelemetryInt("temperature", data.temperature);
  tb.sendTelemetryFloat("humidity", data.humidity);

 display.clearDisplay();

  display.setTextSize(2); // Draw 2X-scale text
  display.setTextColor(SSD1306_WHITE);
  display.setCursor(10, 0);
  display.println(("Suhu  :" + String(data.temperature)));
  display.print("C");
  display.display();      // Show initial text
  delay(100);
 
}