#!   /usr/bin/env   python

# Copyright Creotech SA, 2015
# Author: Marek Guminski <marek.guminski@creotech.pl>
# With small modifications from WZab ;-)
# Wojciech M. Zabolotny <wzab@ise.pw.edu.pl>
# This file just records files for different amplitudes and frequencies
# Licence: GPL v2 or later.
# Website: http://www.ohwr.org


import sys
import time
import os
import csr
import time
import numpy
from pylab import *
import scipy
import scipy.signal
#import scipy.io.numpyio as nio

from spec import *
from ad9516 import *
from dac import *
from ptsexcept import PtsCritical


"""
test01: 
    DAC tests
"""


FIRMWARE_PATH = '/../syn/spec_top.bin'


card=None
default_directory='.'
suite=None

delay = 0;

carrier=spec( FIRMWARE_PATH, 1, True );
    

sys_pll = ad9516(carrier);
gain="1"    
dacinst = dac(carrier);
n_samples = 16384
for i in [0,1,2,4,8,16,32,64,128,256,512,1024,2048,4096,8192]:
#for i in [1,2,4]:
  for f in ["10e6","13e6"]:
    dacinst.set_en(1);
    dacinst.set_ampl_bit(i)
    dacinst.set_shape(dacinst.SHAPE_SQUARE);
    dacinst.set_frequency(float(f));
    time.sleep(1.0)
    os.system("./acq.sh "+str(n_samples)+" "+gain)
    print i
    with open("data.bin","rb") as fin:
      x=fin.read(512) # Discard header
      d=numpy.fromfile(file=fin,dtype=numpy.int16).reshape(n_samples,4)
      for j in range(0,4):
         print str(j)+":"+str(d[:,j].mean())
      dd=scipy.signal.detrend(d[:,0])
      #dd=scipy.signal.detrend(dd)
      w=abs(scipy.fft(dd))
      plot(w)
      title("bit value="+str(i)+" frequency="+f)
      grid()
      savefig("widmo_u"+str(i)+"_f"+f+".png")
      #show()
      clf()



