#!   /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 os
import re
from ctypes import *

from ptsexcept import *

import cp210x_eeprom


"""
test21: Store calibration data to CP2103 EEPROM

The calibration box contains a voltage reference that has to
be calibrated for each input voltage range of the FmcAdc.
A multimeter of at least 6 digits has to be used for the
calibration. The result of the calibration is 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_RANGES = ['10V', '1V', '100mV']


def input_calibr_data(range_str):
    while(True):
        calibr_string = raw_input("Enter calibration voltage for "+range_str+" range (in volts, max 10 char): ")
        pattern = r'\b[0-9]\.[0-9]{8}\b'
        if re.search(pattern, calibr_string):
            return calibr_string
        else:
            print "[ERROR] Calibration string format is wrong, MUST be '\\b[0-9]\.[0-9]{8}\\b' (e.g 0.00000000).\n"
            continue


def main ():
    box_eeprom = cp210x_eeprom.CCP210x_Eeprom("%X"%BOX_USB_VENDOR_ID, "%X"%BOX_USB_PRODUCT_ID)

    # Ask user to input calibration data
    calibr_data = {}
    for range_str in CALIBR_RANGES:
        calibr_data[range_str] = input_calibr_data(range_str)

    # 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 range_str, value in calibr_data.iteritems():
        print "%5s range calibration voltage is: %s V" % (range_str, value)


if __name__ == '__main__' :
    main()
