Exemple #1
0
    def __init__(self):
        gr.top_block.__init__(self)

        ##################################################
        # Variables
        ##################################################
        self.signal_freq = signal_freq = 5000
        self.samp_rate = samp_rate = 48000
        self.bw = bw = 200

        ##################################################
        # Blocks
        ##################################################
        self.gr_probe_ref = gr.probe_signal_f()
        self.gr_probe_mag = gr.probe_signal_f()
        self.gr_probe_arg = gr.probe_signal_f()
        self.gr_nlog10_ff_ref = gr.nlog10_ff(1, 1, 0)
        self.gr_nlog10_ff_0 = gr.nlog10_ff(1, 1, 0)
        self.gr_divide_xx_0 = gr.divide_cc(1)
        self.gr_complex_to_mag_ref = gr.complex_to_mag(1)
        self.gr_complex_to_mag_0 = gr.complex_to_mag(1)
        self.gr_complex_to_arg_0 = gr.complex_to_arg(1)
        self.band_pass_filter_0_0 = gr.fir_filter_fcc(
            1,
            firdes.complex_band_pass(
                1, samp_rate, signal_freq - bw / 2, signal_freq + bw / 2, 100, firdes.WIN_BLACKMAN, 6.76
            ),
        )
        self.band_pass_filter_0 = gr.fir_filter_fcc(
            1,
            firdes.complex_band_pass(
                1, samp_rate, signal_freq - bw / 2, signal_freq + bw / 2, 100, firdes.WIN_BLACKMAN, 6.76
            ),
        )
        self.audio_source_0 = audio.source(samp_rate, "", True)

        ##################################################
        # Connections
        ##################################################
        self.connect((self.band_pass_filter_0_0, 0), (self.gr_complex_to_mag_0, 0))
        self.connect((self.gr_complex_to_mag_0, 0), (self.gr_nlog10_ff_0, 0))
        self.connect((self.gr_divide_xx_0, 0), (self.gr_complex_to_arg_0, 0))
        self.connect((self.band_pass_filter_0_0, 0), (self.gr_divide_xx_0, 0))
        self.connect((self.band_pass_filter_0, 0), (self.gr_divide_xx_0, 1))
        self.connect((self.audio_source_0, 1), (self.band_pass_filter_0_0, 0))
        self.connect((self.audio_source_0, 0), (self.band_pass_filter_0, 0))
        self.connect((self.gr_nlog10_ff_0, 0), (self.gr_probe_mag, 0))
        self.connect((self.gr_complex_to_arg_0, 0), (self.gr_probe_arg, 0))

        self.connect((self.band_pass_filter_0, 0), (self.gr_complex_to_mag_ref, 0))
        self.connect((self.gr_complex_to_mag_ref, 0), (self.gr_nlog10_ff_ref, 0))
        self.connect((self.gr_nlog10_ff_ref, 0), (self.gr_probe_ref, 0))
Exemple #2
0
    def supply_rx_baseband(self):
        ## RX Spectrum
        if self.__dict__.has_key('rx_baseband'):
            return self.rx_baseband

        config = self.config

        fftlen = config.fft_length

        my_window = window.hamming(fftlen)  #.blackmanharris(fftlen)
        rxs_sampler = vector_sampler(gr.sizeof_gr_complex, fftlen)
        rxs_trigger = blocks.vector_source_b(concatenate([[1], [0] * 199]),
                                             True)
        rxs_window = blocks.multiply_const_vcc(my_window)
        rxs_spectrum = gr.fft_vcc(fftlen, True, [], True)
        rxs_mag = gr.complex_to_mag(fftlen)
        rxs_avg = gr.single_pole_iir_filter_ff(0.01, fftlen)
        rxs_logdb = gr.nlog10_ff(20.0, fftlen, -20 * log10(fftlen))
        rxs_decimate_rate = gr.keep_one_in_n(gr.sizeof_float * fftlen, 50)

        t = self.u if self.filter is None else self.filter
        self.connect(rxs_trigger, (rxs_sampler, 1))
        self.connect(t, rxs_sampler, rxs_window, rxs_spectrum, rxs_mag,
                     rxs_avg, rxs_logdb, rxs_decimate_rate)
        if self._options.log:
            log_to_file(self, rxs_decimate_rate, "data/supply_rx.float")
        self.rx_baseband = rxs_decimate_rate
        return rxs_decimate_rate
Exemple #3
0
    def __init__(self, fg, parent, baseband_freq=0,
                 y_per_div=10, ref_level=100, sample_rate=1, fft_size=512,
                 fft_rate=20, average=False, avg_alpha=None, title='',
                 size=default_fftsink_size):

        fft_sink_base.__init__(self, input_is_real=True, baseband_freq=baseband_freq,
                               y_per_div=y_per_div, ref_level=ref_level,
                               sample_rate=sample_rate, fft_size=fft_size,
                               fft_rate=fft_rate,
                               average=average, avg_alpha=avg_alpha, title=title)
                               
        s2p = gr.serial_to_parallel(gr.sizeof_float, fft_size)
        one_in_n = gr.keep_one_in_n(gr.sizeof_float * fft_size,
                                     int(sample_rate/fft_size/fft_rate))

        mywindow = window.blackmanharris(fft_size)
        fft = gr.fft_vfc(self.fft_size, True, mywindow)
        #fft = gr.fft_vfc(fft_size, True, True)
        c2mag = gr.complex_to_mag(fft_size)
        self.avg = gr.single_pole_iir_filter_ff(1.0, fft_size)
        log = gr.nlog10_ff(20, fft_size)
        sink = gr.file_descriptor_sink(gr.sizeof_float * fft_size, self.w_fd)

        fg.connect (s2p, one_in_n, fft, c2mag, self.avg, log, sink)
        gr.hier_block.__init__(self, fg, s2p, sink)

        self.fg = fg
        self.gl_fft_window(self)
    def __init__(self, fg, parent, baseband_freq=0,
                 y_per_div=10, ref_level=50, sample_rate=1, fft_size=512,
                 fft_rate=default_fft_rate, average=False, avg_alpha=None,
                 title='', size=default_fftsink_size, peak_hold=False):

        fft_sink_base.__init__(self, input_is_real=True, baseband_freq=baseband_freq,
                               y_per_div=y_per_div, ref_level=ref_level,
                               sample_rate=sample_rate, fft_size=fft_size,
                               fft_rate=fft_rate,
                               average=average, avg_alpha=avg_alpha, title=title,
                               peak_hold=peak_hold)
                               
        s2p = gr.stream_to_vector(gr.sizeof_float, self.fft_size)
        self.one_in_n = gr.keep_one_in_n(gr.sizeof_float * self.fft_size,
                                         max(1, int(self.sample_rate/self.fft_size/self.fft_rate)))

        mywindow = window.blackmanharris(self.fft_size)
        fft = gr.fft_vfc(self.fft_size, True, mywindow)
        power = 0
        for tap in mywindow:
            power += tap*tap
            
        c2mag = gr.complex_to_mag(self.fft_size)
        self.avg = gr.single_pole_iir_filter_ff(1.0, self.fft_size)

        # FIXME  We need to add 3dB to all bins but the DC bin
        log = gr.nlog10_ff(20, self.fft_size,
                           -20*math.log10(self.fft_size)-10*math.log10(power/self.fft_size))
        sink = gr.message_sink(gr.sizeof_float * self.fft_size, self.msgq, True)

        fg.connect (s2p, self.one_in_n, fft, c2mag, self.avg, log, sink)
        gr.hier_block.__init__(self, fg, s2p, sink)

        self.win = fft_window(self, parent, size=size)
        self.set_average(self.average)
    def __init__(self, parent, baseband_freq=0,
                 y_per_div=10, ref_level=50, sample_rate=1, fft_size=512,
                 fft_rate=default_fft_rate, average=False, avg_alpha=None,
                 title='', size=default_fftsink_size, **kwargs):

        gr.hier_block2.__init__(self, "waterfall_sink_f",
                                gr.io_signature(1, 1, gr.sizeof_float),
                                gr.io_signature(0,0,0))

        waterfall_sink_base.__init__(self, input_is_real=True, baseband_freq=baseband_freq,
                               sample_rate=sample_rate, fft_size=fft_size,
                               fft_rate=fft_rate,
                               average=average, avg_alpha=avg_alpha, title=title)

        self.s2p = gr.serial_to_parallel(gr.sizeof_float, self.fft_size)
        self.one_in_n = gr.keep_one_in_n(gr.sizeof_float * self.fft_size,
                                         max(1, int(self.sample_rate/self.fft_size/self.fft_rate)))

        mywindow = window.blackmanharris(self.fft_size)
        self.fft = gr.fft_vfc(self.fft_size, True, mywindow)
        self.c2mag = gr.complex_to_mag(self.fft_size)
        self.avg = gr.single_pole_iir_filter_ff(1.0, self.fft_size)
        self.log = gr.nlog10_ff(20, self.fft_size, -20*math.log10(self.fft_size))
        self.sink = gr.message_sink(gr.sizeof_float * self.fft_size, self.msgq, True)
	self.connect(self, self.s2p, self.one_in_n, self.fft, self.c2mag, self.avg, self.log, self.sink)

        self.win = waterfall_window(self, parent, size=size)
        self.set_average(self.average)
Exemple #6
0
def main():
  parser = OptionParser(conflict_handler="resolve")
  expert_grp = parser.add_option_group("Expert")
  add_options(parser, expert_grp)
  (options, args) = parser.parse_args ()

  fft_length = options.fft_length or 512
  file = options.file or "input.compl"
  out = options.out or "output.compl"

  src = gr.file_source(gr.sizeof_gr_complex,file)
  sampler = ofdm.vector_sampler( gr.sizeof_gr_complex, fft_length )
  trig = gr.vector_source_b([1],True)

  fft = gr.fft_vcc( fft_length, True, [], True )
  mag = gr.complex_to_mag( fft_length )
  avg = gr.single_pole_iir_filter_ff(0.01, fft_length)
  nlog = gr.nlog10_ff( 20, fft_length, -10*math.log10(fft_length) )
  dst = gr.file_sink( gr.sizeof_float * fft_length, out )

  fg = gr.top_block()
  fg.connect( src, sampler, fft, mag, avg, nlog, dst )
  fg.connect( trig, (sampler,1))
#  fg.connect(src,limit,
#             gr.stream_to_vector(gr.sizeof_gr_complex,fft_length),
#             fft,
#             gr.multiply_const_vcc([1./fft_length]*fft_length),
#             gr.complex_to_mag(fft_length),
#             gr.nlog10_ff(10.0,fft_length),
#             dst)
#  fg.connect( src, fft, dst )

  fg.run()
  print "done"
Exemple #7
0
    def __init__(self, parent, baseband_freq=0,
                 y_per_div=10, ref_level=50, sample_rate=1, fft_size=512,
                 fft_rate=default_fft_rate, average=False, avg_alpha=None,
                 title='', size=default_fftsink_size):

        gr.hier_block2.__init__(self, "waterfall_sink_f",
                                gr.io_signature(1, 1, gr.sizeof_float),
                                gr.io_signature(0,0,0))

        waterfall_sink_base.__init__(self, input_is_real=True, baseband_freq=baseband_freq,
                               sample_rate=sample_rate, fft_size=fft_size,
                               fft_rate=fft_rate,
                               average=average, avg_alpha=avg_alpha, title=title)
                               
        self.s2p = gr.serial_to_parallel(gr.sizeof_float, self.fft_size)
        self.one_in_n = gr.keep_one_in_n(gr.sizeof_float * self.fft_size,
                                         max(1, int(self.sample_rate/self.fft_size/self.fft_rate)))
        
        mywindow = window.blackmanharris(self.fft_size)
        self.fft = gr.fft_vfc(self.fft_size, True, mywindow)
        self.c2mag = gr.complex_to_mag(self.fft_size)
        self.avg = gr.single_pole_iir_filter_ff(1.0, self.fft_size)
        self.log = gr.nlog10_ff(20, self.fft_size, -20*math.log10(self.fft_size))
        self.sink = gr.message_sink(gr.sizeof_float * self.fft_size, self.msgq, True)
	self.connect(self, self.s2p, self.one_in_n, self.fft, self.c2mag, self.avg, self.log, self.sink)

        self.win = waterfall_window(self, parent, size=size)
        self.set_average(self.average)
Exemple #8
0
    def __init__(self, samp_rate=1600000, samp_per_sym=16, verbose=0, msgq=0, freq_error=-0.0025000):
        gr.hier_block2.__init__(
            self, "Wmbus Phy1", gr.io_signature(1, 1, gr.sizeof_gr_complex * 1), gr.io_signature(0, 0, 0)
        )

        ##################################################
        # Parameters
        ##################################################
        self.samp_rate = samp_rate
        self.samp_per_sym = samp_per_sym
        self.verbose = verbose
        self.msgq = msgq
        self.freq_error = freq_error

        ##################################################
        # Blocks
        ##################################################
        self.wmbus_demod_0 = wmbus_demod(samp_rate=1600000, samp_per_sym=16, freq_error=-0.0025000)
        self.gr_nlog10_ff_0 = gr.nlog10_ff(10, 1, 0)
        self.gr_complex_to_mag_squared_0 = gr.complex_to_mag_squared(1)
        self.fir_filter_xxx_0 = filter.fir_filter_fff(samp_per_sym, (16 * [1.0 / 16]))
        self.any_sink_0_1 = mbus.framer(msgq, verbose)
        self.any_0 = mbus.correlate_preamble()

        ##################################################
        # Connections
        ##################################################
        self.connect((self.any_0, 0), (self.any_sink_0_1, 0))
        self.connect((self.gr_complex_to_mag_squared_0, 0), (self.gr_nlog10_ff_0, 0))
        self.connect((self.gr_nlog10_ff_0, 0), (self.fir_filter_xxx_0, 0))
        self.connect((self.fir_filter_xxx_0, 0), (self.any_sink_0_1, 1))
        self.connect((self, 0), (self.gr_complex_to_mag_squared_0, 0))
        self.connect((self, 0), (self.wmbus_demod_0, 0))
        self.connect((self.wmbus_demod_0, 0), (self.any_0, 0))
Exemple #9
0
    def __init__(self, parent, baseband_freq=0,
                 y_per_div=10, sc_y_per_div=0.5, sc_ref_level=40, ref_level=50, sample_rate=1, fft_size=512,
                 fft_rate=15, average=False, avg_alpha=None, title='',
                 size=default_ra_fftsink_size, peak_hold=False, ofunc=None,
                 xydfunc=None):
	gr.hier_block2.__init__(self, "ra_fft_sink_f",
				gr.io_signature(1, 1, gr.sizeof_float),
				gr.io_signature(0, 0, 0))
				
        ra_fft_sink_base.__init__(self, input_is_real=True, baseband_freq=baseband_freq,
                               y_per_div=y_per_div, sc_y_per_div=sc_y_per_div,
                               sc_ref_level=sc_ref_level, ref_level=ref_level,
                               sample_rate=sample_rate, fft_size=fft_size,
                               fft_rate=fft_rate,
                               average=average, avg_alpha=avg_alpha, title=title,
                               peak_hold=peak_hold, ofunc=ofunc, 
                               xydfunc=xydfunc)
                               
        self.binwidth = float(sample_rate/2.0)/float(fft_size)
        s2p = gr.serial_to_parallel(gr.sizeof_float, fft_size)
        one_in_n = gr.keep_one_in_n(gr.sizeof_float * fft_size,
                                    max(1, int(sample_rate/fft_size/fft_rate)))
        mywindow = window.blackmanharris(fft_size)
        fft = gr.fft_vfc(fft_size, True, mywindow)
        c2mag = gr.complex_to_mag(fft_size)
        self.avg = gr.single_pole_iir_filter_ff(1.0, fft_size)
        log = gr.nlog10_ff(20, fft_size, -20*math.log10(fft_size))
        sink = gr.message_sink(gr.sizeof_float * fft_size, self.msgq, True)

        self.connect (self, s2p, one_in_n, fft, c2mag, self.avg, log, sink)

        self.win = fft_window(self, parent, size=size)
        self.set_average(self.average)
    def __init__(self, fg, parent, baseband_freq=0,
                 ref_level=0, sample_rate=1, fft_size=512,
                 fft_rate=default_fft_rate, average=False, avg_alpha=None, 
                 title='', size=default_fftsink_size, report=None, span=40, ofunc=None, xydfunc=None):

        waterfall_sink_base.__init__(self, input_is_real=False,
                                     baseband_freq=baseband_freq,
                                     sample_rate=sample_rate,
                                     fft_size=fft_size,
                                     fft_rate=fft_rate,
                                     average=average, avg_alpha=avg_alpha,
                                     title=title)

        s2p = gr.serial_to_parallel(gr.sizeof_gr_complex, self.fft_size)
        self.one_in_n = gr.keep_one_in_n(gr.sizeof_gr_complex * self.fft_size,
                                         max(1, int(self.sample_rate/self.fft_size/self.fft_rate)))

        mywindow = window.blackmanharris(self.fft_size)
        fft = gr.fft_vcc(self.fft_size, True, mywindow)
        c2mag = gr.complex_to_mag(self.fft_size)
        self.avg = gr.single_pole_iir_filter_ff(1.0, self.fft_size)
        log = gr.nlog10_ff(20, self.fft_size, -20*math.log10(self.fft_size))
        sink = gr.message_sink(gr.sizeof_float * self.fft_size, self.msgq, True)

        self.block_list = (s2p, self.one_in_n, fft, c2mag, self.avg, log, sink)
        self.reconnect( fg )
        gr.hier_block.__init__(self, fg, s2p, sink)

        self.win = waterfall_window(self, parent, size=size, report=report,
                                    ref_level=ref_level, span=span, ofunc=ofunc, xydfunc=xydfunc)
        self.set_average(self.average)
