import serial
import csv
from datetime import datetime

# CHANGE THIS COM PORT:
# Windows: "COM3", "COM4", etc
# Linux: "/dev/ttyUSB0"
# Mac: "/dev/tty.usbserial-xxxx"
PORT = "COM7"
BAUD = 115200

filename = "plant_co2_log.csv"

ser = serial.Serial(PORT, BAUD, timeout=1)

print("Logging started... Press CTRL+C to stop.")

with open(filename, "a", newline="") as file:
    writer = csv.writer(file)

    # Write header only once
    writer.writerow(["Timestamp", "CO2_ppM"])

    try:
        while True:
            line = ser.readline().decode("utf-8").strip()
            
            if line:
                print(line)

                parts = line.split(",")

                if len(parts) == 2:
                    timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
                    co2 = parts[1]

                    writer.writerow([timestamp, co2])
                    file.flush()   # ✅ Prevent data loss on crash

    except KeyboardInterrupt:
        print("\nLogging stopped.")
        ser.close()
