import serial
import csv
import time
from datetime import datetime

# ¡ATENCIÓN! Cambia 'COM3' por el puerto de tu TTGO (ej. '/dev/ttyUSB0' en Linux)
PUERTO_SERIAL = '/dev/ttyUSB0'
BAUD_RATE = 115200
ARCHIVO_CSV = 'cansat_data.csv'

# Inicializar CSV con cabeceras
with open(ARCHIVO_CSV, mode='w', newline='') as file:
    writer = csv.writer(file)
    writer.writerow(["Timestamp", "Temp", "Pres", "AltBMP", "Lat", "Lon", "AltGPS"])

try:
    ser = serial.Serial(PUERTO_SERIAL, BAUD_RATE, timeout=1)
    print(f"Escuchando en {PUERTO_SERIAL}... Presiona Ctrl+C para detener.")

    while True:
        if ser.in_waiting > 0:
            linea = ser.readline().decode('utf-8').strip()
            # Validar que sea un paquete con 6 datos separados por comas
            datos = linea.split(',')
            if len(datos) == 6:
                timestamp = datetime.now().isoformat()
                fila = [timestamp] + datos

                with open(ARCHIVO_CSV, mode='a', newline='') as file:
                    writer = csv.writer(file)
                    writer.writerow(fila)
                print(f"Recibido y guardado: {fila}")
except KeyboardInterrupt:
    print("Captura detenida.")
except Exception as e:
    print(f"Error: {e}")
