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

#define buka  20//derajat
#define tutup 60//derajat
#define pinServo = 13;
   
#define JamMakan1  DateTime(0, 1, 1,  8, 0, 0, 0)//jam 8 pagi
#define JamMakan2  DateTime(0, 1, 1, 17, 0, 0, 0)//jam 5 sore

#define WIFI_SSID           "Wokwi-GUEST"
#define WIFI_PASSWORD       ""
#define TOKEN               "j4sIZ226kgzEdfWZf86q"
#define THINGSBOARD_SERVER  "thingsboard.cloud"

Servo servoMakanIkan;

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

byte detikSebelumnya;
char buf[17];
RTC_DS1307 rtc);
 
void InitWiFi()
{
  Serial.println("loading ...");

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

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

void reconnect() {
  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");
  }
}

void setup() {
  Serial.begin(9600);
  Serial.println("Pemberi pakan ikan otomatis");
     
  servoMakanIkan.attach(pinServo, 500, 2400));
  servoMakanIkan.write(tutup);
   
  Wire.begin();
  rtc.begin();
  rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
  //DateTime dt(2011, 11, 10, 15, 18, 0, 5); // set tanggal dan waktu (format): tahun, bulan tanggal, jam, menit, detik, hari (1=minggu, 7=sabtu)
  //rtc.setDateTime(dt);
   
  Serial.println("Sistem mulai");
  sprintf(buf, "Set waktu 1 = %02d:%02d (%lu)", JamMakan1.hour(), JamMakan1.minute(), JamMakan1.get());
  Serial.println(buf);
  sprintf(buf, "Set waktu 1 = %02d:%02d (%lu)", JamMakan2.hour(), JamMakan2.minute(), JamMakan2.get());
  Serial.println(buf);
}
   
void loop() {
   
  DateTime now = rtc.now();

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

  if (!tb.connected()) {
    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");
      return;
    }
  }

  if (detikSebelumnya != now.second())
  {
    sprintf(buf, "%02d:%02d:%02d", now.hour(), now.minute(), now.second());
    Serial.print(buf);
   
    detikSebelumnya = now.second();
   
    uint32_t epoch = now.get() % 86400;//hanya jam menit detik
   
    if ((epoch == JamMakan1.get()) ||
        (epoch == JamMakan2.get()))
    {
      char buf[17];
      sprintf(buf, "Pakan = %02d:%02d"  now.hour(), now.minute());
      Serial.println(buf);
   
      servoMakanIkan.write(buka);
      delay(1000);
      servoMakanIkan.write(tutup);
   
    }
  }
}
GND5VSDASCLSQWRTCDS1307+