Exemple #11
0
    def __init__(
        self,
        parent,
        baseband_freq=0,
        y_per_div=10,
        ref_level=50,
        sample_rate=1,
        fac_size=512,
        fac_rate=default_fac_rate,
        average=False,
        avg_alpha=None,
        title="",
        size=default_facsink_size,
        peak_hold=False,
    ):

        fac_sink_base.__init__(
            self,
            input_is_real=False,
            baseband_freq=baseband_freq,
            y_per_div=y_per_div,
            ref_level=ref_level,
            sample_rate=sample_rate,
            fac_size=fac_size,
            fac_rate=fac_rate,
            average=average,
            avg_alpha=avg_alpha,
            title=title,
            peak_hold=peak_hold,
        )

        s2p = gr.stream_to_vector(gr.sizeof_gr_complex, self.fac_size)
        self.one_in_n = gr.keep_one_in_n(
            gr.sizeof_gr_complex * self.fac_size, max(1, int(self.sample_rate / self.fac_size / self.fac_rate))
        )

        # windowing removed ...

        fac = gr.fft_vcc(self.fac_size, True, ())
        c2mag = gr.complex_to_mag(fac_size)

        # Things go off into the weeds if we try for an inverse FFT so a forward FFT will have to do...
        fac_fac = gr.fft_vfc(self.fac_size, True, ())
        fac_c2mag = gr.complex_to_mag(fac_size)

        self.avg = gr.single_pole_iir_filter_ff(1.0, fac_size)

        log = gr.nlog10_ff(
            20, self.fac_size, -20 * math.log10(self.fac_size)
        )  #  - 20*math.log10(norm) ) # - self.avg[0] )
        sink = gr.message_sink(gr.sizeof_float * fac_size, self.msgq, True)

        self.connect(s2p, self.one_in_n, fac, c2mag, fac_fac, fac_c2mag, self.avg, log, sink)

        #        gr.hier_block2.__init__(self, fg, s2p, sink)

        self.win = fac_window(self, parent, size=size)
        self.set_average(self.average)

        self.wxgui_connect(self, s2p)
  def supply_rx_baseband(self):
    ## RX Spectrum
    if self.__dict__.has_key('rx_baseband'):
      return self.rx_baseband

    config = self.config

    fftlen = config.fft_length

    my_window = window.hamming(fftlen) #.blackmanharris(fftlen)
    rxs_sampler = vector_sampler(gr.sizeof_gr_complex,fftlen)
    rxs_trigger = gr.vector_source_b(concatenate([[1],[0]*199]),True)
    rxs_window = blocks.multiply_const_vcc(my_window)
    rxs_spectrum = gr.fft_vcc(fftlen,True,[],True)
    rxs_mag = gr.complex_to_mag(fftlen)
    rxs_avg = gr.single_pole_iir_filter_ff(0.01,fftlen)
    rxs_logdb = gr.nlog10_ff(20.0,fftlen,-20*log10(fftlen))
    rxs_decimate_rate = gr.keep_one_in_n(gr.sizeof_float*fftlen,50)

    t = self.u if self.filter is None else self.filter
    self.connect(rxs_trigger,(rxs_sampler,1))
    self.connect(t,rxs_sampler,rxs_window,
                 rxs_spectrum,rxs_mag,rxs_avg,rxs_logdb, rxs_decimate_rate)
    if self._options.log:
          log_to_file(self, rxs_decimate_rate, "data/supply_rx.float")
    self.rx_baseband = rxs_decimate_rate
    return rxs_decimate_rate
Exemple #13
0
def main():
    parser = OptionParser(conflict_handler="resolve")
    expert_grp = parser.add_option_group("Expert")
    add_options(parser, expert_grp)
    (options, args) = parser.parse_args()

    fft_length = options.fft_length or 512
    file = options.file or "input.compl"
    out = options.out or "output.compl"

    src = gr.file_source(gr.sizeof_gr_complex, file)
    sampler = ofdm.vector_sampler(gr.sizeof_gr_complex, fft_length)
    trig = gr.vector_source_b([1], True)

    fft = gr.fft_vcc(fft_length, True, [], True)
    mag = gr.complex_to_mag(fft_length)
    avg = gr.single_pole_iir_filter_ff(0.01, fft_length)
    nlog = gr.nlog10_ff(20, fft_length, -10 * math.log10(fft_length))
    dst = gr.file_sink(gr.sizeof_float * fft_length, out)

    fg = gr.top_block()
    fg.connect(src, sampler, fft, mag, avg, nlog, dst)
    fg.connect(trig, (sampler, 1))
    #  fg.connect(src,limit,
    #             gr.stream_to_vector(gr.sizeof_gr_complex,fft_length),
    #             fft,
    #             gr.multiply_const_vcc([1./fft_length]*fft_length),
    #             gr.complex_to_mag(fft_length),
    #             gr.nlog10_ff(10.0,fft_length),
    #             dst)
    #  fg.connect( src, fft, dst )

    fg.run()
    print "done"
Exemple #14
0
  def publish_rx_spectrum(self,fftlen):
    ## RX Spectrum

    fftlen = 256
    my_window = window.hamming(fftlen) #.blackmanharris(fftlen)
    rxs_sampler = vector_sampler(gr.sizeof_gr_complex,fftlen)
    rxs_trigger = gr.vector_source_b(concatenate([[1],[0]*199]),True)
    rxs_window = blocks.multiply_const_vcc(my_window)
    rxs_spectrum = gr.fft_vcc(fftlen,True,[],True)
    rxs_mag = gr.complex_to_mag(fftlen)
    rxs_avg = gr.single_pole_iir_filter_ff(0.01,fftlen)
    rxs_logdb = gr.nlog10_ff(20.0,fftlen,-20*log10(fftlen))
    rxs_decimate_rate = gr.keep_one_in_n(gr.sizeof_float*fftlen,1)
    msgq = gr.msg_queue(5)
    rxs_msg_sink = gr.message_sink(gr.sizeof_float*fftlen,msgq,True)
    self.connect(rxs_trigger,(rxs_sampler,1))
    t = self.u if self.filter is None else self.filter
    self.connect(t,rxs_sampler,rxs_window,
                 rxs_spectrum,rxs_mag,rxs_avg,rxs_logdb, rxs_decimate_rate,
                 rxs_msg_sink)
    self.servants.append(corba_data_buffer_servant("spectrum",fftlen,msgq))

    print "RXS trigger unique id", rxs_trigger.unique_id()
    
    print "Publishing RX baseband under id: spectrum"
    def __init__(self, sample_rate, fft_size, ref_scale, frame_rate, avg_alpha, average):
    	"""!
	Create an log10(abs(fft)) stream chain.
	Provide access to the setting the filter and sample rate.
	@param sample_rate	Incoming stream sample rate
	@param fft_size		Number of FFT bins
	@param ref_scale	Sets 0 dB value input amplitude
	@param frame_rate	Output frame rate
	@param avg_alpha	FFT averaging (over time) constant [0.0-1.0]
	@param average		Whether to average [True, False]
	"""
	gr.hier_block2.__init__(self, self._name, 
				gr.io_signature(1, 1, self._item_size),          # Input signature
				gr.io_signature(1, 1, gr.sizeof_float*fft_size)) # Output signature

	self._sd = stream_to_vector_decimator(item_size=self._item_size,
					      sample_rate=sample_rate,
					      vec_rate=frame_rate,
					      vec_len=fft_size)
		
	fft_window = window.blackmanharris(fft_size)
	fft = self._fft_block[0](fft_size, True, fft_window)
	window_power = sum(map(lambda x: x*x, fft_window))

	c2mag = gr.complex_to_mag(fft_size)
	self._avg = gr.single_pole_iir_filter_ff(1.0, fft_size)
	self._log = gr.nlog10_ff(20, fft_size,
			         -10*math.log10(fft_size)              # Adjust for number of bins
				 -10*math.log10(window_power/fft_size) # Adjust for windowing loss
			         -20*math.log10(ref_scale/2))          # Adjust for reference scale
	self.connect(self, self._sd, fft, c2mag, self._avg, self._log, self)
	self.set_average(average)
	self.set_avg_alpha(avg_alpha)
    def __init__(self,
                 sample_rate,
                 pspectrum_len,
                 ref_scale,
                 frame_rate,
                 avg_alpha,
                 average,
                 n,
                 m,
                 nsamples,
                 estimator='esprit'):
        """
        Create an log10(abs(spectrum_estimate)) stream chain.
        Provide access to the setting the filter and sample rate.
        @param sample_rate      Incoming stream sample rate
        @param pspectrum_len    Number of FFT bins
        @param ref_scale        Sets 0 dB value input amplitude
        @param frame_rate       Output frame rate
        @param avg_alpha        averaging (over time) constant [0.0-1.0]
        @param average          Whether to average [True, False]
        @param n                Parameter n for the estimator
        @param m                Parameter m for the estimator
        @param nsamples         Number of samples to use for estimation
        @param estimator        Estimator to use, can be either 'esprit' or 'music'
        """
        gr.hier_block2.__init__(
            self,
            self._name,
            gr.io_signature(1, 1, self._item_size),  # Input signature
            gr.io_signature(1, 1, gr.sizeof_float *
                            pspectrum_len))  # Output signature

        self._sd = blks2.stream_to_vector_decimator(item_size=self._item_size,
                                                    sample_rate=sample_rate,
                                                    vec_rate=frame_rate,
                                                    vec_len=nsamples)

        if estimator == 'esprit':
            est = specest.esprit_spectrum_vcf(n, m, nsamples, pspectrum_len)

        elif estimator == 'music':
            est = specest.music_spectrum_vcf(n, m, nsamples, pspectrum_len)

        else:
            est = specest.esprit_spectrum_vcf(n, m, nsamples, pspectrum_len)

        self._avg = gr.single_pole_iir_filter_ff(1.0, pspectrum_len)
        self._log = gr.nlog10_ff(
            20,
            pspectrum_len,
            -20 * math.log10(pspectrum_len)  # Adjust for number of bins
            - 20 * math.log10(ref_scale / 2) +
            3.0)  # Adjust for reference scale
        self.connect(self, self._sd, est, self._avg, self._log, self)

        self._average = average
        self._avg_alpha = avg_alpha
        self.set_avg_alpha(avg_alpha)
        self.set_average(average)
Exemple #17
0
    def __init__(
        self,
        parent,
        baseband_freq=0,
        y_per_div=10,
        ref_level=50,
        sample_rate=1,
        fac_size=512,
        fac_rate=default_fac_rate,
        average=False,
        avg_alpha=None,
        title="",
        size=default_facsink_size,
        peak_hold=False,
    ):

        fac_sink_base.__init__(
            self,
            input_is_real=True,
            baseband_freq=baseband_freq,
            y_per_div=y_per_div,
            ref_level=ref_level,
            sample_rate=sample_rate,
            fac_size=fac_size,
            fac_rate=fac_rate,
            average=average,
            avg_alpha=avg_alpha,
            title=title,
            peak_hold=peak_hold,
        )

        s2p = gr.stream_to_vector(gr.sizeof_float, self.fac_size)
        self.one_in_n = gr.keep_one_in_n(
            gr.sizeof_float * self.fac_size, max(1, int(self.sample_rate / self.fac_size / self.fac_rate))
        )

        # windowing removed...

        fac = gr.fft_vfc(self.fac_size, True, ())

        c2mag = gr.complex_to_mag(self.fac_size)
        self.avg = gr.single_pole_iir_filter_ff(1.0, self.fac_size)

        fac_fac = gr.fft_vfc(self.fac_size, True, ())
        fac_c2mag = gr.complex_to_mag(fac_size)

        # FIXME  We need to add 3dB to all bins but the DC bin
        log = gr.nlog10_ff(20, self.fac_size, -20 * math.log10(self.fac_size))
        sink = gr.message_sink(gr.sizeof_float * self.fac_size, self.msgq, True)

        self.connect(s2p, self.one_in_n, fac, c2mag, fac_fac, fac_c2mag, self.avg, log, sink)

        #        gr.hier_block.__init__(self, fg, s2p, sink)

        self.win = fac_window(self, parent, size=size)
        self.set_average(self.average)

        self.wxgui_connect(self, s2p)
Exemple #18
0
 def _setup_foot(self):
     """ Sets up everything after the spectral estimation. """
     if self.options.linear:
         self.connect(self.head, self.specest, self.sink)
         self.ylabelstr = 'Power Spectrum Density / W/rad'
     else:
         lin2db = gr.nlog10_ff(10, self.options.fft_len)
         self.connect(self.head, self.specest, lin2db, self.sink)
         self.ylabelstr = 'Power Spectrum Density / dBW/rad'
Exemple #19
0
 def _setup_foot(self):
     """ Sets up everything after the spectral estimation. """
     if self.options.linear:
         self.connect(self.head, self.specest, self.sink)
         self.ylabelstr = 'Power Spectrum Density / W/rad'
     else:
         lin2db = gr.nlog10_ff(10, self.options.fft_len)
         self.connect(self.head, self.specest, lin2db, self.sink)
         self.ylabelstr = 'Power Spectrum Density / dBW/rad'
Exemple #20
0
    def __init__(self,
                 parent,
                 baseband_freq=0,
                 y_per_div=10,
                 ref_level=50,
                 sample_rate=1,
                 fac_size=512,
                 fac_rate=default_fac_rate,
                 average=False,
                 avg_alpha=None,
                 title='',
                 size=default_facsink_size,
                 peak_hold=False):

        fac_sink_base.__init__(self,
                               input_is_real=True,
                               baseband_freq=baseband_freq,
                               y_per_div=y_per_div,
                               ref_level=ref_level,
                               sample_rate=sample_rate,
                               fac_size=fac_size,
                               fac_rate=fac_rate,
                               average=average,
                               avg_alpha=avg_alpha,
                               title=title,
                               peak_hold=peak_hold)

        s2p = gr.stream_to_vector(gr.sizeof_float, self.fac_size)
        self.one_in_n = gr.keep_one_in_n(
            gr.sizeof_float * self.fac_size,
            max(1, int(self.sample_rate / self.fac_size / self.fac_rate)))

        # windowing removed...

        fac = gr.fft_vfc(self.fac_size, True, ())

        c2mag = gr.complex_to_mag(self.fac_size)
        self.avg = gr.single_pole_iir_filter_ff(1.0, self.fac_size)

        fac_fac = gr.fft_vfc(self.fac_size, True, ())
        fac_c2mag = gr.complex_to_mag(fac_size)

        # FIXME  We need to add 3dB to all bins but the DC bin
        log = gr.nlog10_ff(20, self.fac_size, -20 * math.log10(self.fac_size))
        sink = gr.message_sink(gr.sizeof_float * self.fac_size, self.msgq,
                               True)

        self.connect(s2p, self.one_in_n, fac, c2mag, fac_fac, fac_c2mag,
                     self.avg, log, sink)

        #        gr.hier_block.__init__(self, fg, s2p, sink)

        self.win = fac_window(self, parent, size=size)
        self.set_average(self.average)

        self.wxgui_connect(self, s2p)
