#!   /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 cp210x_gpio
from PAGE.Agilent33250A import *
from PAGE.SineWaveform import *


"""
calibr_box: Access to calibration box via USB-UART bridge CP2103

"""


class CalibrBoxOperationError(Exception):
    def __init__(self, msg):
        self.msg = msg
    def __str__(self):
        return ("Calibration box: %s" %(self.msg))


class CCalibr_box:
	def __init__(self, device):
                self.cp210x = cp210x_gpio.CCP210x(device)
                # Select AWG as default output
                self.cp210x.gpio_set(0x0)

        def select_output(self, out):
                if('10V' == out):
                        self.cp210x.gpio_set(0xF)
                elif('1V' == out):
                        self.cp210x.gpio_set(0xD)
                elif('100mV' == out):
                        self.cp210x.gpio_set(0xC)
                elif('AWG' == out):
                        self.cp210x.gpio_set(0x0)
                else:
                        raise CalibrBoxOperationError("Invalid output selection!")

        # Select which channel is connected to AWG
        # others are set to Vref for the selected range
        # !! ONLY FOR BOX V2 !!
        def select_output_ch(self, channel, out='100mV'):
                if channel >= 1 and channel <= 4:
                        value = ((4-channel)<<2)
                else:
                        raise CalibrBoxOperationError("Invalid channel number, must be [1..4]!")
                #print hex(value)
                if('10V' == out):
                        value += 0x3
                elif('1V' == out):
                        value += 0x1
                elif('100mV' == out):
                        value += 0x0
                else:
                        raise CalibrBoxOperationError("Invalid output selection!")
                #print hex(value)
                self.cp210x.gpio_set(value)

        def get_config(self):
                return self.cp210x.gpio_get()
