#!   /usr/bin/env   python

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


import spec
import fmcmasterfip as fmc
import utilities as util
import ptsexcept
import time
import sys


REPETITIONS = 20
DELAY = 0.5

    
def main (card=None, default_directory='.',suite=None, serial=""):
    testname= "Test04: DS18B20 thermometer"
    util.header_msg( testname, [ "DS18B20 communication" ] )
    
    box = util.calibration_box_init()
    
    util.section_msg("Hardware initialization")
    abspath = util.find_prj_topdir(util.TOPDIRNAME);
    carrier = spec.spec( abspath );
   
    
    test_results = {}
    
    # FPGA bitstream and FMC presence are verified during initialization
    # any error there causes critical error and test termination
    dut = fmc.fmcmasterfip(carrier, abspath, util.FIRMWARE_PATH)
    
    

    ###############################################################################
    util.section_msg("Reading and verifying unique ID")
    # thermometer is read by gateware in some time intervals
    # in order to avert using long sleep
    # DS18B20 core is polled in small intervals
    for i in xrange(REPETITIONS):
        
        time.sleep(DELAY)
        id = dut.get_unique_id()
        
        if (id & 0xff) == 0x28:
            util.info_msg("Unique IDs match pattern specified in datasheet")
            test_results['DS18B20 ID verification'] =  1
            break;
    # if correct ID is not found in 10 repetitions
    # it is assumed to be wrong
    else:
        util.info_msg("Unique IDs LSB: 0x%X is different then 0x28 as specified in datasheet" % (id & 0xff))
        test_results['DS18B20 ID verification'] =  0
    
    
    
    ###############################################################################
    
    util.section_msg("Verification of temperature")
    
    for i in xrange(REPETITIONS):
        
        time.sleep(DELAY)
        temperature = dut.get_temp()
        
        if (temperature >= util.mintemp) and (temperature <= util.maxtemp):
            util.info_msg("Read correct board temperature: %d" % temperature)
            test_results['Temperature value'] = 1
            break
    else:
        test_results['Temperature value'] = 0

        if temperature > util.maxtemp:
            util.err_msg( "Temperature exceeds %d C" % util.maxtemp ) 
        
        else :
            util.err_msg( "Temperature is lower then %d C" % util.mintemp )
    
    ###############################################################################
    
    errors = util.summarise_test_results( testname, test_results)
    
    sys.stdout.flush()
    return 0
  

if __name__ == '__main__' :
    main()