// Including Required Libraries 
#include <ArduinoJson.h>
#include <UniversalTelegramBot.h>
#include <WiFi.h>
#include <WiFiClientSecure.h>


// Creating Library related variables

const char* ssid = "Ashraf";
const char* password = "Ashraf";

#define BOTtokenValue "x"
#define OUR_CHAT_ID "x"

WiFiClientSecure client;
UniversalTelegramBot bot(BOTtokenValue,client);

const int mSensor = 21; // pin number for motion sensor
const int TempSensor = 34; // pin number for temperature sensor

bool mDetected = false; // to indiate if motion is detected


void IRAM_ATTR movementdetection()
{
  Serial.println("Motion has been detected!");
  mDetected = true;
  }

void setup() {
  // put your setup code here, to run once:
Serial.begin(115200);
pinMode(mSensor, INPUT_PULLUP);
attachInterrupt(digitalPinToInterrupt(mSensor),movementdetection,RISING);

Serial.print("Trying to Connect to WiFi : ");
Serial.println(ssid);
WiFi.mode(WIFI_STA);
WiFi.begin(ssid,password);
client.setCACert(TELEGRAM_CERTIFICATE_ROOT);

while(WiFi.status() != WL_CONNECTED)
{
  Serial.print(".");
  delay(300);
  }

  Serial.println("");
  Serial.println("WiFi Connected");
  Serial.print("IR Address : ");
  Serial.println(WiFi.localIP());

  bot.sendMessage(OUR_CHAT_ID, " Motion and Temperature Bot Started Up","");
}

void loop() {
  // put your main code here, to run repeatedly:
if(mDetected){
  bool result = bot.sendMessage(OUR_CHAT_ID,"Motion has been detected!","");
  Serial.println("Motion has been detected!");
  if(result){
    Serial.println("Message sucessfully sent");}else {
    Serial.println("Error: Message wasn't sent");
    }
  mDetected = false;
  }
}