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

# Copyright CERN, 2013
# Author: Matthieu Cattin <matthieu.cattin@cern.ch>
# Licence: GPL v2 or later.
# Website: http://www.ohwr.org

# Import system modules
import sys
import time
import datetime
import os

# Import specific modules
from fmc_adc_spec import *
from fmc_adc import *

# Import common modules
from ptsexcept import *
from fmc_eeprom import *
import rr


"""
test29: Checks FMC EEPROM for existing data

Note: Requires test00.py to run first to load the gateware!

"""

def main (default_directory='.'):

    # Constants declaration
    TEST_NB = 29
    EXPECTED_BITSTREAM_TYPE = 0x1
    PART_NUMBER = "EDA-02063-V5-0"
    SERIAL_FILENAME = "../../../serial.txt"
    SERIAL_FILENAME = os.path.join(default_directory, SERIAL_FILENAME)
    CALIBR_FILENAME = "calibration_data.txt"
    CALIBR_FILENAME = os.path.join(default_directory, CALIBR_FILENAME)
    SDBFS_DIR = "sdbfs/"
    SDBFS_DIR = os.path.join(default_directory, SDBFS_DIR)
    IPMI_BIN_FILENAME = SDBFS_DIR + "ipmi.sdb"
    CALIBR_BIN_FILENAME = SDBFS_DIR + "calibration.sdb"
    EEPROM_BIN_FILENAME = "eeprom_content.out"
    EEPROM_BIN_FILENAME = os.path.join(default_directory, EEPROM_BIN_FILENAME)
    EEPROM_SIZE = 8192 # in Bytes


    start_test_time = time.time()
    print "================================================================================"
    print "Test%02d start\n" % TEST_NB

    # SPEC object declaration
    print "Loading hardware access library and opening device.\n"
    spec = rr.Gennum()

    # Carrier object declaration (SPEC board specific part)
    try:
        carrier = CFmcAdc100mSpec(spec, EXPECTED_BITSTREAM_TYPE)
    except FmcAdc100mSpecOperationError as e:
        raise PtsCritical("Carrier init failed, test stopped: %s" % e)

    # Mezzanine object declaration (FmcAdc100m14b4cha board specific part)
    try:
        fmc = CFmcAdc100m(spec)
    except FmcAdc100mOperationError as e:
        raise PtsCritical("Mezzanine init failed, test stopped: %s" % e)


    ###########################################################################
    # Real test stuff here
    try:

        #==================================================
        # Calculate number of minutes since 0:00 1/1/96
        now_date = datetime.datetime.now()
        ref_date = datetime.datetime(1996, 1, 1)
        diff_date = now_date - ref_date
        current_date_min = int(diff_date.total_seconds()//60)
        print("Current date/time: %s"%(str(now_date)))
        print(" -> %d minutes (since 0:00 1/1/96)\n" % current_date_min)

        ################################################################################
        # Check if a manufacturing date is present in the EEPROM.
        # If not, put the current date (it means it's the first time the test is run).
        # If a date is present, keep it.

        # EEPROM clear code used to test the test!
        #eeprom_data = [0x0] * EEPROM_SIZE
        #fmc.sys_i2c_eeprom_write(eeprom_data)

        # Read entire EEPROM
        #print "Read EEPROM content."
        eeprom_data_read = fmc.sys_i2c_eeprom_read(0, EEPROM_SIZE)

        # Write EEPROM data to binary file
        #print "Write EEPROM content to file (binary)."
        f_eeprom = open(EEPROM_BIN_FILENAME, "wb")
        for byte in eeprom_data_read:
            f_eeprom.write(chr(byte))
        f_eeprom.close()


        # Read eeprom content from binary file
        f_bin_eeprom = open(EEPROM_BIN_FILENAME, "rb")
        eeprom_data = []
        byte = f_bin_eeprom.read(1) # reads one byte
        while byte:
            eeprom_data.append(ord(byte))
            byte = f_bin_eeprom.read(1) # reads one byte
        f_bin_eeprom.close()

        # Dump EEPROM content to log
        print("Content read from eeprom (length=%d (0x%X)):"%(len(eeprom_data), len(eeprom_data)))
        for i in range(len(eeprom_data)/16):
            print("0x%04X"%(i*16)),
            for j in range(16):
                print("%02X"%eeprom_data[(i*16)+j]),
            print("")

        # Get manufacturing date from EEPROM data, if exists
        print "Get manufacturing date from EEPROM.\n"
        eeprom_data = open(EEPROM_BIN_FILENAME, "rb").read()
        mfg_date_min = ipmi_get_mfg_date(eeprom_data)
        ref_date = datetime.datetime(1996, 1, 1)
        mfg_date = ref_date + datetime.timedelta(minutes=mfg_date_min)
        print("Mfg date read from eeprom: %s"%(str(mfg_date)))
        print(" -> 0x%06X = %d minutes (since 0:00 1/1/96)\n"%(mfg_date_min, mfg_date_min))

        # No manufacturing date present in EEPROM, put the current date
        if(mfg_date_min == 0 | mfg_date_min == 0xffffff):
            print "No manufacturing date found in the EEPROM => taking current date: %d\n" % current_date_min
            mfg_date = current_date_min
        elif(mfg_date > ref_date):
            print "Date found in the EEPROM is in the future => taking current date: %d\n" % current_date_min
            mfg_date = current_date_min
        else:
            print "Manufacturing date found in EEPROM: %d (will be preserved)\n" % mfg_date_min

        # List sdbfs files
        cmd = 'sdb-read -e 0x200 -l ' + EEPROM_BIN_FILENAME
        print("cmd: %s"%(cmd))
        os.system(cmd)



    except FmcAdc100mOperationError as e:
        raise PtsError("Test failed: %s" % e)

    ###########################################################################

    print ""
    print "==> End of test%02d" % TEST_NB
    print "================================================================================"
    end_test_time = time.time()
    print "Test%02d elapsed time: %.2f seconds\n" % (TEST_NB, end_test_time-start_test_time)

    # Check if an error occured during EEPROM verification
    #if(mismatch != 0):
    #    raise PtsError("EEPROM comparison failed: %d mismatch found. Check log for details." % mismatch)


if __name__ == '__main__' :
    main()
