# -*- coding: utf-8 -*-
                 
import pycanum.main as pycan
import math
from matplotlib.pyplot import *
import matplotlib.animation as animation
import numpy
import scipy.signal
import time

sys=pycan.Sysam("SP5")
Umax = 2.0
sys.config_entrees([0],[Umax])
fe=40000.0
te=1.0/fe
duree_totale = 60.0
N = int(duree_totale*fe)
sys.config_echantillon_permanent(te*1e6,N)

duree = 0.05 # durée de la fenêtre du tracé
longueur_bloc = int(duree/te) 
nombre_blocs = int(N*te/duree)
nombre_echant = nombre_blocs*longueur_bloc 

# filtre intégrateur
r=0.995
b=[0.01,0,-0.01]
a=[1,-2*r,r*r]
sys.config_filtre(a,b)

sys.lancer_permanent()
n_tot = 0 

fig,ax = subplots()
subplots_adjust(left=0.1, bottom=0.3)
subplots_adjust(left=0.1, bottom=0.3)
line0, = ax.plot([0],[0],label="x")
line1, = ax.plot([0],[0],label="y")
ax.grid()
ax.axis([0,duree,-Umax,Umax])
ax.set_xlabel("t (s)")
ax.legend(loc="upper right")
axe_gain = axes([0.1,0.1,0.8,0.03])
gain = 1
slider_gain = Slider(axe_gain,"Gain (log)",-1,3,valinit=0)
def update_gain(val):
    global gain,ax,line1
    gain = 10**(slider_gain.val)
slider_gain.on_changed(update_gain)


x = numpy.array([],dtype=numpy.float32)
y = numpy.array([],dtype=numpy.float32)
t = numpy.array([],dtype=numpy.float32)

def animate(i):
    global ax,sys,x,y,t,line0,line1,n_tot,longueur_bloc,Umax,gain
    data = sys.paquet(n_tot)
    u0 = data[1]
    u1 = data[2]
    n_tot += u0.size
    x = numpy.append(x,u0)
    y = numpy.append(y,u1)
    t = numpy.append(t,data[0])
    if n_tot >= nombre_echant:
        print(u"Acquisition terminée")
    i2 = n_tot-1
    if n_tot == 0:
        return
    if n_tot > longueur_bloc:
        i1 = i2-longueur_bloc
    else:
        i1 = 0
    line0.set_data(t[i1:i2],x[i1:i2])
    line1.set_data(t[i1:i2],y[i1:i2]*gain)
    ax.axis([t[i1],t[i2],-Umax,Umax])
        

ani = animation.FuncAnimation(fig,animate,frames=nombre_blocs,repeat=True,interval=duree*100)    
show(block=True)
sys.stopper_acquisition()
time.sleep(1)
sys.fermer()
             
