import serial
from datetime import datetime

# Setup test result file output
# Getting the current date and time
dt = datetime.now()

# Get the timestamp
ts = datetime.timestamp(dt)
ts_c = ts + (86400 * 24107)
ts_i = int(ts_c)
ts_i_s = str(ts_i)
file_name = "NEXIO_RTC_KEEPALIVE_TEST_" + ts_i_s + ".csv"

# Datetime object containing current date and time
now = datetime.now()
 
# dd/mm/YY H:M:S
date_string = now.strftime("%d/%m/%Y")
time_string = now.strftime("%H:%M:%S")

# Create file
# Write Header
fileref = open(("/home/hwdept-testbench/Python/supercap_test_python/TEST_RESULTS/" + file_name), "a")
fileref.write("NEXIO RTC KEEP ALIVE TEST APPLICATION - TEST REPORT\r")
fileref.write("TEST UNIT:," + "10008\r")
fileref.write("TEST START DATE:," + date_string + "\r")
fileref.write("TEST START TIME:," + time_string + "\r")
fileref.write("DATE,TIME,VSCAP(V),VDD3V3(V)\r")
fileref.close()

ser = serial.Serial(port='/dev/ttyACM0', baudrate=115200)

while (True):
    # Check if incoming bytes are waiting to be read from the serial input buffer.
    if (ser.inWaiting() > 7):
        # read the bytes and convert from binary array to ASCII
        in_bytes = ser.read(ser.inWaiting())

        # Check is 'A' and 'R' sync bytes present
        if (in_bytes[0] == 0x41) and (in_bytes[1] == 0x52):
            rx_checksum = in_bytes[2]
            rx_checksum += in_bytes[3]
            rx_checksum += in_bytes[4]
            rx_checksum += in_bytes[5]

            rx_checksum = ~rx_checksum

            rx_checksum = rx_checksum & 0xffff

            rx_checksum_hold = (in_bytes[6] << 8) | in_bytes[7]

            if rx_checksum == rx_checksum_hold:
                v1_adc_raw = (in_bytes[2] << 8) | in_bytes[3]
                v2_adc_raw = (in_bytes[4] << 8) | in_bytes[5]

                adc_cal = 3.326 / 4095

                v1_adc = v1_adc_raw * adc_cal
                v2_adc = v2_adc_raw * adc_cal

                R1_1 = 21980
                R2_1 = 21990
                R1_2 = 21960
                R2_2 = 21970

                v1 = v1_adc / (R2_1 / (R1_1 + R2_1))
                v2 = v2_adc / (R2_2 / (R1_2 + R2_2))

                # Datetime object containing current date and time
                now = datetime.now()

                # dd/mm/YY H:M:S
                date_string = now.strftime("%d/%m/%Y")
                time_string = now.strftime("%H:%M:%S")

                # Write Results
                result_string = date_string + "," + time_string + "," + "{:.2f}".format(v1) + "," + "{:.2f}".format(v2) + "\r"

                fileref = open(("/home/hwdept-testbench/Python/supercap_test_python/TEST_RESULTS/" + file_name), "a")

                fileref.write(result_string) 

                fileref.close()

                print ("DATE: " + date_string + " | TIME: " + time_string + " | VSCAP: " + "{:.2f}".format(v1) + "| VDD3V3: " \
                    + "{:.2f}".format(v2))