Exemple #21
0
    def __init__(self,
                 parent,
                 baseband_freq=0,
                 y_per_div=10,
                 ref_level=50,
                 sample_rate=1,
                 fac_size=512,
                 fac_rate=default_fac_rate,
                 average=False,
                 avg_alpha=None,
                 title='',
                 size=default_facsink_size,
                 peak_hold=False):

        fac_sink_base.__init__(self,
                               input_is_real=False,
                               baseband_freq=baseband_freq,
                               y_per_div=y_per_div,
                               ref_level=ref_level,
                               sample_rate=sample_rate,
                               fac_size=fac_size,
                               fac_rate=fac_rate,
                               average=average,
                               avg_alpha=avg_alpha,
                               title=title,
                               peak_hold=peak_hold)

        s2p = gr.stream_to_vector(gr.sizeof_gr_complex, self.fac_size)
        self.one_in_n = gr.keep_one_in_n(
            gr.sizeof_gr_complex * self.fac_size,
            max(1, int(self.sample_rate / self.fac_size / self.fac_rate)))

        # windowing removed ...

        fac = gr.fft_vcc(self.fac_size, True, ())
        c2mag = gr.complex_to_mag(fac_size)

        # Things go off into the weeds if we try for an inverse FFT so a forward FFT will have to do...
        fac_fac = gr.fft_vfc(self.fac_size, True, ())
        fac_c2mag = gr.complex_to_mag(fac_size)

        self.avg = gr.single_pole_iir_filter_ff(1.0, fac_size)

        log = gr.nlog10_ff(20, self.fac_size, -20 * math.log10(
            self.fac_size))  #  - 20*math.log10(norm) ) # - self.avg[0] )
        sink = gr.message_sink(gr.sizeof_float * fac_size, self.msgq, True)

        self.connect(s2p, self.one_in_n, fac, c2mag, fac_fac, fac_c2mag,
                     self.avg, log, sink)

        #        gr.hier_block2.__init__(self, fg, s2p, sink)

        self.win = fac_window(self, parent, size=size)
        self.set_average(self.average)

        self.wxgui_connect(self, s2p)
 def test_001(self):
     src_data = (-10, 0, 10, 100, 1000, 10000, 100000)
     expected_result = (-180, -180, 10, 20, 30, 40, 50)
     src = gr.vector_source_f(src_data)
     op = gr.nlog10_ff(10)
     dst = gr.vector_sink_f()
     self.tb.connect (src, op, dst)
     self.tb.run()
     result_data = dst.data()
     self.assertFloatTuplesAlmostEqual (expected_result, result_data)
Exemple #23
0
    def __init__(self,
                 parent,
                 baseband_freq=0,
                 ref_level=0,
                 sample_rate=1,
                 fft_size=512,
                 fft_rate=default_fft_rate,
                 average=False,
                 avg_alpha=None,
                 title='',
                 size=default_fftsink_size,
                 report=None,
                 span=40,
                 ofunc=None,
                 xydfunc=None):

        gr.hier_block2.__init__(self, "waterfall_sink_c",
                                gr.io_signature(1, 1, gr.sizeof_gr_complex),
                                gr.io_signature(0, 0, 0))

        waterfall_sink_base.__init__(self,
                                     input_is_real=False,
                                     baseband_freq=baseband_freq,
                                     sample_rate=sample_rate,
                                     fft_size=fft_size,
                                     fft_rate=fft_rate,
                                     average=average,
                                     avg_alpha=avg_alpha,
                                     title=title)

        s2p = gr.serial_to_parallel(gr.sizeof_gr_complex, self.fft_size)
        self.one_in_n = gr.keep_one_in_n(
            gr.sizeof_gr_complex * self.fft_size,
            max(1, int(self.sample_rate / self.fft_size / self.fft_rate)))

        mywindow = window.blackmanharris(self.fft_size)
        fft = gr.fft_vcc(self.fft_size, True, mywindow)
        c2mag = gr.complex_to_mag(self.fft_size)
        self.avg = gr.single_pole_iir_filter_ff(1.0, self.fft_size)
        log = gr.nlog10_ff(20, self.fft_size, -20 * math.log10(self.fft_size))
        sink = gr.message_sink(gr.sizeof_float * self.fft_size, self.msgq,
                               True)

        self.connect(self, s2p, self.one_in_n, fft, c2mag, self.avg, log, sink)
        self.win = waterfall_window(self,
                                    parent,
                                    size=size,
                                    report=report,
                                    ref_level=ref_level,
                                    span=span,
                                    ofunc=ofunc,
                                    xydfunc=xydfunc)
        self.set_average(self.average)
    def set_body(self):
        """
        1) Disconnect old stuff, if necessary.
        2) Set up the new block.
        3) Connect everything.
        """
        self.lock()
        if(self.body is not None and self.decimator is not None and self.foot is not None):
            self.sink.watcher.quit()
            self.disconnect((self.decimator, 0), (self.body, 0))
            self.disconnect((self.body, 0), (self.foot, 0))
            self.disconnect((self.foot, 0), (self.sink, 0))
        elif(self.body is not None and self.decimator is not None and self.foot is None):
            self.sink.watcher.quit()
            self.disconnect((self.decimator, 0), (self.body, 0))
            self.disconnect((self.body, 0), (self.sink, 0))

        try:
            (self.est_input_block_len,
             self.fft_size) = estimators[self.estimator].setup_block(self.shift_fft)
        except KeyError:
            print "Unknown estimator selected."
        except RuntimeError:
            print "Could not initialize Estimator (wrong settings?) !"
        self.body = estimators[self.estimator].block

        self.decimation = 1
        self.sink = plot_sink(gr.sizeof_float, self.fft_size, self.main_box,
                              numpy.float32, self.samp_rate, self.center_f)
        if(self.scale == "Logarithmic"):
            try:
                self.foot = gr.nlog10_ff(10, self.fft_size)
            except RuntimeError:
                print "Wrong sink-data!"
            self.connect((self.foot, 0), (self.sink,  0))
        elif(self.scale == "Linear"):
            try:
                self.foot = None
            except RuntimeError:
                print "Wrong sink-data!"
        else:
            print "Wrong scale-settings!"

        if(self.body is not None and self.decimator is not None):
            self.connect((self.decimator, 0), (self.body, 0))
        if(self.scale == "Logarithmic"):
            self.connect((self.body, 0), (self.foot, 0))
        elif(self.scale == "Linear"):
            self.connect((self.body, 0), (self.sink, 0))
        else:
            print "Wrong scale-settings!"
            self.main_box.first_run = 0
        self.unlock()
Exemple #25
0
  def publish_spectrum(self,fftlen):
    spectrum = gr.fft_vcc(fftlen,True,[],True)
    mag = gr.complex_to_mag(fftlen)
    logdb = gr.nlog10_ff(20.0,fftlen,-20*log10(fftlen))
    decimate_rate = gr.keep_one_in_n(gr.sizeof_gr_complex*fftlen,10)

    msgq = gr.msg_queue(10)
    msg_sink = gr.message_sink(gr.sizeof_float*fftlen,msgq,True)

    self.connect(self.filter,gr.stream_to_vector(gr.sizeof_gr_complex,fftlen),
                 decimate_rate,spectrum,mag,logdb,msg_sink)

    self.servants.append(corba_data_buffer_servant("tx_spectrum",fftlen,msgq))
Exemple #26
0
    def __init__(self,
                 sample_rate,
                 fft_size,
                 ref_scale,
                 frame_rate,
                 avg_alpha,
                 average,
                 win=None):
        """
        Create an log10(abs(fft)) stream chain.
        Provide access to the setting the filter and sample rate.
        @param sample_rate        Incoming stream sample rate
        @param fft_size                Number of FFT bins
        @param ref_scale        Sets 0 dB value input amplitude
        @param frame_rate        Output frame rate
        @param avg_alpha        FFT averaging (over time) constant [0.0-1.0]
        @param average                Whether to average [True, False]
        @param win              the window taps generation function
        """
        gr.hier_block2.__init__(
            self,
            self._name,
            gr.io_signature(1, 1, self._item_size),  # Input signature
            gr.io_signature(1, 1,
                            gr.sizeof_float * fft_size))  # Output signature

        self._sd = stream_to_vector_decimator(item_size=self._item_size,
                                              sample_rate=sample_rate,
                                              vec_rate=frame_rate,
                                              vec_len=fft_size)

        if win is None: win = window.blackmanharris
        fft_window = win(fft_size)
        fft = self._fft_block[0](fft_size, True, fft_window)
        window_power = sum(map(lambda x: x * x, fft_window))

        c2magsq = gr.complex_to_mag_squared(fft_size)
        self._avg = gr.single_pole_iir_filter_ff(1.0, fft_size)
        self._log = gr.nlog10_ff(
            10,
            fft_size,
            -20 * math.log10(fft_size)  # Adjust for number of bins
            - 10 *
            math.log10(window_power / fft_size)  # Adjust for windowing loss
            - 20 * math.log10(ref_scale / 2))  # Adjust for reference scale
        self.connect(self, self._sd, fft, c2magsq, self._avg, self._log, self)

        self._average = average
        self._avg_alpha = avg_alpha
        self.set_avg_alpha(avg_alpha)
        self.set_average(average)
Exemple #27
0
    def __init__(
        self, sample_rate, pspectrum_len, ref_scale, frame_rate, avg_alpha, average, n, m, nsamples, estimator="esprit"
    ):
        """
        Create an log10(abs(spectrum_estimate)) stream chain.
        Provide access to the setting the filter and sample rate.
        @param sample_rate      Incoming stream sample rate
        @param pspectrum_len    Number of FFT bins
        @param ref_scale        Sets 0 dB value input amplitude
        @param frame_rate       Output frame rate
        @param avg_alpha        averaging (over time) constant [0.0-1.0]
        @param average          Whether to average [True, False]
        @param n                Parameter n for the estimator
        @param m                Parameter m for the estimator
        @param nsamples         Number of samples to use for estimation
        @param estimator        Estimator to use, can be either 'esprit' or 'music'
        """
        gr.hier_block2.__init__(
            self,
            self._name,
            gr.io_signature(1, 1, self._item_size),  # Input signature
            gr.io_signature(1, 1, gr.sizeof_float * pspectrum_len),
        )  # Output signature

        self._sd = blks2.stream_to_vector_decimator(
            item_size=self._item_size, sample_rate=sample_rate, vec_rate=frame_rate, vec_len=nsamples
        )

        if estimator == "esprit":
            est = specest.esprit_spectrum_vcf(n, m, nsamples, pspectrum_len)

        elif estimator == "music":
            est = specest.music_spectrum_vcf(n, m, nsamples, pspectrum_len)

        else:
            est = specest.esprit_spectrum_vcf(n, m, nsamples, pspectrum_len)

        self._avg = gr.single_pole_iir_filter_ff(1.0, pspectrum_len)
        self._log = gr.nlog10_ff(
            20,
            pspectrum_len,
            -20 * math.log10(pspectrum_len) - 20 * math.log10(ref_scale / 2) + 3.0,  # Adjust for number of bins
        )  # Adjust for reference scale
        self.connect(self, self._sd, est, self._avg, self._log, self)

        self._average = average
        self._avg_alpha = avg_alpha
        self.set_avg_alpha(avg_alpha)
        self.set_average(average)
    def __init__(self, options):

	gr.hier_block2.__init__(self, "sensing_path",
				gr.io_signature(1, 1, gr.sizeof_gr_complex), # Input signature
				gr.io_signature(0, 0, 0)) # Output signature


        options = copy.copy(options)    # make a copy so we can destructively modify

        self._verbose        = options.verbose
       
        # linklab, fft size for sensing, different from fft length for tx/rx
        self.fft_size = FFT_SIZE

        # interpolation rate: sensing fft size / ofdm fft size
        self.interp_rate = self.fft_size/FFT_SIZE #options.fft_length

        self._fft_length      = FFT_SIZE #options.fft_length
        self._occupied_tones  = FFT_SIZE #options.occupied_tones
        self.msgq             = gr.msg_queue()

        # linklab , setup the sensing path
        # FIXME: some components are not necessary
        self.s2p = gr.stream_to_vector(gr.sizeof_gr_complex, self.fft_size)
        mywindow = window.blackmanharris(self.fft_size)
        self.fft = gr.fft_vcc(self.fft_size, True, mywindow)
        power = 0
        for tap in mywindow:
            power += tap*tap
        self.c2mag = gr.complex_to_mag(self.fft_size)
        self.avg = gr.single_pole_iir_filter_ff(1.0, self.fft_size)

        # linklab, ref scale value from default ref_scale in usrp_fft.py
        ref_scale = 13490.0

        # FIXME  We need to add 3dB to all bins but the DC bin
        self.log = gr.nlog10_ff(20, self.fft_size,
                                -10*math.log10(self.fft_size)              # Adjust for number of bins
                                -10*math.log10(power/self.fft_size)        # Adjust for windowing loss
                                -20*math.log10(ref_scale/2))               # Adjust for reference scale

        self.sink = gr.message_sink(gr.sizeof_float * self.fft_size, self.msgq, True)
        self.connect(self, self.s2p, self.fft, self.c2mag, self.avg, self.log, self.sink)
Exemple #29
0
    def __init__(self, fg):
        self.split = gr.multiply_const_ff(1)
        self.sqr = gr.multiply_ff()
        self.int0 = gr.iir_filter_ffd([.004, 0], [0, .999])
        self.offs = gr.add_const_ff(-30)
        self.gain = gr.multiply_const_ff(70)
        self.log = gr.nlog10_ff(10, 1)
        self.agc = gr.divide_ff()

        fg.connect(self.split, (self.agc, 0))
        fg.connect(self.split, (self.sqr, 0))
        fg.connect(self.split, (self.sqr, 1))
        fg.connect(self.sqr, self.int0)
        fg.connect(self.int0, self.log)
        fg.connect(self.log, self.offs)
        fg.connect(self.offs, self.gain)
        fg.connect(self.gain, (self.agc, 1))

        gr.hier_block.__init__(self, fg, self.split, self.agc)
Exemple #30
0
    def __init__(self, fg):
        self.split = gr.multiply_const_ff(1)
        self.sqr = gr.multiply_ff()
        self.int0 = gr.iir_filter_ffd([0.004, 0], [0, 0.999])
        self.offs = gr.add_const_ff(-30)
        self.gain = gr.multiply_const_ff(70)
        self.log = gr.nlog10_ff(10, 1)
        self.agc = gr.divide_ff()

        fg.connect(self.split, (self.agc, 0))
        fg.connect(self.split, (self.sqr, 0))
        fg.connect(self.split, (self.sqr, 1))
        fg.connect(self.sqr, self.int0)
        fg.connect(self.int0, self.log)
        fg.connect(self.log, self.offs)
        fg.connect(self.offs, self.gain)
        fg.connect(self.gain, (self.agc, 1))

        gr.hier_block.__init__(self, fg, self.split, self.agc)
Exemple #31
0
    def __init__(self, parent, baseband_freq=0, ref_scale=2.0,
                 y_per_div=10, y_divs=8, ref_level=50, sample_rate=1, fft_size=512,
                 fft_rate=default_fft_rate, average=False, avg_alpha=None,
                 title='', size=default_fftsink_size, peak_hold=False, use_persistence=False,persist_alpha=0.2, **kwargs):

        gr.hier_block2.__init__(self, "fft_sink_c",
                                gr.io_signature(1, 1, gr.sizeof_gr_complex),
                                gr.io_signature(0,0,0))

        fft_sink_base.__init__(self, input_is_real=False, baseband_freq=baseband_freq,
                               y_per_div=y_per_div, y_divs=y_divs, ref_level=ref_level,
                               sample_rate=sample_rate, fft_size=fft_size,
                               fft_rate=fft_rate,
                               average=average, avg_alpha=avg_alpha, title=title,
                               peak_hold=peak_hold, use_persistence=use_persistence,persist_alpha=persist_alpha)

        self.s2p = gr.stream_to_vector(gr.sizeof_gr_complex, self.fft_size)
        self.one_in_n = gr.keep_one_in_n(gr.sizeof_gr_complex * self.fft_size,
                                         max(1, int(self.sample_rate/self.fft_size/self.fft_rate)))
        
        mywindow = window.blackmanharris(self.fft_size)
        self.fft = gr.fft_vcc(self.fft_size, True, mywindow)
        power = 0
        for tap in mywindow:
            power += tap*tap
            
        self.c2mag = gr.complex_to_mag(self.fft_size)
        self.avg = gr.single_pole_iir_filter_ff(1.0, self.fft_size)

        # FIXME  We need to add 3dB to all bins but the DC bin
        self.log = gr.nlog10_ff(20, self.fft_size,
                                -10*math.log10(self.fft_size)                # Adjust for number of bins
                                -10*math.log10(power/self.fft_size)        # Adjust for windowing loss
                                -20*math.log10(ref_scale/2))                # Adjust for reference scale
                                
        self.sink = gr.message_sink(gr.sizeof_float * self.fft_size, self.msgq, True)
        self.connect(self, self.s2p, self.one_in_n, self.fft, self.c2mag, self.avg, self.log, self.sink)

        self.win = fft_window(self, parent, size=size)
        self.set_average(self.average)
        self.set_use_persistence(self.use_persistence)
        self.set_persist_alpha(self.persist_alpha)
        self.set_peak_hold(self.peak_hold)
