#!   /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
# Last modifications: 4/6/2012

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

# Add common modules and libraries location to path
sys.path.append('../../../../')
sys.path.append('../../../../gnurabbit/python/')
sys.path.append('../../../../common/')
sys.path.append('usb_box')
sys.path.append('cp210x')

# Import common modules
from ptsexcept import *
import rr

# Import specific modules
from cp210x_eeprom import *


"""
test21: Store calibration data to CP2103 EEPROM

The lengths of the channels of the calibration box
have to be calculated. A reference TDC board needs to be used for the calibration.
Once the calibration values are calculated, the values are stored in the
cp2103 EEPROM.

"""


# Calibration box vendor and product IDs
BOX_USB_VENDOR_ID = 0x10c4  # Cygnal Integrated Products, Inc.
BOX_USB_PRODUCT_ID = 0xea60 # CP210x Composite Device

CALIBR_CHANNELS = ['ch1-ch2', 'ch1-ch3', 'ch1-ch4', 'ch1-ch5']


def input_calibr_data(channel):
    while(True):
        calibr_string = raw_input("Enter calibration for "+channel+" (ps, format 000.00): ")
        pattern = r'\b[0-9]{3}\.[0-9]{2}\b'
        if re.search(pattern, calibr_string):
            return calibr_string
        else:
            print "[ERROR] Calibration string format is wrong, MUST be '\\b[0-9]{3}\.[0-9]{2}\\b' (e.g 000.00).\n"
            continue


def main ():

    try:

        box_eeprom = CCP210x_Eeprom("%X"%BOX_USB_VENDOR_ID, "%X"%BOX_USB_PRODUCT_ID)

        # Ask user to input calibration data
        calibr_data = {}
        for channel in CALIBR_CHANNELS:
            calibr_data[channel] = input_calibr_data(channel)
        print calibr_data

        # Write calibration data to cp210x EEPROM
        box_eeprom.set_calibr_data(calibr_data)

        print "Readback calibration data from cp210x EEPROM."
        calibr_data = box_eeprom.get_calibr_data()
        for channel, value in calibr_data.iteritems():
            print "%5s calibration value is: %s ps" % (channel, value)

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


if __name__ == '__main__' :
    main()
