# Space Mariner - Mission 04 Payload Engineering UV / light logger
# Board:   Adafruit Feather RP2040 Adalogger (CircuitPython 9.x)
# Sensors: LTR390 UV (STEMMA QT, 0x53) chained to VEML7700 light (STEMMA QT, 0x10)
# Writes one line per second to /sd/UVnnn.csv:  seconds,uv_index,lux
# Required in CIRCUITPY/lib: adafruit_ltr390.mpy, adafruit_veml7700.mpy,
#   adafruit_bus_device/ (folder), adafruit_register/ (folder)

import os
import time
import board
import busio
import sdcardio
import storage
import adafruit_ltr390
import adafruit_veml7700

LOG_INTERVAL = 1.0

# ---- 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()
uv = None
light = None
try:
    uv = adafruit_ltr390.LTR390(i2c)
except Exception as e:
    print("LTR390 not found:", e)
try:
    light = adafruit_veml7700.VEML7700(i2c)
except Exception as e:
    print("VEML7700 not found:", e)

path = new_log_path("UV") if mount_sd() else None
if path:
    with open(path, "w") as f:
        f.write("seconds,uv_index,lux\n")
    print("Logging to", path)

start = time.monotonic()
next_t = start
while True:
    now = time.monotonic()
    if now < next_t:
        time.sleep(0.01)
        continue
    next_t += LOG_INTERVAL
    try:
        uvi = "%.2f" % uv.uvi if uv else ""
    except Exception:
        uvi = ""
    try:
        lux = "%.1f" % light.lux if light else ""
    except Exception:
        lux = ""
    line = "%d,%s,%s" % (int(now - start), uvi, lux)
    print(line)
    if path:
        try:
            with open(path, "a") as f:
                f.write(line + "\n")
        except OSError as e:
            print("SD write failed:", e)
