/*
  Receiver ESP32 Sketch for ESP-NOW Communication
*/

#include <esp_now.h>
#include <WiFi.h>


// Structure example to receive data (MUST MATCH SENDER)
typedef struct struct_message {
    char a[32]; // For status text
    int b;      // Integer (e.g., scaled reading)
    float c;    // Float (e.g., magnitude or raw float data)
    bool d;     // Boolean (e.g., movement detected)
} struct_message;


struct_message myData;

// 1. UPDATED CALLBACK FUNCTION SIGNATURE (Crucial Fix!)
void OnDataRecv(const esp_now_recv_info_t *info, const uint8_t *incomingData, int len) {
    // Copy the received data into our local structure variable
    memcpy(&myData, incomingData, sizeof(myData));
    
    Serial.println("=========================================");
    Serial.print("Packet Received from MAC: ");
    for (int i = 0; i < 6; i++) {
        // Use printf formatting for clean hex output
        Serial.printf("%02X", info->src_addr[i]);
        if (i < 5) Serial.print(":");
    }
    Serial.println();

    // Display the received data fields
    Serial.print("Char: ");
    Serial.println(myData.a);
    Serial.print("Int: ");
    Serial.println(myData.b);
    Serial.print("Float: ");
    Serial.println(myData.c);
    Serial.print("Bool: ");
    Serial.println(myData.d ? "TRUE" : "FALSE");
}


void setup() {
  // Initialize Serial Monitor
  Serial.begin(115200);
  
  // Set device as a Wi-Fi Station (Required for ESP-NOW)
  WiFi.mode(WIFI_STA);

  // Init ESP-NOW
  if (esp_now_init() != ESP_OK) {
    Serial.println("Error initializing ESP-NOW");
    return;
  }
  
  // Register the Receive Callback Function
  esp_now_register_recv_cb(OnDataRecv);

  Serial.println("Receiver Initialized and Listening...");
}


void loop() {
  // *** NOTHING HERE IS NEEDED ***
  // The code runs entirely within the OnDataRecv callback function when data arrives.
  delay(10); // Small delay to keep the loop running smoothly (prevents watchdog resets)
}
