#include <SPI.h>
#include <LoRa.h>
#include <Wire.h>
#include <Adafruit_BMP280.h>
#include <TinyGPS++.h>

// Pines LoRa para Heltec V2
#define SS      18
#define RST     14
#define DI0     26
#define BAND    868E6 // Frecuencia para Europa

Adafruit_BMP280 bmp; // Usa I2C (SDA=4, SCL=15 por defecto en Heltec)
TinyGPSPlus gps;

// Usamos el Hardware Serial 2 para el GPS
#define GPS_RX 17
#define GPS_TX 16

unsigned long lastSendTime = 0;

void setup() {
  Serial.begin(115200);
  Serial2.begin(9600, SERIAL_8N1, GPS_RX, GPS_TX);

  // Inicializar I2C para el BMP280
  Wire.begin(4, 15);
  if (!bmp.begin(0x76)) { // La dirección I2C suele ser 0x76 o 0x77
    Serial.println("No se encontró el sensor BMP280");
  } else {
    // Configuración recomendada para cambios de altitud rápidos
    bmp.setSampling(Adafruit_BMP280::MODE_NORMAL,
                    Adafruit_BMP280::SAMPLING_X2,
                    Adafruit_BMP280::SAMPLING_X16,
                    Adafruit_BMP280::FILTER_X16,
                    Adafruit_BMP280::STANDBY_MS_500);
  }

  // Inicializar LoRa
  LoRa.setPins(SS, RST, DI0);
  if (!LoRa.begin(BAND)) {
    Serial.println("Fallo al inicializar LoRa");
    while (1);
  }
  LoRa.setTxPower(20); // Máxima potencia
  Serial.println("Transmisor LoRa Iniciado.");
}

void loop() {
  // Alimentar al objeto GPS continuamente
  while (Serial2.available() > 0) {
    gps.encode(Serial2.read());
  }

  // Transmitir cada 1000 ms (1 segundo)
  if (millis() - lastSendTime > 1000) {
    lastSendTime = millis();

    float temp = bmp.readTemperature();
    float pres = bmp.readPressure() / 100.0; // hPa
    float alt_bmp = bmp.readAltitude(1013.25); // Ajustar QNH local el día del vuelo

    float lat = gps.location.isValid() ? gps.location.lat() : 0.0;
    float lon = gps.location.isValid() ? gps.location.lng() : 0.0;
    float alt_gps = gps.altitude.isValid() ? gps.altitude.meters() : 0.0;

    // Formato del paquete: Temp,Pres,AltBMP,Lat,Lon,AltGPS
    String payload = String(temp) + "," + String(pres) + "," + String(alt_bmp) + "," +
                     String(lat, 6) + "," + String(lon, 6) + "," + String(alt_gps);

    // Enviar paquete
    LoRa.beginPacket();
    LoRa.print(payload);
    LoRa.endPacket();

    Serial.println("Enviado: " + payload);
  }
}
