#include <LiquidCrystal_I2C.h>
#include "RTClib.h"
#include <ESP32Servo.h>
#include "ThingsBoard.h"
#include <WiFi.h>

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

#define WIFI_AP_NAME              "Wokwi-GUEST"
#define WIFI_PASSWORD             ""
#define TOKEN "Qx9miPLQcXpFHxH9Hav4" //"Silahkan isi Token Listrik"
//#define THINGSBOARD_SERVER "demo.thingsboard.io"
#define THINGSBOARD_SERVER "thingsboard.cloud"
LiquidCrystal_I2C lcd(0x27, 20, 4);

RTC_DS1307 rtc;

#define NTC 34
#define Pump 14
#define heater 32
#define DOx 35
#define PH 33
#define ECHO 27
#define TRIG 12
#define Aerator 25
#define drain 26
#define feeder 13

const float BETA = 3950; // should match the Beta Coefficient of the thermistor

int status = WL_IDLE_STATUS;
WiFiClient client;
ThingsBoard tb(client);

Servo drainServo;
Servo feederServo;

//code percobaan Port PWM
const uint8_t PROGMEM gamma8[] = {
  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,  1,  1,  1,
  1,  1,  1,  1,  1,  1,  1,  1,  1,  2,  2,  2,  2,  2,  2,  2,
  2,  3,  3,  3,  3,  3,  3,  3,  4,  4,  4,  4,  4,  5,  5,  5,
  5,  6,  6,  6,  6,  7,  7,  7,  7,  8,  8,  8,  9,  9,  9, 10,
  10, 10, 11, 11, 11, 12, 12, 13, 13, 13, 14, 14, 15, 15, 16, 16,
  17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22, 23, 24, 24, 25,
  25, 26, 27, 27, 28, 29, 29, 30, 31, 32, 32, 33, 34, 35, 35, 36,
  37, 38, 39, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 50,
  51, 52, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 66, 67, 68,
  69, 70, 72, 73, 74, 75, 77, 78, 79, 81, 82, 83, 85, 86, 87, 89,
  90, 92, 93, 95, 96, 98, 99, 101, 102, 104, 105, 107, 109, 110, 112, 114,
  115, 117, 119, 120, 122, 124, 126, 127, 129, 131, 133, 135, 137, 138, 140, 142,
  144, 146, 148, 150, 152, 154, 156, 158, 160, 162, 164, 167, 169, 171, 173, 175,
  177, 180, 182, 184, 186, 189, 191, 193, 196, 198, 200, 203, 205, 208, 210, 213,
  215, 218, 220, 223, 225, 228, 231, 233, 236, 239, 241, 244, 247, 249, 252, 255
};
//definisi untuk Sensor o2 & PH
const float VRefer = 3.3; //Tegangan referensi untuk sensor O2

//definisi untuk Sensor PH
#define Offset 41.02740741      //deviation compensate
#define samplingInterval 20
#define printInterval 800
#define ArrayLenth  40    //times of collection
#define uart  Serial
int pHArray[ArrayLenth];   //Store the average value of the sensor feedback
int pHArrayIndex = 0;

float readDistanceCM() {
  digitalWrite(TRIG, LOW);
  delayMicroseconds(2);
  digitalWrite(TRIG, HIGH);
  delayMicroseconds(10);
  digitalWrite(TRIG, LOW);
  int duration = pulseIn(ECHO, HIGH);
  return duration * 0.034 / 2;
}

void setup() {
  Serial.begin(9600);

  lcd.init();
  lcd.backlight();

  drainServo.attach(drain);
  feederServo.attach(feeder);

  if (! rtc.begin()) {
    Serial.println("Couldn't find RTC");
    while (1);
  }
  rtc.adjust(DateTime(__DATE__, __TIME__));

  WiFi.disconnect();
  WiFi.begin("Wokwi-GUEST", "");
  while ((!(WiFi.status() == WL_CONNECTED))) {
    delay(300);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());

  analogReadResolution(10);
  pinMode(NTC,INPUT);
  pinMode(DOx,INPUT);
  pinMode(PH,INPUT);
  pinMode(Pump, OUTPUT);
  pinMode(heater, OUTPUT);
  pinMode(Aerator, OUTPUT);
  pinMode(TRIG, OUTPUT);
  pinMode(ECHO, INPUT);

  lcd.setCursor(6,0);
  lcd.print("PROJECT");
  lcd.setCursor(5,1);
  lcd.print("BUDIDAYA");
  lcd.setCursor(4,2);
  lcd.print("UDANG VANAME");
  lcd.setCursor(3,3);
  lcd.print("GROUP02 IOT3-9");
  
  lcd.setCursor(4,0);
  lcd.print("UDANG VANAME");
  lcd.setCursor(0,1);
  lcd.print("                   ");
  lcd.setCursor(0,2);
  lcd.print("                  ");
    lcd.setCursor(0,3);
  lcd.print("                   ");

  delay(5000);
  // resolusi jadi 10 bit untuk sensor O2,PH dan NTC
   analogReadResolution(10);
}

