#include <esp_now.h>
#include <WiFi.h>

// Define PMK and LMK keys of 16 bytes each (using hypothetical data).
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};

// MAC Address of the target board.
uint8_t peerMacAddress[] = {0x88, 0x57, 0x21, 0xc2, 0xc0, 0xb4}; 
typedef struct struct_message {
    char a[32];
    int b;
} struct_message;

struct_message myData;


// Callback when sending data.
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);
  delay(5000);
  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);
 
  // 1. Configure the PMK key for your board.
  esp_now_set_pmk(PMK_KEY);

  // 2.Register the peer board and enable encryption.
  esp_now_peer_info_t peerInfo;
  memset(&peerInfo, 0, sizeof(peerInfo)); // <---Clean up junk data.
  memcpy(peerInfo.peer_addr, peerMacAddress, 6);
  peerInfo.channel = 0; 
  
  // Very important: Enter the LMK key and change the encrypt value to true.
  memcpy(peerInfo.lmk, LMK_KEY, 16);
  peerInfo.encrypt = true; 

  if (esp_now_add_peer(&peerInfo) != ESP_OK) {
    Serial.println("Failed to add peer");
    return;
  }



  
}

void loop() {
  strcpy(myData.a, "Hello ESP-NOW");
  myData.b = random(1, 100);

  // ส่งข้อมูล
  esp_err_t result = esp_now_send(peerMacAddress, (uint8_t *) &myData, sizeof(myData));
   
  if (result == ESP_OK) {
    Serial.println("Sent with success");
  } else {
    Serial.println("Error sending the data");
  }
  delay(2000);
}
