#!   /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 time
import os

import cp210x_gpio
from unittest import case


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

"""

def set_bit(number, bit):
    number |= 1 << bit;

def clear_bit(number, bit):
    number &= ~(1 << bit);

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)
        self.set_fip_transmission()
        
    def update_gpio(self):
        self.cp210x.gpio_set(self.state);

    def set_fip_transmission( self ):
        # set VREF to GND
        # CH5 to SYNC
        self.state = 0x00;
        
        # connect CH3 (POS) to AWG IN
        # trigger gets connected to VREF
        self.state |= ( 0x01 << 2 )
        
        
        self.update_gpio()
    
    def trigger_input_low(self):
        # set VREF to GND
        # CH5 to SYNC
        self.state = 0x0
        
        # connect CH3 (POS) to AWG IN
        # trigger gets connected to VREF
        self.state |= ( 0x01 << 2 )
        
        self.update_gpio()
        
    def trigger_input_high(self):
        # set VREF to VDD
        # CH5 (NEG) gets connected to CH4 instead of SYNC
        self.state = 0x03
        
        # connect CH3 (POS) to AWG IN
        # trigger gets connected to VREF
        self.state |= ( 0x01 << 2 )
        
        self.update_gpio()
    
    def trigger_output_to_awg(self):
        # set VREF to VDD
        # CH5 to SYNC
        self.state = 0
        
        # CH1 to AWG IN
        # CH3 to VREF
        self.state |= ( 0x03 <<2 )
       
        self.update_gpio()

    def fip_disconnect(self):
        # set VREF to HIGH
        # CH5 to CH4
        self.state = ( 0x3 << 0 )
        
        # CH1 to AWG IN
        # CH3 to VREF
        self.state |= ( 0x03 <<2 )
       
        self.update_gpio()