void loop() {

  delay(1000);
  if(WiFi.status() != WL_CONNECTED){
    reconnect();
  }

  if(!tb.connected()) {
      Serial.println("Connecting to: ");
      Serial.print(THINGSBOARD_SERVER);
      Serial.print(" with token ");
      Serial.println(TOKEN);
      if(!tb.connect(THINGSBOARD_SERVER, TOKEN)){
        Serial.println("Failed to connect");
        return;
      }
  }

  int analogNTC = analogRead(NTC);
  float celsius = 1 / (log(1 / (1023. / analogNTC - 1)) / BETA + 1.0 / 298.15) - 273.15;
  Serial.print("Temperature: ");
  Serial.print(celsius);
  Serial.println(" °C");
  tb.sendTelemetryFloat("Temperature", celsius );
  lcd.setCursor(0,3);
  lcd.print("Temperature :");
  lcd.setCursor(13,3);
  lcd.print(celsius);
 

  int analogDOx = readConcentration();
  Serial.print("ADC DOx: ");
  Serial.println(analogDOx);
  tb.sendTelemetryFloat("ADC DOx:     ", analogDOx );
  lcd.setCursor(0,3);
  lcd.print("ADC DOx: ");
  lcd.setCursor(13,3);
  lcd.print(analogDOx );


  int analogPH = readPH();
  Serial.print("ADC PH: ");
  Serial.println(analogPH);
  tb.sendTelemetryFloat("ADC PH:      ", analogPH );
  lcd.setCursor(0,3);
  lcd.print("ADC PH: ");
  lcd.setCursor(13,3);
  lcd.print(analogPH );



  float distance = readDistanceCM();
  Serial.print("Jarak: ");
  Serial.println(distance);
  tb.sendTelemetryFloat("jarak", distance );
  lcd.setCursor(0,3);
  lcd.print("Jarak :     ");
  lcd.setCursor(13,3);
  lcd.print(distance );


  if(distance >= 200){
    drainServo.write(90);
    feederServo.write(90);
  }else{
    drainServo.write(0);
    feederServo.write(0);
  }

//  Konsentrasi 02
   if(analogDOx >= 20){
    drainServo.write(90);
   // feederServo.write(0);

       for (int i = 0; i < 255; i++) {
    analogWrite(Pump, pgm_read_byte(&gamma8[i]));
    analogWrite(heater, pgm_read_byte(&gamma8[i]));
    analogWrite(Aerator, pgm_read_byte(&gamma8[i]));
    delay(5);
  }

  }else{
    drainServo.write(0);
   // feederServo.write(0);
     for (int i = 255; i > 0; i--) {
    analogWrite(Pump, pgm_read_byte(&gamma8[i]));
    analogWrite(heater, pgm_read_byte(&gamma8[i]));
    analogWrite(Aerator, pgm_read_byte(&gamma8[i]));
    delay(5);
  }
     
  
  
  }
   //PH
   if(analogPH>= 9){
    drainServo.write(90);
   // feederServo.write(0);
      for (int i = 0; i < 255; i++) {
    analogWrite(Pump, pgm_read_byte(&gamma8[i]));
    analogWrite(heater, pgm_read_byte(&gamma8[i]));
    analogWrite(Aerator, pgm_read_byte(&gamma8[i]));
    delay(5);
  }

  }else{
    drainServo.write(0);
  //  feederServo.write(90);
    
    for (int i = 255; i > 0; i--) {
    analogWrite(Pump, pgm_read_byte(&gamma8[i]));
    analogWrite(heater, pgm_read_byte(&gamma8[i]));
    analogWrite(Aerator, pgm_read_byte(&gamma8[i]));
    delay(5);
  }

  }




  for (int i = 0; i < 255; i++) {
    analogWrite(Pump, pgm_read_byte(&gamma8[i]));
    analogWrite(heater, pgm_read_byte(&gamma8[i]));
    analogWrite(Aerator, pgm_read_byte(&gamma8[i]));
    delay(5);
  }
  for (int i = 255; i > 0; i--) {
    analogWrite(Pump, pgm_read_byte(&gamma8[i]));
    analogWrite(heater, pgm_read_byte(&gamma8[i]));
    analogWrite(Aerator, pgm_read_byte(&gamma8[i]));
    delay(5);
  }

  DateTime time = rtc.now();

  //Full Timestamp
  Serial.println(String("DateTime::TIMESTAMP_FULL:\t")+time.timestamp(DateTime::TIMESTAMP_FULL));

  //Date Only
  Serial.println(String("DateTime::TIMESTAMP_DATE:\t")+time.timestamp(DateTime::TIMESTAMP_DATE));

  //Full Timestamp
  Serial.println(String("DateTime::TIMESTAMP_TIME:\t")+time.timestamp(DateTime::TIMESTAMP_TIME));

  Serial.println("\n");
   tb.loop(); 
}

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

  WiFi.begin(WIFI_AP_NAME, 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_AP_NAME, WIFI_PASSWORD);
    while (WiFi.status() != WL_CONNECTED) {
      delay(500);
      Serial.print(".");
    }
    Serial.println("Connected to AP");
  }
}
//https://wiki.seeedstudio.com/Grove-Gas_Sensor-O2/
float readO2Vout()
{
    long sum = 0;
    for(int i=0; i<32; i++)
    {
        sum += analogRead(DOx);
    }
    sum >>= 5;
    float MeasuredVout = sum * (VRefer / 1023.0);
    return MeasuredVout;
}


