
# -*- coding: utf-8 -*-

import pycan.main as pycan
import math
from matplotlib.pyplot import *
import matplotlib.animation as animation
import numpy
import scipy.signal

sys=pycan.Sysam("SP5")
Umax = 1 # valeur maximale de la tension, à changer en fonction de l'intensité de la lumière
sys.config_entrees([0],[Umax])
fe=100.0 # fréquence d'échantillonnage
te=1.0/fe
N = 100000 # nombre d'échantillons total à acquérir
print(u"Durée de l'acquisition = %f s"%(N*te))
duree = 10.0 # durée des blocs
longueur_bloc = int(duree/te) # taille des blocs traités
nombre_blocs = int(N*te/duree)
nombre_echant = nombre_blocs*longueur_bloc

sys.config_echantillon_permanent(te*1e6,N)

n_tot = 0 # nombre d'échantillons acquis
n_bloc = 0 # nombre d'échantillons acquis dans un bloc

fig,ax = subplots()
t = numpy.arange(longueur_bloc)*te
u = numpy.zeros(longueur_bloc)

line0, = ax.plot(t,u)
ax.grid()
ax.axis([0,duree,-Umax,Umax])
ax.set_xlabel("t (s)")
u = numpy.array([],dtype=numpy.float32)

def animate(i):
    global sys,u,line0,n_tot,n_bloc,longueur_bloc
    data = sys.paquet(n_tot)
    u0 = data[1]
    n_tot += u0.size
    n_bloc += u0.size
    u = numpy.append(u,u0)
    if n_tot >= nombre_echant:
        print(u"Acquisition terminée") 
    if n_bloc > longueur_bloc: # si on a assez d'échantillons pour constituer un bloc
        u = u[0:longueur_bloc]
        n_bloc = 0
        line0.set_ydata(u)
        u = numpy.array([],dtype=numpy.float32)

sys.lancer_permanent()
        
ani = animation.FuncAnimation(fig,animate,frames=nombre_blocs,repeat=False,interval=duree*1000)    
show()
data = sys.paquet(0)
numpy.savetxt("data.txt",data)
sys.fermer()

            