# contact ST32 microcontroller via serial,
# gather the single bytes we recieve and put them together (two by two),
# plot the 16bits numbers.

import serial
import sys
import time

from serial_helpers import vrefint_conv_plot, temp_conv_plot, generic_plot

SERIAL_PORT = '/dev/ttyACM0'
BAUDRATE = 115200
TIMEOUT = 1

ACQ_CHAR = 'a'  # trigger char for acquiring data configured on the board
RCV_CHAR = 's'  # trigger char for sending data configured on the board

# init serial port
try:
    ser = serial.Serial(SERIAL_PORT, BAUDRATE, timeout=TIMEOUT)
except serial.SerialException as e:
    print(f"Serial port init error: {e}")
    sys.exit(1)

# send the acquisition char in ascii encoding (single byte)
ser.write(ACQ_CHAR.encode('ascii'))
time.sleep(1.5)
# send the receiving char in ascii encoding (single byte)
ser.write(RCV_CHAR.encode('ascii'))

# read the full content being sent
recieved = bytearray(ser.readall())

decoded = str(recieved.decode('latin1')).strip()

# check if i recieve a 'special code' telling me i still have to wait (string 'NA' in my case)
if decoded == 'NA':
    print('Dati non ancora disponibili!')
    sys.exit(0)

# join the bytes two by two to get numbers back
# (note: they were stored with little endianess i think, so set appropriate 'byteorder' value)
numbers = [int.from_bytes(recieved[i:i+2], byteorder='little', signed=False) for i in range(0,len(recieved),2)]

trigger_point = numbers[100]
numbers = numbers[0:100]
begin = (trigger_point + 70) % 100
numbers = numbers[begin:100] + numbers[0:begin]

# put here the relevant convert/plot function from serial_helpers
#vrefint_conv_plot(numbers)  # evaluate Vrefint
generic_plot(numbers, trigger_point, 10e-6)
ser.close()