float readConcentration()
{
    // Vout samples are with reference to 3.3V
    float MeasuredVout = readO2Vout();
    //float Concentration = FmultiMap(MeasuredVout, VoutArray,O2ConArray, 6);
    //when its output voltage is 2.0V,
    float Concentration = MeasuredVout * 0.21 / 2.0;
    float Concentration_Percentage=Concentration*100;
    return Concentration_Percentage;
}

//https://wiki.seeedstudio.com/Grove-PH-Sensor-kit/

float readPH()
{
  static unsigned long samplingTime = millis();
  static unsigned long printTime = millis();
  static float pHValue, voltage;
  if (millis() - samplingTime > samplingInterval)
  {
    pHArray[pHArrayIndex++] = analogRead(PH);
    if (pHArrayIndex == ArrayLenth)pHArrayIndex = 0;
    //voltage = avergearray(pHArray, ArrayLenth) * 5.0 / 1024;
    voltage = analogRead(PH) * 3.3 / 1024;
    pHValue = -19.18518519 * voltage + Offset;
    samplingTime = millis();
  }
  return pHValue;

  //if (millis() - printTime > printInterval)  //Every 800 milliseconds, print a numerical, convert the state of the LED indicator
  //{
  //  uart.print("Voltage:");
   //uart.print(voltage, 2);
    //
    //uart.print("    pH value: ");
    //uart.println(pHValue, 2);
   // digitalWrite(LED, digitalRead(LED) ^ 1);
   // printTime = millis();
 // }
}

double avergearray(int* arr, int number) {
  int i;
  int max, min;
  double avg;
  long amount = 0;
  if (number <= 0) {
    Serial.println("Error number for the array to avraging!/n");
    return 0;
  }
  if (number < 5) { //less than 5, calculated directly statistics
    for (i = 0; i < number; i++) {
      amount += arr[i];
    }
    avg = amount / number;
    return avg;
  } else {
    if (arr[0] < arr[1]) {
      min = arr[0]; max = arr[1];
    }
    else {
      min = arr[1]; max = arr[0];
    }
    for (i = 2; i < number; i++) {
      if (arr[i] < min) {
        amount += min;      //arr<min
        min = arr[i];
      } else {
        if (arr[i] > max) {
          amount += max;  //arr>max
          max = arr[i];
        } else {
          amount += arr[i]; //min<=arr<=max
        }
      }//if
    }//for
    avg = (double)amount / (number - 2);
  }//if
  return avg;
}
GND5VSDASCLSQWRTCDS1307+