// 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 "Ashraf:Ashraf"
#define OUR_CHAT_ID "Ashraf"

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
int TempValue = 0;

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;
  }

TempValue = analogRead(TempSensor); // 0 4095
Serial.println(TempValue);
float voltTemp = (float)TempValue * (3300.0/4096.0) ;
Serial.println(voltTemp);
float actualTempC = voltTemp / 10.0;
Serial.println(actualTempC);

// Temp = Vout(mv)/10
if(actualTempC >=30)
{
String sensorMessage = String(actualTempC, DEC);
Serial.println(sensorMessage);
bot.sendMessage(OUR_CHAT_ID,"Temperature","");
bot.sendMessage(OUR_CHAT_ID,sensorMessage,"");  // TempValue+""
//bot.sendMessage(OUR_CHAT_ID,TempValue+"","");
delay(500);
  }


}