#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[] = {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 ? "Delivered 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("--- Information was received from board number 2.: ");
  Serial.print(incomingData.text);
  Serial.print(" | number: ");
  Serial.println(incomingData.counter);
}
 
void setup() {
  Serial.begin(115200);
  WiFi.mode(WIFI_STA);

  // Getting Started ESP-NOW
  if (esp_now_init() != ESP_OK) {
    Serial.println("ESP-NOW startup failed.");
    return;
  }

 // Set up PMK primary Master key.
  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);  
  
  //  // The sender registers as a peer to receive encrypted data.
  memset(&peerInfo, 0, sizeof(peerInfo)); // <--- Clean up junk data.
  memcpy(peerInfo.peer_addr, Address_me_send, 6);
  peerInfo.channel = 0;  
  // Enter the LMK (local Master key) and set the encryption system to true, the same as the sending side.
  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 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(Address_me_send, (uint8_t *) &myData, sizeof(myData));
  if (result != ESP_OK) {
    Serial.println("An error occurred during data transmission.");
  }

  delay(2000);
}
