from matplotlib import pyplot as plt
import numpy as np

VREFINT_CAL = 24175 # internal calibration value (Vref measured with precise 3.3v reference voltage)
VREF_CAL    = 3.306 # [Volts] rough estimate from the internal calibration data from factory

TEMP_30_CAL  = 12406
TEMP_110_CAL = 16472

def vrefint_conv_plot(numbers):
    '''
    convert ADC 16bit numbers to tension and evaluate internal reference voltage correction
    then plot the data
    '''
    N_MEAS = len(numbers)
    
    Vref_cal = (3.3*VREFINT_CAL)/np.mean(numbers)
    print(f'Calibrated reference voltage: {Vref_cal:.5f} V')
    print(f'Vref interno (calibrato): {(VREFINT_CAL*3.3)/2**16:.3f} V')
    # convert ADC read to voltage
    volts = [i*(Vref_cal/(2**16-1)) for i in numbers]
    mean = np.mean(volts)
    # plot the result (both the single points and the curve connecting them)
    x_coords = range(0,N_MEAS)
    plt.plot(x_coords, volts, linewidth='0.8', color='orange', label='result')
    plt.scatter(x_coords, volts, marker='+', color='orange')
    plt.hlines(mean, 0, N_MEAS, label=f'mean - {mean:.3f}V')

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


def temp_conv_plot(numbers):
    '''
    convert ADC 16bit numbers to temperature and plot the data
    '''
    slope = ((110-30)/(TEMP_110_CAL-TEMP_30_CAL))*1000
    N_MEAS = len(numbers)

    temps = [i*(VREF_CAL/2**16)*slope for i in numbers]
    mean = np.mean(temps)
    # plot the result (both the single points and the curve connecting them)
    x_coords = range(0,N_MEAS)
    plt.plot(x_coords, temps, linewidth='0.8', color='orange', label='result')
    plt.scatter(x_coords, temps, marker='+', color='orange')
    plt.hlines(mean, 0, N_MEAS, label=f'mean - {mean:.3f}℃')

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


def generic_plot(numbers, begin, SAMPLE_TIME):
    N_MEAS = len(numbers)
    # convert ADC read to voltage
    volts = [i*(VREF_CAL/(2**16-1)) for i in numbers]
    mean = np.mean(volts)
    # plot the result (both the single points and the curve connecting them)
    x_coords = np.linspace(0, (N_MEAS+1)*SAMPLE_TIME, N_MEAS)

    plt.plot(x_coords, volts, linewidth='0.8', color='orange', label='result')
    plt.scatter(x_coords, volts, marker='+', color='orange')
    #plt.hlines(mean, 0, N_MEAS*SAMPLE_TIME, label=f'mean - {mean:.3f}V')
    plt.vlines(30*SAMPLE_TIME, min(volts), max(volts))   # trigger point
    plt.legend()
    plt.grid(True)
    plt.show()
