
import pycanum.main as pycan
import numpy
import numpy.fft
from matplotlib.pyplot import *

sys = pycan.Sysam("SP5")


def mesure(a0,a1,f):
    global sys
    sys.config_entrees([0,1],[a0,a1])
    fe = f*200
    if fe > 1.0e7:
        fe = 1.0e7
    te = 1.0/fe
    ne = 40000
    print("fe = %f"%fe)
    T = ne*te
    print("T = %f"%T)
    sys.config_echantillon(te*1e6,ne)
    sys.acquerir()
    u=sys.entrees()
    t=sys.temps()[0]
    te = t[1]-t[0]
    Ue = u[0]
    Us = u[1]
    calibre_e = max(abs(numpy.max(Ue)),abs(numpy.min(Ue)))
    calibre_s = max(abs(numpy.max(Us)),abs(numpy.min(Us)))
    Ue=Ue-Ue.mean()
    Us=Us-Us.mean()
    spectre = numpy.absolute(numpy.fft.fft(Ue))
    freq = numpy.argmax(spectre[0:int(ne/2)])*1.0/(te*ne)
    print(freq)
    periode = 1.0/freq
    p = int(periode/te/4) # decalage quadrature
    Ve = numpy.roll(Ue,p,0)
    cos = numpy.mean(Ue*Us)
    sin = numpy.mean(Ve*Us)
    phi = -numpy.angle(cos+sin*1j)
    Uemax = numpy.std(Ue)*numpy.sqrt(2)
    Usmax = numpy.std(Us)*numpy.sqrt(2)              
    return (Uemax,Usmax,freq,phi,calibre_e,calibre_s)

liste_freq = []
liste_Ue = []
liste_Us = []
liste_phi = []
liste_freq = []

while True:
    r = input("Frequence approximative (Hz) (taper N pour finir) ?")
    if r=="N":
        break
    f= float(r)
    (a0,a1,f,phi,calibre_e,calibre_s) = mesure(10,10,f)
    (Uemax,Usmax,f,phi,calibre_e,calibre_s) = mesure(10,calibre_s*1.05,f)
    print("f = %.4e, Ue = %.4e, Us = %.4e, phi = %.4e"%(f,Uemax,Usmax,phi))
    liste_freq.append(f)
    liste_Ue.append(Uemax)
    liste_Us.append(Usmax)
    liste_phi.append(phi)
    
sys.fermer()

a_freq = numpy.array(liste_freq)
a_Ue = numpy.array(liste_Ue)
a_Us = numpy.array(liste_Us)
a_phi = numpy.array(liste_phi)


numpy.savetxt("reponseFreq-G30.txt",numpy.array([a_freq,a_Ue,a_Us,a_phi]).T,delimiter="\t",fmt="%.4e",header="f(Hz)\t Ue(V)\t Us(V)\t phi(rad)")

figure()
plot(a_freq,a_Us,"o")
xlabel("f (Hz)")
ylabel("Uc (V)")
grid()

figure()
plot(a_freq,a_phi,"o")
xlabel("f (Hz)")
ylabel("phi (rad)")
grid()

show(block=True)
                 