#include <esp_now.h>
#include <WiFi.h>

//1. Enter the MAC address of the receiver board here.
uint8_t receiverAddress[] = {0x00, 0x70, 0x07, 0xa3, 0x78, 0x78}; 

// 2. Assign a unique ID to the board (for the second board, change it to 2, 3, ...
#define BOARD_ID 2 

// The data structure to be sent (must match the receiver's data).
typedef struct struct_message {
    int id;
    float temperature;
    float humidity;
} struct_message;

struct_message myData;
esp_now_peer_info_t peerInfo;

// Callback function when data transmission is successful or unsuccessful
void OnDataSent(const uint8_t *mac_addr, esp_now_send_status_t status) {
  Serial.print("\r\nLast Packet Send Status:\t");
  Serial.println(status == ESP_NOW_SEND_SUCCESS ? "Delivery Success" : "Delivery Fail");
}
 
void setup() {
  Serial.begin(115200);
  WiFi.mode(WIFI_STA);

  if (esp_now_init() != ESP_OK) {
    Serial.println("Error initializing ESP-NOW");
    return;
  }

  //esp_now_register_send_cb(OnDataSent);
  esp_now_register_send_cb((esp_now_send_cb_t)OnDataSent);
  
  // Register the receiver board as a Peer.
  memcpy(peerInfo.peer_addr, receiverAddress, 6);
  peerInfo.channel = 0;  
  peerInfo.encrypt = false;
  
  if (esp_now_add_peer(&peerInfo) != ESP_OK){
    Serial.println("Failed to add peer");
    return;
  }
}
 
void loop() {
  // Enter the information you want to send.
  myData.id = BOARD_ID;
  myData.temperature = random(20, 40); //Random sensor sample values
  myData.humidity = random(50, 90);
  
  // Send the data to the receiver's MAC address.
  esp_err_t result = esp_now_send(receiverAddress, (uint8_t *) &myData, sizeof(myData));
   
  if (result == ESP_OK) {
    Serial.println("Sent with success");
  } else {
    Serial.println("Error sending the data");
  }
  delay(5000); //  Sending every 5 seconds.
}
