#!   /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




    
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")
    id = dut.get_unique_id()
    if id != -1:
        util.info_msg("Unique ID read from DS18B20: %.12X" % id)
    else:
        util.info_msg("Failed to read unique ID from DS18B20" % id)
    
    test_results['Get ID from DS18B20'] =  1 if id != -1 else 0
    
    ###############################################################################    
    
    if (id & 0xff) != 0x28:
        util.info_msg("Unique IDs LSB: 0x%X is different then 0x28 as specified in datasheet" % (id & 0xff))
    else:
        util.info_msg("Unique IDs match pattern specified in datasheet")
    
    test_results['DS18B20 ID verification'] =  1 if (id & 0xff) == 0x28 else 0
    
    ###############################################################################
    
    util.section_msg("Verification of temperature")
    
    temperature=dut.get_temp()
    
    util.info_msg("Read board temperature: %d" % temperature)
    
    if temperature > util.maxtemp:
        util.err_msg( "Temperature exceeds %d C" % util.maxtemp ) 
        test_results['Temperature value'] = 0
    
    elif temperature < util.mintemp:
        util.err_msg( "Temperature is lower then %d C" % util.mintemp )
        test_results['Temperature value'] = 0
    
    else:
        test_results['Temperature value'] = 1
                          
    ###############################################################################
    
    errors = util.summarise_test_results( testname, test_results)
    
    return 0
  

if __name__ == '__main__' :
    main()