#include <WiFi.h>
#include <esp_now.h>
#include <esp_wifi.h>
// Identify the MAC address of the receiver board.
uint8_t broadcastAddress[] = {0x88, 0x57, 0x21, 0xb1, 0x28, 0x2c}; 

// Set the channel to match the receiver's Wi-Fi router.
#define WIFI_CHANNEL 9 

typedef struct struct_message {
    char a[32];
    int b;
    float c;
    bool d;
} struct_message;

struct_message myData;
esp_now_peer_info_t peerInfo;

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);

  // Force the board to use the same channel as the router.
  esp_wifi_set_channel(WIFI_CHANNEL, WIFI_SECOND_CHAN_NONE);

  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 as a Peer.
  memcpy(peerInfo.peer_addr, broadcastAddress, 6);
  peerInfo.channel = WIFI_CHANNEL;  // Enter the corresponding channel here as well.
  peerInfo.encrypt = false;
  
  if (esp_now_add_peer(&peerInfo) != ESP_OK){
    Serial.println("Failed to add peer");
    return;
  }
}
 
void loop() {
  // Configure the simulated data and export it.
  strcpy(myData.a, "Hello from Node!");
  myData.b = random(1, 100);
  myData.c = 12.345;
  myData.d = 1;
  
  esp_err_t result = esp_now_send(broadcastAddress, (uint8_t *) &myData, sizeof(myData));
  
    if (result == ESP_OK) {
    Serial.println("Sent with success");
  } else {
    Serial.println("Error sending the data");
  }
  delay(5000);
}
