
import numpy as np
import matplotlib.pyplot as plt
from analog_0_1 import Device,AnalogInput,AnalogOutput
from scipy.signal.windows import get_window
from numpy.fft import fft
time sleep
             
def calculSpectre(s,Te,win,nz):
    # s : signal
    # Te : période d'échantillonnage 
    # win : fenêtrage
    # nz : nombre de blocs de zéros ajoutés
    N = len(s)
    if win=='rect':
        w = np.ones(N)
        a = 1.0
    elif win=='triang':
        w = get_window('triang',N)
        a = 0.5
    elif win=='hamming': 
        w = get_window('hamming',N)
        a = 0.54
    elif win=='hann':
        w = get_window('hann',N)
        a = 0.5
    elif win=='blackman':
        w = get_window('blackman',N)
        a = 0.42
    else:
        return None
    p = int(np.log(nz*N)/np.log(2))+1
    Np = 2**p
    u = np.zeros(Np)
    i1 = Np//2-(N-1)//2
    u[i1:i1+N] = s*w
    tfd = fft(u)*2/N/a
    freq = np.arange(Np)*1/(Np*Te)
    return freq,tfd              
             
freq = 5000
amp = 0.5
output.function(0,'sine',freq,amp)
output.start(0)
time.sleep(0.1)
fEchant = freq*100
duree = 100/freq
longueur = int(duree*fEchant)
time = analog.sampling(fEchant,longueur)
voltage = analog.record()
Ve = voltage[0,:]
Vs = voltage[1,:]
plt.figure()
plt.plot(time,Ve,label="Ve")
plt.plot(time,Vs,label="Vs")
plt.xlabel("t (s)",fontsize=16)
plt.ylabel("u (V)",fontsize=16)
plt.legend(loc="upper right",fontsize=16)
plt.xlim(0,4/freq)
plt.ylim(-1,1)
plt.grid()
Ve_eff = Ve.std()
Vs_eff = Vs.std()
valeurs = "Ve = %0.2f V, Vs = %0.2f V"%(Ve_eff,Vs_eff)
plt.title(valeurs)
print("Ve efficace = %f V"%Ve_eff)
print("Vs efficace = %f V"%Vs_eff)
Te = time[1]-time[0]
f,tfd_Ve = calculSpectre(Ve,Te,"blackman",8)
f,tfd_Vs = calculSpectre(Vs,Te,"blackman",8)
spectre_Ve = np.absolute(tfd_Ve)
spectre_Ve /= spectre_Ve.max()
spectre_Vs = np.absolute(tfd_Vs)
spectre_Vs /= spectre_Vs.max()
plt.figure()
plt.subplot(211)
plt.plot(f,20*np.log10(spectre_Ve),label="Ve")
plt.xlim(0,10*freq)
plt.ylabel("Ve",fontsize=16)
plt.grid()
plt.subplot(212)
plt.plot(f,20*np.log10(np.absolute(spectre_Vs)),label="Vs")
plt.xlabel("f (Hz)",fontsize=16)
plt.ylabel("Vs",fontsize=16)
plt.xlim(0,10*freq)
plt.grid()
plt.show()            
                