#!/usr/bin/env python

from gnuradio import gr, gru, eng_notation, optfir
from gnuradio import audio
from gnuradio import usrp
from gnuradio import blks
from gnuradio.eng_option import eng_option
from gnuradio.wxgui import slider, powermate
from gnuradio.wxgui import stdgui, fftsink, scopesink,form
from optparse import OptionParser
try:
  import usrp_dbid
except:
  from usrpm import usrp_dbid

import sys
import math
import wx

def pick_subdevice(u):
    """
    The user didn't specify a subdevice on the command line.
    Try for one of these, in order: TV_RX, BASIC_RX, whatever is on side A.

    @return a subdev_spec
    """
    return usrp.pick_subdev(u, (usrp_dbid.TV_RX,
                                usrp_dbid.TV_RX_REV_2,
                                usrp_dbid.BASIC_RX))


class wobbelaar_graph (stdgui.gui_flow_graph):
    def __init__(self,frame,panel,vbox,argv):
        stdgui.gui_flow_graph.__init__ (self,frame,panel,vbox,argv)

        parser=OptionParser(option_class=eng_option)
        parser.add_option("-R", "--rx-subdev-spec", type="subdev", default=None,
                          help="select USRP Rx side A or B (default=A)")
        parser.add_option ("-T", "--tx-subdev-spec", type="subdev", default=(0, 0),
                       help="select USRP Tx side A or B")
        parser.add_option("-f", "--freq", type="eng_float", default=0.0,
                          help="set frequency to FREQ", metavar="FREQ")
        parser.add_option("-g", "--gain_rx", type="eng_float", default=None,
                          help="set RX gain in dB (default is midpoint)")
        parser.add_option("-G", "--gain_tx", type="eng_float", default=None,
                          help="set RX gain in dB (default is midpoint)")
        #parser.add_option("-V", "--volume", type="eng_float", default=None,
        #                  help="set volume (default is midpoint)")
        #parser.add_option("-O", "--audio-output", type="string", default="",
        #                  help="pcm device name.  E.g., hw:0,0 or surround51 or /dev/dsp")
        parser.add_option("-n", "--frame-decim", type="int", default=1,
                          help="set oscope frame decimation factor to n [default=1]")
        parser.add_option("-v", "--v-scale", type="eng_float", default=1000,
                          help="set oscope initial V/div to SCALE [default=%default]")
        parser.add_option("-t", "--t-scale", type="eng_float", default=49e-6,
                          help="set oscope initial s/div to SCALE [default=50us]")

        (options, args) = parser.parse_args()
        if len(args) != 0:
            parser.print_help()
            sys.exit(1)
        
        self.frame = frame
        self.panel = panel
        
        self.vol = 0
        self.state = "FREQ"
        self.freq = 0

        # build graph
        self.scope_decim=10
        numsamples=self.scope_decim*2000
        start=-0.4#1.0e-1             #0.0 => 0 Hz
        end=  0.4 # 1.0 => 1 Mhz
        #Make the sawtooth which is responsible for the freqeuncy of the vco and the x-deflection of the scope
        sawtooth=[]
        for i in range(1,numsamples):
          sawtooth.append(float(start)+float(i)*float(end-start)/float(numsamples))




        usrp_decim = 32#64
        usrp_interp=2*usrp_decim
        self.u_rx = usrp.source_c(which=0,decim_rate=usrp_decim)                    # usrp is data source
        self.u_tx = usrp.sink_c (which=0, interp_rate=usrp_interp)       # usrp is data sink
        adc_rate = self.u_rx.adc_rate()                # 64 MS/s

        usrp_rate = adc_rate / usrp_decim              # 1 MS/s or 2 MS/s

        delay_decim64=512+8
        delay_decim32=256+32
        delay=delay_decim64
        sawtooth_delayed=[]
        sawtooth_delayed.extend(sawtooth[delay:numsamples])
        sawtooth_delayed.extend(sawtooth[0:delay])
        for i in range(len(sawtooth_delayed)):
          sawtooth_delayed[i]=sawtooth_delayed[i]*float(usrp_rate)*1.0e-6

        self.vectorsource=gr.vector_source_f (sawtooth, True)
        self.vectorsource_delayed=gr.vector_source_f (sawtooth_delayed, True)
        #vco_f                   k=sensitivity/sampling_rate)
        #frequency_modulator_fc  k=sensitivity
        sensitivity=2*math.pi*float(usrp_rate)  # 1.0 => 1 Mhz for decim=64 1.0 => 2 Mhz for decim=32
        self.rms_alpha=1.0e-2
        self.vco=gr.frequency_modulator_fc(sensitivity/usrp_rate) 
        self.gain_internal=gr.multiply_const_cc(complex(12000,0))
        self.rms=gr.rms_cf(self.rms_alpha)

        #frequency demodulator, this should not have problems with different delays in the pc->usb->usrp->usb->pc path
        #problem is, it won't work with no signal and it won't work with float (only with complex)
        self.do_fmdemod=True
        if self.do_fmdemod:
          max_dev = 1.0
          fm_demod_gain = float(usrp_rate)*1.0e-6/(2*math.pi*max_dev)
          self.fm_demod=gr.quadrature_demod_cf (fm_demod_gain )   	
        
        if options.rx_subdev_spec is None:
            options.rx_subdev_spec = pick_subdevice(self.u_rx)

        self.u_rx.set_mux(usrp.determine_rx_mux_value(self.u_rx, options.rx_subdev_spec))
        self.subdev_rx = usrp.selected_subdev(self.u_rx, options.rx_subdev_spec)
        print "Using RX d'board %s" % (self.subdev_rx.side_and_name(),)


        # determine the daughterboard subdevice we're using
        if options.tx_subdev_spec is None:
          options.tx_subdev_spec = usrp.pick_tx_subdevice(self.u_tx)

        m = usrp.determine_tx_mux_value(self.u_tx, options.tx_subdev_spec)
        #print "mux = %#04x" % (m,)
        self.u_tx.set_mux(m)
        self.subdev_tx = usrp.selected_subdev(self.u_tx, options.tx_subdev_spec)
        print "Using TX d'board %s" % (self.subdev_tx.side_and_name(),)
    
        #self.subdev_tx.set_gain(self.subdev_tx.gain_range()[1])    # set max Tx gain

    
        self.subdev_tx.set_enable(True)                       # enable transmitter

        self.connect(self.vectorsource,self.vco,self.gain_internal,self.u_tx)
        self.connect(self.u_rx,self.rms)
        if self.do_fmdemod:
          self.connect(self.u_rx,self.fm_demod)


        #chan_filt_coeffs = optfir.low_pass (1,           # gain
        #                                    usrp_rate,   # sampling rate
        #                                    80e3,        # passband cutoff
        #                                    115e3,       # stopband cutoff
        #                                    0.1,         # passband ripple
        #                                    60)          # stopband attenuation
        ##print len(chan_filt_coeffs)
        #chan_filt = gr.fir_filter_ccf (chanfilt_decim, chan_filt_coeffs)

  
        # now wire it all together

        self._build_gui(vbox, usrp_rate,options)
       

        if options.gain_rx is None:
            # if no gain was specified, use the mid-point in dB
            g = self.subdev_rx.gain_range()
            options.gain_rx = float(g[0]+g[1])/2

        if options.gain_tx is None:
            # if no gain was specified, use the mid-point in dB
            g = self.subdev_tx.gain_range()
            options.gain_tx = float(g[0]+g[1])/2

            
        if abs(options.freq) < 1e6:
            options.freq *= 1e6

        # set initial values

        self.set_gain_rx(options.gain_rx)
        self.set_gain_tx(options.gain_tx)

        if not(self.set_freq(options.freq)):
            self._set_status_msg("Failed to set initial frequency")


    def _set_status_msg(self, msg, which=0):
        self.frame.GetStatusBar().SetStatusText(msg, which)


    def _build_gui(self, vbox, usrp_rate,options):

        def _form_set_freq(kv):
            return self.set_freq(kv['freq'])

        self.scope = scopesink.scope_sink_f(self, self.panel, sample_rate=usrp_rate/self.scope_decim,
                                            frame_decim=options.frame_decim,
                                            v_scale=options.v_scale,
                                            t_scale=options.t_scale)  
        vbox.Add (self.scope.win, 4, wx.EXPAND) 
        decim1=gr.fir_filter_fff(self.scope_decim,[1.0])
        decim2=gr.fir_filter_fff(self.scope_decim,[1.0])
        v_to_db=gr.nlog10_ff  	( 20.0,1,0)
        #usrp_delay=gr.skiphead (gr.sizeof_float, 16384)
        self.connect (self.rms,decim1, v_to_db,(self.scope,1))
        self.connect (self.vectorsource_delayed, decim2,(self.scope,0)) 

        if self.do_fmdemod:
          self.scope1 = scopesink.scope_sink_f(self, self.panel, sample_rate=usrp_rate/self.scope_decim,
                                            frame_decim=options.frame_decim,
                                            v_scale=options.v_scale,
                                            t_scale=options.t_scale)  
          vbox.Add (self.scope1.win, 4, wx.EXPAND) 
          #decim11=gr.fir_filter_fff(self.scope_decim,[1.0])
          decim21=gr.fir_filter_fff(self.scope_decim,[1.0])
          v_to_db1=gr.nlog10_ff  	( 20.0,1,0)
          #usrp_delay=gr.skiphead (gr.sizeof_float, 16384)
          self.connect ( v_to_db,(self.scope1,1))
          self.connect (self.fm_demod, decim21,(self.scope1,0)) 

        if 0:
          self.scope_int = scopesink.scope_sink_f(self, self.panel, sample_rate=usrp_rate,
                                            frame_decim=options.frame_decim,
                                            v_scale=options.v_scale,
                                            t_scale=options.t_scale)  
          vbox.Add (self.scope_int.win, 4, wx.EXPAND) 
          self.rms_int=gr.rms_cf(self.rms_alpha)
          self.connect(self.gain_internal,self.rms_int,(self.scope_int,1)) 
          self.connect (self.vectorsource, (self.scope_int,0)) 
  
        if 0:
            self.src_fft = fftsink.fft_sink_c (self, self.panel, title="Data from USRP",
                                               fft_size=512, sample_rate=usrp_rate)
            self.connect (self.u_rx, self.src_fft)
            vbox.Add (self.src_fft.win, 4, wx.EXPAND)


        
        # control area form at bottom
        self.myform = myform = form.form()

        hbox = wx.BoxSizer(wx.HORIZONTAL)
        hbox.Add((5,0), 0)
        myform['freq'] = form.float_field(
            parent=self.panel, sizer=hbox, label="Freq", weight=1,
            callback=myform.check_input_and_call(_form_set_freq, self._set_status_msg))

        hbox.Add((5,0), 0)
        myform['freq_slider'] = \
            form.quantized_slider_field(parent=self.panel, sizer=hbox, weight=3,
                                        range=(0.0e6, 32.0e6, 0.25e6),
                                        callback=self.set_freq)
        hbox.Add((5,0), 0)
        vbox.Add(hbox, 0, wx.EXPAND)

        hbox = wx.BoxSizer(wx.HORIZONTAL)
        hbox.Add((5,0), 0)

        myform['gain_rx'] = \
            form.quantized_slider_field(parent=self.panel, sizer=hbox, label="Gain_rx",
                                        weight=3, range=self.subdev_rx.gain_range(),
                                        callback=self.set_gain_rx)
        hbox.Add((5,0), 1)
        myform['gain_tx'] = \
            form.quantized_slider_field(parent=self.panel, sizer=hbox, label="Gain_tx",
                                        weight=3, range=self.subdev_tx.gain_range(),
                                        callback=self.set_gain_tx)

        hbox.Add((5,0), 0)
        vbox.Add(hbox, 0, wx.EXPAND)

        try:
            self.knob = powermate.powermate(self.frame)
            self.rot = 0
            powermate.EVT_POWERMATE_ROTATE (self.frame, self.on_rotate)
            powermate.EVT_POWERMATE_BUTTON (self.frame, self.on_button)
        except:
            print "FYI: No Powermate or Contour Knob found"


    def on_rotate (self, event):
        self.rot += event.delta
        if (self.state == "FREQ"):
            if self.rot >= 3:
                self.set_freq(self.freq + .1e6)
                self.rot -= 3
            elif self.rot <=-3:
                self.set_freq(self.freq - .1e6)
                self.rot += 3
            
    def on_button (self, event):
        if event.value == 0:        # button up
            return
        self.rot = 0
        if self.state == "FREQ":
            self.state = "FREQ"
        else:
            self.state = "FREQ"
        self.update_status_bar ()
        
                                        
    def set_freq(self, target_freq):
        """
        Set the center frequency we're interested in.

        @param target_freq: frequency in Hz
        @rypte: bool

        Tuning is a two step process.  First we ask the front-end to
        tune as close to the desired frequency as it can.  Then we use
        the result of that operation and our target_frequency to
        determine the value for the digital down converter.
        """
        r1 = usrp.tune(self.u_rx, 0, self.subdev_rx, target_freq)
        #r2 = usrp.tune(self.u_tx, 0, self.subdev_tx, target_freq)
        r2 = self.u_tx.tune(self.subdev_tx._which, self.subdev_tx, target_freq)        
        if r1 and r2:
            self.freq = target_freq
            self.myform['freq'].set_value(target_freq)         # update displayed value
            self.myform['freq_slider'].set_value(target_freq)  # update displayed value
            self.update_status_bar()
            self._set_status_msg("OK", 0)
            return True

        self._set_status_msg("Failed to set freq", 0)
        return False

    def set_gain_rx(self, gain_rx):
        self.myform['gain_rx'].set_value(gain_rx)     # update displayed value
        self.subdev_rx.set_gain(gain_rx)
        self.gain_rx=gain_rx

    def set_gain_tx(self, gain_tx):
        self.myform['gain_tx'].set_value(gain_tx)     # update displayed value
        self.subdev_tx.set_gain(gain_tx)
        self.gain_tx=gain_tx

    def update_status_bar (self):
        msg = "gain_rx:%r gain_tx:%r Setting:%s" % (self.gain_rx,self.gain_tx, self.state)
        self._set_status_msg(msg, 1)
        try:
          self.src_fft.set_baseband_freq(self.freq)
        except:
          None #print "no src fft"

        

if __name__ == '__main__':
    app = stdgui.stdapp (wobbelaar_graph, "USRP Wobbelaar")
    app.MainLoop ()

