
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=20000.0 # fréquence de la numérisation
te=1.0/fe
N = 100 # 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-bande
fo=1000.0
omega_a=numpy.pi*fo/(fe/2)
r=0.98
b0=(1-r*r)*0.5
b=[b0,0,-b0]
a=[1,-2*r*numpy.cos(omega_a),r*r]
w,h =scipy.signal.freqz(b,a)
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(a,b)

sys.lancer_permanent(repetition=1) # lancement d'une acquisition sans fin

fig0,ax0 = subplots()
subplots_adjust(left=0.1, bottom=0.3)
t = numpy.arange(longueur_bloc)*te_r
u = numpy.zeros(longueur_bloc)
line0, = ax0.plot(t,u,'r')
line1, = ax0.plot(t,u,'b')
yticks(numpy.linspace(-10,10,21))
ax0.grid()
ax0.axis([0,duree*0.5,-Umax,Umax])
ax0.set_xlabel("t (s)")
fo = 1000
slider_fo = Slider(axes([0.1,0.15,0.8,0.03]),"f0",100,2000,valinit=fo)
def update_fo(va):
    global fo,fe,sys,r,a,b
    fo = slider_fo.val
    omega_a=numpy.pi*fo/(fe/2)
    a=[1,-2*r*numpy.cos(omega_a),r*r]
    sys.config_filtre(a,b)
slider_fo.on_changed(update_fo)
slider_r = Slider(axes([0.1,0.05,0.8,0.03]),"r",0.9,0.999,valinit=r,valfmt='%1.3f')
def update_r(val):
    global fo,fe,sys,r,a,b
    r = slider_r.val
    b0=(1-r*r)*0.5
    b=[b0,0,-b0]
    a=[1,-2*r*numpy.cos(omega_a),r*r]
    sys.config_filtre(a,b)
slider_r.on_changed(update_r)

def animate0(i): # tracé du signal
    global sys,line0,data,u,t
    data = sys.paquet(-1,reduction)
    if data.size!=0:
        u1=data[1]
        u2=data[2]
        i=0
        while u1[i]<0:
            i+=1
        while u1[i]>0:
            i+=1
        ta=t[i:N-1]
        ta=ta-ta[0]
        line0.set_ydata(u1[i:N-1])
        line0.set_xdata(ta)
        line1.set_ydata(u2[i:N-1])
        line1.set_xdata(ta)


ani0 = animation.FuncAnimation(fig0,animate0,frames=100,repeat=True,interval=duree*1000)

show(block=True)
sys.stopper_acquisition()
time.sleep(1)
sys.fermer() 
                  