# Space Mariner - Virtual Mission data logger starter program
# Board:  Adafruit Feather RP2040 Adalogger (CircuitPython 9.x)
# Sensor: MS8607 pressure / temperature / humidity on the STEMMA QT port
# Prints a reading about once per second (watch it in Mu's Serial panel)
# and saves the same line to /sd/LOGnnn.csv on the microSD card.
# Required in CIRCUITPY/lib: adafruit_ms8607.mpy, adafruit_bus_device/ (folder)

import os
import time
import board
import busio
import sdcardio
import storage
import adafruit_ms8607

LOG_INTERVAL = 1.0   # <-- how often to log, in seconds (ages 13+: try changing this)

# ---- microSD (built-in slot on the Feather RP2040 Adalogger) ----
def mount_sd():
    try:
        spi_sd = busio.SPI(board.SD_CLK, board.SD_MOSI, board.SD_MISO)
        card = sdcardio.SDCard(spi_sd, board.SD_CS)
        vfs = storage.VfsFat(card)
        storage.mount(vfs, "/sd")
        return True
    except Exception as e:  # no card, or card not formatted FAT32
        print("microSD not found:", e)
        return False


def new_log_path(prefix):
    # Never overwrite an old flight: pick the first unused number.
    n = 0
    while True:
        path = "/sd/%s%03d.csv" % (prefix, n)
        try:
            os.stat(path)
            n += 1
        except OSError:
            return path


i2c = board.STEMMA_I2C()
sensor = adafruit_ms8607.MS8607(i2c)

path = new_log_path("LOG") if mount_sd() else None
if path:
    with open(path, "w") as f:
        f.write("seconds,pressure_hpa,temp_c,humidity_pct\n")
    print("Saving to", path)
else:
    print("No microSD card: showing readings only")

start = time.monotonic()
while True:
    secs = time.monotonic() - start
    p = sensor.pressure
    t = sensor.temperature
    rh = sensor.relative_humidity
    print("Pressure: %.2f hPa   Temp: %.1f C   Humidity: %.1f %%" % (p, t, rh))
    if path:
        # <-- this is the line that writes to the microSD card
        with open(path, "a") as f:
            f.write("%.1f,%.2f,%.2f,%.1f\n" % (secs, p, t, rh))
    time.sleep(LOG_INTERVAL)