Exemple #32
0
	def __init__(self, samp_rate=1600000, samp_per_sym=16, verbose=0, msgq=0, freq_error=-0.0025000):
		gr.hier_block2.__init__(
			self, "Wmbus Phy1",
			gr.io_signature(1, 1, gr.sizeof_gr_complex*1),
			gr.io_signature(0, 0, 0),
		)

		##################################################
		# Parameters
		##################################################
		self.samp_rate = samp_rate
		self.samp_per_sym = samp_per_sym
		self.verbose = verbose
		self.msgq = msgq
		self.freq_error = freq_error

		##################################################
		# Blocks
		##################################################
		self.wmbus_demod_0 = wmbus_demod(
			samp_rate=1600000,
			samp_per_sym=16,
			freq_error=-0.0025000,
		)
		self.gr_nlog10_ff_0 = gr.nlog10_ff(10, 1, 0)
		self.gr_complex_to_mag_squared_0 = gr.complex_to_mag_squared(1)
		self.fir_filter_xxx_0 = filter.fir_filter_fff(samp_per_sym, (16*[1./16]))
		self.any_sink_0_1 = mbus.framer(msgq, verbose) 
		self.any_0 = mbus.correlate_preamble()

		##################################################
		# Connections
		##################################################
		self.connect((self.any_0, 0), (self.any_sink_0_1, 0))
		self.connect((self.gr_complex_to_mag_squared_0, 0), (self.gr_nlog10_ff_0, 0))
		self.connect((self.gr_nlog10_ff_0, 0), (self.fir_filter_xxx_0, 0))
		self.connect((self.fir_filter_xxx_0, 0), (self.any_sink_0_1, 1))
		self.connect((self, 0), (self.gr_complex_to_mag_squared_0, 0))
		self.connect((self, 0), (self.wmbus_demod_0, 0))
		self.connect((self.wmbus_demod_0, 0), (self.any_0, 0))
    def __init__(self, sample_rate, fft_size, ref_scale, frame_rate, avg_alpha, average, win=None):
        """
        Create an log10(abs(fft)) stream chain.
        Provide access to the setting the filter and sample rate.
        
        Args:
            sample_rate: Incoming stream sample rate
            fft_size: Number of FFT bins
            ref_scale: Sets 0 dB value input amplitude
            frame_rate: Output frame rate
            avg_alpha: FFT averaging (over time) constant [0.0-1.0]
            average: Whether to average [True, False]
            win: the window taps generation function
        """
        gr.hier_block2.__init__(self, self._name,
                                gr.io_signature(1, 1, self._item_size),          # Input signature
                                gr.io_signature(1, 1, gr.sizeof_float*fft_size)) # Output signature

        self._sd = stream_to_vector_decimator(item_size=self._item_size,
                                              sample_rate=sample_rate,
                                              vec_rate=frame_rate,
                                              vec_len=fft_size)

        if win is None: win = window.blackmanharris
        fft_window = win(fft_size)
        fft = self._fft_block[0](fft_size, True, fft_window)
        window_power = sum(map(lambda x: x*x, fft_window))

        c2magsq = gr.complex_to_mag_squared(fft_size)
        self._avg = filter.single_pole_iir_filter_ff(1.0, fft_size)
        self._log = gr.nlog10_ff(10, fft_size,
                                 -20*math.log10(fft_size)              # Adjust for number of bins
                                 -10*math.log10(window_power/fft_size) # Adjust for windowing loss
                                 -20*math.log10(ref_scale/2))      # Adjust for reference scale
        self.connect(self, self._sd, fft, c2magsq, self._avg, self._log, self)

        self._average = average
        self._avg_alpha = avg_alpha
        self.set_avg_alpha(avg_alpha)
        self.set_average(average)
Exemple #34
0
  def __init__(self, data_tones, num_symbols, mode=0):
    symbol_size = data_tones * gr.sizeof_gr_complex
    gr.hier_block2.__init__(self, "SNR",
      gr.io_signature2(2,2, symbol_size, symbol_size),
      gr.io_signature(1,1, gr.sizeof_float))

    sub = gr.sub_cc(data_tones)
    self.connect((self,0), (sub,0))
    self.connect((self,1), (sub,1))

    err = gr.complex_to_mag_squared(data_tones);
    self.connect(sub, err);
    pow = gr.complex_to_mag_squared(data_tones);
    self.connect((self,1), pow);

    if mode == 0:
      # one snr per symbol (num_symbols is ignored)
      snr = gr.divide_ff()
      self.connect(pow, gr.vector_to_stream(gr.sizeof_float, data_tones),
        gr.integrate_ff(data_tones), (snr,0))
      self.connect(err, gr.vector_to_stream(gr.sizeof_float, data_tones),
        gr.integrate_ff(data_tones), (snr,1))
      out = snr
    elif mode == 1:
      # one snr per packet
      snr = gr.divide_ff()
      self.connect(pow, gr.vector_to_stream(gr.sizeof_float, data_tones),
        gr.integrate_ff(data_tones*num_symbols), (snr,0))
      self.connect(err, gr.vector_to_stream(gr.sizeof_float, data_tones),
        gr.integrate_ff(data_tones*num_symbols), (snr,1))
      out = snr
    elif mode == 2:
      # one snr per frequency bin
      snr = gr.divide_ff(data_tones)
      self.connect(pow, raw.symbol_avg(data_tones, num_symbols), (snr,0))
      self.connect(err, raw.symbol_avg(data_tones, num_symbols), (snr,1))
      out = gr.vector_to_stream(gr.sizeof_float, data_tones)
      self.connect(snr, out)

    self.connect(out, gr.nlog10_ff(10), self)
Exemple #35
0
    def __init__( self ):
        gr.hier_block2.__init__(self, "agc",
                                gr.io_signature(1,1,gr.sizeof_float),
                                gr.io_signature(1,1,gr.sizeof_float))

        self.split = gr.multiply_const_ff( 1 )
        self.sqr   = gr.multiply_ff( )
        self.int0  = gr.iir_filter_ffd( [.004, 0], [0, .999] )
        self.offs  = gr.add_const_ff( -30 )
        self.gain  = gr.multiply_const_ff( 70 )
        self.log   = gr.nlog10_ff( 10, 1 )
        self.agc   = gr.divide_ff( )

        self.connect(self,       self.split)
        self.connect(self.split, (self.agc, 0))
        self.connect(self.split, (self.sqr, 0))
        self.connect(self.split, (self.sqr, 1))
        self.connect(self.sqr,    self.int0)
        self.connect(self.int0,   self.log)
        self.connect(self.log,    self.offs)
        self.connect(self.offs,   self.gain)
        self.connect(self.gain,  (self.agc, 1))
        self.connect(self.agc,    self)
Exemple #36
0
    def __init__(self):
        gr.hier_block2.__init__(self, "agc",
                                gr.io_signature(1, 1, gr.sizeof_float),
                                gr.io_signature(1, 1, gr.sizeof_float))

        self.split = gr.multiply_const_ff(1)
        self.sqr = gr.multiply_ff()
        self.int0 = gr.iir_filter_ffd([.004, 0], [0, .999])
        self.offs = gr.add_const_ff(-30)
        self.gain = gr.multiply_const_ff(70)
        self.log = gr.nlog10_ff(10, 1)
        self.agc = gr.divide_ff()

        self.connect(self, self.split)
        self.connect(self.split, (self.agc, 0))
        self.connect(self.split, (self.sqr, 0))
        self.connect(self.split, (self.sqr, 1))
        self.connect(self.sqr, self.int0)
        self.connect(self.int0, self.log)
        self.connect(self.log, self.offs)
        self.connect(self.offs, self.gain)
        self.connect(self.gain, (self.agc, 1))
        self.connect(self.agc, self)
Exemple #37
0
    def __init__(self, subc, vlen, ss):
        gr.hier_block2.__init__(
            self, "new_snr_estimator",
            gr.io_signature(1, 1, gr.sizeof_gr_complex * vlen),
            gr.io_signature(1, 1, gr.sizeof_float))

        print "Created Milan's SNR estimator"

        trigger = [0] * vlen
        trigger[0] = 1

        u = range(vlen / ss * (ss - 1))
        zeros_ind = map(lambda z: z + 1 + z / (ss - 1), u)

        skip1 = skip(gr.sizeof_gr_complex, vlen)
        for x in zeros_ind:
            skip1.skip(x)

        #print "skipped zeros",zeros_ind

        v = range(vlen / ss)
        ones_ind = map(lambda z: z * ss, v)

        skip2 = skip(gr.sizeof_gr_complex, vlen)
        for x in ones_ind:
            skip2.skip(x)

        #print "skipped ones",ones_ind

        v2s = gr.vector_to_stream(gr.sizeof_gr_complex, vlen)
        s2v1 = gr.stream_to_vector(gr.sizeof_gr_complex, vlen / ss)
        trigger_src_1 = gr.vector_source_b(trigger, True)

        s2v2 = gr.stream_to_vector(gr.sizeof_gr_complex, vlen / ss * (ss - 1))
        trigger_src_2 = gr.vector_source_b(trigger, True)

        mag_sq_ones = gr.complex_to_mag_squared(vlen / ss)
        mag_sq_zeros = gr.complex_to_mag_squared(vlen / ss * (ss - 1))

        filt_ones = gr.single_pole_iir_filter_ff(0.1, vlen / ss)
        filt_zeros = gr.single_pole_iir_filter_ff(0.1, vlen / ss * (ss - 1))

        sum_ones = vector_sum_vff(vlen / ss)
        sum_zeros = vector_sum_vff(vlen / ss * (ss - 1))

        D = gr.divide_ff()
        P = gr.multiply_ff()
        mult1 = gr.multiply_const_ff(ss - 1.0)
        add1 = gr.add_const_ff(-1.0)
        mult2 = gr.multiply_const_ff(1. / ss)
        scsnrdb = gr.nlog10_ff(10, 1, 0)
        filt_end = gr.single_pole_iir_filter_ff(0.1)

        self.connect(self, v2s, skip1, s2v1, mag_sq_ones, filt_ones, sum_ones)
        self.connect(trigger_src_1, (skip1, 1))

        self.connect(v2s, skip2, s2v2, mag_sq_zeros, filt_zeros, sum_zeros)
        self.connect(trigger_src_2, (skip2, 1))

        self.connect(sum_ones, D)
        self.connect(sum_zeros, (D, 1))
        self.connect(D, mult1, add1, mult2)

        self.connect(mult2, scsnrdb, filt_end, self)
Exemple #38
0
    def __init__(self,
                 parent,
                 baseband_freq=0,
                 ref_scale=2.0,
                 y_per_div=10,
                 y_divs=8,
                 ref_level=50,
                 sample_rate=1,
                 fft_size=512,
                 fft_rate=default_fft_rate,
                 average=False,
                 avg_alpha=None,
                 title='',
                 size=default_fftsink_size,
                 peak_hold=False,
                 use_persistence=False,
                 persist_alpha=0.2,
                 **kwargs):

        gr.hier_block2.__init__(self, "fft_sink_c",
                                gr.io_signature(1, 1, gr.sizeof_gr_complex),
                                gr.io_signature(0, 0, 0))

        fft_sink_base.__init__(self,
                               input_is_real=False,
                               baseband_freq=baseband_freq,
                               y_per_div=y_per_div,
                               y_divs=y_divs,
                               ref_level=ref_level,
                               sample_rate=sample_rate,
                               fft_size=fft_size,
                               fft_rate=fft_rate,
                               average=average,
                               avg_alpha=avg_alpha,
                               title=title,
                               peak_hold=peak_hold,
                               use_persistence=use_persistence,
                               persist_alpha=persist_alpha)

        self.s2p = gr.stream_to_vector(gr.sizeof_gr_complex, self.fft_size)
        self.one_in_n = gr.keep_one_in_n(
            gr.sizeof_gr_complex * self.fft_size,
            max(1, int(self.sample_rate / self.fft_size / self.fft_rate)))

        mywindow = window.blackmanharris(self.fft_size)
        self.fft = gr.fft_vcc(self.fft_size, True, mywindow)
        power = 0
        for tap in mywindow:
            power += tap * tap

        self.c2mag = gr.complex_to_mag(self.fft_size)
        self.avg = gr.single_pole_iir_filter_ff(1.0, self.fft_size)

        # FIXME  We need to add 3dB to all bins but the DC bin
        self.log = gr.nlog10_ff(
            20,
            self.fft_size,
            -10 * math.log10(self.fft_size)  # Adjust for number of bins
            -
            10 * math.log10(power / self.fft_size)  # Adjust for windowing loss
            - 20 * math.log10(ref_scale / 2))  # Adjust for reference scale

        self.sink = gr.message_sink(gr.sizeof_float * self.fft_size, self.msgq,
                                    True)
        self.connect(self, self.s2p, self.one_in_n, self.fft, self.c2mag,
                     self.avg, self.log, self.sink)

        self.win = fft_window(self, parent, size=size)
        self.set_average(self.average)
        self.set_use_persistence(self.use_persistence)
        self.set_persist_alpha(self.persist_alpha)
        self.set_peak_hold(self.peak_hold)
