#!/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

#for input_watcher
import numpy
import threading

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

        #create an input watcher for the measured delay
        self.msgq = gr.msg_queue(2)         # queue that holds a maximum of 2 messages
        self.queue_watcher = queue_watcher(self.msgq, self.set_delay_compensation)
        self.vblen = gr.sizeof_float*1# *self._length
	#self._s2v = gr.stream_to_vector(gr.sizeof_gr_complex, self._length)
        self.msqsink = gr.message_sink(self.vblen, self.msgq, False)

        # build graph
        self.scope_decim=10
        numsamples=self.scope_decim*2000/4
        start=-0.4#1.0e-1             #0.0 => 0 Hz
        end=  0.4 # 1.0 => 1 Mhz
        self.numsamples=numsamples
        self.freq_start=start
        self.freq_end=end
        self.freq_span=end-start
        #Make the sawtooth which is responsible for the freqeuncy of the vco and the x-deflection of the scope
        #sawtooth=self.generate_sawtooth_vector(numsamples,start,end)
        sawtooth=self.generate_triangle_vector(numsamples,start,end)

        usrp_decim = 64#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
        self.freq_gain_factor=float(usrp_rate)*1.0e-6
        delay_decim64=512+8
        delay_decim32=256+32
        delay=delay_decim64

        sawtooth_delayed=self.generate_modified_vector(sawtooth,delay=delay,gain=self.freq_gain_factor,offset=0.0)

        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-1
        self.vco=gr.frequency_modulator_fc(sensitivity/usrp_rate) 
        self.vco2=gr.frequency_modulator_fc(sensitivity/usrp_rate) 
        self.vco_gain=gr.multiply_const_cc(complex(12000,0))
        self.rms=gr.rms_cf(self.rms_alpha)

        self.delay_comp=gr.delay(gr.sizeof_float,4000)

        #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 )   	

        self.do_fmdemod2=True
        if self.do_fmdemod2:
          self.vco_conj=gr.conjugate_cc()
          self.mixer=gr.multiply_cc()
          max_dev2 = 1.0
          diff_alpha=1.0e-6
          fm_demod_gain2 = float(usrp_rate)*1.0e-6/(2*math.pi*max_dev2)
 
          fm2_bandwidth=float(usrp_rate)/1.0#float(usrp_rate)
          fm2_alpha = 0.25*fm2_bandwidth * math.pi / float(usrp_rate)
          fm2_beta = fm2_alpha * fm2_alpha / 4.0
          fm2_max_freq_hz=float(usrp_rate)
          fm2_max_freq_rps = 2.0*math.pi*fm2_max_freq_hz#/float(usrp_rate)
          self.fm_demod2=gr.quadrature_demod_cf (fm_demod_gain2 )              
          #self.fm_demod2 = gr.pll_freqdet_cf (fm2_alpha,fm2_beta,fm2_max_freq_rps,-fm2_max_freq_rps)
          self.diff_avg = gr.single_pole_iir_filter_ff (diff_alpha, 1) 
          self.compensated_freq = gr.add_ff()   
          self.freq_gain=gr.multiply_const_ff(self.freq_gain_factor)  
          self.freq_gain2=gr.multiply_const_ff(self.freq_gain_factor)
          self.diff_abs_a=gr.float_to_complex()   
          self.diff_abs_b=gr.complex_to_mag()
          self.diff_decim=gr.keep_one_in_n(gr.sizeof_float,numsamples*1000)
        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

        #build outgoing stream
        self.connect(self.vectorsource,self.vco,self.vco_gain,self.u_tx)
        #get level of incoming stream 
        self.connect(self.u_rx,self.rms)
        #build delay compensation
        #  get freq difference betweeen outgoing and incoming signal
        self.connect(self.u_rx,(self.mixer,0))
        self.connect(self.vectorsource,self.vco2,self.vco_conj,(self.mixer,1))
        self.connect(self.vectorsource,self.delay_comp)
        #self.connect(self.mixer,self.fm_demod2,self.diff_avg)
        #self.connect(self.diff_avg,(self.compensated_freq,0))
        #self.connect(self.vectorsource,self.freq_gain,(self.compensated_freq,1))
        self.connect(self.delay_comp,self.freq_gain)

        self.connect(self.mixer,self.fm_demod2,self.diff_abs_a,self.diff_abs_b,self.diff_avg,self.diff_decim)
        self.connect(self.diff_decim,self.msqsink)
        #self.connect(self.vectorsource,self.freq_gain)


        
        #  
        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 generate_sawtooth_vector(self,numsamples,start=-0.4,end=0.4):
        #numsamples=self.scope_decim*2000
        #start=-0.4#1.0e-1             #0.0 => 0 Hz
        #end=  0.4 # 1.0 => 1 Mhz
        #Make a sawtooth which is responsible for the frequency 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))
        return sawtooth

    def generate_triangle_vector(self,numsamples,start=-0.4,end=0.4):
        #numsamples=self.scope_decim*2000
        #start=-0.4# -0.4 => startfreq = -usrp_rate*0.4 Hz
        #end=  0.4 #  0.4 => endfreq   =  usrp_rate*0.4 Hz
        #Make a triangle which is responsible for the frequency of the vco and the x-deflection of the scope
        triangle=[]
        span=end-start
        half_num_samples=numsamples/2
        for i in range(1,half_num_samples):
          triangle.append(float(start)+float(i)*float(span)/float(half_num_samples))
        for i in range(1,half_num_samples):
          triangle.append(float(end)  -float(i)*float(span)/float(half_num_samples))
        return triangle

    def generate_modified_vector(self,input_vector,delay=0,gain=1.0,offset=0.0):
        #Generate a vector based on the input vector with samples delayed, each samples value is multiplied by gain and the offset is added
        #On the borders the samples are wrapped around (if delay !=0)
        #The delay may be negative
        numsamples=len(input_vector)

        output_vector=[]
        if delay>0:
          output_vector.extend(input_vector[delay:numsamples])
          output_vector.extend(input_vector[0:delay])
        elif delay<0:
          output_vector.extend(input_vector[-delay:numsamples])
          output_vector.extend(input_vector[0:-delay])
        else: #delay==0
          output_vector.extend(input_vector)

        for i in range(numsamples):
          output_vector[i]=output_vector[i]*float(gain)+float(offset)
        return output_vector

    def set_delay_compensation(self,delay):
        #self.delay_comp_compensated_xdata=generate_modified_vector(self.xdata,delay,1.0,0.0)

        delay_measured=self.numsamples*delay/self.freq_span
        print delay_measured
        self.delay_comp.set_delay(int(delay_measured))
        #self.frame.flow_graph().stop()
        #self.frame.flow_graph().start()
        return
        old_delay=self.delay_comp.delay()
        if delay_measured >1.0:
          diff_delay=int((delay_measured*10)/100) 
        else:
          diff_delay=0
        #diff_delay=int(delay_measured)/100
        new_delay=int((old_delay*90)/100) + diff_delay
        print "delay_measured",delay_measured," diff",diff_delay," old",old_delay,", new",new_delay
        self.delay_comp.set_delay(new_delay)
        
        
    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,3)) 
        #self.connect (self.compensated_freq, decim2,(self.scope,0)) 
        self.connect (self.freq_gain, decim2,(self.scope,0)) 
        decim3=gr.fir_filter_fff(self.scope_decim,[1.0])
        self.connect (self.fm_demod2,decim3,(self.scope,2))
        #decim4=gr.fir_filter_fff(self.scope_decim,[1.0])
        #self.connect (self.freq_gain,decim4,(self.scope,3))
        decim5=gr.fir_filter_fff(self.scope_decim,[1.0])
        self.connect (self.fm_demod, decim5,(self.scope,3)) 


        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.vco_gain,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"


#-----------------------------------------------------------------------
# Queue watcher.  Dispatches measured delay to callback.
#-----------------------------------------------------------------------
class queue_watcher (threading.Thread):
    def __init__ (self, msgq,  callback, **kwds):
        threading.Thread.__init__ (self, **kwds)
        self.setDaemon (1)
        self.msgq = msgq
        self.callback = callback
        self.keep_running = True
        self.start ()

    def run (self):
        while (self.keep_running):
            msg = self.msgq.delete_head()  # blocking read of message queue
            if self.callback:
              itemsize = int(msg.arg1())
              nitems = int(msg.arg2())

              s = msg.to_string()            # get the body of the msg as a string

              # There may be more than one number in the message.
              # If so, we take only the last one
              if nitems > 1:
                start = itemsize * (nitems - 1)
                s = s[start:start+itemsize]

              float_data = numpy.fromstring (s, numpy.float32)
              self.callback(float_data)
            else:
              print "ERROR: input_watcher received message, but has no callback defined."      

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