    #!   /usr/bin/env   python

# Copyright Creotech SA, 2015
# Author: Marek Guminski <marek.guminski@creotech.pl>
# Licence: GPL v2 or later.
# Website: http://www.ohwr.org


import sys
import time
import os
import time
import datetime
    

from spec import *
from ad9516 import *
from dac import *


from ptsexcept import *
from utilFunctions import *
from spec_identification import *

import numpy

"""
test11:
    Verify MCP9800 temperature measurements.
"""

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


def main (card=None, default_directory='.',suite=None, configure_fpga=True):

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

    carrier=spec( FIRMWARE_PATH, specid, configure_fpga );
       

    sys_pll = IC9(carrier)
    
    dacinst = dac(carrier)
    dacinst.set_frequency(10e6)

    vcxo_pll = IC26(carrier)
    cwd=os.path.dirname(os.path.realpath(__file__))
    vcxo_pll.write_config(load_config(cwd+'/../doc/new_ad9516_pts_test.stp'))

    vcxo_pll.check_lock()

    for chip in range(2):
        print "Doing 10 temperature measurements for chip nr %d:" %chip

        temp = []
        temp_str =""
        for i in range(10):
            temp.append( carrier.read_mpc9800_temperature(chip) )
            print "Temperature: %f oC" % temp[-1]
            temp_str += " "+str(temp[-1])
            time.sleep(0.5)

        MEAN_MIN = 40.
        MEAN_MAX = 80.
        PP = 5.

        if (numpy.mean(temp)>MEAN_MAX) or (numpy.mean(temp)<MEAN_MIN):
            raise Exception("Mean value of these measurements (%f) is out of expected range ( [%f,%f] )." %(numpy.mean(temp), MEAN_MIN, MEAN_MAX))

        if (numpy.max(temp)-numpy.min(temp))>PP:
            raise Exception("Peak-Peak temperature variation exceed expected value of %f" % PP )
        
    print "Measurements are within expected boundaries"
    return 0
        
if __name__ == '__main__' :
    
    import argparse

    parser = argparse.ArgumentParser(description='Start test11')
    parser.add_argument('-p', action='store_true')
    args = vars(parser.parse_args())

    if args['p']:
        main(configure_fpga=False)
    else:
        main()

