#include <esp_now.h>
#include <WiFi.h>

// Enter the MAC address of the second board here.
uint8_t broadcastAddress[] = {0x88, 0x57, 0x21, 0xb1, 0x28, 0x2c};

// Data structure for receiving and sending.
typedef struct struct_message {
    char text[32];
    int counter;
} struct_message;

struct_message myData;       // Information to send
struct_message incomingData; // Received information

esp_now_peer_info_t peerInfo;

//The function is called when data is sent.
void OnDataSent(const uint8_t *mac_addr, esp_now_send_status_t status) {
  Serial.print("\r\nLatest delivery status: ");
  Serial.println(status == ESP_NOW_SEND_SUCCESS ? "Sent successfully." : "Send failed.");
}

// The function is called when data is submitted.
void OnDataRecv(const esp_now_recv_info *info, const uint8_t *incomingDataRaw, int len) {
  memcpy(&incomingData, incomingDataRaw, sizeof(incomingData));
  Serial.print("---I received the information from the board.2: ");
  Serial.print(incomingData.text);
  Serial.print(" |number: ");
  Serial.println(incomingData.counter);
}
 
void setup() {
  Serial.begin(115200);
  WiFi.mode(WIFI_STA);

  // Getting Started with ESP-NOW
  if (esp_now_init() != ESP_OK) {
    Serial.println("ESP-NOW startup failed.");
    return;
  }

  // Register the Callback function for both incoming and outgoing calls.

esp_now_register_send_cb((esp_now_send_cb_t)OnDataSent);

  

esp_now_register_recv_cb((esp_now_recv_cb_t)OnDataRecv);  
  
  // Register the second board as a Peer.
  memcpy(peerInfo.peer_addr, broadcastAddress, 6);
  peerInfo.channel = 0;  
  peerInfo.encrypt = false;
  
  if (esp_now_add_peer(&peerInfo) != ESP_OK){
    Serial.println("Adding a peer failed.");
    return;
  }
}
 
void loop() {
  // Generate and send data to board 2 every 2 seconds.
  strcpy(myData.text, "Greetings from Board 1.");
  //myData.counter++;
   myData.counter = random(1, 100);
  esp_err_t result = esp_now_send(broadcastAddress, (uint8_t *) &myData, sizeof(myData));
  if (result != ESP_OK) {
    Serial.println("An error occurred during data transmission.");
  }

  delay(2000);
}
