#include <WiFi.h>
#include <WiFiClientSecure.h>
#include <UniversalTelegramBot.h>
#include <ArduinoJson.h>

String token = "6572160734:AAF3ZXWwSmQD6fFcZh2lc6MSyTjh6j0Wi28";
#define CHAT_ID "1205962951"


char ssid[] = "Wokwi-GUEST";
char pass[] = "";


WiFiClientSecure client;
UniversalTelegramBot bot(token, client);

const int buzzer = 15;
const int ledPin = 4;                // choose the pin for the LED
const int inputPin = 19;               // choose the input pin (for PIR sensor)
int pirState = LOW;             // we start, assuming no motion detected
int val = 0;                    // variable for reading the pin status

// Cek Pesan Setiap 1 detik
int interval = 1000;
unsigned long waktu_terakhir;

void setup() {
  Serial.begin(115200);
  Serial.println("Memulai Telegram Bot");
  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, pass);
  client.setCACert(TELEGRAM_CERTIFICATE_ROOT);
	while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.println("Sedang menghubungkan ke WiFi..");
  }
  bot.sendMessage(CHAT_ID, "Monitoring Gerakan IOT");

  
  pinMode(inputPin,INPUT);
  pinMode(buzzer, OUTPUT);
  pinMode(ledPin, OUTPUT); 
}

void loop() {
	
  val = digitalRead(inputPin);  // read input value
  if (val == HIGH) {            // check if the input is HIGH
    digitalWrite(ledPin, HIGH);  // turn LED ON
    if (pirState == LOW) {
      // we have just turned on
      Serial.println("Gerakan Terdeteksi");
      tone(buzzer, 200);
      
      bot.sendMessage(CHAT_ID, "Ada Gerakan");
      // We only want to print on the output change, not state
      pirState = HIGH;
    }
  } else {
    digitalWrite(ledPin, LOW); // turn LED OFF
    if (pirState == HIGH) {
      // we have just turned of
      Serial.println("Gerakan Berakhir");
      tone(buzzer, 0);
      bot.sendMessage(CHAT_ID, "Gerakan Berakhir");

      // We only want to print on the output change, not state
      pirState = LOW;
    }
  }
  
  delay(3000); //deley 3 detik
}