Exemple #39
0
    def __init__(self):
        gr.top_block.__init__(self)

        usage = "usage: %prog [options] min_freq max_freq"
        parser = OptionParser(option_class=eng_option, usage=usage)
        parser.add_option("-R", "--rx-subdev-spec", type="subdev", default=(0,0),
                          help="select USRP Rx side A or B (default=A)")
        parser.add_option("-g", "--gain", type="eng_float", default=None,
                          help="set gain in dB (default is midpoint)")
        parser.add_option("", "--tune-delay", type="eng_float", default=1e-3, metavar="SECS",
                          help="time to delay (in seconds) after changing frequency [default=%default]")
        parser.add_option("", "--dwell-delay", type="eng_float", default=10e-3, metavar="SECS",
                          help="time to dwell (in seconds) at a given frequncy [default=%default]")
        parser.add_option("-F", "--fft-size", type="int", default=256,
                          help="specify number of FFT bins [default=%default]")
        parser.add_option("-d", "--decim", type="intx", default=16,
                          help="set decimation to DECIM [default=%default]")
        parser.add_option("", "--real-time", action="store_true", default=False,
                          help="Attempt to enable real-time scheduling")
        parser.add_option("-B", "--fusb-block-size", type="int", default=0,
                          help="specify fast usb block size [default=%default]")
        parser.add_option("-N", "--fusb-nblocks", type="int", default=0,
                          help="specify number of fast usb blocks [default=%default]")

        (options, args) = parser.parse_args()
        if len(args) != 2:
            parser.print_help()
            sys.exit(1)

        self.min_freq = eng_notation.str_to_num(args[0])
        self.max_freq = eng_notation.str_to_num(args[1])

        if self.min_freq > self.max_freq:
            self.min_freq, self.max_freq = self.max_freq, self.min_freq   # swap them

	self.fft_size = options.fft_size


        if not options.real_time:
            realtime = False
        else:
            # Attempt to enable realtime scheduling
            r = gr.enable_realtime_scheduling()
            if r == gr.RT_OK:
                realtime = True
            else:
                realtime = False
                print "Note: failed to enable realtime scheduling"

        # If the user hasn't set the fusb_* parameters on the command line,
        # pick some values that will reduce latency.

        if 1:
            if options.fusb_block_size == 0 and options.fusb_nblocks == 0:
                if realtime:                        # be more aggressive
                    options.fusb_block_size = gr.prefs().get_long('fusb', 'rt_block_size', 1024)
                    options.fusb_nblocks    = gr.prefs().get_long('fusb', 'rt_nblocks', 16)
                else:
                    options.fusb_block_size = gr.prefs().get_long('fusb', 'block_size', 4096)
                    options.fusb_nblocks    = gr.prefs().get_long('fusb', 'nblocks', 16)
    
        #print "fusb_block_size =", options.fusb_block_size
	#print "fusb_nblocks    =", options.fusb_nblocks

        # build graph
        
        self.u = usrp.source_c(fusb_block_size=options.fusb_block_size,
                               fusb_nblocks=options.fusb_nblocks)


        adc_rate = self.u.adc_rate()                # 64 MS/s
        usrp_decim = options.decim
        self.u.set_decim_rate(usrp_decim)
        usrp_rate = adc_rate / usrp_decim

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


	s2v = gr.stream_to_vector(gr.sizeof_gr_complex, self.fft_size)

        mywindow = window.blackmanharris(self.fft_size)
        fft = gr.fft_vcc(self.fft_size, True, mywindow)
        power = 0
        for tap in mywindow:
            power += tap*tap
            
        c2mag = gr.complex_to_mag_squared(self.fft_size)

        # FIXME the log10 primitive is dog slow
        log = gr.nlog10_ff(10, self.fft_size,
                           -20*math.log10(self.fft_size)-10*math.log10(power/self.fft_size))
		
        # Set the freq_step to 75% of the actual data throughput.
        # This allows us to discard the bins on both ends of the spectrum.

        self.freq_step = 0.75 * usrp_rate
        self.min_center_freq = self.min_freq + self.freq_step/2
        nsteps = math.ceil((self.max_freq - self.min_freq) / self.freq_step)
        self.max_center_freq = self.min_center_freq + (nsteps * self.freq_step)

        self.next_freq = self.min_center_freq
        
        tune_delay  = max(0, int(round(options.tune_delay * usrp_rate / self.fft_size)))  # in fft_frames
        dwell_delay = max(1, int(round(options.dwell_delay * usrp_rate / self.fft_size))) # in fft_frames

        self.msgq = gr.msg_queue(16)
        self._tune_callback = tune(self)        # hang on to this to keep it from being GC'd
        stats = gr.bin_statistics_f(self.fft_size, self.msgq,
                                    self._tune_callback, tune_delay, dwell_delay)

        # FIXME leave out the log10 until we speed it up
	#self.connect(self.u, s2v, fft, c2mag, log, stats)
	self.connect(self.u, s2v, fft, c2mag, stats)

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

        self.set_gain(options.gain)
	print "gain =", options.gain
    def __init__(self):
        gr.top_block.__init__(self)

        usage = "usage: %prog [options] host min_freq max_freq"
        parser = OptionParser(option_class=eng_option, usage=usage)
        parser.add_option("-g", "--gain", type="eng_float", default=None,
                          help="set gain in dB (default is midpoint)")
        parser.add_option("", "--tune-delay", type="eng_float", default=5e-5, metavar="SECS",
                          help="time to delay (in seconds) after changing frequency [default=%default]")
        parser.add_option("", "--dwell-delay", type="eng_float", default=50e-5, metavar="SECS",
                          help="time to dwell (in seconds) at a given frequncy [default=%default]")
        parser.add_option("-F", "--fft-size", type="int", default=256,
                          help="specify number of FFT bins [default=%default]")
        parser.add_option("-d", "--decim", type="intx", default=16,
                          help="set decimation to DECIM [default=%default]")
        parser.add_option("", "--real-time", action="store_true", default=False,
                          help="Attempt to enable real-time scheduling")

        (options, args) = parser.parse_args()
        if len(args) != 3:
            parser.print_help()
            sys.exit(1)

        self.address  = args[0]
        self.min_freq = eng_notation.str_to_num(args[1])
        self.max_freq = eng_notation.str_to_num(args[2])

        self.decim = options.decim
        self.gain  = options.gain
        
        if self.min_freq > self.max_freq:
            self.min_freq, self.max_freq = self.max_freq, self.min_freq   # swap them

	self.fft_size = options.fft_size

        if not options.real_time:
            realtime = False
        else:
            # Attempt to enable realtime scheduling
            r = gr.enable_realtime_scheduling()
            if r == gr.RT_OK:
                realtime = True
            else:
                realtime = False
                print "Note: failed to enable realtime scheduling"

        adc_rate = 102.4e6
        self.int_rate = adc_rate / self.decim
        print "Sampling rate: ", self.int_rate

        # build graph
        self.port = 10001
        self.src = msdd.source_simple(self.address, self.port)
        self.src.set_decim_rate(self.decim)

        self.set_gain(self.gain)
        self.set_freq(self.min_freq)

	s2v = gr.stream_to_vector(gr.sizeof_gr_complex, self.fft_size)

        mywindow = window.blackmanharris(self.fft_size)
        fft = gr.fft_vcc(self.fft_size, True, mywindow, True)
        power = 0
        for tap in mywindow:
            power += tap*tap
        
        norm = gr.multiply_const_cc(1.0/self.fft_size)
        c2mag = gr.complex_to_mag_squared(self.fft_size)

        # FIXME the log10 primitive is dog slow
        log = gr.nlog10_ff(10, self.fft_size,
                           -20*math.log10(self.fft_size)-10*math.log10(power/self.fft_size))
		
        # Set the freq_step to % of the actual data throughput.
        # This allows us to discard the bins on both ends of the spectrum.
        self.percent = 0.4

        self.freq_step = self.percent * self.int_rate
        self.min_center_freq = self.min_freq + self.freq_step/2
        nsteps = math.ceil((self.max_freq - self.min_freq) / self.freq_step)
        self.max_center_freq = self.min_center_freq + (nsteps * self.freq_step)

        self.next_freq = self.min_center_freq
        
        tune_delay  = max(0, int(round(options.tune_delay * self.int_rate / self.fft_size)))  # in fft_frames
        dwell_delay = max(1, int(round(options.dwell_delay * self.int_rate / self.fft_size))) # in fft_frames

        self.msgq = gr.msg_queue(16)
        self._tune_callback = tune(self)        # hang on to this to keep it from being GC'd
        stats = gr.bin_statistics_f(self.fft_size, self.msgq,
                                    self._tune_callback, tune_delay, dwell_delay)

        # FIXME leave out the log10 until we speed it up
	self.connect(self.src, s2v, fft, c2mag, log, stats)
    def __init__(self):
        gr.top_block.__init__(self)

        usage = "usage: %prog [options] min_freq max_freq"
        parser = OptionParser(option_class=eng_option, usage=usage)
        parser.add_option("-a", "--args", type="string", default="",
                          help="UHD device device address args [default=%default]")
        parser.add_option("", "--spec", type="string", default=None,
	                  help="Subdevice of UHD device where appropriate")
        parser.add_option("-A", "--antenna", type="string", default=None,
                          help="select Rx Antenna where appropriate")
        parser.add_option("-s", "--samp-rate", type="eng_float", default=1e6,
                          help="set sample rate [default=%default]")
        parser.add_option("-g", "--gain", type="eng_float", default=None,
                          help="set gain in dB (default is midpoint)")
        parser.add_option("", "--tune-delay", type="eng_float",
                          default=1e-3, metavar="SECS",
                          help="time to delay (in seconds) after changing frequency [default=%default]")
        parser.add_option("", "--dwell-delay", type="eng_float",
                          default=10e-3, metavar="SECS",
                          help="time to dwell (in seconds) at a given frequency [default=%default]")
        parser.add_option("", "--channel-bandwidth", type="eng_float",
                          default=12.5e3, metavar="Hz",
                          help="channel bandwidth of fft bins in Hz [default=%default]")
        parser.add_option("-F", "--fft-size", type="int", default=256,
                          help="specify number of FFT bins [default=%default]")
        parser.add_option("", "--real-time", action="store_true", default=False,
                          help="Attempt to enable real-time scheduling")

        (options, args) = parser.parse_args()
        if len(args) != 2:
            parser.print_help()
            sys.exit(1)

        self.min_freq = eng_notation.str_to_num(args[0])
        self.max_freq = eng_notation.str_to_num(args[1])

        if self.min_freq > self.max_freq:
            # swap them
            self.min_freq, self.max_freq = self.max_freq, self.min_freq

        self.fft_size = options.fft_size
        self.channel_bandwidth = options.channel_bandwidth
        
        if not options.real_time:
            realtime = False
        else:
            # Attempt to enable realtime scheduling
            r = gr.enable_realtime_scheduling()
            if r == gr.RT_OK:
                realtime = True
            else:
                realtime = False
                print "Note: failed to enable realtime scheduling"

        # build graph
        self.u = uhd.usrp_source(device_addr=options.args,
                                 stream_args=uhd.stream_args('fc32'))

        # Set the subdevice spec
        if(options.spec):
            self.u.set_subdev_spec(options.spec, 0)

        # Set the antenna
        if(options.antenna):
            self.u.set_antenna(options.antenna, 0)

        self.usrp_rate = usrp_rate = options.samp_rate
        self.u.set_samp_rate(usrp_rate)
        dev_rate = self.u.get_samp_rate()

        s2v = gr.stream_to_vector(gr.sizeof_gr_complex, self.fft_size)

        mywindow = window.blackmanharris(self.fft_size)
        fft = gr.fft_vcc(self.fft_size, True, mywindow, True)
        power = 0
        for tap in mywindow:
            power += tap*tap

        c2mag = gr.complex_to_mag_squared(self.fft_size)

        # FIXME the log10 primitive is dog slow
        log = gr.nlog10_ff(10, self.fft_size,
                           -20*math.log10(self.fft_size)-10*math.log10(power/self.fft_size))

        # Set the freq_step to 75% of the actual data throughput.
        # This allows us to discard the bins on both ends of the spectrum.

        self.freq_step = 0.75 * usrp_rate
        self.min_center_freq = self.min_freq + self.freq_step/2
        nsteps = math.ceil((self.max_freq - self.min_freq) / self.freq_step)
        self.max_center_freq = self.min_center_freq + (nsteps * self.freq_step)

        self.next_freq = self.min_center_freq

        tune_delay  = max(0, int(round(options.tune_delay * usrp_rate / self.fft_size)))  # in fft_frames
        dwell_delay = max(1, int(round(options.dwell_delay * usrp_rate / self.fft_size))) # in fft_frames

        self.msgq = gr.msg_queue(16)
        self._tune_callback = tune(self)        # hang on to this to keep it from being GC'd
        stats = gr.bin_statistics_f(self.fft_size, self.msgq,
                                    self._tune_callback, tune_delay,
                                    dwell_delay)

        # FIXME leave out the log10 until we speed it up
        #self.connect(self.u, s2v, fft, c2mag, log, stats)
        self.connect(self.u, s2v, fft, c2mag, stats)

        if options.gain is None:
            # if no gain was specified, use the mid-point in dB
            g = self.u.get_gain_range()
            options.gain = float(g.start()+g.stop())/2.0

        self.set_gain(options.gain)
        print "gain =", options.gain
    def __init__(self):
        gr.top_block.__init__(self)

        # Build an options parser to bring in information from the user on usage
        usage = "usage: %prog [options] host min_freq max_freq"
        parser = OptionParser(option_class=eng_option, usage=usage)
        parser.add_option("-g", "--gain", type="eng_float", default=32,
                          help="set gain in dB (default is midpoint)")
        parser.add_option("", "--tune-delay", type="eng_float", default=5e-5, metavar="SECS",
                          help="time to delay (in seconds) after changing frequency [default=%default]")
        parser.add_option("", "--dwell-delay", type="eng_float", default=50e-5, metavar="SECS",
                          help="time to dwell (in seconds) at a given frequncy [default=%default]")
        parser.add_option("-F", "--fft-size", type="int", default=256,
                          help="specify number of FFT bins [default=%default]")
        parser.add_option("-d", "--decim", type="intx", default=16,
                          help="set decimation to DECIM [default=%default]")
        parser.add_option("", "--real-time", action="store_true", default=False,
                          help="Attempt to enable real-time scheduling")

        (options, args) = parser.parse_args()
        if len(args) != 3:
            parser.print_help()
            sys.exit(1)

        # get user-provided info on address of MSDD and frequency to sweep
        self.address  = args[0]
        self.min_freq = eng_notation.str_to_num(args[1])
        self.max_freq = eng_notation.str_to_num(args[2])

        self.decim = options.decim
        self.gain  = options.gain
        
        if self.min_freq > self.max_freq:
            self.min_freq, self.max_freq = self.max_freq, self.min_freq   # swap them

	self.fft_size = options.fft_size

        if not options.real_time:
            realtime = False
        else:
            # Attempt to enable realtime scheduling
            r = gr.enable_realtime_scheduling()
            if r == gr.RT_OK:
                realtime = True
            else:
                realtime = False
                print "Note: failed to enable realtime scheduling"

        # Sampling rate is hardcoded and cannot be read off device
        adc_rate = 102.4e6
        self.int_rate = adc_rate / self.decim
        print "Sampling rate: ", self.int_rate

        # build graph
        self.port = 10001   # required port for UDP packets
	
	#	which board,	op mode,	adx,	port
#        self.src = msdd.source_c(0, 1, self.address, self.port)  # build source object

	self.conv = gr.interleaved_short_to_complex();

	self.src = msdd.source_simple(self.address,self.port);
        self.src.set_decim_rate(self.decim)                      # set decimation rate
