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

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

import sys
import rr
import time
import datetime
import os
import libxml2

import spec_fmc_adc
import fmc_adc


"""
test19_eeprom: Test eeprom data formatting

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


def main (default_directory = '.'):

    # Objects declaration
    spec = rr.Gennum() # bind to the SPEC board
    spec_fmc = spec_fmc_adc.CSpecFmcAdc100Ms(spec)
    fmc = fmc_adc.CFmcAdc100Ms(spec)

    ############################################################################
    # Append serial number and mfg date to XML file
    ############################################################################
    serial_filename = "../../../serial.txt"
    f_serial = open(serial_filename, 'r+')
    serial = f_serial.readline()
    f_serial.close()

    serial = serial[:-1] # remove EOL char
    print "serial number: %s"%serial
    serial = '+' + serial + '.0'

    # Calculate number of minutes since 1/1/96
    now_date = datetime.datetime.now()
    ref_date = datetime.datetime(1996, 1, 1)
    diff_date = now_date - ref_date
    minutes = "%d"%int(diff_date.total_seconds()//60)
    print "Mfg date/time: %s"%minutes

    sys.exit()

    xml_filename = "test19_eeprom_input.xml"
    doc = libxml2.parseFile(xml_filename)
    root = doc.getRootElement()
    area = root.children

    while area is not None:
        if area.type == "element":
            areaContent = area.children
            while areaContent is not None:
                if areaContent.type == "element":
                    if areaContent.prop('name') == "Board_serial_number":
                        areaContent.setProp('content', serial)
                        print "Board serial number %s written to XML file"%serial
                    if areaContent.prop('name') == "Mfg. Date/Time":
                        areaContent.setProp('content', minutes)
                        print "Mfg date/time %s written to XML file"%minutes
                areaContent=areaContent.next
        area=area.next

    f = open(xml_filename, 'w')
    doc.saveTo(f)
    f.close

    ############################################################################
    # Format FMC EEPROM data
    ############################################################################
    print "Formatting FMC EEPROM data"
    os.system("python fmc_eeprom_gen.py -i test19_eeprom_input.xml -o test19_formatted_data.txt -r test19_corr_data.txt")

    ############################################################################
    # Write data to FMC EEPROM
    ############################################################################
    in_filename = "test19_formatted_data.txt"
    eeprom_content = []
    eeprom_addr = []
    f_in = open(in_filename,"r+")
    for line in f_in:
        addr,data=line.split()
        eeprom_content.append(int(data,2))
        eeprom_addr.append(int(addr,2))
    if len(eeprom_content) == 0:
        print "[ERROR] Formatted data file is empty"
    else:
        byte_to_write = len(eeprom_content)
        addr = 0
        while byte_to_write:
            if byte_to_write > 32:
                size = 32
            else:
                size = byte_to_write
            fmc.sys_i2c_eeprom_write(addr,eeprom_content[addr:(addr+size)])
            byte_to_write -= size
            addr += size
            time.sleep(0.01) # have to wait between writes otherwise the eeprom gives NACK on the i2c bus
        print "Data written to FMC EEPROM"
    f_in.close()

    ############################################################################
    # Verify EEPROM data
    ############################################################################
    time.sleep(0.1)
    if len(eeprom_content) != 0:
        eeprom_content_read = fmc.sys_i2c_eeprom_read(0,len(eeprom_content))
        error = 0
        for i in range(len(eeprom_content)):
            if eeprom_content[i] != eeprom_content_read[i]:
                print "[ERROR] eeprom data corruption @ addr:%d expect:0x%.2X read:0x%.2X"%(i, eeprom_content[i], eeprom_content_read[i])
                error += 1
        if error == 0:
            print "Data verification OK!"



if __name__ == '__main__' :
    main()
