# 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
from matplotlib import pyplot as plt
import numpy as np

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

CONTROL_CHAR = 'h'  # trigger char for sending data configured on the board

# define the expected resulting function and plot it
AMP = 40000
TAU1 = 25
TAU2 = 8
def dexp(x):
    exp1 = AMP * np.exp(-x/TAU1)
    exp2 = AMP * np.exp(-x/TAU2)
    return exp1-exp2
x_coord = np.linspace(0,100,1000)
plt.plot(x_coord, dexp(x_coord), linestyle='dashed', linewidth='0.7', color='blue', label='expected')

# 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 control char in ascii encoding (single byte)
ser.write(CONTROL_CHAR.encode('ascii'))
# read the full content being sent
recieved = bytearray(ser.readall())
# 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)]

# plot the result (both the single points and the curve connecting them)
plt.plot(range(0,100), numbers, linewidth='0.8', color='orange', label='result')
plt.scatter(range(0,100), numbers, marker='+', color='orange')

plt.legend()
plt.grid(True)
plt.show()

ser.close()