#        self.src.set_desired_packet_size(0, 1460)                # set packet size to collect

        self.set_gain(self.gain)                                 # set receiver's attenuation
        self.set_freq(self.min_freq)                             # set receiver's rx frequency
        
        # restructure into vector format for FFT input
	s2v = gr.stream_to_vector(gr.sizeof_gr_complex, self.fft_size)

        # set up FFT processing block
        mywindow = window.blackmanharris(self.fft_size)
        fft = gr.fft_vcc(self.fft_size, True, mywindow, True)
        power = 0
        for tap in mywindow:
            power += tap*tap
        
        # calculate magnitude squared of output of FFT
        c2mag = gr.complex_to_mag_squared(self.fft_size)

        # FIXME the log10 primitive is dog slow
        log = gr.nlog10_ff(10, self.fft_size,
                           -20*math.log10(self.fft_size)-10*math.log10(power/self.fft_size))
		
        # Set the freq_step to % of the actual data throughput.
        # This allows us to discard the bins on both ends of the spectrum.
        self.percent = 0.4

        # Calculate the frequency steps to use in the collection over the whole bandwidth
        self.freq_step = self.percent * self.int_rate
        self.min_center_freq = self.min_freq + self.freq_step/2
        nsteps = math.ceil((self.max_freq - self.min_freq) / self.freq_step)
        self.max_center_freq = self.min_center_freq + (nsteps * self.freq_step)

        self.next_freq = self.min_center_freq
        
        # use these values to set receiver settling time between samples and sampling time
        # the default values provided seem to work well with the MSDD over 100 Mbps ethernet
        tune_delay  = max(0, int(round(options.tune_delay * self.int_rate / self.fft_size)))  # in fft_frames
        dwell_delay = max(1, int(round(options.dwell_delay * self.int_rate / self.fft_size))) # in fft_frames

        # set up message callback routine to get data from bin_statistics_f block
        self.msgq = gr.msg_queue(16)
        self._tune_callback = tune(self)        # hang on to this to keep it from being GC'd

        # FIXME this block doesn't like to work with negatives because of the "d_max[i]=0" on line
        # 151 of gr_bin_statistics_f.cc file. Set this to -10000 or something to get it to work.
        stats = gr.bin_statistics_f(self.fft_size, self.msgq,
                                    self._tune_callback, tune_delay, dwell_delay)

        # FIXME there's a concern over the speed of the log calculation
        # We can probably calculate the log inside the stats block
	self.connect(self.src, self.conv, s2v, fft, c2mag, log, stats)
    def __init__(self, demod_class, rx_callback, options, source_block):
        gr.hier_block2.__init__(self, "receive_path",
                                gr.io_signature(1, 1, gr.sizeof_gr_complex),
                                gr.io_signature(0, 0, 0))

        options = copy.copy(
            options)  # make a copy so we can destructively modify

        self._verbose = options.verbose
        self._bitrate = options.bitrate  # desired bit rate

        self._rx_callback = rx_callback  # this callback is fired when a packet arrives

        self._demod_class = demod_class  # the demodulator_class we're using

        self._chbw_factor = options.chbw_factor  # channel filter bandwidth factor

        # Get demod_kwargs
        demod_kwargs = self._demod_class.extract_kwargs_from_options(options)

        #Give hooks of usrp to blocks downstream
        self.source_block = source_block

        #########################################
        # Build Blocks
        #########################################

        # Build the demodulator
        self.demodulator = self._demod_class(**demod_kwargs)

        # Make sure the channel BW factor is between 1 and sps/2
        # or the filter won't work.
        if (self._chbw_factor < 1.0
                or self._chbw_factor > self.samples_per_symbol() / 2):
            sys.stderr.write(
                "Channel bandwidth factor ({0}) must be within the range [1.0, {1}].\n"
                .format(self._chbw_factor,
                        self.samples_per_symbol() / 2))
            sys.exit(1)

    # Design filter to get actual channel we want
        sw_decim = 1
        chan_coeffs = gr.firdes.low_pass(
            1.0,  # gain
            sw_decim * self.samples_per_symbol(),  # sampling rate
            self._chbw_factor,  # midpoint of trans. band
            0.5,  # width of trans. band
            gr.firdes.WIN_HANN)  # filter type
        self.channel_filter = gr.fft_filter_ccc(sw_decim, chan_coeffs)

        # receiver
        self.packet_receiver = \
            digital.demod_pkts(self.demodulator,
                               access_code=None,
                               callback=self._rx_callback,
                               threshold=-1)

        # Carrier Sensing Blocks
        alpha = 0.001
        thresh = 30  # in dB, will have to adjust
        self.probe = gr.probe_avg_mag_sqrd_c(thresh, alpha)

        # Display some information about the setup
        if self._verbose:
            self._print_verbage()

        # More Carrier Sensing with FFT
        #self.gr_vector_sink = gr.vector_sink_c(1024)
        #self.gr_stream_to_vector = gr.stream_to_vector(gr.sizeof_gr_complex*1, 1024)
        #self.gr_head = gr.head(gr.sizeof_gr_complex*1024, 1024)
        #self.fft = fft.fft_vcc(1024, True, (window.blackmanharris(1024)), True, 1)

        # Parameters
        usrp_rate = options.bitrate
        self.fft_size = 1024
        self.min_freq = 2.4e9 - 0.75e6
        self.max_freq = 2.4e9 + 0.75e6
        self.tune_delay = 0.001
        self.dwell_delay = 0.01

        s2v = gr.stream_to_vector(gr.sizeof_gr_complex, self.fft_size)

        mywindow = window.blackmanharris(self.fft_size)
        fft = gr.fft_vcc(self.fft_size, True, mywindow)
        power = 0
        for tap in mywindow:
            power += tap * tap

        c2mag = gr.complex_to_mag_squared(self.fft_size)

        # FIXME the log10 primitive is dog slow
        log = gr.nlog10_ff(
            10, self.fft_size, -20 * math.log10(self.fft_size) -
            10 * math.log10(power / self.fft_size))

        # Set the freq_step to 75% of the actual data throughput.
        # This allows us to discard the bins on both ends of the spectrum.
        #self.freq_step = 0.75 * usrp_rate
        #self.min_center_freq = self.min_freq + self.freq_step/2
        #nsteps = math.ceil((self.max_freq - self.min_freq) / self.freq_step)
        #self.max_center_freq = self.min_center_freq + (nsteps * self.freq_step)

        self.freq_step = 1.5e6
        self.min_center_freq = self.min_freq
        nsteps = 1
        self.max_center_freq = self.max_freq

        self.next_freq = self.min_center_freq

        tune_delay = max(0,
                         int(round(self.tune_delay * usrp_rate /
                                   self.fft_size)))  # in fft_frames
        dwell_delay = max(1,
                          int(
                              round(self.dwell_delay * usrp_rate /
                                    self.fft_size)))  # in fft_frames

        self.msgq = gr.msg_queue(16)
        self._tune_callback = tune(
            self)  # hang on to this to keep it from being GC'd
        stats = gr.bin_statistics_f(self.fft_size, self.msgq,
                                    self._tune_callback, tune_delay,
                                    dwell_delay)

        ######################################################
        # Connect Blocks Together
        ######################################################
        #channel-filter-->Probe_Avg_Mag_Sqrd
        #	       -->Packet_Receiver (Demod Done Here!!)
        #

        # connect FFT sampler to system
        #self.connect(self, self.gr_stream_to_vector, self.fft, self.gr_vector_sink)

        # connect block input to channel filter
        self.connect(self, self.channel_filter)

        # connect the channel input filter to the carrier power detector
        self.connect(self.channel_filter, self.probe)

        # connect channel filter to the packet receiver
        self.connect(self.channel_filter, self.packet_receiver)

        # FIXME leave out the log10 until we speed it up
        #self.connect(self.u, s2v, fft, c2mag, log, stats)
        self.connect(self.channel_filter, s2v, fft, c2mag, stats)
    def __init__(self):
        gr.top_block.__init__(self)

        # Build an options parser to bring in information from the user on usage
        usage = "usage: %prog [options] host min_freq max_freq"
        parser = OptionParser(option_class=eng_option, usage=usage)
        parser.add_option("-g",
                          "--gain",
                          type="eng_float",
                          default=32,
                          help="set gain in dB (default is midpoint)")
        parser.add_option(
            "",
            "--tune-delay",
            type="eng_float",
            default=5e-5,
            metavar="SECS",
            help=
            "time to delay (in seconds) after changing frequency [default=%default]"
        )
        parser.add_option(
            "",
            "--dwell-delay",
            type="eng_float",
            default=50e-5,
            metavar="SECS",
            help=
            "time to dwell (in seconds) at a given frequncy [default=%default]"
        )
        parser.add_option("-F",
                          "--fft-size",
                          type="int",
                          default=256,
                          help="specify number of FFT bins [default=%default]")
        parser.add_option("-d",
                          "--decim",
                          type="intx",
                          default=16,
                          help="set decimation to DECIM [default=%default]")
        parser.add_option("",
                          "--real-time",
                          action="store_true",
                          default=False,
                          help="Attempt to enable real-time scheduling")

        (options, args) = parser.parse_args()
        if len(args) != 3:
            parser.print_help()
            sys.exit(1)

        # get user-provided info on address of MSDD and frequency to sweep
        self.address = args[0]
        self.min_freq = eng_notation.str_to_num(args[1])
        self.max_freq = eng_notation.str_to_num(args[2])

        self.decim = options.decim
        self.gain = options.gain

        if self.min_freq > self.max_freq:
            self.min_freq, self.max_freq = self.max_freq, self.min_freq  # swap them

        self.fft_size = options.fft_size

        if not options.real_time:
            realtime = False
        else:
            # Attempt to enable realtime scheduling
            r = gr.enable_realtime_scheduling()
            if r == gr.RT_OK:
                realtime = True
            else:
                realtime = False
                print "Note: failed to enable realtime scheduling"

        # Sampling rate is hardcoded and cannot be read off device
        adc_rate = 102.4e6
        self.int_rate = adc_rate / self.decim
        print "Sampling rate: ", self.int_rate

        # build graph
        self.port = 10001  # required port for UDP packets

        #	which board,	op mode,	adx,	port
        #        self.src = msdd.source_c(0, 1, self.address, self.port)  # build source object

        self.conv = gr.interleaved_short_to_complex()

        self.src = msdd.source_simple(self.address, self.port)
        self.src.set_decim_rate(self.decim)  # set decimation rate
        #        self.src.set_desired_packet_size(0, 1460)                # set packet size to collect

        self.set_gain(self.gain)  # set receiver's attenuation
        self.set_freq(self.min_freq)  # set receiver's rx frequency

        # restructure into vector format for FFT input
        s2v = gr.stream_to_vector(gr.sizeof_gr_complex, self.fft_size)

        # set up FFT processing block
        mywindow = window.blackmanharris(self.fft_size)
        fft = gr.fft_vcc(self.fft_size, True, mywindow, True)
        power = 0
        for tap in mywindow:
            power += tap * tap

        # calculate magnitude squared of output of FFT
        c2mag = gr.complex_to_mag_squared(self.fft_size)

        # FIXME the log10 primitive is dog slow
        log = gr.nlog10_ff(
            10, self.fft_size, -20 * math.log10(self.fft_size) -
            10 * math.log10(power / self.fft_size))

        # Set the freq_step to % of the actual data throughput.
        # This allows us to discard the bins on both ends of the spectrum.
        self.percent = 0.4

        # Calculate the frequency steps to use in the collection over the whole bandwidth
        self.freq_step = self.percent * self.int_rate
        self.min_center_freq = self.min_freq + self.freq_step / 2
        nsteps = math.ceil((self.max_freq - self.min_freq) / self.freq_step)
        self.max_center_freq = self.min_center_freq + (nsteps * self.freq_step)

        self.next_freq = self.min_center_freq

        # use these values to set receiver settling time between samples and sampling time
        # the default values provided seem to work well with the MSDD over 100 Mbps ethernet
        tune_delay = max(0,
                         int(
                             round(options.tune_delay * self.int_rate /
                                   self.fft_size)))  # in fft_frames
        dwell_delay = max(1,
                          int(
                              round(options.dwell_delay * self.int_rate /
                                    self.fft_size)))  # in fft_frames

        # set up message callback routine to get data from bin_statistics_f block
        self.msgq = gr.msg_queue(16)
        self._tune_callback = tune(
            self)  # hang on to this to keep it from being GC'd

        # FIXME this block doesn't like to work with negatives because of the "d_max[i]=0" on line
        # 151 of gr_bin_statistics_f.cc file. Set this to -10000 or something to get it to work.
        stats = gr.bin_statistics_f(self.fft_size, self.msgq,
                                    self._tune_callback, tune_delay,
                                    dwell_delay)

        # FIXME there's a concern over the speed of the log calculation
        # We can probably calculate the log inside the stats block
        self.connect(self.src, self.conv, s2v, fft, c2mag, log, stats)
    def __init__(self):
        gr.top_block.__init__(self)

        usage = "usage: %prog [options] min_freq max_freq"
        parser = OptionParser(option_class=eng_option, usage=usage)
        parser.add_option("-R", "--rx-subdev-spec", type="subdev", default=(0,0),
                          help="select USRP Rx side A or B (default=A)")
        parser.add_option("-g", "--gain", type="eng_float", default=None,
                          help="set gain in dB (default is midpoint)")
        parser.add_option("", "--tune-delay", type="eng_float", default=1e-4, metavar="SECS",
                          help="time to delay (in seconds) after changing frequency [default=%default]")
        parser.add_option("", "--dwell-delay", type="eng_float", default=1e-3, metavar="SECS",
                          help="time to dwell (in seconds) at a given frequncy [default=%default]")
        parser.add_option("-F", "--fft-size", type="int", default=256,
                          help="specify number of FFT bins [default=%default]")
        parser.add_option("-d", "--decim", type="intx", default=16,
                          help="set decimation to DECIM [default=%default]")
        parser.add_option("", "--real-time", action="store_true", default=False,
                          help="Attempt to enable real-time scheduling")
        parser.add_option("-f", "--freq", type="eng_float",
                          default = 5.2e9, help="set USRP2 carrier frequency, [default=%default]",
                          metavar="FREQ")
        
        (options, args) = parser.parse_args()
        #if len(args) != 2:
            #parser.print_help()
            #sys.exit(1)
        #self.min_freq = eng_notation.str_to_num(args[0])
        #self.max_freq = eng_notation.str_to_num(args[1])
        self.min_freq = options.freq
        self.max_freq = options.freq

        if self.min_freq > self.max_freq:
            self.min_freq, self.max_freq = self.max_freq, self.min_freq   # swap them

	self.fft_size = options.fft_size


        if not options.real_time:
            realtime = False
        else:
            # Attempt to enable realtime scheduling
            r = gr.enable_realtime_scheduling()
            if r == gr.RT_OK:
                realtime = True
            else:
                realtime = False
	        print "Note: failed to enable realtime scheduling"

      #build graph
        
        self.u = usrp2.source_32fc()
        adc_rate = self.u.adc_rate()              # 64 MS/s
        usrp2_decim = options.decim
        self.u.set_decim(usrp2_decim)
        usrp2_rate = adc_rate / usrp2_decim

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


	s2v = gr.stream_to_vector(gr.sizeof_gr_complex, self.fft_size)

        mywindow = window.blackmanharris(self.fft_size)
        fft = gr.fft_vcc(self.fft_size, True, mywindow)
        power = 0
        for tap in mywindow:
            power += tap*tap
            
        c2mag = gr.complex_to_mag_squared(self.fft_size)

        # FIXME the log10 primitive is dog slow
        log = gr.nlog10_ff(10, self.fft_size,
                           -20*math.log10(self.fft_size)-10*math.log10(power/self.fft_size))
		
        # Set the freq_step to 75% of the actual data throughput.
        # This allows us to discard the bins on both ends of the spectrum.

        self.freq_step = 0.75 * usrp2_rate
        self.min_center_freq = self.min_freq + self.freq_step/2
        nsteps = math.ceil((self.max_freq - self.min_freq) / self.freq_step)
        self.max_center_freq = self.min_center_freq + (nsteps * self.freq_step)

        self.next_freq = self.min_center_freq
        
        tune_delay  = max(0, int(round(options.tune_delay * usrp2_rate / self.fft_size)))  # in fft_frames
        dwell_delay = max(1, int(round(options.dwell_delay * usrp2_rate / self.fft_size))) # in fft_frames

        self.msgq = gr.msg_queue(16)
        self._tune_callback = tune(self)        # hang on to this to keep it from being GC'd
        stats = gr.bin_statistics_f(self.fft_size, self.msgq,
                                    self._tune_callback, tune_delay, dwell_delay)

        # FIXME leave out the log10 until we speed it up
	#self.connect(self.u, s2v, fft, c2mag, log, stats)
	self.connect(self.u, s2v, fft, c2mag, stats)

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

        self.u.set_gain(options.gain)
    def __init__(self):
        gr.top_block.__init__(self)

        usage = "usage: %prog [options] min_freq max_freq"
        parser = OptionParser(option_class=eng_option, usage=usage)
        parser.add_option("-a", "--args", type="string", default="",
                          help="UHD device device address args [default=%default]")
        parser.add_option("", "--spec", type="string", default=None,
	                  help="Subdevice of UHD device where appropriate")
        parser.add_option("-A", "--antenna", type="string", default=None,
                          help="select Rx Antenna where appropriate")
        parser.add_option("-s", "--samp-rate", type="eng_float", default=1e6,
                          help="set sample rate [default=%default]")
        parser.add_option("-g", "--gain", type="eng_float", default=None,
                          help="set gain in dB (default is midpoint)")
        parser.add_option("", "--tune-delay", type="eng_float",
                          default=1e-3, metavar="SECS",
                          help="time to delay (in seconds) after changing frequency [default=%default]")
        parser.add_option("", "--dwell-delay", type="eng_float",
                          default=10e-3, metavar="SECS",
                          help="time to dwell (in seconds) at a given frequncy [default=%default]")
        parser.add_option("-F", "--fft-size", type="int", default=256,
                          help="specify number of FFT bins [default=%default]")
        parser.add_option("", "--real-time", action="store_true", default=False,
                          help="Attempt to enable real-time scheduling")

        (options, args) = parser.parse_args()
        if len(args) != 2:
            parser.print_help()
            sys.exit(1)

        self.min_freq = eng_notation.str_to_num(args[0])
        self.max_freq = eng_notation.str_to_num(args[1])

        if self.min_freq > self.max_freq:
            # swap them
            self.min_freq, self.max_freq = self.max_freq, self.min_freq

	self.fft_size = options.fft_size

        if not options.real_time:
            realtime = False
        else:
            # Attempt to enable realtime scheduling
            r = gr.enable_realtime_scheduling()
            if r == gr.RT_OK:
                realtime = True
            else:
                realtime = False
                print "Note: failed to enable realtime scheduling"

        # build graph
        self.u = uhd.usrp_source(device_addr=options.args,
                                 stream_args=uhd.stream_args('fc32'))

        # Set the subdevice spec
        if(options.spec):
            self.u.set_subdev_spec(options.spec, 0)

        # Set the antenna
        if(options.antenna):
            self.u.set_antenna(options.antenna, 0)

        usrp_rate = options.samp_rate
        self.u.set_samp_rate(usrp_rate)
        dev_rate = self.u.get_samp_rate()

	s2v = gr.stream_to_vector(gr.sizeof_gr_complex, self.fft_size)

        mywindow = window.blackmanharris(self.fft_size)
        fft = gr.fft_vcc(self.fft_size, True, mywindow)
        power = 0
        for tap in mywindow:
            power += tap*tap

        c2mag = gr.complex_to_mag_squared(self.fft_size)

        # FIXME the log10 primitive is dog slow
        log = gr.nlog10_ff(10, self.fft_size,
                           -20*math.log10(self.fft_size)-10*math.log10(power/self.fft_size))

        # Set the freq_step to 75% of the actual data throughput.
        # This allows us to discard the bins on both ends of the spectrum.

        self.freq_step = 0.75 * usrp_rate
        self.min_center_freq = self.min_freq + self.freq_step/2
        nsteps = math.ceil((self.max_freq - self.min_freq) / self.freq_step)
        self.max_center_freq = self.min_center_freq + (nsteps * self.freq_step)

        self.next_freq = self.min_center_freq

        tune_delay  = max(0, int(round(options.tune_delay * usrp_rate / self.fft_size)))  # in fft_frames
        dwell_delay = max(1, int(round(options.dwell_delay * usrp_rate / self.fft_size))) # in fft_frames

        self.msgq = gr.msg_queue(16)
        self._tune_callback = tune(self)        # hang on to this to keep it from being GC'd
        stats = gr.bin_statistics_f(self.fft_size, self.msgq,
                                    self._tune_callback, tune_delay,
                                    dwell_delay)

        # FIXME leave out the log10 until we speed it up
	#self.connect(self.u, s2v, fft, c2mag, log, stats)
	self.connect(self.u, s2v, fft, c2mag, stats)

        if options.gain is None:
            # if no gain was specified, use the mid-point in dB
            g = self.u.get_gain_range()
            options.gain = float(g.start()+g.stop())/2.0

        self.set_gain(options.gain)
	print "gain =", options.gain
    def __init__(self):
        gr.top_block.__init__(self)

        usage = "usage: %prog [options] min_freq max_freq"
        parser = OptionParser(option_class=eng_option, usage=usage)
        parser.add_option("-R", "--rx-subdev-spec", type="subdev", default=(0,0),
                          help="select USRP Rx side A or B (default=A)")
        parser.add_option("-g", "--gain", type="eng_float", default=None,
                          help="set gain in dB (default is midpoint)")
        parser.add_option("", "--tune-delay", type="eng_float", default=.01, metavar="SECS",
                          help="time to delay (in seconds) after changing frequency [default=%default]")
        parser.add_option("", "--dwell-delay", type="eng_float", default=.05, metavar="SECS",
                          help="time to dwell (in seconds) at a given frequncy [default=%default]")
        parser.add_option("-F", "--fft-size", type="int", default=1024,
                          help="specify number of FFT bins [default=%default]")
        #updated 2011 May 27, MR
        parser.add_option("-s", "--samp_rate", type="intx", default=6000000,
        				  help="set sample rate to SAMP_RATE [default=%default]")
        parser.add_option("", "--chan-bandwidth", type="intx", default=6000000,
        				  help="set channel bw [default=%default]")
        #parser.add_option("-d", "--decim", type="intx", default=16,
        #                  help="set decimation to DECIM [default=%default]")
        parser.add_option("", "--real-time", action="store_true", default=False,
                          help="Attempt to enable real-time scheduling")
        #parser.add_option("-B", "--fusb-block-size", type="int", default=0,
        #                  help="specify fast usb block size [default=%default]")
        #parser.add_option("-N", "--fusb-nblocks", type="int", default=0,
        #                  help="specify number of fast usb blocks [default=%default]")
        #options added 2011 May 31, MR
        parser.add_option("", "--threshold", type="eng_float", default=-70, 
        				  help="set detection threshold [default=%default]")
        parser.add_option("", "--num-tests", type="intx", default=200,
        				  help="set the number of times to test the frequency band [default=%default]")
        parser.add_option("", "--log-file", action="store_true", default=False,
                          help="log output to a file")

        (options, args) = parser.parse_args()
        if len(args) != 2:
            parser.print_help()
            sys.exit(1)
            
        self.num_tests = options.num_tests
            
        self.threshold = options.threshold
        self.samp_rate = options.samp_rate
        
        self.min_freq = eng_notation.str_to_num(args[0])
        self.max_freq = eng_notation.str_to_num(args[1])
        
        self.log_file = options.log_file
        
        self.num_channels = int((self.max_freq - self.min_freq)/self.samp_rate) + 2
        
        if self.min_freq > self.max_freq:
            self.min_freq, self.max_freq = self.max_freq, self.min_freq   # swap them
            
        self.fft_size = options.fft_size


        if not options.real_time:
            realtime = False
        else:
            # Attempt to enable realtime scheduling
            r = gr.enable_realtime_scheduling()
            if r == gr.RT_OK:
                realtime = True
            else:
                realtime = False
                print "Note: failed to enable realtime scheduling"

        #removed 2011 May 27, MR
        # If the user hasn't set the fusb_* parameters on the command line,
        # pick some values that will reduce latency.

        #if 1:
        #    if options.fusb_block_size == 0 and options.fusb_nblocks == 0:
        #        if realtime:                        # be more aggressive
        #            options.fusb_block_size = gr.prefs().get_long('fusb', 'rt_block_size', 1024)
        #            options.fusb_nblocks    = gr.prefs().get_long('fusb', 'rt_nblocks', 16)
        #        else:
        #            options.fusb_block_size = gr.prefs().get_long('fusb', 'block_size', 4096)
        #            options.fusb_nblocks    = gr.prefs().get_long('fusb', 'nblocks', 16)
    
        #print "fusb_block_size =", options.fusb_block_size
	    #print "fusb_nblocks    =", options.fusb_nblocks

        # build graph
        
        #updated 2011 May 27, MR
        self.u = uhd.usrp_source(device_addr="", io_type=uhd.io_type.COMPLEX_FLOAT32, num_channels=1)
        self.u.set_subdev_spec("", 0)
        self.u.set_antenna("TX/RX", 0)
        self.u.set_samp_rate(options.samp_rate)
        #self.u = usrp.source_c(fusb_block_size=options.fusb_block_size,
        #                       fusb_nblocks=options.fusb_nblocks)


        #adc_rate = self.u.adc_rate()                # 64 MS/s
        #usrp_decim = options.decim
        #self.u.set_decim_rate(usrp_decim)
        self.usrp_rate = self.u.get_samp_rate() #adc_rate / usrp_decim
        print "sample rate is", self.usrp_rate

        #self.u.set_mux(usrp.determine_rx_mux_value(self.u, options.rx_subdev_spec))
        #self.subdev = usrp.selected_subdev(self.u, options.rx_subdev_spec)
        print "Using RX d'board %s" % (self.u.get_dboard_sensor_names(chan=0))#(self.subdev.side_and_name(),)
        
        s2v = gr.stream_to_vector(gr.sizeof_gr_complex, self.fft_size)

        mywindow = window.blackmanharris(self.fft_size)
        fft = gr.fft_vcc(self.fft_size, True, mywindow)
        power = 0
        for tap in mywindow:
            power += tap*tap
            
        c2mag = gr.complex_to_mag_squared(self.fft_size)

        # FIXME the log10 primitive is dog slow
        log = gr.nlog10_ff(10, self.fft_size,
                           -20*math.log10(self.fft_size)-10*math.log10(power/self.fft_size))
		
        # Set the freq_step to 75% of the actual data throughput.
        # This allows us to discard the bins on both ends of the spectrum.

        #changed on 2011 May 31, MR -- maybe change back at some point
        #self.freq_step = 0.75 * self.usrp_rate
        self.freq_step = options.chan_bandwidth
        self.min_center_freq = self.min_freq + self.freq_step/2
        nsteps = math.ceil((self.max_freq - self.min_freq) / self.freq_step)
        self.max_center_freq = self.min_center_freq + (nsteps * self.freq_step)

        self.next_freq = self.min_center_freq
        
        tune_delay  = max(0, int(round(options.tune_delay * self.usrp_rate / self.fft_size)))  # in fft_frames
        dwell_delay = max(1, int(round(options.dwell_delay * self.usrp_rate / self.fft_size))) # in fft_frames

        self.msgq = gr.msg_queue(16)
        self._tune_callback = tune(self)        # hang on to this to keep it from being GC'd
        stats = gr.bin_statistics_f(self.fft_size, self.msgq,
                                    self._tune_callback, tune_delay, dwell_delay)

        # FIXME leave out the log10 until we speed it up
        #self.connect(self.u, s2v, fft, c2mag, log, stats)
        self.connect(self.u, s2v, fft, c2mag, stats)

        if options.gain is None:
            # if no gain was specified, use the mid-point in dB
            # updated 2011 May 31, MR
            #g = self.subdev.gain_range()
            g = self.u.get_gain_range()
            options.gain = float(g.start()+g.stop())/2

        self.set_gain(options.gain)
        print "gain =", options.gain
