

import sys
import random
import time
import csr
import i2c
import math
import os
import signal

from ctypes import *
from ptsexcept import *

from regs_lib import *
from ad9510_lib import *



#     print massage that have to be logged
def log( msg ):
    print msg

#     print question for user - doesn't need to be logged
def info( msg ):
    print msg
    
 
class adf4002:
    
    PIN_CLK     = 0;
    PIN_LE      = 1;
    PIN_DATA    = 2;
    PIN_LD      = 3;
    
    #    void adf4002_configure(struct wr_rf_device *dev, int r_div, int n_div, int mon_output)
    def __init__(self, carrier, muxout, ndiv=2, rdiv=2 ):
        
        self.ndiv = ndiv;
        self.rdiv = rdiv;
        self.muxout = muxout;
        self.carrier = carrier;
        
        # 2 least significant bits of data configuratinon register set
        
        # not sure why input clocks are divided
        # reference clock input divider
        self.write(( 0 << 0 ) | (rdiv << 2));
        
        # rf clock input divider
        self.write(( 1 << 0 ) | (ndiv << 8));
        
        # 15, 18 - charge pump current settings
        # 7 - positive polarization
        # 4 - muxout output function
        self.write( ( 2 << 0 ) | (7<<15) | (7<<18) | (1<<7) | ( muxout << 4)); 
       

    def write(self, value):
        self.gpio_set( self.PIN_CLK, 0);
        time.sleep(0.00001);
        self.gpio_set( self.PIN_LE, 0);
        time.sleep(0.00001);
        
        for i in range( 24 ):
        
            value <<= 1;
            self.gpio_set( self.PIN_DATA, 1 if value & (1<<24) else 0);
            time.sleep(0.00001);
            self.gpio_set( self.PIN_CLK, 1);
            time.sleep(0.00001);
            self.gpio_set( self.PIN_CLK, 0);
                
        
        self.gpio_set( self.PIN_LE, 1);
        time.sleep(0.00001);


    def gpio_set(self, pin, value):
        
        if pin == self.PIN_CLK:
            self.carrier.gpio_set( DDS_GPIOR_ADF_CLK(), value);
        elif pin == self.PIN_LE:
            self.carrier.gpio_set( DDS_GPIOR_ADF_LE(), value);
        elif pin == self.PIN_DATA:
            self.carrier.gpio_set( DDS_GPIOR_ADF_DATA(), value);
    
            
    def gpio_get(self, pin):
        if pin == self.PIN_CLK:
            return 1 if self.carrier.gpio_get( DDS_GPIOR_ADF_CLK() ) > 0 else 0;
        elif pin == self.PIN_LE:
            return 1 if self.carrier.gpio_get( DDS_GPIOR_ADF_LE() ) > 0 else 0;
        elif pin == self.PIN_DATA:
            return 1 if self.carrier.gpio_get( DDS_GPIOR_ADF_DATA() ) > 0 else 0;
        elif pin == self.PIN_LD:
            return 1 if self.carrier.gpio_get( DDS_GPIOR_ADF_LD() ) > 0 else 0;
            
        