#include <WiFi.h> 
#include <ThingsBoard.h>

//WiFi Setup 
#define WIFI_SSID        	"Wokwi-GUEST" 
#define WIFI_PASSWORD    	""
WiFiClient espClient;
ThingsBoard tb(espClient); 
int status = WL_IDLE_STATUS;

//ThingsBoard Setup 
#define CURRENT_FIRMWARE_TITLE 		"TEST" 
#define CURRENT_FIRMWARE_VERSION 	"1.0.0" 
#define TOKEN				"3O2bQlcgHGikrrqf8VF4" 
#define THINGSBOARD_SERVER 		"thingsboard.cloud"

#define PIR_PIN 4 
#define buzzerPin 27 
#define LED_PIN 14 
#define LDR_PIN 36

#define motiondetect "Gerakan Terdeteksi!" 
#define motionnotdetect "Tidak Ada Gerakan!"

int val = 0;

const float GAMMA = 0.7; 
const float RL10 = 50;
float distance = 0;
float X=400/397.63;

void InitWiFi()
{
 Serial.println("Connecting to AP ..."); 
 WiFi.begin(WIFI_SSID, WIFI_PASSWORD); 
 while (WiFi.status() != WL_CONNECTED) {
  delay(500); 
  Serial.print(".");
 }
 Serial.println("Connected to AP");
}

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(115200); 
 Serial.println(); 
 InitWiFi();
 
 pinMode(LED_PIN, OUTPUT); 
 pinMode(buzzerPin, OUTPUT); 
 pinMode(PIR_PIN, INPUT);
}

void loop() {
 delay(1000);
 
 val = digitalRead(PIR_PIN);
 
 int analogValue = analogRead(LDR_PIN); 
 float voltage = analogValue / 1024. * 5; 
 float resistance = 2000 * voltage / (1 - voltage / 5); 
 float lux = pow(RL10 * 1e3 * pow(10, GAMMA) / resistance, (1 / GAMMA));
 
 if (WiFi.status() != WL_CONNECTED) {
  reconnect();
 }
 
 if (!tb.connected()) {
 // Connect to the ThingsBoard 
 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 ( lux < 50){ 
  digitalWrite(LED_PIN, HIGH); 
  tone (buzzerPin, 40); 
  delay(1000); 
  noTone (buzzerPin); 
  delay(1000);
 }
 else{ 
 noTone (buzzerPin);
  digitalWrite(LED_PIN, LOW);
 }
 
Serial.println("Sending data...");

tb.sendTelemetryFloat("Intensitas Cahaya", lux);

Serial.print(lux); 
Serial.println(" LUX");

if(val == HIGH) {
 tone (buzzerPin, 20); 
 delay(1000); 
 noTone (buzzerPin); 
 delay(1000); 
 tb.sendTelemetryString("Gerakan", motiondetect); 
 Serial.println(motiondetect);
}

  else{
   noTone (buzzerPin); 
   tb.sendTelemetryString("Gerakan", motionnotdetect); 
   Serial.println(motionnotdetect);
  } 
  tb.loop();
  }