Exemple #48
0
    def __init__(self):
        gr.top_block.__init__(self, "Simple QAM Simulation")
        Qt.QWidget.__init__(self)
        self.setWindowTitle("Simple QAM Simulation")
        self.setWindowIcon(Qt.QIcon.fromTheme('gnuradio-grc'))
        self.top_scroll_layout = Qt.QVBoxLayout()
        self.setLayout(self.top_scroll_layout)
        self.top_scroll = Qt.QScrollArea()
        self.top_scroll.setFrameStyle(Qt.QFrame.NoFrame)
        self.top_scroll_layout.addWidget(self.top_scroll)
        self.top_scroll.setWidgetResizable(True)
        self.top_widget = Qt.QWidget()
        self.top_scroll.setWidget(self.top_widget)
        self.top_layout = Qt.QVBoxLayout(self.top_widget)
        self.top_grid_layout = Qt.QGridLayout()
        self.top_layout.addLayout(self.top_grid_layout)

        ##################################################
        # Variables
        ##################################################
        self.constellation_cardinality = constellation_cardinality = 16
        self.const_object = const_object = constellations()['qam'](
            constellation_cardinality)
        self.snr_db = snr_db = 20
        self.constellation = constellation = const_object.points()
        self.sps = sps = 8
        self.samp_rate = samp_rate = 250000
        self.noise_amp = noise_amp = sqrt((10**(-snr_db / 10.)) / 2.)
        self.constellation_power = constellation_power = sqrt(
            sum([abs(i)**2
                 for i in constellation]) / constellation_cardinality)

        ##################################################
        # Blocks
        ##################################################
        self.tabid_0 = Qt.QTabWidget()
        self.tabid_0_widget_0 = Qt.QWidget()
        self.tabid_0_layout_0 = Qt.QBoxLayout(Qt.QBoxLayout.TopToBottom,
                                              self.tabid_0_widget_0)
        self.tabid_0_grid_layout_0 = Qt.QGridLayout()
        self.tabid_0_layout_0.addLayout(self.tabid_0_grid_layout_0)
        self.tabid_0.addTab(self.tabid_0_widget_0, "TX")
        self.tabid_0_widget_1 = Qt.QWidget()
        self.tabid_0_layout_1 = Qt.QBoxLayout(Qt.QBoxLayout.TopToBottom,
                                              self.tabid_0_widget_1)
        self.tabid_0_grid_layout_1 = Qt.QGridLayout()
        self.tabid_0_layout_1.addLayout(self.tabid_0_grid_layout_1)
        self.tabid_0.addTab(self.tabid_0_widget_1, "CHANNEL")
        self.tabid_0_widget_2 = Qt.QWidget()
        self.tabid_0_layout_2 = Qt.QBoxLayout(Qt.QBoxLayout.TopToBottom,
                                              self.tabid_0_widget_2)
        self.tabid_0_grid_layout_2 = Qt.QGridLayout()
        self.tabid_0_layout_2.addLayout(self.tabid_0_grid_layout_2)
        self.tabid_0.addTab(self.tabid_0_widget_2, "RX")
        self.top_grid_layout.addWidget(self.tabid_0, 30, 0, 10, 100)
        self.tabid_2 = Qt.QTabWidget()
        self.tabid_2_widget_0 = Qt.QWidget()
        self.tabid_2_layout_0 = Qt.QBoxLayout(Qt.QBoxLayout.TopToBottom,
                                              self.tabid_2_widget_0)
        self.tabid_2_grid_layout_0 = Qt.QGridLayout()
        self.tabid_2_layout_0.addLayout(self.tabid_2_grid_layout_0)
        self.tabid_2.addTab(self.tabid_2_widget_0, "symbol-based")
        self.tabid_2_widget_1 = Qt.QWidget()
        self.tabid_2_layout_1 = Qt.QBoxLayout(Qt.QBoxLayout.TopToBottom,
                                              self.tabid_2_widget_1)
        self.tabid_2_grid_layout_1 = Qt.QGridLayout()
        self.tabid_2_layout_1.addLayout(self.tabid_2_grid_layout_1)
        self.tabid_2.addTab(self.tabid_2_widget_1, "bit-based")
        self.tabid_2_widget_2 = Qt.QWidget()
        self.tabid_2_layout_2 = Qt.QBoxLayout(Qt.QBoxLayout.TopToBottom,
                                              self.tabid_2_widget_2)
        self.tabid_2_grid_layout_2 = Qt.QGridLayout()
        self.tabid_2_layout_2.addLayout(self.tabid_2_grid_layout_2)
        self.tabid_2.addTab(self.tabid_2_widget_2, "BER")
        self.tabid_0_layout_2.addWidget(self.tabid_2)
        self.tabid_1 = Qt.QTabWidget()
        self.tabid_1_widget_0 = Qt.QWidget()
        self.tabid_1_layout_0 = Qt.QBoxLayout(Qt.QBoxLayout.TopToBottom,
                                              self.tabid_1_widget_0)
        self.tabid_1_grid_layout_0 = Qt.QGridLayout()
        self.tabid_1_layout_0.addLayout(self.tabid_1_grid_layout_0)
        self.tabid_1.addTab(self.tabid_1_widget_0, "bit-based")
        self.tabid_1_widget_1 = Qt.QWidget()
        self.tabid_1_layout_1 = Qt.QBoxLayout(Qt.QBoxLayout.TopToBottom,
                                              self.tabid_1_widget_1)
        self.tabid_1_grid_layout_1 = Qt.QGridLayout()
        self.tabid_1_layout_1.addLayout(self.tabid_1_grid_layout_1)
        self.tabid_1.addTab(self.tabid_1_widget_1, "scrambled")
        self.tabid_1_widget_2 = Qt.QWidget()
        self.tabid_1_layout_2 = Qt.QBoxLayout(Qt.QBoxLayout.TopToBottom,
                                              self.tabid_1_widget_2)
        self.tabid_1_grid_layout_2 = Qt.QGridLayout()
        self.tabid_1_layout_2.addLayout(self.tabid_1_grid_layout_2)
        self.tabid_1.addTab(self.tabid_1_widget_2, "symbol-based")
        self.tabid_0_grid_layout_0.addWidget(self.tabid_1, 0, 0, 10, 10)
        self.qtgui_time_sink_x_0 = qtgui.time_sink_f(
            1024,  #size
            samp_rate,  #bw
            "QT GUI Plot",  #name
            1  #number of inputs
        )
        self._qtgui_time_sink_x_0_win = sip.wrapinstance(
            self.qtgui_time_sink_x_0.pyqwidget(), Qt.QWidget)
        self.tabid_2_layout_2.addWidget(self._qtgui_time_sink_x_0_win)
        self.qtgui_sink_x_0_1_0_0 = qtgui.sink_f(
            1024,  #fftsize
            firdes.WIN_BLACKMAN_hARRIS,  #wintype
            0,  #fc
            samp_rate,  #bw
            "QT GUI Plot",  #name
            False,  #plotfreq
            False,  #plotwaterfall
            True,  #plottime
            True,  #plotconst
        )
        self._qtgui_sink_x_0_1_0_0_win = sip.wrapinstance(
            self.qtgui_sink_x_0_1_0_0.pyqwidget(), Qt.QWidget)
        self.tabid_1_layout_0.addWidget(self._qtgui_sink_x_0_1_0_0_win)
        self.qtgui_sink_x_0_1_0 = qtgui.sink_f(
            1024,  #fftsize
            firdes.WIN_BLACKMAN_hARRIS,  #wintype
            0,  #fc
            samp_rate,  #bw
            "QT GUI Plot",  #name
            True,  #plotfreq
            False,  #plotwaterfall
            True,  #plottime
            True,  #plotconst
        )
        self._qtgui_sink_x_0_1_0_win = sip.wrapinstance(
            self.qtgui_sink_x_0_1_0.pyqwidget(), Qt.QWidget)
        self.tabid_1_layout_1.addWidget(self._qtgui_sink_x_0_1_0_win)
        self.qtgui_sink_x_0_1 = qtgui.sink_c(
            1024,  #fftsize
            firdes.WIN_BLACKMAN_hARRIS,  #wintype
            0,  #fc
            samp_rate,  #bw
            "QT GUI Plot",  #name
            False,  #plotfreq
            False,  #plotwaterfall
            True,  #plottime
            True,  #plotconst
        )
        self._qtgui_sink_x_0_1_win = sip.wrapinstance(
            self.qtgui_sink_x_0_1.pyqwidget(), Qt.QWidget)
        self.tabid_1_layout_2.addWidget(self._qtgui_sink_x_0_1_win)
        self.qtgui_sink_x_0_0_0_0 = qtgui.sink_c(
            1024,  #fftsize
            firdes.WIN_BLACKMAN_hARRIS,  #wintype
            0,  #fc
            samp_rate,  #bw
            "QT GUI Plot",  #name
            True,  #plotfreq
            False,  #plotwaterfall
            True,  #plottime
            True,  #plotconst
        )
        self._qtgui_sink_x_0_0_0_0_win = sip.wrapinstance(
            self.qtgui_sink_x_0_0_0_0.pyqwidget(), Qt.QWidget)
        self.tabid_2_layout_0.addWidget(self._qtgui_sink_x_0_0_0_0_win)
        self.qtgui_sink_x_0_0_0 = qtgui.sink_f(
            1024,  #fftsize
            firdes.WIN_BLACKMAN_hARRIS,  #wintype
            0,  #fc
            samp_rate,  #bw
            "QT GUI Plot",  #name
            False,  #plotfreq
            False,  #plotwaterfall
            True,  #plottime
            True,  #plotconst
        )
        self._qtgui_sink_x_0_0_0_win = sip.wrapinstance(
            self.qtgui_sink_x_0_0_0.pyqwidget(), Qt.QWidget)
        self.tabid_2_layout_1.addWidget(self._qtgui_sink_x_0_0_0_win)
        self.qtgui_sink_x_0_0 = qtgui.sink_c(
            1024,  #fftsize
            firdes.WIN_BLACKMAN_hARRIS,  #wintype
            0,  #fc
            samp_rate,  #bw
            "QT GUI Plot",  #name
            True,  #plotfreq
            False,  #plotwaterfall
            True,  #plottime
            False,  #plotconst
        )
        self._qtgui_sink_x_0_0_win = sip.wrapinstance(
            self.qtgui_sink_x_0_0.pyqwidget(), Qt.QWidget)
        self.tabid_0_layout_1.addWidget(self._qtgui_sink_x_0_0_win)
        self.gr_vector_source_x_0_0 = gr.vector_source_b(([1, 0]), True, 1)
        self.gr_vector_source_x_0 = gr.vector_source_b(([1, 0]), True, 1)
        self.gr_unpack_k_bits_bb_0 = gr.unpack_k_bits_bb(
            int(log2(constellation_cardinality)))
        self.gr_throttle_0 = gr.throttle(gr.sizeof_gr_complex * 1, samp_rate)
        self.gr_pack_k_bits_bb_0 = gr.pack_k_bits_bb(
            int(log2(constellation_cardinality)))
        self.gr_null_sink_0 = gr.null_sink(gr.sizeof_char * 1)
        self.gr_noise_source_x_0 = gr.noise_source_c(gr.GR_GAUSSIAN, noise_amp,
                                                     0)
        self.gr_nlog10_ff_0 = gr.nlog10_ff(1, 1, 0)
        self.gr_multiply_const_vxx_0_0 = gr.multiply_const_vcc(
            (1. / constellation_power, ))
        self.gr_multiply_const_vxx_0 = gr.multiply_const_vcc(
            (constellation_power, ))
        self.gr_file_sink_0_1_0 = gr.file_sink(gr.sizeof_gr_complex * 1,
                                               "rx_sym.32fc")
        self.gr_file_sink_0_1_0.set_unbuffered(False)
        self.gr_file_sink_0_1 = gr.file_sink(gr.sizeof_gr_complex * 1,
                                             "tx_sym.32fc")
        self.gr_file_sink_0_1.set_unbuffered(False)
        self.gr_file_sink_0_0 = gr.file_sink(gr.sizeof_char * 1, "rx.8b")
        self.gr_file_sink_0_0.set_unbuffered(False)
        self.gr_file_sink_0 = gr.file_sink(gr.sizeof_char * 1, "tx.8b")
        self.gr_file_sink_0.set_unbuffered(False)
        self.gr_descrambler_bb_0 = gr.descrambler_bb(0xe4001, 0x7ffff, 19)
        self.gr_char_to_float_1_0 = gr.char_to_float(1, 1)
        self.gr_char_to_float_1 = gr.char_to_float(1, 1)
        self.gr_char_to_float_0 = gr.char_to_float(1, 1)
        self.gr_add_xx_0 = gr.add_vcc(1)
        self.digital_scrambler_bb_0 = digital.scrambler_bb(
            0xe4001, 0x7fffF, 19)
        self.digital_constellation_receiver_cb_0 = digital.constellation_receiver_cb(
            const_object.base(), 6.28 / 100, -0.25, +0.25)
        self.digital_chunks_to_symbols_xx_0 = digital.chunks_to_symbols_bc(
            (constellation), 1)
        self.blks2_error_rate_0 = grc_blks2.error_rate(
            type='BER',
            win_size=samp_rate,
            bits_per_symbol=1,
        )

        ##################################################
        # Connections
        ##################################################
        self.connect((self.gr_vector_source_x_0, 0),
                     (self.digital_scrambler_bb_0, 0))
        self.connect((self.digital_scrambler_bb_0, 0),
                     (self.gr_pack_k_bits_bb_0, 0))
        self.connect((self.gr_pack_k_bits_bb_0, 0),
                     (self.digital_chunks_to_symbols_xx_0, 0))
        self.connect((self.digital_constellation_receiver_cb_0, 0),
                     (self.gr_file_sink_0_0, 0))
        self.connect((self.digital_constellation_receiver_cb_0, 0),
                     (self.gr_unpack_k_bits_bb_0, 0))
        self.connect((self.gr_unpack_k_bits_bb_0, 0),
                     (self.gr_descrambler_bb_0, 0))
        self.connect((self.gr_descrambler_bb_0, 0), (self.gr_null_sink_0, 0))
        self.connect((self.gr_multiply_const_vxx_0, 0),
                     (self.digital_constellation_receiver_cb_0, 0))
        self.connect((self.gr_descrambler_bb_0, 0),
                     (self.gr_char_to_float_0, 0))
        self.connect((self.gr_char_to_float_0, 0),
                     (self.qtgui_sink_x_0_0_0, 0))
        self.connect((self.gr_add_xx_0, 0), (self.gr_throttle_0, 0))
        self.connect((self.gr_noise_source_x_0, 0), (self.gr_add_xx_0, 1))
        self.connect((self.digital_chunks_to_symbols_xx_0, 0),
                     (self.gr_multiply_const_vxx_0_0, 0))
        self.connect((self.gr_multiply_const_vxx_0_0, 0),
                     (self.gr_file_sink_0_1, 0))
        self.connect((self.gr_multiply_const_vxx_0_0, 0),
                     (self.qtgui_sink_x_0_1, 0))
        self.connect((self.gr_char_to_float_1, 0),
                     (self.qtgui_sink_x_0_1_0, 0))
        self.connect((self.gr_pack_k_bits_bb_0, 0),
                     (self.gr_char_to_float_1, 0))
        self.connect((self.gr_pack_k_bits_bb_0, 0), (self.gr_file_sink_0, 0))
        self.connect((self.gr_char_to_float_1_0, 0),
                     (self.qtgui_sink_x_0_1_0_0, 0))
        self.connect((self.gr_vector_source_x_0, 0),
                     (self.gr_char_to_float_1_0, 0))
        self.connect((self.gr_multiply_const_vxx_0_0, 0),
                     (self.gr_add_xx_0, 0))
        self.connect((self.gr_add_xx_0, 0), (self.qtgui_sink_x_0_0, 0))
        self.connect((self.gr_throttle_0, 0),
                     (self.gr_multiply_const_vxx_0, 0))
        self.connect((self.gr_throttle_0, 0), (self.gr_file_sink_0_1_0, 0))
        self.connect((self.gr_throttle_0, 0), (self.qtgui_sink_x_0_0_0_0, 0))
        self.connect((self.gr_nlog10_ff_0, 0), (self.qtgui_time_sink_x_0, 0))
        self.connect((self.blks2_error_rate_0, 0), (self.gr_nlog10_ff_0, 0))
        self.connect((self.gr_vector_source_x_0_0, 0),
                     (self.blks2_error_rate_0, 0))
        self.connect((self.gr_descrambler_bb_0, 0),
                     (self.blks2_error_rate_0, 1))
