/*************************************************************
  Blynk is a platform with iOS and Android apps to control
  ESP32, Arduino, Raspberry Pi and the likes over the Internet.
  You can easily build mobile and web interfaces for any
  projects by simply dragging and dropping widgets.

    Downloads, docs, tutorials: https://www.blynk.io
    Sketch generator:           https://examples.blynk.cc
    Blynk community:            https://community.blynk.cc
    Follow us:                  https://www.fb.com/blynkapp
                                https://twitter.com/blynk_app

  Blynk library is licensed under MIT license
 *************************************************************
  Blynk.Edgent implements:
  - Blynk.Inject - Dynamic WiFi credentials provisioning
  - Blynk.Air    - Over The Air firmware updates
  - Device state indication using a physical LED
  - Credentials reset using a physical Button
 *************************************************************/

/* Fill in information from your Blynk Template here */
/* Read more: https://bit.ly/BlynkInject */
#define BLYNK_TEMPLATE_ID "TMPL6edI2Bqsh"
#define BLYNK_TEMPLATE_NAME "Quickstart Template"
#define BLYNK_AUTH_TOKEN "e0eTso8Do2QNIouhBfIZImxZwDui9Cb-" //janlup ntr comment buat provisioning


#define BLYNK_FIRMWARE_VERSION        "0.0.0"

#define BLYNK_PRINT Serial


//#define BLYNK_DEBUG
#define APP_DEBUG


//#include "BlynkEdgent.h"

// Uncomment your board, or configure a custom board in Settings.h
#define USE_ESP32_DEV_MODULE

#include <WiFi.h> //Library WiFi
#include <WiFiClient.h> //Library WiFiClient
#include <BlynkSimpleEsp32.h> //Library BlynkESP32
#include <NTPClient.h>
#include <WiFiUdp.h>
//#include "RTClib.h"

BlynkTimer timer;
WiFiUDP ntpUDP;
NTPClient timeClient(ntpUDP, "pool.ntp.org", 25200);  // 25200 seconds is 7 hours (GMT+7)
//RTC_DS3231 rtc;
//char daysOfTheWeek[7][12] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
const int stepPin = 12; 
const int dirPin = 13; 
const int motorpwm = 27;
const int motorlow = 26;
const int motorhigh = 25;
const int switchpin = 2;
const int sclrtc = 22;
const int sdartc = 21;
const int ledpin = 4;

int jumlahikan = 0;
double beratsample = 0;
double sum = 0;
double jumlahpangan = 0;
double presentase = 0;
double pakanpersesi = 0.2;
double takaran = 0.02;
double stepStepper = 25;
bool flagoverride = false;

bool motorsActivated = false;
int jamPakanSesi[3];
int stepCounter = 0;
int targetSteps = 0;
char timeprint[20];
int jamPakanSesi1;
int jamPakanSesi2;
int jamPakanSesi3;

// Buat jam
char timertc[20];
volatile bool interruptTriggered = false;
unsigned long previousMillis = 0;
const long interval = 1000;  // Update every 1 second


// INI FLAG UNTUK JAM PERTAMA
bool flagjam1 = false;

// INI FLAG UNTUK JAM KEDUA
bool flagjam2 = false;

// INI FLAG UNTUK JAM KETIGA
bool flagjam3 = false;

int indikatorstepper = 0;
String gettime;
String getday;

char ssid[] = "Wokwi-GUEST"; //Nama WiFi yang digunakan
char pass[] = ""; //Password WiFi yang digunakan

BLYNK_WRITE(V0) {
  jumlahikan = param.asInt();   
}

BLYNK_WRITE(V1) {
  beratsample = param.asFloat(); 
}

BLYNK_WRITE(V6) {
  presentase = param.asFloat(); 
}
BLYNK_WRITE(V7) {
  jamPakanSesi1 = param.asInt();   
}

BLYNK_WRITE(V8) {
  jamPakanSesi2 = param.asInt();   
}

BLYNK_WRITE(V9) {
  jamPakanSesi3 = param.asInt();   
}

BLYNK_WRITE(V2) { // Button on V2
  if (param.asInt()) { // if button is pressed
    sum = jumlahikan * beratsample; // calculate the sum
    jumlahpangan = (sum * presentase) / 100;
    pakanpersesi = jumlahpangan / 3;
    Blynk.virtualWrite(V3, jumlahpangan); // display the sum on V3
    Blynk.virtualWrite(V4, sum); // display the sum on V4
    Blynk.virtualWrite(V5, pakanpersesi);
    jamPakanSesi[0] = jamPakanSesi1;
    jamPakanSesi[1] = jamPakanSesi2;
    jamPakanSesi[2] = jamPakanSesi3; 
    
  }
}

