import sys
import time
import os
import time
from sys import __stdout__

import warnings
with warnings.catch_warnings():
    warnings.simplefilter("ignore", category=DeprecationWarning)
    import scipy
    import scipy.signal

import numpy
from pylab import *
from spec import *
from ad9516 import *
from dac import *
from ptsexcept import *

from spec_identification import *


FIRMWARE_PATH = '/../gateware/syn/spec_top.bin'
# WORK_PATH='/python/'
WORK_PATH='//'
LOG_PATH = 'log_fmcdac600m12b1chadds/tmp'

n_samples = 16384


specid = spec_identification()[0];
if specid < 0 :
    raise PtsCritical("Bus number of FmcDac600m12b1chadds was not found")

adcid = spec_identification()[1];
if adcid < 0 :
    raise PtsCritical("Bus number of FmcAdc100m14b was not found")


carrier=spec( FIRMWARE_PATH, specid, False );
sys_pll = IC9(carrier);
dacinst = dac(carrier);


def measure(bit,freq):

    if bit<9:
        urange="1"
    else:
        urange="10"


    n_repeat=1
    dacinst.set_en(1);
    dacinst.set_ampl_bit(1<<bit)
    dacinst.set_shape(dacinst.SHAPE_SQUARE);
    dacinst.set_frequency(freq);
    time.sleep(2)
    curr = os.getcwd()
    os.system(curr+WORK_PATH+"acq.sh "+str(n_samples*n_repeat)+" "+urange + " " + str( adcid ) +"")

    with open("/tmp/data.bin","rb") as fin:
        # Discard header
        x=fin.read(512) 
        # read samples from file
        # all the channels are triggered simultaneusly
        d=numpy.fromfile(file=fin,dtype=numpy.int16)
        print d[:50]
        figure(3)
        plot(d)
        d=d.reshape(n_samples*n_repeat,4)

        i=0
        # get the vector indexes
        y=range(n_samples*i,n_samples*(i+1))
        # get raw data

        for chan in range(4):
            raw = d[y,chan]
            figure(1)
            plot(raw, label='Chan %d'% chan)

            print raw[0:50]

            # detrend daw data
            dd=scipy.signal.detrend(raw)
            
            # calculate fft
            wt=abs(scipy.fft(dd))

            figure(2)
            plot(wt, label='Chan %d'% chan)

        figure(1)
        legend()
        figure(2)
        legend()

        show()