Exemple #49
0
    def __init__(self, subc, vlen, ss):
        gr.hier_block2.__init__(
            self,
            "new_snr_estimator",
            gr.io_signature(2, 2, gr.sizeof_gr_complex * vlen),
            #gr.io_signature2(2,2,gr.sizeof_float*vlen,gr.sizeof_float*vlen/ss*(ss-1)))
            gr.io_signature2(2, 2, gr.sizeof_float * vlen, gr.sizeof_float))

        print "Created Milan's SINR estimator 3"

        #    trigger = [0]*vlen
        #    trigger[0] = 1
        #
        #    v = range (vlen/ss)
        #    ones_ind= map(lambda z: z*ss,v)
        #
        #    skip2_pr0 = skip(gr.sizeof_gr_complex,vlen)
        #    skip2_pr1 = skip(gr.sizeof_gr_complex,vlen)
        #    for x in ones_ind:
        #      skip2_pr0.skip(x)
        #      skip2_pr1.skip(x)
        #
        #    #print "skipped ones",ones_ind
        #
        #    v2s_pr0 = gr.vector_to_stream(gr.sizeof_gr_complex,vlen)
        #    v2s_pr1 = gr.vector_to_stream(gr.sizeof_gr_complex,vlen)
        #
        #    s2v2_pr0 = gr.stream_to_vector(gr.sizeof_gr_complex,vlen/ss*(ss-1))
        #    trigger_src_2_pr0 = gr.vector_source_b(trigger,True)
        #    s2v2_pr1 = gr.stream_to_vector(gr.sizeof_gr_complex,vlen/ss*(ss-1))
        #    trigger_src_2_pr1 = gr.vector_source_b(trigger,True)
        #
        #    mag_sq_zeros_pr0 = gr.complex_to_mag_squared(vlen/ss*(ss-1))
        #    mag_sq_zeros_pr1 = gr.complex_to_mag_squared(vlen/ss*(ss-1))
        #
        #
        #    filt_zeros_pr0 = gr.single_pole_iir_filter_ff(0.01,vlen/ss*(ss-1))
        #    filt_zeros_pr1 = gr.single_pole_iir_filter_ff(0.01,vlen/ss*(ss-1))
        #    v1 = vlen/ss*(ss-1)
        #    vevc1 =[-1]*v1
        #    neg_nomin_z = gr.multiply_const_vff(vevc1)
        #    div_z=gr.divide_ff(vlen/ss*(ss-1))
        #    on_zeros = gr.add_const_vff(vevc1)
        #    sum_zeros = add_vff(vlen/ss*(ss-1))
        #
        # For average
        #sum_all = vector_sum_vff(vlen)
        #mult = gr.multiply_const_ff(1./vlen)
        scsnr_db_av = gr.nlog10_ff(10, 1, 0)
        filt_end_av = gr.single_pole_iir_filter_ff(0.1)
        #
        #
        #    self.connect((self,0),v2s_pr0,skip2_pr0,s2v2_pr0,mag_sq_zeros_pr0,filt_zeros_pr0)
        #    self.connect(trigger_src_2_pr0,(skip2_pr0,1))
        #
        #
        #
        #    self.connect((self,1),v2s_pr1,skip2_pr1,s2v2_pr1,mag_sq_zeros_pr1,filt_zeros_pr1)
        #    self.connect(trigger_src_2_pr1,(skip2_pr1,1))
        #
        #
        #    # On zeros
        #    self.connect(filt_zeros_pr1,(sum_zeros,0))
        #    self.connect(filt_zeros_pr0,neg_nomin_z,(sum_zeros,1))
        #    self.connect(sum_zeros,div_z)
        #    self.connect(filt_zeros_pr0,(div_z,1))

        estimator = sinr_estimator2(vlen, ss)

        scsnr_db = gr.nlog10_ff(10, vlen, 0)
        filt_end = gr.single_pole_iir_filter_ff(0.1, vlen)

        dd = []
        for i in range(vlen / ss):
            dd.extend([i * ss])
        #print dd
        #interpolator = sinr_interpolator(vlen, ss,dd)

        self.connect((self, 0), (estimator, 0))
        self.connect((self, 1), (estimator, 1))
        self.connect(estimator, filt_end, scsnr_db, self)
        self.connect((estimator, 1), scsnr_db_av, filt_end_av, (self, 1))
Exemple #50
0
    def __init__(self, usrp_rate, tuner_callback, options):
        gr.hier_block2.__init__(self, "sense_path",
                gr.io_signature(1, 1, gr.sizeof_gr_complex), # Input signature
                gr.io_signature(0, 0, 0)) # Output signature
        
        self.usrp_rate = usrp_rate
        self.usrp_tune = tuner_callback

        self.num_tests = options.num_tests
            
        self.threshold = options.threshold
        
        self.min_freq = options.start_freq
        self.max_freq = options.end_freq

        if self.min_freq > self.max_freq:
            self.min_freq, self.max_freq = self.max_freq, self.min_freq   # swap them
            
        self.fft_size = options.fft_size


        if not options.real_time:
            realtime = False
        else:
            # Attempt to enable realtime scheduling
            r = gr.enable_realtime_scheduling()
            if r == gr.RT_OK:
                realtime = True
            else:
                realtime = False
                print "Note: failed to enable realtime scheduling"

        # build graph
        s2v = gr.stream_to_vector(gr.sizeof_gr_complex, self.fft_size)

        mywindow = window.blackmanharris(self.fft_size)
        fft = gr.fft_vcc(self.fft_size, True, mywindow)
        power = 0
        for tap in mywindow:
            power += tap*tap
            
        c2mag = gr.complex_to_mag_squared(self.fft_size)

        # FIXME the log10 primitive is dog slow
        log = gr.nlog10_ff(10, self.fft_size,
                           -20*math.log10(self.fft_size)-10*math.log10(power/self.fft_size))
        
        # Set the freq_step to 75% of the actual data throughput.
        # This allows us to discard the bins on both ends of the spectrum.

        #changed on 2011 May 31, MR -- maybe change back at some point
        self.freq_step = self.usrp_rate
        self.min_center_freq = self.min_freq + self.freq_step/2
        nsteps = math.ceil((self.max_freq - self.min_freq) / self.freq_step)
        self.max_center_freq = self.min_center_freq + (nsteps * self.freq_step)

        self.next_freq = self.min_center_freq
        
        tune_delay  = max(0, int(round(options.tune_delay * self.usrp_rate / self.fft_size)))  # in fft_frames
        dwell_delay = max(1, int(round(options.dwell_delay * self.usrp_rate / self.fft_size))) # in fft_frames

        self.msgq = gr.msg_queue(16)
        self._tune_callback = tune(self)        # hang on to this to keep it from being GC'd
        stats = gr.bin_statistics_f(self.fft_size, self.msgq,
                                    self._tune_callback, tune_delay, dwell_delay)

        # FIXME leave out the log10 until we speed it up
        #self.connect(self, s2v, fft, c2mag, log, stats)
        self.connect(self, s2v, fft, c2mag, stats)
Exemple #51
0
    def __init__(self, tuner_callback, options):
        gr.hier_block2.__init__(
            self,
            "sense_path",
            gr.io_signature(1, 1, gr.sizeof_gr_complex),  # Input signature
            gr.io_signature(0, 0, 0))  # Output signature

        self.usrp_rate = options.channel_rate
        self.usrp_tune = tuner_callback

        self.threshold = options.threshold

        #self.freq_step = options.chan_bandwidth
        #self.min_freq = options.start_freq
        #self.max_freq = options.end_freq
        self.hold_freq = False

        self.channels = [
            600000000, 620000000, 625000000, 640000000, 645000000, 650000000
        ]
        self.current_chan = 0
        self.num_channels = len(
            self.channels)  #(self.max_freq - self.min_freq)/self.freq_step

        #if self.min_freq > self.max_freq:
        #    self.min_freq, self.max_freq = self.max_freq, self.min_freq   # swap them

        self.fft_size = options.sense_fft_size

        if not options.real_time:
            realtime = False
        else:
            # Attempt to enable realtime scheduling
            r = gr.enable_realtime_scheduling()
            if r == gr.RT_OK:
                realtime = True
            else:
                realtime = False
                print "Note: failed to enable realtime scheduling"

        # build graph
        s2v = gr.stream_to_vector(gr.sizeof_gr_complex, self.fft_size)

        mywindow = window.blackmanharris(self.fft_size)
        fft = gr.fft_vcc(self.fft_size, True, mywindow)
        power = 0
        for tap in mywindow:
            power += tap * tap

        c2mag = gr.complex_to_mag_squared(self.fft_size)

        # FIXME the log10 primitive is dog slow
        log = gr.nlog10_ff(
            10, self.fft_size, -20 * math.log10(self.fft_size) -
            10 * math.log10(power / self.fft_size))

        # Set the freq_step to 75% of the actual data throughput.
        # This allows us to discard the bins on both ends of the spectrum.

        #changed on 2011 May 31, MR -- maybe change back at some point

        #self.min_center_freq = self.min_freq + self.freq_step/2
        #nsteps = math.ceil((self.max_freq - self.min_freq) / self.freq_step)
        #self.max_center_freq = self.min_center_freq + (nsteps * self.freq_step)

        self.next_freq = self.channels[
            self.current_chan]  #self.min_center_freq

        tune_delay = max(0,
                         int(
                             round(options.tune_delay * self.usrp_rate /
                                   self.fft_size)))  # in fft_frames
        dwell_delay = max(1,
                          int(
                              round(options.dwell_delay * self.usrp_rate /
                                    self.fft_size)))  # in fft_frames

        self.msgq = gr.msg_queue(16)
        self._tune_callback = tune(
            self)  # hang on to this to keep it from being GC'd
        self.stats = gr.bin_statistics_f(self.fft_size, self.msgq,
                                         self._tune_callback, tune_delay,
                                         dwell_delay)

        # FIXME leave out the log10 until we speed it up
        #self.connect(self, s2v, fft, c2mag, log, stats)
        self.connect(self, s2v, fft, c2mag, self.stats)