void controlstepper(double pakanpersesi) {
  double slotrequired = pakanpersesi / takaran;
  double totalstep = slotrequired * stepStepper;
  targetSteps = ceil(totalstep);  // Update targetSteps based on totalstep
  digitalWrite(dirPin, HIGH); // Enables the motor to move in a particular direction
  for (int x = 0; x <= targetSteps; x++) {
    digitalWrite(stepPin, HIGH);
    delay(15);
    digitalWrite(stepPin, LOW);
    delay(15);
    if (x % 25 == 0) {
      delay(1500);
    }
    stepCounter++;
    Serial.println("Stepper berjalan: ");
    Serial.print(x);

    // Cek apakah stepper sudah mencapai target langkah
    if (stepCounter >= targetSteps) {
      // Hentikan stepper
      stopStepper();
      // Reset stepCounter
      stepCounter = 0;
    }
  }
}

void controlmotor(){
  digitalWrite(ledpin, HIGH);
  int motorSpeed = 200;
  digitalWrite(motorhigh, HIGH);
  digitalWrite(motorlow, LOW);
  analogWrite(motorpwm, motorSpeed); 
  //delay(100);  // Tunda 2 detik
}

void stopStepper() {
  digitalWrite(stepPin, LOW);
  digitalWrite(dirPin, LOW);
  Serial.println("Stepper Stop");
}

void stopMotors() {
  digitalWrite(motorhigh, LOW);
  digitalWrite(motorlow, LOW);
  digitalWrite(motorpwm, LOW);
  digitalWrite(ledpin, LOW);
  Serial.println("Motor Mati");
}

void setup()
{
  Serial.begin(115200);
  pinMode(switchpin, INPUT_PULLUP);
  pinMode(stepPin,OUTPUT); 
  pinMode(dirPin,OUTPUT);
  pinMode(motorpwm, OUTPUT);
  pinMode(motorlow, OUTPUT);
  pinMode(motorhigh, OUTPUT);
  pinMode(ledpin, OUTPUT);
  delay(100);
  // if (! rtc.begin()) {
  //   Serial.println("RTC module is NOT found");
  //   while (1);
  // }
  //rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
  //rtc.adjust(DateTime(2023, 12, 10, 13, 55, 0));
  Serial.println("===TESTING===");
  //BlynkEdgent.begin();


  Blynk.begin(BLYNK_AUTH_TOKEN, ssid, pass);
  timeClient.begin();

}


void loop() {
  Blynk.run();
  timeClient.update();

  //DateTime now = rtc.now();
  //int readbutton = digitalRead(switchpin);


  // Cek apakah waktu saat ini sama dengan salah satu jam pakan sesi
  if (timeClient.getHours() == jamPakanSesi[0]){
    if (!flagjam1) {
       // Jika motor belum diaktifkan, aktifkan motor DC dan stepper
       controlmotor();
       delay(3000);  // Tunggu 3 detik sebelum mengaktifkan stepper
       controlstepper(pakanpersesi);
       delay(3000);
       stopMotors();
       flagjam1 = true;
    }
  }
   if (timeClient.getHours() == jamPakanSesi[1]) {
      if (!flagjam2) {
        // Jika motor belum diaktifkan, aktifkan motor DC dan stepper
        controlmotor();
        delay(3000);  // Tunggu 3 detik sebelum mengaktifkan stepper
        controlstepper(pakanpersesi);
        delay(3000);
        stopMotors();
        flagjam2 = true;
      }
    }
   if (timeClient.getHours() == jamPakanSesi[2]) {
      if (!flagjam3) {
        // Jika motor belum diaktifkan, aktifkan motor DC dan stepper
        controlmotor();
        delay(3000);  // Tunggu 3 detik sebelum mengaktifkan stepper
        controlstepper(pakanpersesi);
        delay(3000);
        stopMotors();
        flagjam3 = true;
      }
    }


  // if((readbutton == 1) && !flagoverride){
  //    controlmotor();
  //    delay(3000);
  //    controlstepper(pakanpersesi);
  //    stopMotors();
  //    //flagoverride = true;
  // }
  // else if(readbutton == 0){
  //   //flagoverride = false;
  // }


    if(timeClient.getHours() == 23){
        flagjam1 = false;
        flagjam2 = false;
        flagjam3 = false;
    }


}
A4988