import csv
import re
import time

import serial


def log_aos(log_path, device_port="COM2", device_baud=19200):

    ser = serial.Serial(device_port, device_baud)
    print(f"Logging data from {device_port} at baud {device_baud}.")

    while True:
        try:
            cc = ser.readline()
            timestamp = time.time()
            cc = cc.decode().strip()

            print(f"{timestamp:.3F}, {cc}")

            data = [int(s) for s in re.findall("[-\d]+", cc)]
            data.insert(0, timestamp)

            with open(log_path, mode='a', newline='') as f:
                csv_writer = csv.writer(f, delimiter=',')
                csv_writer.writerow(data)

        except KeyboardInterrupt:
            print("Aborting.")
            break


if __name__ == "__main__":
    from time import strftime

    start_pause = 30  # sec
    print("MBARI AOS Serial Logger.")
    print(f"Data logging will start in {start_pause} seconds.")
    time.sleep(start_pause)

    logfile_path = "C:/Users/kbblab/LRAUV/AOS_logs/AOS_{}.csv".format(strftime('%Y%m%dT%H%M%S'))
    log_aos(logfile_path)
