#include <WiFi.h>
#include "soc/soc.h"
#include "soc/rtc_cntl_reg.h"
#include <esp_now.h>
#include <Arduino.h>
#include <HCSR04.h>
#include <esp_sleep.h>

#define WIFI_SSID "Wokwi-GUEST"
#define uS_TO_S_FACTOR 1000000
#define TIME_TO_SLEEP  10 //Slep for 10 seconds
RTC_DATA_ATTR int bootCount = 0;

uint8_t broadcastAddress[] = {0x8C, 0xAA, 0xB5, 0x84, 0xFB, 0x90};

esp_now_peer_info_t peerInfo;

// Define the trigger and echo pins for the HC-SR04 sensor
const int TRIGPIN = 36; // Replace with the actual pin
const int ECHOPIN = 42;    // Replace with the actual pin

HCSR04 hc(TRIGPIN, ECHOPIN); //创建HCSR04对象(参数:trig引脚 , echo引脚)

void OnDataSent(const uint8_t *mac_addr, esp_now_send_status_t status) {
  Serial.print("Send Status: ");
  Serial.println(status == ESP_NOW_SEND_SUCCESS ? "Ok" : "Error");
}

//Receiving Callback
void OnDataRecv(const uint8_t * mac, const uint8_t *data, int len) {
  Serial.print("Message received: ");
  char receivedString[len];
  memcpy(receivedString, data, len);
  Serial.println(String(receivedString));
}

void initWiFi() {
  // Connect to Wi-Fi
  WiFi.begin(WIFI_SSID);
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.println("Connecting to WiFi...");
  }
  Serial.println("Connected to WiFi");
}

void initESPNow() {
  // Initialize ESP-NOW
  if (esp_now_init() != ESP_OK) {
    Serial.println("ESP-NOW initialization failed");
    ESP.restart();
  }
  esp_now_register_send_cb(OnDataSent);
  esp_now_register_recv_cb(OnDataRecv);
  memcpy(peerInfo.peer_addr, broadcastAddress, 6);
  peerInfo.channel = 0;
  peerInfo.encrypt = false;
  esp_now_add_peer(&peerInfo);
  }

void setup(){
  Serial.begin(115200);
  delay(2000);
   initWiFi();
  initESPNow();
    WiFi.mode(WIFI_STA);
  delay(2000);
  ++bootCount;
  Serial.println("Boot number: " + String(bootCount));
  delay(2000);
  

   //Increment boot number and print it every reboot
    float distance = hc.dist();    //获取距离数据
  delay(5000);
    String message;
    if(distance<50){
      message = "OCCUPIED";  
    }
    else{
      message = "FREE";
    }

    esp_now_send(broadcastAddress, (uint8_t*)message.c_str(), message.length() + 1);
  Serial.println("Going to sleep now");
  delay(100);
 esp_sleep_enable_timer_wakeup(TIME_TO_SLEEP * uS_TO_S_FACTOR);
  Serial.println("ESP32 sleep every " + String(TIME_TO_SLEEP));
  esp_deep_sleep_start();

 
  //Serial.flush(); 
  //esp_deep_sleep_start();
  //esp_light_sleep_start();
 
}

void loop(){

  
}