#!/usr/bin/python
#coding: utf8

# Copyright CERN, 2012 (Seven Solutions S.L.)
# Author: Tomasz?
# Author: Richard Carrillo <rcarrillo(AT)sevensols.com>
# Licence: GPL v2 or later.
# Website: http://www.ohwr.org
# Website: http://www.sevensols.com
# Version: 1.0 (Last modifications: 29/4/2012)

from ptsexcept import *
from dio_fmc import *

import rr
import os


"""
test01: Check fmc-dio-5chttl-board digital thermometer operation
Conditions: Mezzanine presence line asserted (test00 passed)
User intervention required: No
Procedure details:
- Load firmware
- Test mezzanine presence line.
- Initialize the board OneWire device (digital thermometer (DS18B20))
- Check that DS18B20 is present and responds
- Check and store temperature sensor ID
- Check and store acquired temperature.
"""

class test01:
   def __init__(self, spec):
      """ Initialize the board and check PRESENT pin state """
      try:
         self.dio = CFmcDio(spec, 0x80000, True, False, False) # Init only the OneWire device
      except CFmcDioError as e:
         err_msg="While fmc-dio-5chttla initialization: "+str(e)
         if e.bus_name == "FMC":
            raise PtsCritical(err_msg) # Critical error: the fmc-dio-5chttl-board is apparently not present
         else:
            raise PtsError(err_msg) # Non-critical error: further tests could be performed successfully

   def test_temp(self):
      """ Check OneWire device response correctly and check temperature acquisition """
      try:
         print "  chip lasered code: {:x}".format(self.dio.get_unique_id())
      except CFmcDioError as e:
         print str(e)
         ret_error=["E","While getting DS18B20 I.C. unique ID: "+str(e)]
      else:
         try:
            ret_error=None # test completed successfully
            temper=self.dio.get_temp()
            print "  chip temperature: {:.2f}°C".format(temper)
            if temper > 50 or temper < 10:
               ret_error=["W","While getting temperature with DS18B20 I.C.: TSTWRN05: Strange temperature value measured"]
         except CFmcDioError as e:
            print str(e)
            ret_error=["E","While getting temperature with DS18B20 I.C.: "+str(e)]
      return ret_error

def main(default_directory="."):
   # Configure the FPGA using the program fpga_loader
   path_fpga_loader = '../firmwares/fpga_loader'
   path_firmware = '../firmwares/spec_top.bin'
   firmware_loader = os.path.join(default_directory, path_fpga_loader)
   bitstream = os.path.join(default_directory, path_firmware)
   print "Loading firmware: %s" % (firmware_loader + ' ' + bitstream)
   os.system( firmware_loader + ' ' + bitstream )

   # Load board library and open the corresponding device
   print "Loading hardware access library and opening device\n"
   spec = rr.Gennum()

   print "Test01 Start"

   init_test_time = time.time()
   print "Configuring and checking fmc-dio-5chttla board"
   test=test01(spec)
   print "\nChecking temperature acquisition I.C. (DS18B20)"
   ret_error=test.test_temp()

   end_test_time = time.time()
   print "\nEnd of Test01"
   print "RESULT: [{}]".format("FAIL" if ret_error and ret_error[0]=="E" else ("OK with warnings" if ret_error and ret_error[0]=="W" else "OK"))
   print 'Test01 elapsed time: {:.2f} seconds'.format(end_test_time-init_test_time)

   if ret_error:
      if ret_error[0]=="W": # Warning message returned by test funciton
         raise PtsWarning(ret_error[1])
      else:  # Error message returned by test funciton
         raise PtsError(ret_error[1])


if __name__ == "__main__":
    main(".")

