#include <esp_now.h>
#include <WiFi.h>

int tl = 1000; //ms
int tr;
String success;

// MAC del receptor
uint8_t broadcastAddress[] = {0x8C, 0xAA, 0xB5, 0x84, 0xFB, 0x90}; //1
//uint8_t broadcastAddress[] = {0x8C, 0xAA, 0xB5, 0x86, 0x36, 0x0C}; //2

esp_now_peer_info_t peerInfo;

//Funcion callback de envio
/*esp_now_send(uint8_t *da, uint8_t *data, uint8_t *len)
  Parámetros:
    uint8_t *da: array de la dirección MAC del par al que se envía el paquete de datos. Si la dirección es NULL los datos se envían a todas las direcciones de la Tabla de Comunicación.
    uint8_t *data: array con el paquete de datos a enviar.
    uint8_t len: longitud del array del paquete de datos.
    */
void OnDataSent(const uint8_t *mac_addr, esp_now_send_status_t status) {
  Serial.print("Ultimo paquete enviado: ");
  Serial.println(status == ESP_NOW_SEND_SUCCESS ? "Ok" : "Error");
}

//Funcion callback de recepcion
void OnDataRecv(const uint8_t * mac, const uint8_t *data, int len) {
  //memcpy(tr, incomingData, sizeof(tr));
  Serial.print("Bytes received: ");
  Serial.println(len);
  Serial.println(*data);
  //incomingTemp = incomingReadings.temp;
  //incomingHum = incomingReadings.hum;
  //incomingPres = incomingReadings.pres;
}

void setup() {
  Serial.begin(115200);
  WiFi.mode(WIFI_STA);

  // Init ESP-NOW
  if (esp_now_init() != ESP_OK) {
    Serial.println("Error initializing ESP-NOW");
    return;
  }
  //callback de envio
  esp_now_register_send_cb(OnDataSent);
  //callback de recepcion
  esp_now_register_recv_cb(OnDataRecv);
  
  // Registrando peer
  memcpy(peerInfo.peer_addr, broadcastAddress, 6);
  peerInfo.channel = 0;  
  peerInfo.encrypt = false;
  /* Add peer 
   esp_now_add_peer(uint8_t *mac_addr, uint8_t role, uint8_t channel, uint8_t *key, uint8_t key_len)
   Parámetros:
         uint8_t *mac_addr: array de la dirección MAC del par de comunicación.
         uint8_t role: papel del par de comunicación (0=ocioso, 1=maestro, 2 esclavo y 3=maestro + esclavo.
         uint8_t channel: canal de comunicación, por lo general de 1 a 13 (algunas áreas pueden utilizar el canal 14).
         uint8_t *key: array de 16 bytes con la clave de comunicación. NULL indica que no hay clave.
         uint8_t key_len: longitud de la clave de comunicación. Actualmente deben ser 16 bytes.*/

  if (esp_now_add_peer(&peerInfo) != ESP_OK){
    Serial.println("Failed to add peer");
    return;
  }

}
void loop() {
  String pp;
  // Send message via ESP-NOW
  esp_err_t result = esp_now_send(broadcastAddress,(uint8_t *)tl, sizeof(tl));   
  if (result == ESP_OK) {
    Serial.print("Submitted successfully ");
    Serial.println(sizeof(tl));
  }
  else {
    Serial.println("Error de envio");
  }
  delay(1000);
}

/*// Define variables to store BME280 readings to be sent
float temperature;
float humidity;
float pressure;

// Define variables to store incoming readings
float incomingTemp;
float incomingHum;
float incomingPres;

// Variable to store if sending data was successful
String success;

//Structure example to send data
//Must match the receiver structure
typedef struct struct_message {
    float temp;
    float hum;
    float pres;
} struct_message;

// Create a struct_message called BME280Readings to hold sensor readings
struct_message sendingReadings;

// Create a struct_message to hold incoming sensor readings
struct_message incomingReadings;

esp_now_peer_info_t peerInfo;

// Callback when data is sent
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");
  if (status ==0){
    success = "Delivery Success :)";
  }
  else{
    success = "Delivery Fail :(";
  }
}

// Callback when data is received
void OnDataRecv(const uint8_t * mac, const uint8_t *incomingData, int len) {
  memcpy(&incomingReadings, incomingData, sizeof(incomingReadings));
  Serial.print("Bytes received: ");
  Serial.println(len);
  incomingTemp = incomingReadings.temp;
  incomingHum = incomingReadings.hum;
  incomingPres = incomingReadings.pres;
}
 
void setup() {
  // Init Serial Monitor
  Serial.begin(115200);
 
  // Set device as a Wi-Fi Station
  WiFi.mode(WIFI_STA);

  // 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 Send CB to
  // get the status of Trasnmitted packet
  esp_now_register_send_cb(OnDataSent);
  
  // Register peer
  memcpy(peerInfo.peer_addr, broadcastAddress, 6);
  peerInfo.channel = 0;  
  peerInfo.encrypt = false;
  
  // Add peer        
  if (esp_now_add_peer(&peerInfo) != ESP_OK){
    Serial.println("Failed to add peer");
    return;
  }
  // Register for a callback function that will be called when data is received
  esp_now_register_recv_cb(OnDataRecv);
}
 
void loop() {
  getReadings();
 
  // Set values to send
  BME280Readings.temp = temperature;
  BME280Readings.hum = humidity;
  BME280Readings.pres = pressure;

  // Send message via ESP-NOW
  esp_err_t result = esp_now_send(broadcastAddress, (uint8_t *) &BME280Readings, sizeof(BME280Readings));
   
  if (result == ESP_OK) {
    Serial.println("Sent with success");
  }
  else {
    Serial.println("Error sending the data");
  }
  updateDisplay();
  delay(10000);
}
void getReadings(){
  temperature = bme.readTemperature();
  humidity = bme.readHumidity();
  pressure = (bme.readPressure() / 100.0F);
}

void updateDisplay(){
  // Display Readings on OLED Display
  display.clearDisplay();
  display.setTextSize(1);
  display.setTextColor(WHITE);
  display.setCursor(0, 0);
  display.println("INCOMING READINGS");
  display.setCursor(0, 15);
  display.print("Temperature: ");
  display.print(incomingTemp);
  display.cp437(true);
  display.write(248);
  display.print("C");
  display.setCursor(0, 25);
  display.print("Humidity: ");
  display.print(incomingHum);
  display.print("%");
  display.setCursor(0, 35);
  display.print("Pressure: ");
  display.print(incomingPres);
  display.print("hPa");
  display.setCursor(0, 56);
  display.print(success);
  display.display();
  
  // Display Readings in Serial Monitor
  Serial.println("INCOMING READINGS");
  Serial.print("Temperature: ");
  Serial.print(incomingReadings.temp);
  Serial.println(" ºC");
  Serial.print("Humidity: ");
  Serial.print(incomingReadings.hum);
  Serial.println(" %");
  Serial.print("Pressure: ");
  Serial.print(incomingReadings.pres);
  Serial.println(" hPa");
  Serial.println();
}*/