#include <esp_now.h>
#include <WiFi.h>
// Define PMK and LMK keys of 16 bytes

const uint8_t PMK_KEY[] = {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F};
const uint8_t LMK_KEY[] = {0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F};




// Enter the MAC address of the board that will receive the data.
uint8_t Address_me_send[] = {0x8c, 0x94, 0xdf, 0x61, 0xda, 0x04};



// 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
int x=10;

esp_now_peer_info_t peerInfo;

esp_now_peer_info_t peerInfo1;

// The function is called when data is sent.
void OnDataSent(const uint8_t *mac_addr, esp_now_send_status_t status) {
  Serial.print("\r\n Latest 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.1: ");
  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;
  }

  esp_now_set_pmk(PMK_KEY);

// 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 board me send as a Peer.---------------------------------
  memset(&peerInfo, 0, sizeof(peerInfo)); // <--- Clean up junk data.
  memcpy(peerInfo.peer_addr, Address_me_send, 6);
  peerInfo.channel = 0;  
  memcpy(peerInfo.lmk, LMK_KEY, 16);
  peerInfo.encrypt = true; 

  
  if (esp_now_add_peer(&peerInfo) != ESP_OK){
    Serial.println("Adding a peer failed.");
    return;
  }


  
}
 
void loop() {
  //Generate and send data to board 1 every 2 seconds.
  strcpy(myData.text, "Greetings from board number 2.");
  
  myData.counter = random(1, 100);
 
  esp_err_t result = esp_now_send(Address_me_send, (uint8_t *) &myData, sizeof(myData));
  if (result != ESP_OK) {
    Serial.println("An error occurred during data transmission.");
  }

  delay(2000);
}
