#include "espnow.h"


//Mac Adress Receiver:  24:58:7c:ce:fa:dc

// Create a struct_message
struct_message espnowdata;

void readMacAddress(){
  uint8_t baseMac[6];
  esp_err_t ret = esp_wifi_get_mac(WIFI_IF_STA, baseMac);
  if (ret == ESP_OK) {
    Serial.printf("%02x:%02x:%02x:%02x:%02x:%02x\n",
                  baseMac[0], baseMac[1], baseMac[2],
                  baseMac[3], baseMac[4], baseMac[5]);
  } else {
    Serial.println("Failed to read MAC address");
  }
}

void initESPNOW() {
  
  WiFi.mode(WIFI_STA);
  Serial.print("WiFi-Channel Default: ");
  Serial.println(WiFi.channel());
  
  esp_wifi_set_promiscuous(true);
  esp_wifi_set_channel(CHANNEL, WIFI_SECOND_CHAN_NONE);
  esp_wifi_set_promiscuous(false);
  
  Serial.print("WiFi-Channel Update : ");
  Serial.println(WiFi.channel());
  //WiFi.begin();


  Serial.print("[DEFAULT] ESP32 Board MAC Address: ");
  readMacAddress();


  // Init ESP-NOW
  if (esp_now_init() != ESP_OK) {
    Serial.println("Error initializing ESP-NOW");
    return;
  }


  
  // Once ESPNow is successfully Init, we will register for recv CB to
  // get recv packer info
  esp_now_register_recv_cb(esp_now_recv_cb_t(OnDataRecv));

}





void OnDataRecv(const uint8_t * mac, const uint8_t *incomingData, int len) {
  memcpy(&espnowdata, incomingData, sizeof(espnowdata));
  Serial.print("Bytes received: ");
  Serial.println(len);

  

  processCommand(espnowdata);
   
  Serial.println();
}