
import pycanum.main as pycan
import math
from matplotlib.pyplot import *
import matplotlib.animation as animation
import numpy
import scipy.signal
import time
import cmath


sys=pycan.Sysam("SP5")
Umax = 10.0
sys.config_entrees([0],[Umax])
fe=40000.0 # fréquence de la numérisation
te=1.0/fe
N = 1000 # nombre d'échantillons dans la liste circulaire (fenêtre d'analyse)
duree = N*te
print(u"Durée de la fenêtre = %f s"%(duree))
sys.config_echantillon_permanent(te*1e6,N)
reduction = 1 # réduction de la fréquence d'échantillonnage après filtrage
fe_r = fe/reduction
te_r = te*reduction
longueur_bloc = int(N/reduction)


#filtre passe-bas 
fc = 1000 # fréquence de coupure
b = scipy.signal.firwin(numtaps=40,cutoff=[fc/fe],nyq=0.5,window='hann')
w,h =scipy.signal.freqz(b)
g = numpy.absolute(h)
phase = numpy.unwrap(numpy.angle(h))
figure()
plot(w/(2*math.pi)*fe,g)
xlabel("f (Hz)")
ylabel("G")
grid()
figure()
plot(w/(2*math.pi)*fe,phase)
xlabel("f (Hz)")
ylabel("phi")
grid()
show() # tracé de la réponse fréquentielle du filtre
sys.config_filtre([1],b)

sys.lancer_permanent(repetition=1) # lancement d'une acquisition sans fin

fig0,ax0 = subplots()
t = numpy.arange(longueur_bloc)*te_r
u = numpy.zeros(longueur_bloc)
line0, = ax0.plot(t,u,'r')
line1, = ax0.plot(t,u,'b')
ax0.grid()
ax0.axis([0,duree,-Umax,Umax])
ax0.set_xlabel("t (s)")

fig1,ax1 = subplots()
freq = numpy.arange(longueur_bloc)*1.0/duree
A = numpy.zeros(longueur_bloc)
line2, = ax1.plot(freq,A)
ax1.grid()
ax1.axis([0,fe/reduction,0,1.0])
ax1.set_xlabel("f (Hz)")

def animate0(i): # tracé du signal
    global sys,line0,data,u
    data = sys.paquet(-1,reduction)
    if data.size!=0:
        u = data[1]
        line0.set_ydata(u)
        line1.set_ydata(data[2])

def animate1(i): # tracé du spectre
    global line1,u
    if u.size==longueur_bloc:
        A = numpy.absolute(numpy.fft.fft(u))/longueur_bloc
        line2.set_ydata(A)

ani0 = animation.FuncAnimation(fig0,animate0,frames=100,repeat=True,interval=duree*1000)
ani1 = animation.FuncAnimation(fig1,animate1,frames=100,repeat=True,interval=duree*1000)
show(block=True)
sys.stopper_acquisition()
time.sleep(1)
sys.fermer()
                 