Esempio n. 1
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)
Esempio n. 2
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)
Esempio n. 3
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))
Esempio n. 4
0
    def __init__(self, rate, threshold, queue, use_pmf=False):
        gr.hier_block2.__init__(self, "modes_rx_path",
                                gr.io_signature(1, 1, gr.sizeof_gr_complex),
                                gr.io_signature(0,0,0))

        self._rate = int(rate)
        self._threshold = threshold
        self._queue = queue
        self._spc = int(rate/2e6)

        # Convert incoming I/Q baseband to amplitude
        self._demod = gr.complex_to_mag()
        self._bb = self._demod

        # Pulse matched filter for 0.5us pulses
        if use_pmf:
            self._pmf = gr.moving_average_ff(self._spc, 1.0/self._spc, self._rate)
            self.connect(self._demod, self._pmf)
            self._bb = self._pmf

        # Establish baseline amplitude (noise, interference)
        self._avg = gr.moving_average_ff(48*self._spc, 1.0/(48*self._spc), self._rate) # 3 preambles

        # Synchronize to Mode-S preamble
        self._sync = air_modes_swig.modes_preamble(self._rate, self._threshold)

        # Slice Mode-S bits and send to message queue
        self._slicer = air_modes_swig.modes_slicer(self._rate, self._queue)

        # Wire up the flowgraph
        self.connect(self, self._demod)
        self.connect(self._bb, (self._sync, 0))
        self.connect(self._bb, self._avg, (self._sync, 1))
        self.connect(self._sync, self._slicer)
Esempio n. 5
0
def build_graph (input, output, coeffs, mag):

    # Initialize empty flow graph
    fg = gr.top_block ()

    # Set up file source
    src = gr.file_source (gr.sizeof_gr_complex, input)

    # Read coefficients for the matched filter
    dfile = open(coeffs, 'r')
    data = []
    for line in dfile:
      data.append(complex(*map(float,line.strip().strip("()").split(" "))).conjugate())
    dfile.close()
    data.reverse()
    mfilter = gr.fir_filter_ccc(1, data)

    # If the output is magnitude, it is float, else its complex
    if mag:
      magnitude = gr.complex_to_mag(1)
      dst = gr.file_sink (gr.sizeof_float, output)
      fg.connect(src, mfilter, magnitude, dst)
    else:
      dst = gr.file_sink (gr.sizeof_gr_complex, output)
      fg.connect(src, mfilter, dst)

    return fg
    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)
Esempio n. 7
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)
Esempio n. 9
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"
Esempio n. 10
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, rx, reader, tx):
        gr.top_block.__init__(self)
               
        samp_freq = (64 / dec_rate) * 1e6
        amplitude = 33000

        num_taps = int(64000 / (dec_rate * up_link_freq * 2))  #Matched filter for 1/2 cycle

        taps = [complex(1,1)] * num_taps
        
        print num_taps

        filt = gr.fir_filter_ccc(sw_dec, taps)
        
        to_mag = gr.complex_to_mag()
        amp = gr.multiply_const_cc(amplitude)

        c_gate = rfid.cmd_gate(dec_rate * sw_dec, reader.STATE_PTR)
        zc = rfid.clock_recovery_zc_ff(samples_per_pulse, 2);
        
        dummy = gr.null_sink(gr.sizeof_float)
        to_complex = gr.float_to_complex()


        r = gr.enable_realtime_scheduling()
        if r != gr.RT_OK:
            print "Warning: failed to enable realtime scheduling"
    
        


        self.connect(rx, filt, to_mag, c_gate, zc,  reader, amp, tx);   
Esempio n. 12
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 = 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
Esempio n. 13
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"
Esempio n. 14
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)
    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 build_graph (input, raw, snr, freq_offset, coeffs, mag):

    # Initialize empty flow graph
    fg = gr.top_block ()

    # Set up file source
    src = gr.file_source (1, input)

    # Set up GMSK modulator, 2 samples per symbol
    mod = gmsk_mod(2)

    # Amplify the signal
    tx_amp = 1
    amp = gr.multiply_const_cc(1)
    amp.set_k(tx_amp)

    # Compute proper noise voltage based on SNR
    SNR = 10.0**(snr/10.0)
    power_in_signal = abs(tx_amp)**2
    noise_power = power_in_signal/SNR
    noise_voltage = math.sqrt(noise_power)

    # Generate noise
    rseed = int(time.time())
    noise = gr.noise_source_c(gr.GR_GAUSSIAN, noise_voltage, rseed)
    adder = gr.add_cc()
    fg.connect(noise, (adder, 1))
    
    # Create the frequency offset, 0 for now
    offset = gr.sig_source_c(1, gr.GR_SIN_WAVE, freq_offset, 1.0, 0.0)
    mixer = gr.multiply_cc()
    fg.connect(offset, (mixer, 1))

    # Pass the noisy data to the matched filter
    dfile = open(coeffs, 'r')
    data = []
    for line in dfile:
      data.append(complex(*map(float,line.strip().strip("()").split(" "))).conjugate())
    dfile.close()
    data.reverse()
    mfilter = gr.fir_filter_ccc(1, data)


    # Connect the flow graph
    fg.connect(src, mod)
    fg.connect(mod, (mixer, 0))
    fg.connect(mixer, (adder, 0))

    if mag:
      raw_dst = gr.file_sink (gr.sizeof_float, raw)
      magnitude = gr.complex_to_mag(1)
      fg.connect(adder, mfilter, magnitude, raw_dst)
    else:
      raw_dst = gr.file_sink (gr.sizeof_gr_complex, raw)
      fg.connect(adder, mfilter, raw_dst)

    print "SNR(db): " + str(snr)
    print "Frequency Offset: " + str(freq_offset)

    return fg
Esempio n. 17
0
	def __init__(self, infile="data", samp_rate=1000000, outfile="data.wav", amp=70):
		gr.top_block.__init__(self, "Analyze")

		##################################################
		# Parameters
		##################################################
		self.infile = infile
		self.samp_rate = samp_rate
		self.outfile = outfile
		self.amp = amp

		##################################################
		# Blocks
		##################################################
		self.gr_wavfile_sink_0 = gr.wavfile_sink(outfile, 3, samp_rate, 16)
		self.gr_multiply_const_vxx_0 = gr.multiply_const_vcc((amp, ))
		self.gr_file_source_0 = gr.file_source(gr.sizeof_gr_complex*1, infile, False)
		self.gr_complex_to_mag_0 = gr.complex_to_mag(1)
		self.gr_complex_to_float_0 = gr.complex_to_float(1)

		##################################################
		# Connections
		##################################################
		self.connect((self.gr_file_source_0, 0), (self.gr_multiply_const_vxx_0, 0))
		self.connect((self.gr_multiply_const_vxx_0, 0), (self.gr_complex_to_float_0, 0))
		self.connect((self.gr_multiply_const_vxx_0, 0), (self.gr_complex_to_mag_0, 0))
		self.connect((self.gr_complex_to_mag_0, 0), (self.gr_wavfile_sink_0, 2))
		self.connect((self.gr_complex_to_float_0, 1), (self.gr_wavfile_sink_0, 1))
		self.connect((self.gr_complex_to_float_0, 0), (self.gr_wavfile_sink_0, 0))
Esempio n. 18
0
	def __init__(self, decim=16, N_id_1=134, N_id_2=0):
		grc_wxgui.top_block_gui.__init__(self, title="Sss Corr Gui")
		_icon_path = "/usr/share/icons/hicolor/32x32/apps/gnuradio-grc.png"
		self.SetIcon(wx.Icon(_icon_path, wx.BITMAP_TYPE_ANY))

		##################################################
		# Parameters
		##################################################
		self.decim = decim
		self.N_id_1 = N_id_1
		self.N_id_2 = N_id_2

		##################################################
		# Variables
		##################################################
		self.sss_start_ts = sss_start_ts = 10608 - 2048 - 144
		self.samp_rate = samp_rate = 30720e3/decim

		##################################################
		# Blocks
		##################################################
		self.wxgui_scopesink2_0 = scopesink2.scope_sink_f(
			self.GetWin(),
			title="Scope Plot",
			sample_rate=200,
			v_scale=0,
			v_offset=0,
			t_scale=0,
			ac_couple=False,
			xy_mode=False,
			num_inputs=1,
			trig_mode=gr.gr_TRIG_MODE_AUTO,
			y_axis_label="Counts",
		)
		self.Add(self.wxgui_scopesink2_0.win)
		self.gr_vector_to_stream_0 = gr.vector_to_stream(gr.sizeof_gr_complex*1, 2048/decim)
		self.gr_throttle_0 = gr.throttle(gr.sizeof_gr_complex*1, samp_rate*decim)
		self.gr_stream_to_vector_0 = gr.stream_to_vector(gr.sizeof_gr_complex*1, 2048/decim)
		self.gr_skiphead_0 = gr.skiphead(gr.sizeof_gr_complex*1, sss_start_ts)
		self.gr_multiply_const_vxx_0 = gr.multiply_const_vcc((gen_sss_fd(N_id_1, N_id_2, 2048/decim).get_sss_conj_rev()))
		self.gr_integrate_xx_0 = gr.integrate_cc(2048/decim)
		self.gr_file_source_0 = gr.file_source(gr.sizeof_gr_complex*1, "/home/user/git/gr-lte/gr-lte/test/traces/lte_02_796m_30720k_frame.cfile", True)
		self.gr_fft_vxx_0 = gr.fft_vcc(2048/decim, True, (window.blackmanharris(1024)), True, 1)
		self.gr_complex_to_mag_0 = gr.complex_to_mag(1)
		self.fir_filter_xxx_0 = filter.fir_filter_ccc(decim, (firdes.low_pass(1, decim*samp_rate, 550e3, 100e3)))

		##################################################
		# Connections
		##################################################
		self.connect((self.gr_file_source_0, 0), (self.gr_throttle_0, 0))
		self.connect((self.gr_stream_to_vector_0, 0), (self.gr_fft_vxx_0, 0))
		self.connect((self.gr_fft_vxx_0, 0), (self.gr_multiply_const_vxx_0, 0))
		self.connect((self.gr_multiply_const_vxx_0, 0), (self.gr_vector_to_stream_0, 0))
		self.connect((self.gr_vector_to_stream_0, 0), (self.gr_integrate_xx_0, 0))
		self.connect((self.gr_integrate_xx_0, 0), (self.gr_complex_to_mag_0, 0))
		self.connect((self.gr_complex_to_mag_0, 0), (self.wxgui_scopesink2_0, 0))
		self.connect((self.gr_throttle_0, 0), (self.gr_skiphead_0, 0))
		self.connect((self.gr_skiphead_0, 0), (self.fir_filter_xxx_0, 0))
		self.connect((self.fir_filter_xxx_0, 0), (self.gr_stream_to_vector_0, 0))
Esempio n. 19
0
  def __init__(self, options, args, queue):
    gr.top_block.__init__(self)

    self.options = options
    self.args = args
    rate = int(options.rate)

    if options.filename is None:
      self.u = uhd.single_usrp_source("", uhd.io_type_t.COMPLEX_FLOAT32, 1)
      time_spec = uhd.time_spec(0.0)
      self.u.set_time_now(time_spec)

      #if(options.rx_subdev_spec is None):
      #  options.rx_subdev_spec = ""
      #self.u.set_subdev_spec(options.rx_subdev_spec)
      if not options.antenna is None:
        self.u.set_antenna(options.antenna)

      self.u.set_samp_rate(rate)
      rate = int(self.u.get_samp_rate()) #retrieve actual

      if options.gain is None: #set to halfway
        g = self.u.get_gain_range()
        options.gain = (g.start()+g.stop()) / 2.0

      if not(self.tune(options.freq)):
        print "Failed to set initial frequency"

      print "Setting gain to %i" % (options.gain,)
      self.u.set_gain(options.gain)
      print "Gain is %i" % (self.u.get_gain(),)

    else:
      self.u = gr.file_source(gr.sizeof_gr_complex, options.filename)

    print "Rate is %i" % (rate,)

    pass_all = 0
    if options.output_all :
      pass_all = 1

    self.demod = gr.complex_to_mag()
    self.avg = gr.moving_average_ff(100, 1.0/100, 400)
    
    #the DBSRX especially tends to be spur-prone; the LPF keeps out the
    #spur multiple that shows up at 2MHz
    self.lpfiltcoeffs = gr.firdes.low_pass(1, rate, 1.8e6, 100e3)
    self.lpfilter = gr.fir_filter_ccf(1, self.lpfiltcoeffs)
    
    self.preamble = air.modes_preamble(rate, options.threshold)
    #self.framer = air.modes_framer(rate)
    self.slicer = air.modes_slicer(rate, queue)
    
    self.connect(self.u, self.lpfilter, self.demod)
    self.connect(self.demod, self.avg)
    self.connect(self.demod, (self.preamble, 0))
    self.connect(self.avg, (self.preamble, 1))
    self.connect((self.preamble, 0), (self.slicer, 0))
Esempio n. 20
0
     def __init__(self):
          gr.hier_block2.__init__(self, "HierBlock_tone",
                         gr.io_signature(1, 1, gr.sizeof_float),
                         gr.io_signature(1, 1, 4))

          mag = gr.complex_to_mag ()
		
          dft= gr.goertzel_fc(AUDIO_RATE,TONE_DUR_SAMP,TONE_FREQ) 

          self.connect(self,dft,mag,self)
Esempio n. 21
0
 def test_complex_to_mag (self):
     src_data = (0, 1, -1, 3+4j, -3-4j, -3+4j)
     expected_result = (0, 1, 1, 5, 5, 5)
     src = gr.vector_source_c (src_data)
     op = gr.complex_to_mag ()
     dst = gr.vector_sink_f ()
     self.tb.connect (src, op)
     self.tb.connect (op, dst)
     self.tb.run ()
     actual_result = dst.data ()
     self.assertFloatTuplesAlmostEqual (expected_result, actual_result,5)
Esempio n. 22
0
  def __init__(self, options, args, queue):
    gr.top_block.__init__(self)

    self.options = options
    self.args = args
    rate = int(options.rate)

    if options.filename is None:
      self.u = rtl_source_c()

      #if(options.rx_subdev_spec is None):
      #  options.rx_subdev_spec = ""
      #self.u.set_subdev_spec(options.rx_subdev_spec)
      if not options.antenna is None:
        self.u.set_antenna(options.antenna)

      self.u.set_sample_rate(rate)

      if not(self.tune(options.freq)):
        print "Failed to set initial frequency"

      print "Setting gain to %i" % (options.gain,)
      self.u.set_gain(options.gain)
      print "Gain is %i" % (options.gain,)

      self.u.set_verbose(0)
    else:
      self.u = gr.file_source(gr.sizeof_gr_complex, options.filename)

    print "Rate is %i" % (rate,)

    pass_all = 0
    if options.output_all :
      pass_all = 1

    self.demod = gr.complex_to_mag()
    self.avg = gr.moving_average_ff(100, 1.0/100, 400)
    
    #the DBSRX especially tends to be spur-prone; the LPF keeps out the
    #spur multiple that shows up at 2MHz
#    self.lpfiltcoeffs = gr.firdes.low_pass(1, rate, 0.9*rate/2, 50e3)
#    self.lpfiltcoeffs = gr.firdes.low_pass(1, rate, 0.9*rate/2, 100e3)
    self.lpfiltcoeffs = gr.firdes.high_pass(1, rate, 1e3, 100e3)
    self.lpfilter = gr.fir_filter_ccf(1, self.lpfiltcoeffs)
    
    self.preamble = air.modes_preamble(rate, options.threshold)
    #self.framer = air.modes_framer(rate)
    self.slicer = air.modes_slicer(rate, queue)
    
    self.connect(self.u, self.lpfilter, self.demod)
    self.connect(self.demod, self.avg)
    self.connect(self.demod, (self.preamble, 0))
    self.connect(self.avg, (self.preamble, 1))
    self.connect((self.preamble, 0), (self.slicer, 0))
Esempio n. 23
0
	def __init__(self, u, center_freq, hw_dec_rate, downsample_rate, pulse_width, tari, debug_on, output_data):
		gr.top_block.__init__(self)

		# sample_rate = 100e6 / hw_dec_rate
		sample_rate = 2e6

		self.u = u
		# self.u.set_decim(hw_dec_rate)
		g = u.get_gain_range()
		print "-----------"

		self.u.set_gain(float(g.start() + g.stop()) / 4)
		print "Using gain of", float(g.start() + g.stop()) / 4 , "(", g.stop(), "-", g.start(), ")"
		tune_req = uhd.tune_request_t(center_freq,sample_rate)
		# r = rx.set_center_freq(tune_req)
		x = self.u.set_center_freq(tune_req)
		if not x:
			print "Couldn't set rx freq"
            
		self.u.set_samp_rate(sample_rate)
		us_per_sample = 1e6 / sample_rate * downsample_rate
		print "USRP Sample Rate: "+ str(sample_rate) + " us Per Sample: " + str(us_per_sample)

		# 25 Msps is too much to process. But we don't want to decimate at the USRP because we want the full band.
		# We can downsample, because we don't care about aliasing. 
		self.downsample = gr.keep_one_in_n(gr.sizeof_gr_complex, int(downsample_rate))
		self.to_mag = gr.complex_to_mag()
		
		# For TARI = 24, PW == DELIM. So we can't do a matched filter, or everything becomes a delimiter and a zero.
		# PW / 2 smooths reasonably well.
		# self.smooth = gr.moving_average_ff(int(pulse_width / us_per_sample) /2  , int(pulse_width / us_per_sample) /2 ) 
		self.smooth = gr.moving_average_ff(int(1), 1.0) 
		self.rd = rfid.reader_decoder(us_per_sample, tari)

		if(debug_on):
			# fileInfo = "_smooth1_b"
        	# time = strftime("%H_%M_%S", localtime())
        	# threshFileName = "rm_thresh_" + time + fileInfo + ".out"
        	# signalFileName = "rm_signal_" + time + fileInfo + ".out"

			signalFileName = "rm_signal.out"
			threshFileName = "rm_thresh.out"
			self.sink = gr.file_sink(gr.sizeof_float, threshFileName)
			# self.signal_sink = gr.file_sink(gr.sizeof_float, signalFileName)
			# self.connect(self.smooth, self.signal_sink)
		else:
			self.sink = gr.null_sink(gr.sizeof_float)

		self.connect(self.u, self.downsample, self.to_mag, self.smooth, self.rd, self.sink)

		# Change to "gr.sizeof_gr_complex" if "block_x" is "rx" 
		file_rx_sink = gr.file_sink(gr.sizeof_gr_complex, output_data) 
		self.connect(self.u, file_rx_sink)
Esempio n. 24
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)
Esempio n. 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))
    def __init__(self, fg, channel_rate, audio_decim, audio_pass, audio_stop):
	MAG = gr.complex_to_mag()
	DCR = gr.add_const_ff(-1.0)

	audio_taps = optfir.low_pass(0.5, 	   # Filter gain
	                             channel_rate, # Sample rate
				     audio_pass,   # Audio passband
				     audio_stop,   # Audio stopband
				     0.1, 	   # Passband ripple
				     60)	   # Stopband attenuation
	LPF = gr.fir_filter_fff(audio_decim, audio_taps)

	fg.connect(MAG, DCR, LPF)
	gr.hier_block.__init__(self, fg, MAG, LPF)
Esempio n. 27
0
    def __init__(self, channel_rate, threshold):
        gr.hier_block2.__init__(self, "ppm_demod",
                              gr.io_signature(1, 1, gr.sizeof_gr_complex),
                              gr.io_signature(1, 1, 512))

        chan_rate = 8000000 # Minimum sample rate

        if channel_rate < chan_rate:
            raise ValueError, "Invalid channel rate %d. Must be 8000000 sps or higher" % (channel_rate)
        
        if channel_rate >= 10000000:
            chan_rate = 10000000    # Higher Performance Receiver

        # if rate is not supported then resample
        if channel_rate != chan_rate:
            interp = gru.lcm(channel_rate, chan_rate)/channel_rate
            decim  = gru.lcm(channel_rate, chan_rate)/chan_rate
            self.RESAMP = rational_resampler_ccf(self, interp, decim)

        # Calculate the leading edge threshold per sample time
        leading_edge = risetime_threshold_db/(chan_rate/data_rate)

        # Calculate the number of following samples above threshold needed to make a sample a valid pulse position
        valid_pulse_position = 2
        if chan_rate == 10000000:
            valid_pulse_position = 3

        # Demodulate AM with classic sqrt (I*I + Q*Q)
        self.MAG = gr.complex_to_mag()
        self.DETECT = air.ms_pulse_detect(leading_edge, threshold, valid_pulse_position) # Attack, Threshold, Pulsewidth
        self.SYNC = air.ms_preamble(chan_rate)
        self.FRAME = air.ms_framer(chan_rate)
        self.BIT   = air.ms_ppm_decode(chan_rate)
        self.PARITY = air.ms_parity()
        self.EC    =  air.ms_ec_brute()

        if channel_rate != chan_rate:
            # Resample the stream first
            self.connect(self, self.RESAMP, self.MAG, self.DETECT)
        else: 
            self.connect(self, self.MAG, self.DETECT)

        self.connect((self.DETECT, 0), (self.SYNC, 0))
        self.connect((self.DETECT, 1), (self.SYNC, 1))
        self.connect((self.SYNC, 0), (self.FRAME, 0))
        self.connect((self.SYNC, 1), (self.FRAME, 1))
        self.connect((self.FRAME, 0), (self.BIT, 0))
        self.connect((self.FRAME, 1), (self.BIT, 1))
        self.connect(self.BIT, self.PARITY, self.EC, self)
Esempio n. 28
0
def log_to_file(hb, block, filename, mag=False, char_to_float=False):
    streamsize = determine_streamsize(block)

    if mag:
        vlen = streamsize / gr.sizeof_gr_complex
        gr_mag = gr.complex_to_mag(vlen)
        hb.connect(block, gr_mag)
        log_to_file(hb, gr_mag, filename)
    elif char_to_float:
        vlen = streamsize / gr.sizeof_char
        ctf = gr.char_to_float(vlen)
        hb.connect(block, ctf)
        log_to_file(hb, ctf, filename)
    else:
        file_log = blocks.file_sink(streamsize, filename)
        hb.connect(block, file_log)
    def __init__(self, rx, matched_filter, reader_monitor_cmd_gate, cr, tag_monitor):
        gr.top_block.__init__(self)
               
        # ASK/PSK demodulator
     	to_mag = gr.complex_to_mag()
        
	# Null sink for terminating the graph
	null_sink = gr.null_sink(gr.sizeof_float*1)

	# Enable real-time scheduling	
        r = gr.enable_realtime_scheduling()
    	if r != gr.RT_OK:
            print "Warning: failed to enable realtime scheduling"

	# Create flow-graph
	self.connect(rx, to_mag, matched_filter, reader_monitor_cmd_gate, cr, tag_monitor, null_sink)	
Esempio n. 30
0
def log_to_file(hb,block,filename,mag=False,char_to_float=False):
  streamsize = determine_streamsize(block)
  
  if mag:
    vlen = streamsize/gr.sizeof_gr_complex
    gr_mag = gr.complex_to_mag(vlen)
    hb.connect( block, gr_mag )
    log_to_file( hb, gr_mag, filename )
  elif char_to_float:
    vlen = streamsize/gr.sizeof_char
    ctf = gr.char_to_float( vlen )
    hb.connect( block, ctf )
    log_to_file( hb, ctf, filename )
  else:
    file_log = blocks.file_sink(streamsize,filename)
    hb.connect(block,file_log)
Esempio n. 31
0
    def __init__( self, if_rate, af_rate ):
        gr.hier_block2.__init__(self, "ssb_demod",
                                gr.io_signature(1,1,gr.sizeof_gr_complex),
                                gr.io_signature(1,1,gr.sizeof_float))

        self.if_rate  = int(if_rate)
        self.af_rate  = int(af_rate)
        self.if_decim = int(if_rate / af_rate)
        self.sideband = 1

        self.xlate_taps = ([complex(v) for v in file('ssb_taps').readlines()])

        self.audio_taps = gr.firdes.low_pass(
            1.0,
            self.af_rate,
            3e3,
            600,
            gr.firdes.WIN_HAMMING )

        self.xlate = gr.freq_xlating_fir_filter_ccc(
            self.if_decim,
            self.xlate_taps,
            0,
            self.if_rate )

        self.split = gr.complex_to_float()

        self.lpf = gr.fir_filter_fff(
            1, self.audio_taps )

        self.sum   = gr.add_ff( )
        self.am_sel = gr.multiply_const_ff( 0 )
        self.sb_sel = gr.multiply_const_ff( 1 )
        self.mixer  = gr.add_ff()
        self.am_det = gr.complex_to_mag()

        self.connect(self,             self.xlate)
        self.connect(self.xlate,       self.split)
        self.connect((self.split, 0), (self.sum, 0))
        self.connect((self.split, 1), (self.sum, 1))
        self.connect(self.sum,         self.sb_sel)
        self.connect(self.xlate,       self.am_det)
        self.connect(self.sb_sel,     (self.mixer, 0))
        self.connect(self.am_det,      self.am_sel)
        self.connect(self.am_sel,     (self.mixer, 1))
        self.connect(self.mixer,       self.lpf)
        self.connect(self.lpf,         self)
Esempio n. 32
0
    def __init__(self, channel_rate, audio_decim, audio_pass, audio_stop):
	gr.hier_block2.__init__(self, "am_demod_cf",
				gr.io_signature(1, 1, gr.sizeof_gr_complex), # Input signature
				gr.io_signature(1, 1, gr.sizeof_float))      # Input signature

	MAG = gr.complex_to_mag()
	DCR = gr.add_const_ff(-1.0)

	audio_taps = optfir.low_pass(0.5, 	   # Filter gain
	                             channel_rate, # Sample rate
				     audio_pass,   # Audio passband
				     audio_stop,   # Audio stopband
				     0.1, 	   # Passband ripple
				     60)	   # Stopband attenuation
	LPF = gr.fir_filter_fff(audio_decim, audio_taps)

	self.connect(self, MAG, DCR, LPF, self)
Esempio n. 33
0
    def __init__(self, channel_rate, audio_decim, audio_pass, audio_stop):
	gr.hier_block2.__init__(self, "am_demod_cf",
				gr.io_signature(1, 1, gr.sizeof_gr_complex), # Input signature
				gr.io_signature(1, 1, gr.sizeof_float))      # Input signature

	MAG = gr.complex_to_mag()
	DCR = gr.add_const_ff(-1.0)

	audio_taps = optfir.low_pass(0.5, 	   # Filter gain
	                             channel_rate, # Sample rate
				     audio_pass,   # Audio passband
				     audio_stop,   # Audio stopband
				     0.1, 	   # Passband ripple
				     60)	   # Stopband attenuation
	LPF = gr.fir_filter_fff(audio_decim, audio_taps)

	self.connect(self, MAG, DCR, LPF, self)
    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)
Esempio n. 35
0
    def __init__(self, rx, matched_filter, reader_monitor_cmd_gate, cr,
                 tag_monitor):
        gr.top_block.__init__(self)

        # ASK/PSK demodulator
        to_mag = gr.complex_to_mag()

        # Null sink for terminating the graph
        null_sink = gr.null_sink(gr.sizeof_float * 1)

        # Enable real-time scheduling
        r = gr.enable_realtime_scheduling()
        if r != gr.RT_OK:
            print "Warning: failed to enable realtime scheduling"

# Create flow-graph
        self.connect(rx, to_mag, matched_filter, reader_monitor_cmd_gate, cr,
                     tag_monitor, null_sink)
    def __init__(self, u, center_freq, hw_dec_rate, downsample_rate,
                 pulse_width, tari, debug_on):
        gr.top_block.__init__(self)

        self.u = u
        self.u.set_decim(hw_dec_rate)
        g = u.gain_range()
        self.u.set_gain(float(g[0] + g[1]) / 4)
        print "Using gain of", float(g[0] +
                                     g[1]) / 4, "(", g[0], "-", g[1], ")"
        x = self.u.set_center_freq(center_freq)
        if not x:
            print "Couldn't set rx freq"

        sample_rate = self.u.adc_rate() / hw_dec_rate
        us_per_sample = 1e6 / sample_rate * downsample_rate
        print "USRP Sample Rate: " + str(
            sample_rate) + " us Per Sample: " + str(us_per_sample)

        #25 Msps is too much to process. But we don't want to decimate at the USRP because we want the full band.
        # We can downsample, because we don't care about aliasing.
        self.downsample = gr.keep_one_in_n(gr.sizeof_gr_complex,
                                           int(downsample_rate))

        self.to_mag = gr.complex_to_mag()

        #For TARI = 24, PW == DELIM. So we can't do a matched filter, or everything becomes a delimiter and a zero.
        # PW / 2 smooths reasonably well.
        self.smooth = gr.moving_average_ff(
            int(pulse_width / us_per_sample) / 2,
            int(pulse_width / us_per_sample) / 2)

        self.rd = rfid.reader_decoder(us_per_sample, tari)

        if (debug_on):
            self.sink = gr.file_sink(gr.sizeof_float, "rm.out")
            self.signal_sink = gr.file_sink(gr.sizeof_float, "rm_signal.out")
            self.connect(self.smooth, self.signal_sink)

        else:
            self.sink = gr.null_sink(gr.sizeof_float)

        self.connect(self.u, self.downsample, self.to_mag, self.smooth,
                     self.rd, self.sink)
Esempio n. 37
0
    def __init__(self):
        gr.hier_block2.__init__(self, "rx_path", gr.io_signature(0, 0, 0),
                                gr.io_signature(0, 0, 0))

        self.frequency = 13.56e6
        self.gain = 10

        # USRP settings
        self.u_rx = usrp.source_c()  #create the USRP source for RX
        #try and set the LF_RX for this
        rx_subdev_spec = usrp.pick_subdev(self.u_rx,
                                          (usrp_dbid.LF_RX, usrp_dbid.LF_TX))

        #Configure the MUX for the daughterboard
        self.u_rx.set_mux(
            usrp.determine_rx_mux_value(self.u_rx, rx_subdev_spec))
        #Tell it to use the LF_RX
        self.subdev_rx = usrp.selected_subdev(self.u_rx, rx_subdev_spec)
        #Make sure it worked
        print "Using RX dboard %s" % (self.subdev_rx.side_and_name(), )

        #Set gain.. duh
        self.subdev_rx.set_gain(self.gain)

        #Tune the center frequency
        self.u_rx.tune(0, self.subdev_rx, self.frequency)

        adc_rate = self.u_rx.adc_rate()  #64 MS/s
        usrp_decim = 256
        self.u_rx.set_decim_rate(usrp_decim)
        #BW = 64 MS/s / decim = 64,000,000 / 256 = 250 kHz
        #Not sure if this decim rate exceeds USRP capabilities,
        #if it does then some software decim may have to be done as well
        usrp_rx_rate = adc_rate / usrp_decim

        self.iir = gr.single_pole_iir_filter_ff(.001)
        self.mag = gr.complex_to_mag()
        self.snk = gr.probe_signal_f()

        # dst = audio.sink (sample_rate, "")
        # stv = gr.stream_to_vector (gr.sizeof_float, fft_size)
        # c2m = gr.complex_to_mag_squared (fft_size)

        self.connect(self.u_rx, self.mag, self.iir, self.snk)
Esempio n. 38
0
    def __init__(self,
                 infile="data",
                 samp_rate=1000000,
                 outfile="data.wav",
                 amp=70):
        gr.top_block.__init__(self, "Analyze")

        ##################################################
        # Parameters
        ##################################################
        self.infile = infile
        self.samp_rate = samp_rate
        self.outfile = outfile
        self.amp = amp

        ##################################################
        # Blocks
        ##################################################
        self.gr_wavfile_sink_0 = gr.wavfile_sink(outfile, 3, samp_rate, 16)
        self.gr_multiply_const_vxx_0 = gr.multiply_const_vcc((amp, ))
        self.gr_file_source_0 = gr.file_source(gr.sizeof_gr_complex * 1,
                                               infile, False)
        self.gr_complex_to_mag_0 = gr.complex_to_mag(1)
        self.gr_complex_to_float_0 = gr.complex_to_float(1)

        ##################################################
        # Connections
        ##################################################
        self.connect((self.gr_file_source_0, 0),
                     (self.gr_multiply_const_vxx_0, 0))
        self.connect((self.gr_multiply_const_vxx_0, 0),
                     (self.gr_complex_to_float_0, 0))
        self.connect((self.gr_multiply_const_vxx_0, 0),
                     (self.gr_complex_to_mag_0, 0))
        self.connect((self.gr_complex_to_mag_0, 0),
                     (self.gr_wavfile_sink_0, 2))
        self.connect((self.gr_complex_to_float_0, 1),
                     (self.gr_wavfile_sink_0, 1))
        self.connect((self.gr_complex_to_float_0, 0),
                     (self.gr_wavfile_sink_0, 0))
Esempio n. 39
0
    def __init__(self, if_rate, af_rate):
        gr.hier_block2.__init__(self, "ssb_demod",
                                gr.io_signature(1, 1, gr.sizeof_gr_complex),
                                gr.io_signature(1, 1, gr.sizeof_float))

        self.if_rate = int(if_rate)
        self.af_rate = int(af_rate)
        self.if_decim = int(if_rate / af_rate)
        self.sideband = 1

        self.xlate_taps = ([complex(v) for v in file('ssb_taps').readlines()])

        self.audio_taps = gr.firdes.low_pass(1.0, self.af_rate, 3e3, 600,
                                             gr.firdes.WIN_HAMMING)

        self.xlate = gr.freq_xlating_fir_filter_ccc(self.if_decim,
                                                    self.xlate_taps, 0,
                                                    self.if_rate)

        self.split = gr.complex_to_float()

        self.lpf = gr.fir_filter_fff(1, self.audio_taps)

        self.sum = gr.add_ff()
        self.am_sel = gr.multiply_const_ff(0)
        self.sb_sel = gr.multiply_const_ff(1)
        self.mixer = gr.add_ff()
        self.am_det = gr.complex_to_mag()

        self.connect(self, self.xlate)
        self.connect(self.xlate, self.split)
        self.connect((self.split, 0), (self.sum, 0))
        self.connect((self.split, 1), (self.sum, 1))
        self.connect(self.sum, self.sb_sel)
        self.connect(self.xlate, self.am_det)
        self.connect(self.sb_sel, (self.mixer, 0))
        self.connect(self.am_det, self.am_sel)
        self.connect(self.am_sel, (self.mixer, 1))
        self.connect(self.mixer, self.lpf)
        self.connect(self.lpf, self)
Esempio n. 40
0
    def __init__(self, vlen):
        gr.hier_block2.__init__(
            self, "vector_equalizer",
            gr.io_signature(1, 1, gr.sizeof_gr_complex * vlen),
            gr.io_signature(1, 1, gr.sizeof_gr_complex * vlen))

        self.input = gr.add_const_vcc([0.0] * vlen)
        self.connect(self, self.input)

        c2mag = gr.complex_to_mag(vlen)
        max_v = gr.max_ff(vlen)
        interpolator = gr.interp_fir_filter_fff(vlen, [1.0] * vlen)
        f2c = gr.float_to_complex()
        v2s = gr.vector_to_stream(gr.sizeof_gr_complex, vlen)
        normalizer = gr.divide_cc()
        s2v = gr.stream_to_vector(gr.sizeof_gr_complex, vlen)

        self.connect(self.input, v2s, (normalizer, 0))
        self.connect(self.input, c2mag, max_v, interpolator, f2c,
                     (normalizer, 1))
        self.connect(normalizer, s2v)
        self.connect(s2v, self)
Esempio n. 41
0
    def __init__(self, fg, if_rate, af_rate):

        self.if_rate = if_rate
        self.af_rate = af_rate
        self.if_decim = if_rate / af_rate
        self.sideband = 1

        self.xlate_taps = ([complex(v) for v in file('ssb_taps').readlines()])

        self.audio_taps = gr.firdes.low_pass(1.0, self.af_rate, 3e3, 600,
                                             gr.firdes.WIN_HAMMING)

        self.xlate = gr.freq_xlating_fir_filter_ccc(self.if_decim,
                                                    self.xlate_taps, 0,
                                                    self.if_rate)

        self.split = gr.complex_to_float()

        self.lpf = gr.fir_filter_fff(1, self.audio_taps)

        self.sum = gr.add_ff()
        self.am_sel = gr.multiply_const_ff(0)
        self.sb_sel = gr.multiply_const_ff(1)
        self.mixer = gr.add_ff()
        self.am_det = gr.complex_to_mag()

        fg.connect(self.xlate, self.split)
        fg.connect((self.split, 0), (self.sum, 0))
        fg.connect((self.split, 1), (self.sum, 1))
        fg.connect(self.sum, self.sb_sel)
        fg.connect(self.xlate, self.am_det)
        fg.connect(self.sb_sel, (self.mixer, 0))
        fg.connect(self.am_det, self.am_sel)
        fg.connect(self.am_sel, (self.mixer, 1))
        fg.connect(self.mixer, self.lpf)

        gr.hier_block.__init__(self, fg, self.xlate, self.lpf)
Esempio n. 42
0
    def __init__(self):
        gr.top_block.__init__(self)
           
        amplitude = 30000

        filt_out = gr.file_sink(gr.sizeof_gr_complex, "./filt.out")
        filt2_out = gr.file_sink(gr.sizeof_gr_complex, "./filt2.out")
        ffilt_out = gr.file_sink(gr.sizeof_float, "./ffilt.out")
        ffilt2_out = gr.file_sink(gr.sizeof_float, "./ffilt2.out")

        interp_rate = 128
        dec_rate = 8
        sw_dec = 4

        num_taps = int(64000 / ( (dec_rate * 4) * 256 )) #Filter matched to 1/4 of the 256 kHz tag cycle
        taps = [complex(1,1)] * num_taps
        
        matched_filt = gr.fir_filter_ccc(sw_dec, taps);  
          
        agc = gr.agc2_cc(0.3, 1e-3, 1, 1, 100) 
     
        to_mag = gr.complex_to_mag()

        center = rfid.center_ff(4)

        omega = 2
        mu = 0.25
        gain_mu = 0.25
        gain_omega = .25 * gain_mu * gain_mu
        omega_relative_limit = .05

        mm = gr.clock_recovery_mm_ff(omega, gain_omega, mu, gain_mu, omega_relative_limit)


        self.reader = rfid.reader_f(int(128e6/interp_rate)); 
        
        tag_decoder = rfid.tag_decoder_f()
        
        command_gate = rfid.command_gate_cc(12, 60, 64000000 / dec_rate / sw_dec)
        

       
       
        to_complex = gr.float_to_complex()
        amp = gr.multiply_const_ff(amplitude)
        
        f_sink = gr.file_sink(gr.sizeof_gr_complex, 'f_sink.out');
        f_sink2 = gr.file_sink(gr.sizeof_gr_complex, 'f_sink2.out');


            #TX
      


        freq = 915e6
        rx_gain = 20  
    
        tx = usrp.sink_c(fusb_block_size = 1024, fusb_nblocks=8)
        tx.set_interp_rate(interp_rate)
        tx_subdev = (0,0)
        tx.set_mux(usrp.determine_tx_mux_value(tx, tx_subdev))
        subdev = usrp.selected_subdev(tx, tx_subdev)
        subdev.set_enable(True)
        subdev.set_gain(subdev.gain_range()[2])
        t = tx.tune(subdev.which(), subdev, freq)
        if not t:
            print "Couldn't set tx freq"
#End TX
             
#RX
        rx = usrp.source_c(0, dec_rate, fusb_block_size = 512 * 4, fusb_nblocks = 16)
        rx_subdev_spec = (1,0)
        rx.set_mux(usrp.determine_rx_mux_value(rx, rx_subdev_spec))
        rx_subdev = usrp.selected_subdev(rx, rx_subdev_spec)
        rx_subdev.set_gain(rx_gain)
        rx_subdev.set_auto_tr(False)
        rx_subdev.set_enable(True)
        
        r = usrp.tune(rx, 0, rx_subdev, freq)

        self.rx = rx
        if not r:
            print "Couldn't set rx freq"

#End RX

        command_gate.set_ctrl_out(self.reader.ctrl_q())
        tag_decoder.set_ctrl_out(self.reader.ctrl_q())
        agc2 = gr.agc2_ff(0.3, 1e-3, 1, 1, 100) 


#########Build Graph
        self.connect(rx, matched_filt)
        self.connect(matched_filt, command_gate)
        self.connect(command_gate, agc)
        self.connect(agc, to_mag) 
        self.connect(to_mag, center, agc2, mm, tag_decoder)
        self.connect(tag_decoder, self.reader, amp, to_complex, tx);
#################

        
        self.connect(matched_filt, filt_out)
Esempio n. 43
0
  def __init__(self, options):
    gr.hier_block2.__init__(self, "fbmc_receive_path",
        gr.io_signature(1,1,gr.sizeof_gr_complex),
        gr.io_signature(0,0,0))

    print "This is  FBMC receive path 1x1"

    common_options.defaults(options)

    config = self.config = station_configuration()

    config.data_subcarriers     = dsubc = options.subcarriers
    config.cp_length            = 0
    config.frame_data_blocks    = options.data_blocks
    config._verbose             = options.verbose #TODO: update
    config.fft_length           = options.fft_length
    config.dc_null             = options.dc_null
    config.training_data        = default_block_header(dsubc,
                                          config.fft_length,config.dc_null,options)
    config.coding              = options.coding
    config.ber_window           = options.ber_window

    config.periodic_parts       = 8

    config.frame_id_blocks      = 1 # FIXME

    self._options               = copy.copy(options) #FIXME: do we need this?
    
    config.fbmc                 = options.fbmc

    

    config.block_length = config.fft_length + config.cp_length
    config.frame_data_part = config.frame_data_blocks + config.frame_id_blocks
    config.frame_length = config.training_data.fbmc_no_preambles + 2*config.frame_data_part 
    
    config.postpro_frame_length = config.frame_data_part + \
                          config.training_data.no_pilotsyms
    config.subcarriers = dsubc + \
                         config.training_data.pilot_subcarriers
    config.virtual_subcarriers = config.fft_length - config.subcarriers - config.dc_null

    total_subc = config.subcarriers
    


    # check some bounds
    if config.fft_length < config.subcarriers:
      raise SystemError, "Subcarrier number must be less than FFT length"
    if config.fft_length < config.cp_length:
      raise SystemError, "Cyclic prefix length must be less than FFT length"



    #self.input =  gr.kludge_copy(gr.sizeof_gr_complex)
    #self.connect( self, self.input )
    self.input = self
    self.ideal = options.ideal
    self.ideal2 = options.ideal2


    ## Inner receiver

    ## Timing & Frequency Synchronization
    ## Channel estimation + Equalization
    ## Phase Tracking for sampling clock frequency offset correction
    inner_receiver = self.inner_receiver = fbmc_inner_receiver( options, options.log )
    self.connect( self.input, inner_receiver )
    ofdm_blocks = ( inner_receiver, 2 )
    frame_start = ( inner_receiver, 1 )
    disp_ctf = ( inner_receiver, 0 )
    #self.snr_est_preamble = ( inner_receiver, 3 )
    #terminate_stream(self,snr_est_preamble)
    disp_cfo =  ( inner_receiver, 3 )
    
    if self.ideal is False and self.ideal2 is False:
        self.zmq_probe_freqoff = zeromq.pub_sink(gr.sizeof_float, 1, "tcp://*:5557")
        self.connect(disp_cfo, self.zmq_probe_freqoff)
    else:
        self.connect(disp_cfo, blocks.null_sink(gr.sizeof_float))




    # for ID decoder
    used_id_bits = config.used_id_bits = 8 #TODO: constant in source code!
    rep_id_bits = config.rep_id_bits = dsubc/used_id_bits #BPSK
    if options.log:
      print "rep_id_bits %d" % (rep_id_bits)
    if dsubc % used_id_bits <> 0:
      raise SystemError,"Data subcarriers need to be multiple of 10"

    ## Workaround to avoid periodic structure
    seed(1)
    whitener_pn = [randint(0,1) for i in range(used_id_bits*rep_id_bits)]





    ## NOTE!!! BIG HACK!!!
    ## first preamble ain't equalized ....
    ## for Milan's SNR estimator






    ## Outer Receiver

    ## Make new inner receiver compatible with old outer receiver
    ## FIXME: renew outer receiver

    self.ctf = disp_ctf

    #frame_sampler = ofdm_frame_sampler(options)
    frame_sampler = fbmc_frame_sampler(options)

    self.connect( ofdm_blocks, frame_sampler)
    self.connect( frame_start, (frame_sampler,1) )


#
#    ft = [0] * config.frame_length
#    ft[0] = 1
#
#    # The next block ensures that only complete frames find their way into
#    # the old outer receiver. The dynamic frame start trigger is hence
#    # replaced with a static one, fixed to the frame length.
#
#    frame_sampler = ofdm.vector_sampler( gr.sizeof_gr_complex * total_subc,
#                                              config.frame_length )
#    self.symbol_output = blocks.vector_to_stream( gr.sizeof_gr_complex * total_subc,
#                                              config.frame_length )
#    delayed_frame_start = blocks.delay( gr.sizeof_char, config.frame_length - 1 )
#    damn_static_frame_trigger = blocks.vector_source_b( ft, True )
#
#    if options.enable_erasure_decision:
#      frame_gate = vector_sampler(
#        gr.sizeof_gr_complex * total_subc * config.frame_length, 1 )
#      self.connect( ofdm_blocks, frame_sampler, frame_gate,
#                    self.symbol_output )
#    else:
#      self.connect( ofdm_blocks, frame_sampler, self.symbol_output )
#
#    self.connect( frame_start, delayed_frame_start, ( frame_sampler, 1 ) )

    if options.enable_erasure_decision:
      frame_gate = frame_sampler.frame_gate

    self.symbol_output = frame_sampler

    orig_frame_start = frame_start
    frame_start = (frame_sampler,1)
    self.frame_trigger = frame_start
    #terminate_stream(self, self.frame_trigger)








    ## Pilot block filter
    pb_filt = self._pilot_block_filter = fbmc_pilot_block_filter()
    self.connect(self.symbol_output,pb_filt)
    self.connect(self.frame_trigger,(pb_filt,1))

    self.frame_data_trigger = (pb_filt,1)
    
    #self.symbol_output = pb_filt
    

    #if options.log:
      #log_to_file(self, pb_filt, "data/pb_filt_out.compl")


    if config.fbmc:
        pda_in = pb_filt

    else:
        ## Pilot subcarrier filter
        ps_filt = self._pilot_subcarrier_filter = pilot_subcarrier_filter()
        self.connect(self.symbol_output,ps_filt)

        if options.log:
            log_to_file(self, ps_filt, "data/ps_filt_out.compl")
            
        pda_in = ps_filt

    


    ## Workaround to avoid periodic structure
    # for ID decoder
    seed(1)
    whitener_pn = [randint(0,1) for i in range(used_id_bits*rep_id_bits)]

    

    if not options.enable_erasure_decision:

      ## ID Block Filter
      # Filter ID block, skip data blocks
      id_bfilt = self._id_block_filter = vector_sampler(
            gr.sizeof_gr_complex * dsubc, 1 )
      if not config.frame_id_blocks == 1:
        raise SystemExit, "# ID Blocks > 1 not supported"

      self.connect(   pda_in     ,   id_bfilt      )
      self.connect( self.frame_data_trigger, ( id_bfilt, 1 ) ) # trigger

      #log_to_file( self, id_bfilt, "data/id_bfilt.compl" )

      ## ID Demapper and Decoder, soft decision
      self.id_dec = self._id_decoder = ofdm.coded_bpsk_soft_decoder( dsubc,
          used_id_bits, whitener_pn )
      self.connect( id_bfilt, self.id_dec )
      

      print "Using coded BPSK soft decoder for ID detection"


    else: # options.enable_erasure_decision:

      id_bfilt = self._id_block_filter = vector_sampler(
        gr.sizeof_gr_complex * total_subc, config.frame_id_blocks )

      id_bfilt_trig_delay = 0
      for x in range( config.frame_length ):
        if x in config.training_data.pilotsym_pos:
          id_bfilt_trig_delay += 1
        else:
          break
      print "Position of ID block within complete frame: %d" %(id_bfilt_trig_delay)

      assert( id_bfilt_trig_delay > 0 ) # else not supported

      id_bfilt_trig = blocks.delay( gr.sizeof_char, id_bfilt_trig_delay )

      self.connect( ofdm_blocks, id_bfilt )
      self.connect( orig_frame_start, id_bfilt_trig, ( id_bfilt, 1 ) )

      self.id_dec = self._id_decoder = ofdm.coded_bpsk_soft_decoder( total_subc,
          used_id_bits, whitener_pn, config.training_data.shifted_pilot_tones )
      self.connect( id_bfilt, self.id_dec )

      print "Using coded BPSK soft decoder for ID detection"

      # The threshold block either returns 1.0 if the llr-value from the
      # id decoder is below the threshold, else 0.0. Hence we convert this
      # into chars, 0 and 1, and use it as trigger for the sampler.

      min_llr = ( self.id_dec, 1 )
      erasure_threshold = gr.threshold_ff( 10.0, 10.0, 0 ) # FIXME is it the optimal threshold?
      erasure_dec = gr.float_to_char()
      id_gate = vector_sampler( gr.sizeof_short, 1 )
      ctf_gate = vector_sampler( gr.sizeof_float * total_subc, 1 )


      self.connect( self.id_dec ,       id_gate )
      self.connect( self.ctf,      ctf_gate )

      self.connect( min_llr,       erasure_threshold,  erasure_dec )
      self.connect( erasure_dec, ( frame_gate, 1 ) )
      self.connect( erasure_dec, ( id_gate,    1 ) )
      self.connect( erasure_dec, ( ctf_gate,   1 ) )

      self.id_dec = self._id_decoder = id_gate
      self.ctf = ctf_gate



      print "Erasure decision for IDs is enabled"




    if options.log:
      id_dec_f = gr.short_to_float()
      self.connect(self.id_dec,id_dec_f)
      log_to_file(self, id_dec_f, "data/id_dec_out.float")


    if options.log:
      log_to_file(self, id_bfilt, "data/id_blockfilter_out.compl")


    # TODO: refactor names




    if options.log:
      map_src_f = gr.char_to_float(dsubc)
      self.connect(map_src,map_src_f)
      log_to_file(self, map_src_f, "data/map_src_out.float")

    ## Allocation Control
    if options.static_allocation: #DEBUG
        
        if options.coding:
            mode = 1 # Coding mode 1-9
            bitspermode = [0.5,1,1.5,2,3,4,4.5,5,6] # Information bits per mode
            bitcount_vec = [(int)(config.data_subcarriers*config.frame_data_blocks*bitspermode[mode-1])]
            bitloading = mode
        else:
            bitloading = 1
            bitcount_vec = [config.data_subcarriers*config.frame_data_blocks*bitloading]
        #bitcount_vec = [config.data_subcarriers*config.frame_data_blocks]
        self.bitcount_src = blocks.vector_source_i(bitcount_vec,True,1)
        # 0s for ID block, then data
        #bitloading_vec = [0]*dsubc+[0]*(dsubc/2)+[2]*(dsubc/2)
        bitloading_vec = [0]*dsubc+[bitloading]*dsubc
        bitloading_src = blocks.vector_source_b(bitloading_vec,True,dsubc)
        power_vec = [1]*config.data_subcarriers
        power_src = blocks.vector_source_f(power_vec,True,dsubc)
    else:
        self.allocation_buffer = ofdm.allocation_buffer(config.data_subcarriers, config.frame_data_blocks, "tcp://"+options.tx_hostname+":3333",config.coding)
        self.bitcount_src = (self.allocation_buffer,0)
        bitloading_src = (self.allocation_buffer,1)
        power_src = (self.allocation_buffer,2)
        self.connect(self.id_dec, self.allocation_buffer)
        if options.benchmarking:
            self.allocation_buffer.set_allocation([4]*config.data_subcarriers,[1]*config.data_subcarriers)

    if options.log:
        log_to_file(self, self.bitcount_src, "data/bitcount_src_rx.int")
        log_to_file(self, bitloading_src, "data/bitloading_src_rx.char")
        log_to_file(self, power_src, "data/power_src_rx.cmplx")
        log_to_file(self, self.id_dec, "data/id_dec_rx.short")

    ## Power Deallocator
    pda = self._power_deallocator = multiply_frame_fc(config.frame_data_part, dsubc)
    self.connect(pda_in,(pda,0))
    self.connect(power_src,(pda,1))

    ## Demodulator
#    if 0:
#          ac_vector = [0.0+0.0j]*208
#          ac_vector[0] = (2*10**(-0.452))
#          ac_vector[3] = (10**(-0.651))
#          ac_vector[7] = (10**(-1.151))
#          csi_vector_inv=abs(numpy.fft.fft(numpy.sqrt(ac_vector)))**2
#          dm_csi = numpy.fft.fftshift(csi_vector_inv) # TODO

    dm_csi = [1]*dsubc # TODO
    dm_csi = blocks.vector_source_f(dm_csi,True)
    ## Depuncturer
    dp_trig = [0]*(config.frame_data_blocks/2)
    dp_trig[0] = 1
    dp_trig = blocks.vector_source_b(dp_trig,True) # TODO



    if(options.coding):
        fo=ofdm.fsm(1,2,[91,121])
        if options.interleave:
            int_object=trellis.interleaver(2000,666)
            deinterlv = trellis.permutation(int_object.K(),int_object.DEINTER(),1,gr.sizeof_float)
        
        demod = self._data_demodulator = generic_softdemapper_vcf(dsubc, config.frame_data_part, config.coding)
        #self.connect(dm_csi,blocks.stream_to_vector(gr.sizeof_float,dsubc),(demod,2))
        if(options.ideal):
            self.connect(dm_csi,blocks.stream_to_vector(gr.sizeof_float,dsubc),(demod,2))
        else:
            dm_csi_filter = self.dm_csi_filter = filter.single_pole_iir_filter_ff(0.01,dsubc)
            self.connect(self.ctf, self.dm_csi_filter,(demod,2))
            #log_to_file(self, dm_csi_filter, "data/softs_csi.float")
        #self.connect(dm_trig,(demod,3))
    else:
        demod = self._data_demodulator = generic_demapper_vcb(dsubc, config.frame_data_part)
    if options.benchmarking:
        # Do receiver benchmarking until the number of frames x symbols are collected
        self.connect(pda,blocks.head(gr.sizeof_gr_complex*dsubc, options.N*config.frame_data_blocks),demod)
    else:        
        self.connect(pda,demod)
    self.connect(bitloading_src,(demod,1))

    if(options.coding):
        ## Depuncturing
        if not options.nopunct:
            depuncturing = depuncture_ff(dsubc,0)
            frametrigger_bitmap_filter = blocks.vector_source_b([1,0],True)
            self.connect(bitloading_src,(depuncturing,1))
            self.connect(dp_trig,(depuncturing,2))

        ## Decoding
        chunkdivisor = int(numpy.ceil(config.frame_data_blocks/5.0))
        print "Number of chunks at Viterbi decoder: ", chunkdivisor
        decoding = self._data_decoder = ofdm.viterbi_combined_fb(fo,dsubc,-1,-1,2,chunkdivisor,[-1,-1,-1,1,1,-1,1,1],ofdm.TRELLIS_EUCLIDEAN)

        
        if options.log and options.coding:
            log_to_file(self, decoding, "data/decoded.char")
            if not options.nopunct:
                log_to_file(self, depuncturing, "data/vit_in.float")

        if not options.nopunct:
            if options.interleave:
                self.connect(demod,deinterlv,depuncturing,decoding)
            else:
                self.connect(demod,depuncturing,decoding)
        else:
            self.connect(demod,decoding)
        self.connect(self.bitcount_src, multiply_const_ii(1./chunkdivisor), (decoding,1))

    if options.scatterplot or options.scatter_plot_before_phase_tracking:
        if self.ideal2 is False:
            scatter_vec_elem = self._scatter_vec_elem = ofdm.vector_element(dsubc,40)
            scatter_s2v = self._scatter_s2v = blocks.stream_to_vector(gr.sizeof_gr_complex,config.frame_data_blocks)
    
            scatter_id_filt = skip(gr.sizeof_gr_complex*dsubc,config.frame_data_blocks)
            scatter_id_filt.skip_call(0)
            scatter_trig = [0]*config.frame_data_part
            scatter_trig[0] = 1
            scatter_trig = blocks.vector_source_b(scatter_trig,True)
            self.connect(scatter_trig,(scatter_id_filt,1))
            self.connect(scatter_vec_elem,scatter_s2v)
    
            if not options.scatter_plot_before_phase_tracking:
                print "Enabling Scatterplot for data subcarriers"
                self.connect(pda,scatter_id_filt,scatter_vec_elem)
                  # Work on this
                  #scatter_sink = ofdm.scatterplot_sink(dsubc)
                  #self.connect(pda,scatter_sink)
                  #self.connect(map_src,(scatter_sink,1))
                  #self.connect(dm_trig,(scatter_sink,2))
                  #print "Enabled scatterplot gui interface"
                self.zmq_probe_scatter = zeromq.pub_sink(gr.sizeof_gr_complex,config.frame_data_blocks, "tcp://*:5560")
                self.connect(scatter_s2v, blocks.keep_one_in_n(gr.sizeof_gr_complex*config.frame_data_blocks,20), self.zmq_probe_scatter)
            else:
                print "Enabling Scatterplot for data before phase tracking"
                inner_rx = inner_receiver.before_phase_tracking
                #scatter_sink2 = ofdm.scatterplot_sink(dsubc,"phase_tracking")
                op = copy.copy(options)
                op.enable_erasure_decision = False
                new_framesampler = ofdm_frame_sampler(op)
                self.connect( inner_rx, new_framesampler )
                self.connect( orig_frame_start, (new_framesampler,1) )
                new_ps_filter = pilot_subcarrier_filter()
                new_pb_filter = fbmc_pilot_block_filter()
    
                self.connect( (new_framesampler,1), (new_pb_filter,1) )
                self.connect( new_framesampler, new_pb_filter,
                             new_ps_filter, scatter_id_filt, scatter_vec_elem )
    
                #self.connect( new_ps_filter, scatter_sink2 )
                #self.connect( map_src, (scatter_sink2,1))
                #self.connect( dm_trig, (scatter_sink2,2))


    if options.log:
      if(options.coding):
          log_to_file(self, demod, "data/data_stream_out.float")
      else:
          data_f = gr.char_to_float()
          self.connect(demod,data_f)
          log_to_file(self, data_f, "data/data_stream_out.float")



    if options.sfo_feedback:
      used_id_bits = 8
      rep_id_bits = config.data_subcarriers/used_id_bits

      seed(1)
      whitener_pn = [randint(0,1) for i in range(used_id_bits*rep_id_bits)]

      id_enc = ofdm.repetition_encoder_sb(used_id_bits,rep_id_bits,whitener_pn)
      self.connect( self.id_dec, id_enc )

      id_mod = ofdm_bpsk_modulator(dsubc)
      self.connect( id_enc, id_mod )

      id_mod_conj = gr.conjugate_cc(dsubc)
      self.connect( id_mod, id_mod_conj )

      id_mult = blocks.multiply_vcc(dsubc)
      self.connect( id_bfilt, ( id_mult,0) )
      self.connect( id_mod_conj, ( id_mult,1) )

#      id_mult_avg = filter.single_pole_iir_filter_cc(0.01,dsubc)
#      self.connect( id_mult, id_mult_avg )

      id_phase = gr.complex_to_arg(dsubc)
      self.connect( id_mult, id_phase )

      log_to_file( self, id_phase, "data/id_phase.float" )

      est=ofdm.LS_estimator_straight_slope(dsubc)
      self.connect(id_phase,est)

      slope=blocks.multiply_const_ff(1e6/2/3.14159265)
      self.connect( (est,0), slope )

      log_to_file( self, slope, "data/slope.float" )
      log_to_file( self, (est,1), "data/offset.float" )

    # ------------------------------------------------------------------------ #




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

    ## debug logging ##
    if options.log:
#      log_to_file(self,self.ofdm_symbols,"data/unequalized_rx_ofdm_symbols.compl")
#      log_to_file(self,self.ofdm_symbols,"data/unequalized_rx_ofdm_symbols.float",mag=True)


      fftlen = 256
      my_window = window.hamming(fftlen) #.blackmanharris(fftlen)
      rxs_sampler = vector_sampler(gr.sizeof_gr_complex,fftlen)
      rxs_sampler_vect = concatenate([[1],[0]*49])
      rxs_trigger = blocks.vector_source_b(rxs_sampler_vect.tolist(),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 = filter.single_pole_iir_filter_ff(0.01,fftlen)
      #rxs_logdb = blocks.nlog10_ff(20.0,fftlen,-20*log10(fftlen))
      rxs_logdb = gr.kludge_copy( gr.sizeof_float * fftlen )
      rxs_decimate_rate = gr.keep_one_in_n(gr.sizeof_float*fftlen,1)
      self.connect(rxs_trigger,(rxs_sampler,1))
      self.connect(self.input,rxs_sampler,rxs_window,
                   rxs_spectrum,rxs_mag,rxs_avg,rxs_logdb, rxs_decimate_rate)
      log_to_file( self, rxs_decimate_rate, "data/psd_input.float" )


    #output branches
    self.publish_rx_performance_measure()
Esempio n. 44
0
    def __init__(self, options, log=False):

        ## Read configuration
        config = station_configuration()

        fft_length = config.fft_length
        #cp_length     = config.cp_length
        block_header = config.training_data
        data_subc = config.data_subcarriers
        virtual_subc = config.virtual_subcarriers
        total_subc = config.subcarriers
        block_length = config.block_length
        frame_length = config.frame_length

        L = block_header.mm_periodic_parts

        cp_length = config.cp_length

        print "data_subc: ", config.data_subcarriers
        print "total_subc: ", config.subcarriers
        print "frame_lengthframe_length: ", frame_length

        ## Set Input/Output signature
        gr.hier_block2.__init__(
            self,
            "fbmc_inner_receiver",
            gr.io_signature(1, 1, gr.sizeof_gr_complex),
            gr.io_signaturev(
                4,
                4,
                [
                    gr.sizeof_float * total_subc,  # Normalized |CTF|^2 
                    gr.sizeof_char,  # Frame start
                    gr.sizeof_gr_complex * total_subc,  # OFDM blocks, SNR est
                    gr.sizeof_float
                ]))  # CFO

        ## Input and output ports
        self.input = rx_input = self

        out_ofdm_blocks = (self, 2)
        out_frame_start = (self, 1)
        out_disp_ctf = (self, 0)
        out_disp_cfo = (self, 3)
        #out_snr_pream    = ( self, 3 )

        ## pre-FFT processing
        '''
    ## Compute autocorrelations for S&C preamble
    ## and cyclic prefix
    
    self._sc_metric = sc_metric = autocorrelator( fft_length/2, fft_length/2 )
    self._gi_metric = gi_metric = autocorrelator( fft_length, cp_length )
    
    self.connect( rx_input, sc_metric )
    self.connect( rx_input, gi_metric )
    terminate_stream(self, gi_metric)
    
    ## Sync. Output contains OFDM blocks
    sync = ofdm.time_sync( fft_length/2, 1)
    self.connect( rx_input, ( sync, 0 ) )
    self.connect( sc_metric, ( sync, 1 ) )
    self.connect( sc_metric, ( sync, 2 ) )
    
    ofdm_blocks = ( sync, 0 )
    frame_start = ( sync, 1 )
    log_to_file( self, ( sync, 1 ), "data/fbmc_peak_detector.char" )
    '''
        if options.ideal is False and options.ideal2 is False:
            #Testing old/new metric
            self.tm = schmidl.recursive_timing_metric(2 * fft_length)
            self.connect(self.input, self.tm)
            #log_to_file( self, self.tm, "data/fbmc_rec_sc_metric_ofdm.float" )

            timingmetric_shift = 0  #-2 #int(-cp_length * 0.8)
            tmfilter = filter.fft_filter_fff(
                1, [2. / fft_length] * (fft_length / 2)
            )  # ofdm.lms_fir_ff( fft_length, 1e-3 ) #; filter.fir_filter_fff(1, [1./fft_length]*fft_length)
            self.connect(self.tm, tmfilter)
            self.tm = tmfilter
            #log_to_file( self, self.tm, "data/fbmc_rec_sc_metric_ofdm2.float" )

            self._pd_thres = 0.6
            self._pd_lookahead = fft_length  # empirically chosen
            peak_detector = ofdm.peak_detector_02_fb(self._pd_lookahead,
                                                     self._pd_thres)
            self.connect(self.tm, peak_detector)
            #log_to_file( self, peak_detector, "data/fbmc_rec_peak_detector.char" )

            #frame_start = [0]*frame_length
            #frame_start[0] = 1
            #frame_start = blocks.vector_source_b(frame_start,True)

            #OLD
            #delayed_timesync = blocks.delay(gr.sizeof_char,
            #                           (frame_length-10)*fft_length/2 - fft_length/4 -1 + timingmetric_shift)
            delayed_timesync = blocks.delay(
                gr.sizeof_char,
                (frame_length - 10) * fft_length / 2 - fft_length / 4 +
                int(2.5 * fft_length) + timingmetric_shift - 1)
            #delayed_timesync = blocks.delay(gr.sizeof_char,
            #(frame_length-10)*fft_length/2 - fft_length/4 + int(3.5*fft_length)  + timingmetric_shift-1)
            self.connect(peak_detector, delayed_timesync)

            self.block_sampler = ofdm.vector_sampler(
                gr.sizeof_gr_complex, fft_length / 2 * frame_length)

            self.connect(self.input, self.block_sampler)
            self.connect(delayed_timesync, (self.block_sampler, 1))
            #log_to_file( self, self.block_sampler, "data/fbmc_block_sampler.compl" )

            vt2s = blocks.vector_to_stream(gr.sizeof_gr_complex * fft_length,
                                           frame_length / 2)
            self.connect(self.block_sampler, vt2s)
            #terminate_stream(self,ofdm_blocks)

            ofdm_blocks = vt2s
            '''
        # TODO: dynamic solution
        vt2s = blocks.vector_to_stream(gr.sizeof_gr_complex*block_length/2,
                                                frame_length)
        self.connect(self.block_sampler,vt2s)
        terminate_stream(self,( sync, 0 ))
        ofdm_blocks = vt2s
        '''

            ##stv_help = blocks.stream_to_vector(gr.sizeof_gr_complex*config.fft_length/2, 1)
            #stv_help = blocks.vector_to_stream(gr.sizeof_gr_complex*config.fft_length/2, 2)
            ##self.connect(ofdm_blocks, stv_help)
            ##ofdm_blocks = stv_help
            #ofdm_blocks = ( sync, 0 )
            #frame_start = ( sync, 1 )
            #log_to_file(self, frame_start, "data/frame_start.compl")

            #log_to_file( self, sc_metric, "data/sc_metric.float" )
            #log_to_file( self, gi_metric, "data/gi_metric.float" )
            #log_to_file( self, (sync,1), "data/sync.float" )

            #    log_to_file(self,ofdm_blocks,"data/ofdm_blocks_original.compl")
            frame_start = [0] * int(frame_length / 2)
            frame_start[0] = 1
            frame_start = blocks.vector_source_b(frame_start, True)

            #frame_start2 = [0]*int(frame_length/2)
            #frame_start2[0] = 1
            #frame_start2 = blocks.vector_source_b(frame_start2,True)

        if options.disable_time_sync or options.ideal or options.ideal2:
            if options.ideal is False and options.ideal2 is False:
                terminate_stream(self, ofdm_blocks)
                terminate_stream(self, frame_start)

            serial_to_parallel = blocks.stream_to_vector(
                gr.sizeof_gr_complex, fft_length)
            #discard_cp = ofdm.vector_mask(block_length,cp_length,fft_length,[])
            #serial_to_parallel = blocks.stream_to_vector(gr.sizeof_gr_complex,block_length)
            #discard_cp = ofdm.vector_mask(block_length,cp_length,fft_length,[])
            #self.connect( rx_input,serial_to_parallel)

            #self.connect( rx_input, blocks.delay(gr.sizeof_gr_complex,0),serial_to_parallel)
            initial_skip = blocks.skiphead(gr.sizeof_gr_complex,
                                           2 * fft_length)
            self.connect(rx_input, initial_skip)
            if options.ideal is False and options.ideal2 is False:
                self.connect(initial_skip, serial_to_parallel)
                ofdm_blocks = serial_to_parallel
            else:
                ofdm_blocks = initial_skip
            #self.connect( rx_input, serial_to_parallel, discard_cp )

            frame_start = [0] * int(frame_length / 2)
            frame_start[0] = 1
            frame_start = blocks.vector_source_b(frame_start, True)

            #frame_start2 = [0]*int(frame_length/2)
            #frame_start2[0] = 1
            #frame_start2 = blocks.vector_source_b(frame_start2,True)

            print "Disabled time synchronization stage"

        print "\t\t\t\t\tframe_length = ", frame_length

        if options.ideal is False and options.ideal2 is False:
            ## Extract preamble, feed to Morelli & Mengali frequency offset estimator
            assert (block_header.mm_preamble_pos == 0)
            morelli_foe = ofdm.mm_frequency_estimator(fft_length, 2, 1,
                                                      config.fbmc)
            sampler_preamble = ofdm.vector_sampler(
                gr.sizeof_gr_complex * fft_length, 1)
            self.connect(ofdm_blocks, (sampler_preamble, 0))
            self.connect(frame_start, blocks.delay(gr.sizeof_char, 1),
                         (sampler_preamble, 1))
            self.connect(sampler_preamble, morelli_foe)
            freq_offset = morelli_foe
            print "FRAME_LENGTH: ", frame_length
            #log_to_file( self, sampler_preamble, "data/sampler_preamble.compl" )
            #log_to_file( self, rx_input, "data/rx_input.compl" )
            #log_to_file( self, ofdm_blocks, "data/rx_input.compl" )

            #Extracting preamble for SNR estimation
            #fft_snr_est = fft_blocks.fft_vcc( fft_length, True, [], True )
            #self.connect( sampler_preamble, blocks.stream_to_vector(gr.sizeof_gr_complex*fft_length/2, 2),  fft_snr_est )

            ## Remove virtual subcarriers
            #if fft_length > data_subc:
            #subcarrier_mask_snr_est = ofdm.vector_mask( fft_length, virtual_subc/2,
            #                       total_subc, [] )
            #self.connect( fft_snr_est, subcarrier_mask_snr_est )
            #fft_snr_est = subcarrier_mask_snr_est
            #log_to_file(self, ofdm_blocks, "data/vec_mask.compl")
            ## Least Squares estimator for channel transfer function (CTF)

            #self.connect( fft_snr_est, out_snr_pream ) # Connecting to output

            ## Adaptive LMS FIR filtering of frequency offset
            lms_fir = ofdm.lms_fir_ff(20,
                                      1e-3)  # TODO: verify parameter choice
            self.connect(freq_offset, lms_fir)
            freq_offset = lms_fir

            self.connect(freq_offset,
                         blocks.keep_one_in_n(gr.sizeof_float,
                                              20), out_disp_cfo)
        else:
            self.connect(blocks.vector_source_f([1]), out_disp_cfo)

        #log_to_file(self, lms_fir, "data/lms_fir.float")

        if options.disable_freq_sync or options.ideal or options.ideal2:
            if options.ideal is False and options.ideal2 is False:
                terminate_stream(self, freq_offset)
                freq_offset = blocks.vector_source_f([0.0], True)
            print "Disabled frequency synchronization stage"

        if options.ideal is False and options.ideal2 is False:
            ## Correct frequency shift, feed-forward structure
            frequency_shift = ofdm.frequency_shift_vcc(fft_length,
                                                       -1.0 / fft_length, 0)

            #freq_shift = blocks.multiply_cc()
            #norm_freq = -0.1 / config.fft_length
            #freq_off = self.freq_off_src = analog.sig_source_c(1.0, analog.GR_SIN_WAVE, norm_freq, 1.0, 0.0 )

            self.connect(ofdm_blocks, (frequency_shift, 0))
            self.connect(freq_offset, (frequency_shift, 1))
            self.connect(frame_start, blocks.delay(gr.sizeof_char, 0),
                         (frequency_shift, 2))

            #self.connect(frequency_shift,s2help)
            #ofdm_blocks = s2help
            ofdm_blocks = frequency_shift
        #terminate_stream(self, frequency_shift)

        #inner_pb_filt = self._inner_pilot_block_filter = fbmc_inner_pilot_block_filter()
        #self.connect(ofdm_blocks,inner_pb_filt)
        #self.connect(frame_start,(inner_pb_filt,1))
        #self.connect((inner_pb_filt,1),blocks.null_sink(gr.sizeof_char))

        #ofdm_blocks = (inner_pb_filt,0)

        overlap_ser_to_par = ofdm.fbmc_overlapping_serial_to_parallel_cvc(
            fft_length)
        self.separate_vcvc = ofdm.fbmc_separate_vcvc(fft_length, 2)
        self.polyphase_network_vcvc_1 = ofdm.fbmc_polyphase_network_vcvc(
            fft_length, 4, 4 * fft_length - 1, True)
        self.polyphase_network_vcvc_2 = ofdm.fbmc_polyphase_network_vcvc(
            fft_length, 4, 4 * fft_length - 1, True)
        self.junction_vcvc = ofdm.fbmc_junction_vcvc(fft_length, 2)
        self.fft_fbmc = fft_blocks.fft_vcc(fft_length, True, [], True)

        print "config.training_data.fbmc_no_preambles: ", config.training_data.fbmc_no_preambles
        #center_preamble = [1, -1j, -1, 1j]

        #self.preamble = preamble = [0]*total_subc + center_preamble*((int)(total_subc/len(center_preamble)))+[0]*total_subc

        self.preamble = preamble = config.training_data.fbmc_pilotsym_fd_list
        #inv_preamble = 1. / numpy.array(self.preamble)
        #print "self.preamble: ", len(self.preamble
        #print "inv_preamble: ", list(inv_preamble)

        #print "self.preamble", self.preamble
        #print "self.preamble2", self.preamble2

        self.multiply_const = ofdm.multiply_const_vcc(
            ([1.0 / (math.sqrt(fft_length * 0.6863))] * total_subc))
        self.beta_multiplier_vcvc = ofdm.fbmc_beta_multiplier_vcvc(
            total_subc, 4, 4 * fft_length - 1, 0)
        #self.skiphead = blocks.skiphead(gr.sizeof_gr_complex*total_subc, 2*4-1-1)
        self.skiphead = blocks.skiphead(gr.sizeof_gr_complex * total_subc, 2)
        self.skiphead_1 = blocks.skiphead(gr.sizeof_gr_complex * total_subc, 0)
        #self.remove_preamble_vcvc = ofdm.fbmc_remove_preamble_vcvc(total_subc, config.frame_data_part/2, config.training_data.fbmc_no_preambles*total_subc/2)
        #self.subchannel_processing_vcvc = ofdm.fbmc_subchannel_processing_vcvc(total_subc, config.frame_data_part, 1, 2, 1, 0)
        self.oqam_postprocessing_vcvc = ofdm.fbmc_oqam_postprocessing_vcvc(
            total_subc, 0, 0)

        #log_to_file( self, ofdm_blocks, "data/PRE_FBMC.compl" )
        #log_to_file( self, self.fft_fbmc, "data/FFT_FBMC.compl" )

        if options.ideal is False and options.ideal2 is False:
            self.subchannel_processing_vcvc = ofdm.fbmc_subchannel_processing_vcvc(
                total_subc, config.frame_data_part, 3, 2, 1, 0)
            help2 = blocks.keep_one_in_n(gr.sizeof_gr_complex * total_subc,
                                         frame_length)
            self.connect((self.subchannel_processing_vcvc, 1), help2)
            #log_to_file( self, self.subchannel_processing_vcvc, "data/fbmc_subc.compl" )

        #terminate_stream(self, help2)

        if options.ideal is False and options.ideal2 is False:
            self.connect(
                ofdm_blocks,
                blocks.vector_to_stream(gr.sizeof_gr_complex, fft_length),
                overlap_ser_to_par)
        else:
            self.connect(ofdm_blocks, overlap_ser_to_par)

        self.connect(overlap_ser_to_par, self.separate_vcvc)
        self.connect((self.separate_vcvc, 1),
                     (self.polyphase_network_vcvc_2, 0))
        self.connect((self.separate_vcvc, 0),
                     (self.polyphase_network_vcvc_1, 0))
        self.connect((self.polyphase_network_vcvc_1, 0),
                     (self.junction_vcvc, 0))
        self.connect((self.polyphase_network_vcvc_2, 0),
                     (self.junction_vcvc, 1))
        self.connect(self.junction_vcvc, self.fft_fbmc)

        ofdm_blocks = self.fft_fbmc
        print "config.dc_null: ", config.dc_null
        if fft_length > data_subc:
            subcarrier_mask_fbmc = ofdm.vector_mask_dc_null(
                fft_length, virtual_subc / 2, total_subc, config.dc_null, [])
            self.connect(ofdm_blocks, subcarrier_mask_fbmc)
            ofdm_blocks = subcarrier_mask_fbmc
            #log_to_file(self, ofdm_blocks, "data/vec_mask.compl")
            ## Least Squares estimator for channel transfer function (CTF)
            #log_to_file( self, subcarrier_mask, "data/OFDM_Blocks.compl" )

        self.connect(ofdm_blocks, self.beta_multiplier_vcvc)

        ofdm_blocks = self.beta_multiplier_vcvc
        #self.connect(ofdm_blocks,self.multiply_const)
        #self.connect(self.multiply_const, (self.skiphead, 0))

        self.connect(ofdm_blocks, (self.skiphead, 0))
        #log_to_file( self, self.skiphead, "data/fbmc_skiphead_4.compl" )

        #self.connect(ofdm_blocks, self.multiply_const)
        #self.connect(self.multiply_const, self.beta_multiplier_vcvc)
        #self.connect((self.beta_multiplier_vcvc, 0), (self.skiphead, 0))
        if options.ideal or options.ideal2:
            self.connect((self.skiphead, 0), (self.skiphead_1, 0))
        else:
            self.connect((self.skiphead, 0),
                         (self.subchannel_processing_vcvc, 0))
            self.connect((self.subchannel_processing_vcvc, 0),
                         (self.skiphead_1, 0))

        #log_to_file( self, self.skiphead, "data/fbmc_subc.compl" )
        #self.connect((self.skiphead_1, 0),(self.remove_preamble_vcvc, 0))
        #self.connect((self.remove_preamble_vcvc, 0),  (self.oqam_postprocessing_vcvc, 0))

        #ofdm_blocks = self.oqam_postprocessing_vcvc
        #log_to_file( self, self.subchannel_processing_vcvc, "data/subc_0.compl" )
        #log_to_file( self, (self.subchannel_processing_vcvc,1), "data/subc_1.compl" )

        self.connect((self.skiphead_1, 0), (self.oqam_postprocessing_vcvc, 0))
        #self.connect((self.oqam_postprocessing_vcvc, 0), (self.remove_preamble_vcvc, 0) )

        ofdm_blocks = (self.oqam_postprocessing_vcvc, 0
                       )  #(self.remove_preamble_vcvc, 0)
        #log_to_file( self, (self.oqam_postprocessing_vcvc, 0), "data/fbmc_before_remove.compl" )

        #log_to_file( self, self.skiphead, "data/SKIP_HEAD_FBMC.compl" )
        #log_to_file( self, self.beta_multiplier_vcvc, "data/BETA_REC_FBMC.compl" )
        #log_to_file( self, self.oqam_postprocessing_vcvc, "data/REC_OUT_FBMC.compl" )
        """ DISABLED OFDM CHANNEL ESTIMATION PREMBLE -> CORRECT LATER to compare FBMC and OFDM channel estimation
    #TAKING THE CHANNEL ESTIMATION PREAMBLE
    chest_pre_trigger = blocks.delay( gr.sizeof_char, 3 )
    sampled_chest_preamble = ofdm.vector_sampler( gr.sizeof_gr_complex * fft_length/2, 2 )
      
    self.connect( frame_start,       chest_pre_trigger )
    self.connect( chest_pre_trigger, ( sampled_chest_preamble, 1 ) )
    self.connect( frequency_shift,       ( sampled_chest_preamble, 0 ) )
    #ofdm_blocks = sampled_chest_preamble
    
        
    ## FFT
    fft = fft_blocks.fft_vcc( fft_length, True, [], True )
    self.connect( sampled_chest_preamble, fft )
    ofdm_blocks_est = fft
    log_to_file( self, sampled_chest_preamble, "data/SAMPLED_EST_PREAMBLE.compl" )
    log_to_file( self, ofdm_blocks_est, "data/FFT.compl" )
    
    
    ## Remove virtual subcarriers
    if fft_length > data_subc:
      subcarrier_mask = ofdm.vector_mask( fft_length, virtual_subc/2,
                                           total_subc, [] )
      self.connect( ofdm_blocks_est, subcarrier_mask )
      ofdm_blocks_est = subcarrier_mask
      #log_to_file(self, ofdm_blocks, "data/vec_mask.compl")
       ## Least Squares estimator for channel transfer function (CTF)
      log_to_file( self, subcarrier_mask, "data/OFDM_Blocks.compl" )
    
          
    ## post-FFT processing
      
    
    
    ## extract channel estimation preamble from frame
    ##chest_pre_trigger = blocks.delay( gr.sizeof_char, 
                                  ##1 )
    ##sampled_chest_preamble = \
     ## ofdm.vector_sampler( gr.sizeof_gr_complex * total_subc, 1 )
    ##self.connect( frame_start,       chest_pre_trigger )
    ##self.connect( chest_pre_trigger, ( sampled_chest_preamble, 1 ) )
    ##self.connect( ofdm_blocks,       ( sampled_chest_preamble, 0 ) )
    

    
    ## Least Squares estimator for channel transfer function (CTF)
    inv_preamble_fd = numpy.array( block_header.pilotsym_fd[ 
        block_header.channel_estimation_pilot[0] ] )
    #print "Channel estimation pilot: ", inv_preamble_fd
    inv_preamble_fd = 1. / inv_preamble_fd
    
    LS_channel_estimator = ofdm.multiply_const_vcc( list( inv_preamble_fd ) )
    self.connect( ofdm_blocks_est, LS_channel_estimator )
    estimated_CTF = LS_channel_estimator
    terminate_stream(self,estimated_CTF)
    """
        if options.ideal is False and options.ideal2 is False:
            if options.logcir:
                log_to_file(self, sampled_chest_preamble, "data/PREAM.compl")

            if not options.disable_ctf_enhancer:

                if options.logcir:
                    ifft1 = fft_blocks.fft_vcc(total_subc, False, [], True)
                    self.connect(
                        estimated_CTF, ifft1,
                        gr.null_sink(gr.sizeof_gr_complex * total_subc))
                    summ1 = ofdm.vector_sum_vcc(total_subc)
                    c2m = gr.complex_to_mag(total_subc)
                    self.connect(estimated_CTF, summ1,
                                 gr.null_sink(gr.sizeof_gr_complex))
                    self.connect(estimated_CTF, c2m,
                                 gr.null_sink(gr.sizeof_float * total_subc))
                    log_to_file(self, ifft1, "data/CIR1.compl")
                    log_to_file(self, summ1, "data/CTFsumm1.compl")
                    log_to_file(self, estimated_CTF, "data/CTF1.compl")
                    log_to_file(self, c2m, "data/CTFmag1.float")

                ## MSE enhancer
                ctf_mse_enhancer = ofdm.CTF_MSE_enhancer(
                    total_subc, cp_length + cp_length)
                self.connect(estimated_CTF, ctf_mse_enhancer)
                #      log_to_file( self, ctf_mse_enhancer, "data/ctf_mse_enhancer_original.compl")
                #ifft3 = fft_blocks.fft_vcc(total_subc,False,[],True)
                #null_noise = ofdm.noise_nulling(total_subc, cp_length + cp_length)
                #ctf_mse_enhancer = fft_blocks.fft_vcc(total_subc,True,[],True)
                #ctf_mse_enhancer = ofdm.vector_mask( fft_length, virtual_subc/2,
                # total_subc, [] )
                #self.connect( estimated_CTF, ifft3,null_noise,ctf_mse_enhancer )

                estimated_CTF = ctf_mse_enhancer
                print "Disabled CTF MSE enhancer"

            if options.logcir:
                ifft2 = fft_blocks.fft_vcc(total_subc, False, [], True)
                self.connect(estimated_CTF, ifft2,
                             gr.null_sink(gr.sizeof_gr_complex * total_subc))
                summ2 = ofdm.vector_sum_vcc(total_subc)
                c2m2 = gr.complex_to_mag(total_subc)
                self.connect(estimated_CTF, summ2,
                             gr.null_sink(gr.sizeof_gr_complex))
                self.connect(estimated_CTF, c2m2,
                             gr.null_sink(gr.sizeof_float * total_subc))
                log_to_file(self, ifft2, "data/CIR2.compl")
                log_to_file(self, summ2, "data/CTFsumm2.compl")
                log_to_file(self, estimated_CTF, "data/CTF2.compl")
                log_to_file(self, c2m2, "data/CTFmag2.float")

            ## Postprocess the CTF estimate
            ## CTF -> inverse CTF (for equalizer)
            ## CTF -> norm |.|^2 (for CTF display)
            ctf_postprocess = ofdm.fbmc_postprocess_CTF_estimate(total_subc)

            self.connect(help2, ctf_postprocess)
            #estimated_SNR = ( ctf_postprocess, 0 )
            disp_CTF = (ctf_postprocess, 0)
            #self.connect(estimated_SNR,out_snr_pream)
            #log_to_file( self, estimated_SNR, "data/fbmc_SNR.float" )

            #Disable measured SNR output
            #terminate_stream(self, estimated_SNR)
            #self.connect(blocks.vector_source_f([10.0],True) ,out_snr_pream)


#     if options.disable_equalization or options.ideal:
#       terminate_stream(self, inv_estimated_CTF)
#       inv_estimated_CTF_vec = blocks.vector_source_c([1.0/fft_length*math.sqrt(total_subc)]*total_subc,True,total_subc)
#       inv_estimated_CTF_str = blocks.vector_to_stream(gr.sizeof_gr_complex, total_subc)
#       self.inv_estimated_CTF_mul = ofdm.multiply_const_ccf( 1.0/config.rms_amplitude )
#       #inv_estimated_CTF_mul.set_k(1.0/config.rms_amplitude)
#       inv_estimated_CTF = blocks.stream_to_vector(gr.sizeof_gr_complex, total_subc)
#       self.connect( inv_estimated_CTF_vec, inv_estimated_CTF_str, self.inv_estimated_CTF_mul, inv_estimated_CTF)
#       print "Disabled equalization stage"
        '''
    ## LMS Phase tracking
    ## Track residual frequency offset and sampling clock frequency offset

    nondata_blocks = []
    for i in range(config.frame_length):
      if i in config.training_data.pilotsym_pos:
        nondata_blocks.append(i)
        
    print"\t\t\t\t\tnondata_blocks=",nondata_blocks
    pilot_subc = block_header.pilot_tones
    pilot_subcarriers = block_header.pilot_subc_sym
    print "PILOT SUBCARRIERS: ", pilot_subcarriers
        
    phase_tracking = ofdm.lms_phase_tracking_03( total_subc, pilot_subc,
                                               nondata_blocks, pilot_subcarriers,0 )
    self.connect( ofdm_blocks, ( phase_tracking, 0 ) )
    self.connect( inv_estimated_CTF, ( phase_tracking, 1 ) )
    self.connect( frame_start, ( phase_tracking, 2 ) ) ##
    
    if options.scatter_plot_before_phase_tracking:
      self.before_phase_tracking = equalizer
      
    
    if options.disable_phase_tracking or options.ideal:
      terminate_stream(self, phase_tracking)
      print "Disabled phase tracking stage"
    else:
      ofdm_blocks = phase_tracking
    '''
        ## Channel Equalizer
        ##equalizer = ofdm.channel_equalizer( total_subc )
        ##self.connect( ofdm_blocks,       ( equalizer, 0 ) )
        ##self.connect( inv_estimated_CTF, ( equalizer, 1 ) )
        ##self.connect( frame_start,       ( equalizer, 2 ) )
        ##ofdm_blocks = equalizer
        #log_to_file(self, equalizer,"data/equalizer_siso.compl")

        #log_to_file(self, ofdm_blocks, "data/equalizer.compl")

        ## LMS Phase tracking
        ## Track residual frequency offset and sampling clock frequency offset

        nondata_blocks = []
        for i in range(config.frame_length):
            if i in config.training_data.pilotsym_pos:
                nondata_blocks.append(i)

        print "\t\t\t\t\tnondata_blocks=", nondata_blocks
        pilot_subc = block_header.pilot_tones
        pilot_subcarriers = block_header.pilot_subc_sym
        print "PILOT SUBCARRIERS: ", pilot_subcarriers

        if options.scatter_plot_before_phase_tracking:
            self.before_phase_tracking = equalizer

        ## Output connections

        self.connect(ofdm_blocks, out_ofdm_blocks)
        self.connect(frame_start, out_frame_start)
        if options.ideal is False and options.ideal2 is False:
            self.connect(disp_CTF, out_disp_ctf)
        else:
            self.connect(blocks.vector_source_f([1.0] * total_subc),
                         blocks.stream_to_vector(gr.sizeof_float, total_subc),
                         out_disp_ctf)

        if log:
            log_to_file(self, sc_metric, "data/sc_metric.float")
            log_to_file(self, gi_metric, "data/gi_metric.float")
            log_to_file(self, morelli_foe, "data/morelli_foe.float")
            log_to_file(self, lms_fir, "data/lms_fir.float")
            log_to_file(self, sampler_preamble, "data/preamble.compl")
            log_to_file(self, sync, "data/sync.compl")
            log_to_file(self, frequency_shift, "data/frequency_shift.compl")
            log_to_file(self, fft, "data/fft.compl")
            log_to_file(self, fft, "data/fft.float", mag=True)

            if vars().has_key('subcarrier_mask'):
                log_to_file(self, subcarrier_mask,
                            "data/subcarrier_mask.compl")

            log_to_file(self, ofdm_blocks, "data/ofdm_blocks_out.compl")
            log_to_file(self,
                        frame_start,
                        "data/frame_start.float",
                        char_to_float=True)

            log_to_file(self, sampled_chest_preamble,
                        "data/sampled_chest_preamble.compl")
            log_to_file(self, LS_channel_estimator,
                        "data/ls_channel_estimator.compl")
            log_to_file(self,
                        LS_channel_estimator,
                        "data/ls_channel_estimator.float",
                        mag=True)

            if "ctf_mse_enhancer" in locals():
                log_to_file(self, ctf_mse_enhancer,
                            "data/ctf_mse_enhancer.compl")
                log_to_file(self,
                            ctf_mse_enhancer,
                            "data/ctf_mse_enhancer.float",
                            mag=True)

            log_to_file(self, (ctf_postprocess, 0),
                        "data/inc_estimated_ctf.compl")
            log_to_file(self, (ctf_postprocess, 1), "data/disp_ctf.float")

            log_to_file(self, equalizer, "data/equalizer.compl")
            log_to_file(self, equalizer, "data/equalizer.float", mag=True)

            log_to_file(self, phase_tracking, "data/phase_tracking.compl")
Esempio n. 45
0
    def __init__(self, frame, panel, vbox, argv):
        stdgui2.std_top_block.__init__(self, frame, panel, vbox, argv)

        parser = OptionParser(option_class=eng_option)
        parser.add_option("-a",
                          "--args",
                          type="string",
                          default="",
                          help="UHD 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 (bandwidth) [default=%default]")
        parser.add_option("-f",
                          "--freq",
                          type="eng_float",
                          default=1008.0e3,
                          help="set frequency to FREQ",
                          metavar="FREQ")
        parser.add_option(
            "-I",
            "--use-if-freq",
            action="store_true",
            default=False,
            help=
            "use intermediate freq (compensates DC problems in quadrature boards)"
        )
        parser.add_option("-g",
                          "--gain",
                          type="eng_float",
                          default=None,
                          help="set gain in dB (default is maximum)")
        parser.add_option("-V",
                          "--volume",
                          type="eng_float",
                          default=None,
                          help="set volume (default is midpoint)")
        parser.add_option(
            "-O",
            "--audio-output",
            type="string",
            default="",
            help="pcm device name.  E.g., hw:0,0 or surround51 or /dev/dsp")

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

        self.frame = frame
        self.panel = panel
        self.use_IF = options.use_if_freq
        if self.use_IF:
            self.IF_freq = 64000.0
        else:
            self.IF_freq = 0.0

        self.vol = 0
        self.state = "FREQ"
        self.freq = 0

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

        usrp_rate = 256e3
        demod_rate = 64e3
        audio_rate = 32e3
        chanfilt_decim = int(usrp_rate // demod_rate)
        audio_decim = int(demod_rate // audio_rate)

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

        # Resample signal to exactly self.usrp_rate
        # FIXME: make one of the follow-on filters an arb resampler
        rrate = usrp_rate / dev_rate
        self.resamp = blks2.pfb_arb_resampler_ccf(rrate)

        chan_filt_coeffs = gr.firdes.low_pass_2(
            1,  # gain
            usrp_rate,  # sampling rate
            8e3,  # passband cutoff
            4e3,  # transition bw
            60)  # stopband attenuation

        if self.use_IF:
            # Turn If to baseband and filter.
            self.chan_filt = gr.freq_xlating_fir_filter_ccf(
                chanfilt_decim, chan_filt_coeffs, self.IF_freq, usrp_rate)
        else:
            self.chan_filt = gr.fir_filter_ccf(chanfilt_decim,
                                               chan_filt_coeffs)

        self.agc = gr.agc_cc(0.1, 1, 1, 100000)
        self.am_demod = gr.complex_to_mag()
        self.volume_control = gr.multiply_const_ff(self.vol)

        audio_filt_coeffs = gr.firdes.low_pass_2(
            1,  # gain
            demod_rate,  # sampling rate
            8e3,  # passband cutoff
            2e3,  # transition bw
            60)  # stopband attenuation
        self.audio_filt = gr.fir_filter_fff(audio_decim, audio_filt_coeffs)

        # sound card as final sink
        self.audio_sink = audio.sink(int(audio_rate), options.audio_output,
                                     False)  # ok_to_block

        # now wire it all together
        self.connect(self.u, self.resamp, self.chan_filt, self.agc,
                     self.am_demod, self.audio_filt, self.volume_control,
                     self.audio_sink)

        self._build_gui(vbox, usrp_rate, demod_rate, audio_rate)

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

        if options.volume is None:
            v = self.volume_range()
            options.volume = float(v[0] * 3 + v[1]) / 4.0

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

        # set initial values

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

        # 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)
Esempio n. 46
0
    def __init__(self):
        gr.top_block.__init__(self)

        usage=("%prog: [options] output_filename.\nSpecial output_filename" + \
            "\"sdl\" will use video_sink_sdl as realtime output window. " + \
            "You then need to have gr-video-sdl installed.\n" +\
            "Make sure your input capture file containes interleaved " + \
            "shorts not complex floats")
        parser = OptionParser(option_class=eng_option, usage=usage)
        parser.add_option("-a",
                          "--args",
                          type="string",
                          default="",
                          help="UHD 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")
        parser.add_option("-c",
                          "--contrast",
                          type="eng_float",
                          default=1.0,
                          help="set contrast (default is 1.0)")
        parser.add_option("-b",
                          "--brightness",
                          type="eng_float",
                          default=0.0,
                          help="set brightness (default is 0)")
        parser.add_option("-i", "--in-filename", type="string", default=None,
                          help="Use input file as source. samples must be " + \
                            "interleaved shorts \n Use usrp_rx_file.py or " + \
                            "usrp_rx_cfile.py --output-shorts.\n Special " + \
                            "name \"usrp\" results in realtime capturing " + \
                            "and processing using usrp.\n" + \
                            "You then probably need a decimation factor of 64 or higher.")
        parser.add_option(
            "-f",
            "--freq",
            type="eng_float",
            default=519.25e6,
            help=
            "set frequency to FREQ.\nNote that the frequency of the video carrier is not at the middle of the TV channel",
            metavar="FREQ")
        parser.add_option("-g",
                          "--gain",
                          type="eng_float",
                          default=None,
                          help="set gain in dB (default is midpoint)")
        parser.add_option("-p",
                          "--pal",
                          action="store_true",
                          default=False,
                          help="PAL video format (this is the default)")
        parser.add_option("-n",
                          "--ntsc",
                          action="store_true",
                          default=False,
                          help="NTSC video format")
        parser.add_option("-r",
                          "--repeat",
                          action="store_false",
                          default=True,
                          help="repeat in_file in a loop")
        parser.add_option("-N",
                          "--nframes",
                          type="eng_float",
                          default=None,
                          help="number of frames to collect [default=+inf]")
        parser.add_option("",
                          "--freq-min",
                          type="eng_float",
                          default=50.25e6,
                          help="Set a minimum frequency [default=%default]")
        parser.add_option("",
                          "--freq-max",
                          type="eng_float",
                          default=900.25e6,
                          help="Set a maximum frequency [default=%default]")
        (options, args) = parser.parse_args()
        if not (len(args) == 1):
            parser.print_help()
            sys.stderr.write('You must specify the output. FILENAME or sdl \n')
            sys.exit(1)

        filename = args[0]

        self.tv_freq_min = options.freq_min
        self.tv_freq_max = options.freq_max

        if options.in_filename is None:
            parser.print_help()
            sys.stderr.write(
                'You must specify the input -i FILENAME or -i usrp\n')
            raise SystemExit, 1

        if not (filename == "sdl"):
            options.repeat = False

        input_rate = options.samp_rate
        print "video sample rate %s" % (eng_notation.num_to_str(input_rate))

        if not (options.in_filename == "usrp"):
            # file is data source, capture with usr_rx_csfile.py
            self.filesource = gr.file_source(gr.sizeof_short,
                                             options.in_filename,
                                             options.repeat)
            self.istoc = gr.interleaved_short_to_complex()
            self.connect(self.filesource, self.istoc)
            self.src = self.istoc
        else:
            if options.freq is None:
                parser.print_help()
                sys.stderr.write(
                    'You must specify the frequency with -f FREQ\n')
                raise SystemExit, 1

            # build the 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.u.set_samp_rate(input_rate)
            dev_rate = self.u.get_samp_rate()

            self.src = self.u

            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.u.set_gain(options.gain)

            r = self.u.set_center_freq(options.freq)
            if not r:
                sys.stderr.write('Failed to set frequency\n')
                raise SystemExit, 1

        self.agc = gr.agc_cc(1e-7, 1.0, 1.0)  #1e-7
        self.am_demod = gr.complex_to_mag()
        self.set_blacklevel = gr.add_const_ff(options.brightness + 255.0)
        self.invert_and_scale = gr.multiply_const_ff(-options.contrast *
                                                     128.0 * 255.0 / (200.0))
        self.f2uc = gr.float_to_uchar()

        # sdl window as final sink
        if not (options.pal or options.ntsc):
            options.pal = True  #set default to PAL
        if options.pal:
            lines_per_frame = 625.0
            frames_per_sec = 25.0
            show_width = 768
        elif options.ntsc:
            lines_per_frame = 525.0
            frames_per_sec = 29.97002997
            show_width = 640
        width = int(input_rate / (lines_per_frame * frames_per_sec))
        height = int(lines_per_frame)

        if filename == "sdl":
            #Here comes the tv screen, you have to build and install
            #gr-video-sdl for this (subproject of gnuradio, only in cvs
            #for now)
            try:
                video_sink = video_sdl.sink_uc(frames_per_sec, width, height,
                                               0, show_width, height)
            except:
                print "gr-video-sdl is not installed"
                print "realtime \"sdl\" video output window is not available"
                raise SystemExit, 1
            self.dst = video_sink
        else:
            print "You can use the imagemagick display tool to show the resulting imagesequence"
            print "use the following line to show the demodulated TV-signal:"
            print "display -depth 8 -size " + str(width) + "x" + str(
                height) + " gray:" + filename
            print "(Use the spacebar to advance to next frames)"
            file_sink = gr.file_sink(gr.sizeof_char, filename)
            self.dst = file_sink

        if options.nframes is None:
            self.connect(self.src, self.agc)
        else:
            self.head = gr.head(gr.sizeof_gr_complex,
                                int(options.nframes * width * height))
            self.connect(self.src, self.head, self.agc)

        self.connect(self.agc, self.am_demod, self.invert_and_scale,
                     self.set_blacklevel, self.f2uc, self.dst)
Esempio n. 47
0
    def __init__(self,
                 agc_max=100,
                 agc_decay=0.1,
                 freq_offset=1000000,
                 outfile="datafifo",
                 bandpass_bandwidth=20,
                 threshold_buffer=0.25,
                 threshold_center=0.5,
                 agc_attack=0.1,
                 bandpass_transition_width=1000000):
        gr.top_block.__init__(self, "Collect")

        ##################################################
        # Parameters
        ##################################################
        self.agc_max = agc_max
        self.agc_decay = agc_decay
        self.freq_offset = freq_offset
        self.outfile = outfile
        self.bandpass_bandwidth = bandpass_bandwidth
        self.threshold_buffer = threshold_buffer
        self.threshold_center = threshold_center
        self.agc_attack = agc_attack
        self.bandpass_transition_width = bandpass_transition_width

        ##################################################
        # Variables
        ##################################################
        self.samp_rate = samp_rate = 64000000

        ##################################################
        # Blocks
        ##################################################
        self.uhd_usrp_source_0 = uhd.usrp_source(
            device_addr="",
            io_type=uhd.io_type.COMPLEX_FLOAT32,
            num_channels=1,
        )
        self.uhd_usrp_source_0.set_samp_rate(samp_rate)
        self.uhd_usrp_source_0.set_center_freq(915000000 - freq_offset, 0)
        self.uhd_usrp_source_0.set_gain(0, 0)
        self.uhd_usrp_source_0.set_antenna("TX/RX", 0)
        self.gr_threshold_ff_0 = gr.threshold_ff(
            threshold_center - threshold_buffer,
            threshold_center + threshold_buffer, 0)
        self.gr_map_bb_0 = gr.map_bb(([48, 49]))
        self.gr_float_to_char_0 = gr.float_to_char()
        self.gr_file_sink_0 = gr.file_sink(gr.sizeof_char * 1, outfile)
        self.gr_file_sink_0.set_unbuffered(False)
        self.gr_complex_to_mag_0 = gr.complex_to_mag(1)
        self.gr_agc2_xx_0_0 = gr.agc2_cc(agc_attack, agc_decay, 1.0, 1.0,
                                         agc_max)
        self.band_pass_filter_0 = gr.fir_filter_ccf(
            1,
            firdes.band_pass(1, samp_rate,
                             freq_offset - bandpass_bandwidth / 2,
                             freq_offset + bandpass_bandwidth / 2,
                             bandpass_transition_width, firdes.WIN_HAMMING,
                             6.76))

        ##################################################
        # Connections
        ##################################################
        self.connect((self.gr_float_to_char_0, 0), (self.gr_map_bb_0, 0))
        self.connect((self.gr_map_bb_0, 0), (self.gr_file_sink_0, 0))
        self.connect((self.uhd_usrp_source_0, 0), (self.gr_agc2_xx_0_0, 0))
        self.connect((self.gr_agc2_xx_0_0, 0), (self.band_pass_filter_0, 0))
        self.connect((self.gr_threshold_ff_0, 0), (self.gr_float_to_char_0, 0))
        self.connect((self.gr_complex_to_mag_0, 0),
                     (self.gr_threshold_ff_0, 0))
        self.connect((self.band_pass_filter_0, 0),
                     (self.gr_complex_to_mag_0, 0))
Esempio n. 48
0
    def __init__(self,frame,panel,vbox,argv):
        stdgui2.std_top_block.__init__ (self,frame,panel,vbox,argv)

        usage="%prog: [options] [input_filename]. \n If you don't specify an input filename the usrp will be used as source\n " \
              "Make sure your input capture file containes interleaved shorts not complex floats"
        parser=OptionParser(option_class=eng_option, usage=usage)
        parser.add_option("-a", "--args", type="string", default="",
                          help="UHD 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")
        parser.add_option("-f", "--freq", type="eng_float", default=519.25e6,
                          help="set frequency to FREQ", metavar="FREQ")
        parser.add_option("-g", "--gain", type="eng_float", default=None,
                          help="set gain in dB (default is midpoint)")
        parser.add_option("-c", "--contrast", type="eng_float", default=1.0,
                          help="set contrast (default is 1.0)")
        parser.add_option("-b", "--brightness", type="eng_float", default=0.0,
                          help="set brightness (default is 0)")
        parser.add_option("-p", "--pal", action="store_true", default=False,
                          help="PAL video format (this is the default)")
        parser.add_option("-n", "--ntsc", action="store_true", default=False,
                          help="NTSC video format")
        parser.add_option("-o", "--out-filename", type="string", default="sdl",
                          help="For example out_raw_uchar.gray. If you don't specify an output filename you will get a video_sink_sdl realtime output window. You then need to have gr-video-sdl installed)")
        parser.add_option("-r", "--repeat", action="store_false", default=True,
                          help="repeat file in a loop")
        parser.add_option("", "--freq-min", type="eng_float", default=50.25e6,
                          help="Set a minimum frequency [default=%default]")
        parser.add_option("", "--freq-max", type="eng_float", default=900.25e6,
                          help="Set a maximum frequency [default=%default]")

        (options, args) = parser.parse_args()
        if not ((len(args) == 1) or (len(args) == 0)):
            parser.print_help()
            sys.exit(1)

        if len(args) == 1:
          filename = args[0]
        else:
          filename = None

        self.frame = frame
        self.panel = panel

        self.contrast = options.contrast
        self.brightness = options.brightness
        self.state = "FREQ"
        self.freq = 0

        self.tv_freq_min = options.freq_min
        self.tv_freq_max = options.freq_max

        # build graph
        self.u=None

        if not (options.out_filename=="sdl"):
          options.repeat=False

        usrp_rate = options.samp_rate

        if not ((filename is None) or (filename=="usrp")):
          # file is data source
          self.filesource = gr.file_source(gr.sizeof_short,filename,options.repeat)
          self.istoc = gr.interleaved_short_to_complex()
          self.connect(self.filesource,self.istoc)
          self.src=self.istoc

          options.gain=0.0
          self.gain=0.0

        else: # use a UHD device
          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.u.set_samp_rate(usrp_rate)
          dev_rate = self.u.get_samp_rate()

          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.src=self.u

        self.gain = options.gain

        f2uc=gr.float_to_uchar()

        # sdl window as final sink
        if not (options.pal or options.ntsc):
          options.pal=True #set default to PAL

        if options.pal:
          lines_per_frame=625.0
          frames_per_sec=25.0
          show_width=768

        elif options.ntsc:
          lines_per_frame=525.0
          frames_per_sec=29.97002997
          show_width=640

        width=int(usrp_rate/(lines_per_frame*frames_per_sec))
        height=int(lines_per_frame)

        if (options.out_filename=="sdl"):
          #Here comes the tv screen, you have to build and install
          #gr-video-sdl for this (subproject of gnuradio, only in cvs
          #for now)
          try:
            video_sink = video_sdl.sink_uc ( frames_per_sec, width, height, 0,
                                             show_width, height)
          except:
            print "gr-video-sdl is not installed"
            print "realtime \"sdl\" video output window is not available"
            raise SystemExit, 1
          self.dst=video_sink
        else:
          print "You can use the imagemagick display tool to show the resulting imagesequence"
          print "use the following line to show the demodulated TV-signal:"
          print "display -depth 8 -size " +str(width)+ "x" + str(height) \
              + " gray:" + options.out_filename
          print "(Use the spacebar to advance to next frames)"
          options.repeat=False
          file_sink=gr.file_sink(gr.sizeof_char, options.out_filename)
          self.dst =file_sink

        self.agc=gr.agc_cc(1e-7,1.0,1.0) #1e-7
        self.am_demod = gr.complex_to_mag ()
        self.set_blacklevel=gr.add_const_ff(0.0)
        self.invert_and_scale = gr.multiply_const_ff (0.0) #-self.contrast *128.0*255.0/(200.0)

        # now wire it all together
        #sample_rate=options.width*options.height*options.framerate

        process_type='do_no_sync'
        if process_type=='do_no_sync':
          self.connect (self.src, self.agc,self.am_demod,
                        self.invert_and_scale, self.set_blacklevel,
                        f2uc,self.dst)
        elif process_type=='do_tv_sync_adv':
          #defaults: gr.tv_sync_adv (double sampling_freq, unsigned
          #int tv_format,bool output_active_video_only=false, bool
          #do_invert=false, double wanted_black_level=0.0, double
          #wanted_white_level=255.0, double avg_alpha=0.1, double
          #initial_gain=1.0, double initial_offset=0.0,bool
          #debug=false)

          #note, this block is not yet in cvs
          self.tv_sync_adv=gr.tv_sync_adv(usrp_rate, 0, False, False,
                                          0.0, 255.0, 0.01, 1.0, 0.0, False)
          self.connect (self.src, self.am_demod, self.invert_and_scale,
                        self.tv_sync_adv, s2f, f2uc, self.dst)

        elif process_type=='do_nullsink':
          #self.connect (self.src, self.am_demod,self.invert_and_scale,f2uc,video_sink)
          c2r=gr.complex_to_real()
          nullsink=gr.null_sink(gr.sizeof_float)
          self.connect (self.src, c2r,nullsink) #video_sink)
        elif process_type=='do_tv_sync_corr':
          frame_size=width*height #int(usrp_rate/25.0)
          nframes=10# 32
          search_window=20*nframes
          debug=False
          video_alpha=0.3 #0.1
          corr_alpha=0.3

          #Note: this block is not yet in cvs
          tv_corr=gr.tv_correlator_ff(frame_size,nframes, search_window,
                                      video_alpha, corr_alpha,debug)
          shift=gr.add_const_ff(-0.7)

          self.connect (self.src, self.agc, self.am_demod, tv_corr,
                        self.invert_and_scale, self.set_blacklevel,
                        f2uc, self.dst)
        else: # process_type=='do_test_image':
          src_vertical_bars = gr.sig_source_f (usrp_rate, gr.GR_SIN_WAVE,
                                               10.0 *usrp_rate/320, 255,128)
          self.connect(src_vertical_bars, f2uc, self.dst)

        self._build_gui(vbox, usrp_rate, usrp_rate, usrp_rate)


        frange = self.u.get_freq_range()
        if(frange.start() > self.tv_freq_max or frange.stop() <  self.tv_freq_min):
            sys.stderr.write("Radio does not support required frequency range.\n")
            sys.exit(1)
        if(options.freq < self.tv_freq_min or options.freq > self.tv_freq_max):
            sys.stderr.write("Requested frequency is outside of required frequency range.\n")
            sys.exit(1)

        # set initial values
        self.set_gain(options.gain)
        self.set_contrast(self.contrast)
        self.set_brightness(options.brightness)
        if not(self.set_freq(options.freq)):
            self._set_status_msg("Failed to set initial frequency")
Esempio n. 49
0
    def __init__(self, frame, panel, vbox, argv):
        stdgui2.std_top_block.__init__(self, frame, panel, vbox, argv)

        parser = OptionParser(option_class=eng_option)
        parser.add_option("-a",
                          "--args",
                          type="string",
                          default="",
                          help="UHD 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("-f",
                          "--freq",
                          type="string",
                          default="131725000",
                          help="Frequency in Hz")
        parser.add_option("-o",
                          "--output",
                          type="string",
                          default="output.txt",
                          help="ACARS log output")
        parser.add_option(
            "-s",
            "--samp-rate",
            type="eng_float",
            default="250e3",
            help="set sample rate (bandwidth) [default=%default]")
        parser.add_option(
            "-d",
            "--device",
            type="string",
            default="",
            help="PCM device name, e.g. hw:0,0  /dev/dsp  pulse  etc.")
        parser.add_option("-w",
                          "--wav-file",
                          type="string",
                          default="",
                          help="WAV file output.")
        (options, args) = parser.parse_args()
        if len(args) != 0:
            parser.print_help()
            sys.exit(1)

        self.frame = frame
        self.panel = panel
        self.freq = float(options.freq)

        usrp_rate = options.samp_rate
        audio_rate = 48e3

        # init USRP source block
        self.usrp = uhd.usrp_source(device_addr=options.args,
                                    stream_args=uhd.stream_args('fc32'))
        if (options.spec):
            self.usrp.set_subdev_spec(options.spec, 0)
        if (options.antenna):
            self.usrp.set_antenna(options.antenna, 0)
        self.usrp.set_samp_rate(usrp_rate)
        self.usrp.set_center_freq(self.freq, 0)

        # FIR block (5KHz low pass filter)
        chan_filt_coeffs = gr.firdes.low_pass_2(
            8,  # gain
            usrp_rate,  # sampling rate
            5e3,  # passband_cutoff
            1e2,  # transition bw
            60)  # stopband attenuation
        self.chan_filt = gr.freq_xlating_fir_filter_ccf(
            1,  # decimation
            chan_filt_coeffs,  # taps
            0,  # center freq
            usrp_rate)  # samp rate

        # AM demodulator block
        self.am_demod = gr.complex_to_mag()

        # resampler block
        self.resamp = blks2.rational_resampler_fff(
            interpolation=int(audio_rate),
            decimation=int(usrp_rate),
            taps=None,
            fractional_bw=None)

        # acars2 demod/decode blocks
        self.acars2_demod = acars2.demod(int(audio_rate))
        self.acars2_decode = acars2.decode()

        # file sink
        self.file_sink = gr.file_sink(gr.sizeof_char, options.output)

        # build flow graph
        self.connect(self.usrp, self.chan_filt, self.am_demod, self.resamp,
                     self.acars2_demod, self.acars2_decode, self.file_sink)

        # add audio sink (optional)
        if (options.device):
            print "using audio device %s" % options.device
            self.audio_sink = audio.sink(int(audio_rate), options.device, True)
            self.connect(self.resamp, self.audio_sink)

        # add WAV file sink (optional)
        if (options.wav_file):
            print "writing to WAV file %s" % options.wav_file
            self.wavsink = gr.wavfile_sink(options.wav_file, 1,
                                           int(audio_rate), 16)
            self.connect(self.resamp, self.wavsink)

        self._build_gui(vbox, usrp_rate, audio_rate)

        print "built flow graph..."
Esempio n. 50
0
    def __init__(self, options, log=False):

        ## Read configuration
        config = station_configuration()

        fft_length = config.fft_length
        cp_length = config.cp_length
        block_header = config.training_data
        data_subc = config.data_subcarriers
        virtual_subc = config.virtual_subcarriers
        total_subc = config.subcarriers
        block_length = config.block_length
        frame_length = config.frame_length
        dc_null = config.dc_null

        L = block_header.mm_periodic_parts

        ## Set Input/Output signature
        gr.hier_block2.__init__(
            self,
            "ofdm_inner_receiver",
            gr.io_signature(1, 1, gr.sizeof_gr_complex),
            gr.io_signaturev(
                4,
                4,
                [
                    gr.sizeof_gr_complex * total_subc,  # OFDM blocks
                    gr.sizeof_char,  # Frame start
                    gr.sizeof_float * total_subc,
                    gr.sizeof_float
                ]))  # Normalized |CTF|^2

        ## Input and output ports
        self.input = rx_input = self

        out_ofdm_blocks = (self, 0)
        out_frame_start = (self, 1)
        out_disp_ctf = (self, 2)
        out_disp_cfo = (self, 3)

        ## pre-FFT processing
        if options.ideal is False and options.ideal2 is False:
            if options.old_receiver is False:
                ## Compute autocorrelations for S&C preamble
                ## and cyclic prefix

                self._sc_metric = sc_metric = autocorrelator(
                    fft_length / 2, fft_length / 2)
                self._gi_metric = gi_metric = autocorrelator(
                    fft_length, cp_length)

                self.connect(rx_input, sc_metric)
                self.connect(rx_input, gi_metric)

                ## Sync. Output contains OFDM blocks
                sync = ofdm.time_sync(fft_length, cp_length)
                self.connect(rx_input, (sync, 0))
                self.connect(sc_metric, (sync, 1))
                self.connect(gi_metric, (sync, 2))
                ofdm_blocks = (sync, 0)
                frame_start = (sync, 1)
                #log_to_file( self, ( sync, 1 ), "data/peak_detector.char" )
            else:

                #Testing old/new metric
                self.tm = schmidl.recursive_timing_metric(fft_length)
                self.connect(self.input, self.tm)
                #log_to_file( self, self.tm, "data/rec_sc_metric_ofdm.float" )

                timingmetric_shift = -2  #int(-cp_length/4)# 0#-2 #int(-cp_length * 0.8)
                tmfilter = filter.fft_filter_fff(1,
                                                 [1. / cp_length] * cp_length)
                self.connect(self.tm, tmfilter)
                self.tm = tmfilter

                self._pd_thres = 0.3
                self._pd_lookahead = fft_length / 2  # empirically chosen
                peak_detector = ofdm.peak_detector_02_fb(
                    self._pd_lookahead, self._pd_thres)
                self.connect(self.tm, peak_detector)
                #log_to_file( self, peak_detector, "data/rec_peak_detector.char" )

                frame_start = [0] * frame_length
                frame_start[0] = 1
                frame_start = self.frame_trigger_old = blocks.vector_source_b(
                    frame_start, True)

                delayed_timesync = blocks.delay(
                    gr.sizeof_char,
                    (frame_length - 1) * block_length + timingmetric_shift)
                self.connect(peak_detector, delayed_timesync)

                self.block_sampler = ofdm.vector_sampler(
                    gr.sizeof_gr_complex, block_length * frame_length)
                self.discard_cp = ofdm.vector_mask(block_length, cp_length,
                                                   fft_length, [])

                self.connect(self.input, self.block_sampler)
                self.connect(delayed_timesync, (self.block_sampler, 1))

                # TODO: dynamic solution
                vt2s = blocks.vector_to_stream(
                    gr.sizeof_gr_complex * block_length, frame_length)
                self.connect(self.block_sampler, vt2s, self.discard_cp)
                #terminate_stream(self,ofdm_blocks)
                ofdm_blocks = self.discard_cp
#     else:
#       serial_to_parallel = blocks.stream_to_vector(gr.sizeof_gr_complex,block_length)
#       discard_cp = ofdm.vector_mask(block_length,cp_length,fft_length,[])
#       ofdm_blocks = discard_cp
#       self.connect( rx_input, serial_to_parallel, discard_cp )
#       frame_start = [0]*frame_length
#       frame_start[0] = 1
#       frame_start = blocks.vector_source_b(frame_start,True)
#
#       print "Disabled time synchronization stage"

## Compute autocorrelations for S&C preamble
## and cyclic prefix

#log_to_file( self, sc_metric, "data/sc_metric_ofdm.float" )
#log_to_file(self, frame_start, "data/frame_start.compl")

#    log_to_file(self,ofdm_blocks,"data/ofdm_blocks_original.compl")

        if options.disable_time_sync or options.ideal or options.ideal2:
            if options.ideal is False and options.ideal2 is False:
                terminate_stream(self, ofdm_blocks)
                terminate_stream(self, frame_start)

            serial_to_parallel = blocks.stream_to_vector(
                gr.sizeof_gr_complex, block_length)
            discard_cp = ofdm.vector_mask_dc_null(block_length, cp_length,
                                                  fft_length, dc_null, [])
            ofdm_blocks = discard_cp
            self.connect(rx_input, serial_to_parallel, discard_cp)

            frame_start = [0] * frame_length
            frame_start[0] = 1
            frame_start = blocks.vector_source_b(frame_start, True)

            print "Disabled time synchronization stage"

        print "\t\t\t\t\tframe_length = ", frame_length

        if options.ideal is False and options.ideal2 is False:
            ## Extract preamble, feed to Morelli & Mengali frequency offset estimator
            assert (block_header.mm_preamble_pos == 0)
            morelli_foe = ofdm.mm_frequency_estimator(fft_length, L, 1, 0)
            sampler_preamble = ofdm.vector_sampler(
                gr.sizeof_gr_complex * fft_length, 1)
            self.connect(ofdm_blocks, (sampler_preamble, 0))
            self.connect(frame_start, (sampler_preamble, 1))
            self.connect(sampler_preamble, morelli_foe)
            freq_offset = morelli_foe

            ## Adaptive LMS FIR filtering of frequency offset
            lms_fir = ofdm.lms_fir_ff(20,
                                      1e-3)  # TODO: verify parameter choice
            self.connect(freq_offset, lms_fir)
            freq_offset = lms_fir

            #self.zmq_probe_freqoff = zeromq.pub_sink(gr.sizeof_float, 1, "tcp://*:5557")
            self.connect(lms_fir, blocks.keep_one_in_n(gr.sizeof_float, 20),
                         out_disp_cfo)
        else:
            self.connect(blocks.vector_source_f([1]), out_disp_cfo)

            #log_to_file(self, lms_fir, "data/lms_fir.float")

        if options.disable_freq_sync or options.ideal or options.ideal2:
            if options.ideal is False and options.ideal2 is False:
                terminate_stream(self, freq_offset)
                freq_offset = blocks.vector_source_f([0.0], True)
            print "Disabled frequency synchronization stage"

        if options.ideal is False and options.ideal2 is False:
            ## Correct frequency shift, feed-forward structure
            frequency_shift = ofdm.frequency_shift_vcc(fft_length,
                                                       -1.0 / fft_length,
                                                       cp_length)
            self.connect(ofdm_blocks, (frequency_shift, 0))
            self.connect(freq_offset, (frequency_shift, 1))
            self.connect(frame_start, (frequency_shift, 2))
            ofdm_blocks = frequency_shift

        ## FFT
        fft = fft_blocks.fft_vcc(fft_length, True, [], True)
        self.connect(ofdm_blocks, fft)
        ofdm_blocks = fft
        #log_to_file( self, fft, "data/compen.float" )

        ## Remove virtual subcarriers
        if fft_length > data_subc:
            subcarrier_mask = ofdm.vector_mask_dc_null(fft_length,
                                                       virtual_subc / 2,
                                                       total_subc, dc_null, [])
            self.connect(ofdm_blocks, subcarrier_mask)
            ofdm_blocks = subcarrier_mask
            #log_to_file(self, ofdm_blocks, "data/vec_mask.compl")
            ## Least Squares estimator for channel transfer function (CTF)

            if options.logcir:
                log_to_file(self, ofdm_blocks, "data/OFDM_Blocks.compl")

                inv_preamble_fd = numpy.array(block_header.pilotsym_fd[
                    block_header.channel_estimation_pilot[0]])
                inv_preamble_fd = numpy.concatenate([
                    inv_preamble_fd[:total_subc / 2],
                    inv_preamble_fd[total_subc / 2 + dc_null:]
                ])
                #print "Channel estimation pilot: ", inv_preamble_fd
                inv_preamble_fd = 1. / inv_preamble_fd
                LS_channel_estimator0 = ofdm.multiply_const_vcc(
                    list(inv_preamble_fd))
                self.connect(ofdm_blocks, LS_channel_estimator0,
                             gr.null_sink(gr.sizeof_gr_complex * total_subc))
                log_to_file(self, LS_channel_estimator0,
                            "data/OFDM_Blocks_eq.compl")

        ## post-FFT processing

        ## extract channel estimation preamble from frame
        if options.ideal is False and options.ideal2 is False:
            chest_pre_trigger = blocks.delay(gr.sizeof_char, 1)
            sampled_chest_preamble = ofdm.vector_sampler(
                gr.sizeof_gr_complex * total_subc, 1)
            self.connect(frame_start, chest_pre_trigger)
            self.connect(chest_pre_trigger, (sampled_chest_preamble, 1))
            self.connect(ofdm_blocks, (sampled_chest_preamble, 0))

            ## Least Squares estimator for channel transfer function (CTF)
            inv_preamble_fd = numpy.array(block_header.pilotsym_fd[
                block_header.channel_estimation_pilot[0]])
            inv_preamble_fd = numpy.concatenate([
                inv_preamble_fd[:total_subc / 2],
                inv_preamble_fd[total_subc / 2 + dc_null:]
            ])
            #print "Channel estimation pilot: ", inv_preamble_fd
            inv_preamble_fd = 1. / inv_preamble_fd

            LS_channel_estimator = ofdm.multiply_const_vcc(
                list(inv_preamble_fd))
            self.connect(sampled_chest_preamble, LS_channel_estimator)
            estimated_CTF = LS_channel_estimator

            if options.logcir:
                log_to_file(self, sampled_chest_preamble, "data/PREAM.compl")

            if not options.disable_ctf_enhancer:

                if options.logcir:
                    ifft1 = fft_blocks.fft_vcc(total_subc, False, [], True)
                    self.connect(
                        estimated_CTF, ifft1,
                        gr.null_sink(gr.sizeof_gr_complex * total_subc))
                    summ1 = ofdm.vector_sum_vcc(total_subc)
                    c2m = gr.complex_to_mag(total_subc)
                    self.connect(estimated_CTF, summ1,
                                 gr.null_sink(gr.sizeof_gr_complex))
                    self.connect(estimated_CTF, c2m,
                                 gr.null_sink(gr.sizeof_float * total_subc))
                    log_to_file(self, ifft1, "data/CIR1.compl")
                    log_to_file(self, summ1, "data/CTFsumm1.compl")
                    log_to_file(self, estimated_CTF, "data/CTF1.compl")
                    log_to_file(self, c2m, "data/CTFmag1.float")

                ## MSE enhancer
                ctf_mse_enhancer = ofdm.CTF_MSE_enhancer(
                    total_subc, cp_length + cp_length)
                self.connect(estimated_CTF, ctf_mse_enhancer)
                #      log_to_file( self, ctf_mse_enhancer, "data/ctf_mse_enhancer_original.compl")
                #ifft3 = fft_blocks.fft_vcc(total_subc,False,[],True)
                #null_noise = ofdm.noise_nulling(total_subc, cp_length + cp_length)
                #ctf_mse_enhancer = fft_blocks.fft_vcc(total_subc,True,[],True)
                #ctf_mse_enhancer = ofdm.vector_mask( fft_length, virtual_subc/2,
                # total_subc, [] )
                #self.connect( estimated_CTF, ifft3,null_noise,ctf_mse_enhancer )

                estimated_CTF = ctf_mse_enhancer
                print "Disabled CTF MSE enhancer"

            if options.logcir:
                ifft2 = fft_blocks.fft_vcc(total_subc, False, [], True)
                self.connect(estimated_CTF, ifft2,
                             gr.null_sink(gr.sizeof_gr_complex * total_subc))
                summ2 = ofdm.vector_sum_vcc(total_subc)
                c2m2 = gr.complex_to_mag(total_subc)
                self.connect(estimated_CTF, summ2,
                             gr.null_sink(gr.sizeof_gr_complex))
                self.connect(estimated_CTF, c2m2,
                             gr.null_sink(gr.sizeof_float * total_subc))
                log_to_file(self, ifft2, "data/CIR2.compl")
                log_to_file(self, summ2, "data/CTFsumm2.compl")
                log_to_file(self, estimated_CTF, "data/CTF2.compl")
                log_to_file(self, c2m2, "data/CTFmag2.float")

        ## Postprocess the CTF estimate
        ## CTF -> inverse CTF (for equalizer)
        ## CTF -> norm |.|^2 (for CTF display)
            ctf_postprocess = ofdm.postprocess_CTF_estimate(total_subc)
            self.connect(estimated_CTF, ctf_postprocess)
            inv_estimated_CTF = (ctf_postprocess, 0)
            disp_CTF = (ctf_postprocess, 1)


#     if options.disable_equalization or options.ideal:
#       terminate_stream(self, inv_estimated_CTF)
#       inv_estimated_CTF_vec = blocks.vector_source_c([1.0/fft_length*math.sqrt(total_subc)]*total_subc,True,total_subc)
#       inv_estimated_CTF_str = blocks.vector_to_stream(gr.sizeof_gr_complex, total_subc)
#       self.inv_estimated_CTF_mul = ofdm.multiply_const_ccf( 1.0/config.rms_amplitude )
#       #inv_estimated_CTF_mul.set_k(1.0/config.rms_amplitude)
#       inv_estimated_CTF = blocks.stream_to_vector(gr.sizeof_gr_complex, total_subc)
#       self.connect( inv_estimated_CTF_vec, inv_estimated_CTF_str, self.inv_estimated_CTF_mul, inv_estimated_CTF)
#       print "Disabled equalization stage"
        '''
    ## LMS Phase tracking
    ## Track residual frequency offset and sampling clock frequency offset

    nondata_blocks = []
    for i in range(config.frame_length):
      if i in config.training_data.pilotsym_pos:
        nondata_blocks.append(i)
        
    print"\t\t\t\t\tnondata_blocks=",nondata_blocks
    pilot_subc = block_header.pilot_tones
    pilot_subcarriers = block_header.pilot_subc_sym
    print "PILOT SUBCARRIERS: ", pilot_subcarriers
        
    phase_tracking = ofdm.lms_phase_tracking_03( total_subc, pilot_subc,
                                               nondata_blocks, pilot_subcarriers,0 )
    self.connect( ofdm_blocks, ( phase_tracking, 0 ) )
    self.connect( inv_estimated_CTF, ( phase_tracking, 1 ) )
    self.connect( frame_start, ( phase_tracking, 2 ) ) ##
    
    if options.scatter_plot_before_phase_tracking:
      self.before_phase_tracking = equalizer
      
    
    if options.disable_phase_tracking or options.ideal:
      terminate_stream(self, phase_tracking)
      print "Disabled phase tracking stage"
    else:
      ofdm_blocks = phase_tracking
    '''
        ## Channel Equalizer
        if options.disable_equalization or options.ideal or options.ideal2:
            print "Disabled equalization stage"
            if options.ideal is False and options.ideal2 is False:
                terminate_stream(self, inv_estimated_CTF)
        else:
            equalizer = ofdm.channel_equalizer(total_subc)
            self.connect(ofdm_blocks, (equalizer, 0))
            self.connect(inv_estimated_CTF, (equalizer, 1))
            self.connect(frame_start, (equalizer, 2))
            ofdm_blocks = equalizer
        #log_to_file(self, equalizer,"data/equalizer_siso.compl")

        #log_to_file(self, ofdm_blocks, "data/equalizer.compl")

        ## LMS Phase tracking
        ## Track residual frequency offset and sampling clock frequency offset
        if options.ideal is False and options.ideal2 is False:
            nondata_blocks = []
            for i in range(config.frame_length):
                if i in config.training_data.pilotsym_pos:
                    nondata_blocks.append(i)

            print "\t\t\t\t\tnondata_blocks=", nondata_blocks
            pilot_subc = block_header.pilot_tones
            pilot_subcarriers = block_header.pilot_subc_sym
            print "PILOT SUBCARRIERS: ", pilot_subcarriers

            phase_tracking2 = ofdm.lms_phase_tracking_dc_null(
                total_subc, pilot_subc, nondata_blocks, pilot_subcarriers,
                dc_null)
            self.connect(ofdm_blocks, (phase_tracking2, 0))
            self.connect(frame_start, (phase_tracking2, 1))  ##

        if options.disable_phase_tracking or options.ideal or options.ideal2:
            if options.ideal is False and options.ideal2 is False:
                terminate_stream(self, phase_tracking2)
            print "Disabled phase tracking stage"
        else:
            ofdm_blocks = phase_tracking2

        if options.scatter_plot_before_phase_tracking:
            self.before_phase_tracking = equalizer

        ## Output connections

        self.connect(ofdm_blocks, out_ofdm_blocks)
        self.connect(frame_start, out_frame_start)
        if options.ideal is False and options.ideal2 is False:
            self.connect(disp_CTF, out_disp_ctf)
        else:
            self.connect(blocks.vector_source_f([1.0] * total_subc),
                         blocks.stream_to_vector(gr.sizeof_float, total_subc),
                         out_disp_ctf)

        if log:
            log_to_file(self, sc_metric, "data/sc_metric.float")
            log_to_file(self, gi_metric, "data/gi_metric.float")
            log_to_file(self, morelli_foe, "data/morelli_foe.float")
            log_to_file(self, lms_fir, "data/lms_fir.float")
            log_to_file(self, sampler_preamble, "data/preamble.compl")
            log_to_file(self, sync, "data/sync.compl")
            log_to_file(self, frequency_shift, "data/frequency_shift.compl")
            log_to_file(self, fft, "data/fft.compl")
            log_to_file(self, fft, "data/fft.float", mag=True)

            if vars().has_key('subcarrier_mask'):
                log_to_file(self, subcarrier_mask,
                            "data/subcarrier_mask.compl")

            log_to_file(self, ofdm_blocks, "data/ofdm_blocks_out.compl")
            log_to_file(self,
                        frame_start,
                        "data/frame_start.float",
                        char_to_float=True)

            log_to_file(self, sampled_chest_preamble,
                        "data/sampled_chest_preamble.compl")
            log_to_file(self, LS_channel_estimator,
                        "data/ls_channel_estimator.compl")
            log_to_file(self,
                        LS_channel_estimator,
                        "data/ls_channel_estimator.float",
                        mag=True)

            if "ctf_mse_enhancer" in locals():
                log_to_file(self, ctf_mse_enhancer,
                            "data/ctf_mse_enhancer.compl")
                log_to_file(self,
                            ctf_mse_enhancer,
                            "data/ctf_mse_enhancer.float",
                            mag=True)

            log_to_file(self, (ctf_postprocess, 0),
                        "data/inc_estimated_ctf.compl")
            log_to_file(self, (ctf_postprocess, 1), "data/disp_ctf.float")

            log_to_file(self, equalizer, "data/equalizer.compl")
            log_to_file(self, equalizer, "data/equalizer.float", mag=True)

            log_to_file(self, phase_tracking, "data/phase_tracking.compl")
Esempio n. 51
0
    def __init__(self, fft_length, cp_length, snr, kstime, logging):
        ''' Maximum Likelihood OFDM synchronizer:
        J. van de Beek, M. Sandell, and P. O. Borjesson, "ML Estimation
        of Time and Frequency Offset in OFDM Systems," IEEE Trans.
        Signal Processing, vol. 45, no. 7, pp. 1800-1805, 1997.
        '''

	gr.hier_block2.__init__(self, "ofdm_sync_ml",
				gr.io_signature(1, 1, gr.sizeof_gr_complex), # Input signature
                                gr.io_signature2(2, 2, gr.sizeof_float, gr.sizeof_char)) # Output signature

        self.input = gr.add_const_cc(0)

        SNR = 10.0**(snr/10.0)
        rho = SNR / (SNR + 1.0)
        symbol_length = fft_length + cp_length

        # ML Sync

        # Energy Detection from ML Sync

        self.connect(self, self.input)

        # Create a delay line
        self.delay = gr.delay(gr.sizeof_gr_complex, fft_length)
        self.connect(self.input, self.delay)

        # magnitude squared blocks
        self.magsqrd1 = gr.complex_to_mag_squared()
        self.magsqrd2 = gr.complex_to_mag_squared()
        self.adder = gr.add_ff()

        moving_sum_taps = [rho/2 for i in range(cp_length)]
        self.moving_sum_filter = gr.fir_filter_fff(1,moving_sum_taps)
        
        self.connect(self.input,self.magsqrd1)
        self.connect(self.delay,self.magsqrd2)
        self.connect(self.magsqrd1,(self.adder,0))
        self.connect(self.magsqrd2,(self.adder,1))
        self.connect(self.adder,self.moving_sum_filter)
        

        # Correlation from ML Sync
        self.conjg = gr.conjugate_cc();
        self.mixer = gr.multiply_cc();

        movingsum2_taps = [1.0 for i in range(cp_length)]
        self.movingsum2 = gr.fir_filter_ccf(1,movingsum2_taps)
        
        # Correlator data handler
        self.c2mag = gr.complex_to_mag()
        self.angle = gr.complex_to_arg()
        self.connect(self.input,(self.mixer,1))
        self.connect(self.delay,self.conjg,(self.mixer,0))
        self.connect(self.mixer,self.movingsum2,self.c2mag)
        self.connect(self.movingsum2,self.angle)

        # ML Sync output arg, need to find maximum point of this
        self.diff = gr.sub_ff()
        self.connect(self.c2mag,(self.diff,0))
        self.connect(self.moving_sum_filter,(self.diff,1))

        #ML measurements input to sampler block and detect
        self.f2c = gr.float_to_complex()
        self.pk_detect = gr.peak_detector_fb(0.2, 0.25, 30, 0.0005)
        self.sample_and_hold = gr.sample_and_hold_ff()

        # use the sync loop values to set the sampler and the NCO
        #     self.diff = theta
        #     self.angle = epsilon
                          
        self.connect(self.diff, self.pk_detect)

        # The DPLL corrects for timing differences between CP correlations
        use_dpll = 0
        if use_dpll:
            self.dpll = gr.dpll_bb(float(symbol_length),0.01)
            self.connect(self.pk_detect, self.dpll)
            self.connect(self.dpll, (self.sample_and_hold,1))
        else:
            self.connect(self.pk_detect, (self.sample_and_hold,1))
            
        self.connect(self.angle, (self.sample_and_hold,0))

        ################################
        # correlate against known symbol
        # This gives us the same timing signal as the PN sync block only on the preamble
        # we don't use the signal generated from the CP correlation because we don't want
        # to readjust the timing in the middle of the packet or we ruin the equalizer settings.
        kstime = [k.conjugate() for k in kstime]
        kstime.reverse()
        self.kscorr = gr.fir_filter_ccc(1, kstime)
        self.corrmag = gr.complex_to_mag_squared()
        self.div = gr.divide_ff()

        # The output signature of the correlation has a few spikes because the rest of the
        # system uses the repeated preamble symbol. It needs to work that generically if 
        # anyone wants to use this against a WiMAX-like signal since it, too, repeats.
        # The output theta of the correlator above is multiplied with this correlation to
        # identify the proper peak and remove other products in this cross-correlation
        self.threshold_factor = 0.1
        self.slice = gr.threshold_ff(self.threshold_factor, self.threshold_factor, 0)
        self.f2b = gr.float_to_char()
        self.b2f = gr.char_to_float()
        self.mul = gr.multiply_ff()
        
        # Normalize the power of the corr output by the energy. This is not really needed
        # and could be removed for performance, but it makes for a cleaner signal.
        # if this is removed, the threshold value needs adjustment.
        self.connect(self.input, self.kscorr, self.corrmag, (self.div,0))
        self.connect(self.moving_sum_filter, (self.div,1))
        
        self.connect(self.div, (self.mul,0))
        self.connect(self.pk_detect, self.b2f, (self.mul,1))
        self.connect(self.mul, self.slice)
        
        # Set output signals
        #    Output 0: fine frequency correction value
        #    Output 1: timing signal
        self.connect(self.sample_and_hold, (self,0))
        self.connect(self.slice, self.f2b, (self,1))


        if logging:
            self.connect(self.moving_sum_filter, gr.file_sink(gr.sizeof_float, "ofdm_sync_ml-energy_f.dat"))
            self.connect(self.diff, gr.file_sink(gr.sizeof_float, "ofdm_sync_ml-theta_f.dat"))
            self.connect(self.angle, gr.file_sink(gr.sizeof_float, "ofdm_sync_ml-epsilon_f.dat"))
            self.connect(self.corrmag, gr.file_sink(gr.sizeof_float, "ofdm_sync_ml-corrmag_f.dat"))
            self.connect(self.kscorr, gr.file_sink(gr.sizeof_gr_complex, "ofdm_sync_ml-kscorr_c.dat"))
            self.connect(self.div, gr.file_sink(gr.sizeof_float, "ofdm_sync_ml-div_f.dat"))
            self.connect(self.mul, gr.file_sink(gr.sizeof_float, "ofdm_sync_ml-mul_f.dat"))
            self.connect(self.slice, gr.file_sink(gr.sizeof_float, "ofdm_sync_ml-slice_f.dat"))
            self.connect(self.pk_detect, gr.file_sink(gr.sizeof_char, "ofdm_sync_ml-peaks_b.dat"))
            if use_dpll:
                self.connect(self.dpll, gr.file_sink(gr.sizeof_char, "ofdm_sync_ml-dpll_b.dat"))

            self.connect(self.sample_and_hold, gr.file_sink(gr.sizeof_float, "ofdm_sync_ml-sample_and_hold_f.dat"))
            self.connect(self.input, gr.file_sink(gr.sizeof_gr_complex, "ofdm_sync_ml-input_c.dat"))
Esempio n. 52
0
    def __init__(self):
        gr.top_block.__init__(self)
           
        amplitude = 5000        
        interp_rate = 256
        dec_rate = 16
        sw_dec = 5

        num_taps = int(64000 / ( (dec_rate * 4) * 40 )) #Filter matched to 1/4 of the 40 kHz tag cycle
        taps = [complex(1,1)] * num_taps
        
        matched_filt = gr.fir_filter_ccc(sw_dec, taps);  
          
        agc = gr.agc2_cc(0.3, 1e-3, 1, 1, 100) 
     
        to_mag = gr.complex_to_mag()

        center = rfid.center_ff(10)

        omega = 5
        mu = 0.25
        gain_mu = 0.25
        gain_omega = .25 * gain_mu * gain_mu
        omega_relative_limit = .05

        mm = gr.clock_recovery_mm_ff(omega, gain_omega, mu, gain_mu, omega_relative_limit)


        self.reader = rfid.reader_f(int(128e6/interp_rate)); 
        
        tag_decoder = rfid.tag_decoder_f()
        
        command_gate = rfid.command_gate_cc(12, 250, 64000000 / dec_rate / sw_dec)
        
        
        to_complex = gr.float_to_complex()
        amp = gr.multiply_const_ff(amplitude)
        
        #output the TX and RX signals only
        f_txout = gr.file_sink(gr.sizeof_gr_complex, 'f_txout.out');
        f_rxout = gr.file_sink(gr.sizeof_gr_complex, 'f_rxout.out');
        
#TX
		# working frequency at 915 MHz by default and RX Gain of 20
        freq = options.center_freq #915e6 
        rx_gain = options.rx_gain #20  
    
        tx = usrp.sink_c(fusb_block_size = 512, fusb_nblocks=4)
        tx.set_interp_rate(256)
        tx_subdev = (0,0)
        tx.set_mux(usrp.determine_tx_mux_value(tx, tx_subdev))
        subdev = usrp.selected_subdev(tx, tx_subdev)
        subdev.set_enable(True)
        subdev.set_gain(subdev.gain_range()[2])
        t = tx.tune(subdev.which(), subdev, freq)
        if not t:
            print "Couldn't set tx freq"
#End TX
             
#RX
        rx = usrp.source_c(0, dec_rate, fusb_block_size = 512, fusb_nblocks = 4)
        rx_subdev_spec = (1,0)
        rx.set_mux(usrp.determine_rx_mux_value(rx, rx_subdev_spec))
        rx_subdev = usrp.selected_subdev(rx, rx_subdev_spec)
        rx_subdev.set_gain(rx_gain)
        rx_subdev.set_auto_tr(False)
        rx_subdev.set_enable(True)
        
        r = usrp.tune(rx, 0, rx_subdev, freq)

        self.rx = rx
        if not r:
            print "Couldn't set rx freq"

#End RX

        command_gate.set_ctrl_out(self.reader.ctrl_q())
        tag_decoder.set_ctrl_out(self.reader.ctrl_q())



#########Build Graph
        self.connect(rx, matched_filt)
        self.connect(matched_filt, command_gate)
        self.connect(command_gate, agc)
        self.connect(agc, to_mag) 
        self.connect(to_mag, center, mm, tag_decoder)
        self.connect(tag_decoder, self.reader, amp, to_complex, tx);
#################
		
		#Output dumps for debug
        self.connect(rx, f_rxout);
        self.connect(to_complex, f_txout);
Esempio n. 53
0
    def __init__(self, frame, panel, vbox, argv):
        stdgui2.std_top_block.__init__(self, frame, panel, vbox, argv)

        self.frame = frame
        self.panel = panel
        
        parser = OptionParser(option_class=eng_option)
        parser.add_option("-w", "--which", type="int", default=0,
                          help="select which USRP (0, 1, ...) default is %default", metavar="NUM")
        parser.add_option("-R", "--rx-subdev-spec", type="subdev", default=None,
                          help="select USRP Rx side A or B (default=first one with a daughterboard)")
        parser.add_option("-A", "--antenna", default=None,
                          help="select Rx Antenna (only on RFX-series boards)")
        parser.add_option("-d", "--decim", type="int", default=16,
                          help="set fgpa decimation rate to DECIM [default=%default]")
        parser.add_option("-f", "--freq", type="eng_float", default=None,
                          help="set frequency to FREQ", metavar="FREQ")
        parser.add_option("-g", "--gain", type="eng_float", default=None,
                          help="set gain in dB [default is midpoint]")
        parser.add_option("-W", "--waterfall", action="store_true", default=False,
                          help="Enable waterfall display")
        parser.add_option("-8", "--width-8", action="store_true", default=False,
                          help="Enable 8-bit samples across USB")
        parser.add_option( "--no-hb", action="store_true", default=False,
                          help="don't use halfband filter in usrp")
        parser.add_option("-S", "--oscilloscope", action="store_true", default=False,
                          help="Enable oscilloscope display")
        parser.add_option("", "--avg-alpha", type="eng_float", default=1e-1,
                          help="Set fftsink averaging factor, [default=%default]")
        parser.add_option("", "--ref-scale", type="eng_float", default=13490.0,
                          help="Set dBFS=0dB input value, [default=%default]")
        parser.add_option("", "--fft-size", type="int", default=1024,
                          help="Set FFT frame size, [default=%default]");

        (options, args) = parser.parse_args()
        if len(args) != 0:
            parser.print_help()
            sys.exit(1)
        self.options = options
        self.show_debug_info = True
        
        # build the graph
        if options.no_hb or (options.decim<8):
          #Min decimation of this firmware is 4. 
          #contains 4 Rx paths without halfbands and 0 tx paths.
          self.fpga_filename="std_4rx_0tx.rbf"
          self.u = usrp.source_c(which=options.which, decim_rate=options.decim, fpga_filename=self.fpga_filename)
        else:
          #Min decimation of standard firmware is 8. 
          #standard fpga firmware "std_2rxhb_2tx.rbf" 
          #contains 2 Rx paths with halfband filters and 2 tx paths (the default)
          self.u = usrp.source_c(which=options.which, decim_rate=options.decim)

        if options.rx_subdev_spec is None:
            options.rx_subdev_spec = pick_subdevice(self.u)
        self.u.set_mux(usrp.determine_rx_mux_value(self.u, options.rx_subdev_spec))

        if options.width_8:
            width = 8
            shift = 8
            format = self.u.make_format(width, shift)
            print "format =", hex(format)
            r = self.u.set_format(format)
            print "set_format =", r
            
        # determine the daughterboard subdevice we're using
        self.subdev = usrp.selected_subdev(self.u, options.rx_subdev_spec)

        input_rate = self.u.adc_freq() / self.u.decim_rate()

        if options.waterfall:
            self.scope = \
              waterfallsink2.waterfall_sink_f (panel, fft_size=options.fft_size, sample_rate=input_rate)
        elif options.oscilloscope:
            self.scope = scopesink2.scope_sink_f(panel, sample_rate=input_rate)	#v_scale, t_scale, v_offset, frame_rate
        else:
            self.scope = fftsink2.fft_sink_f (panel, fft_size=options.fft_size, sample_rate=input_rate, 
                ref_scale=options.ref_scale, ref_level=0.0, y_divs = 10, avg_alpha=options.avg_alpha)

        self.MAG = gr.complex_to_mag()	# AM
        self.connect(self.u, self.MAG, self.scope)

        self._build_gui(vbox)
        self._setup_events()

        # set initial values

        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

        if options.freq is None:
            # if no freq was specified, use the mid-point
            r = self.subdev.freq_range()
            options.freq = float(r[0]+r[1])/2

        self.set_gain(options.gain)

        if options.antenna is not None:
            #print "Selecting antenna %s" % (options.antenna,)
            #self.subdev.select_rx_antenna(options.antenna)
            self.set_antenna(options.antenna)

        if self.show_debug_info:
            self.myform['decim'].set_value(self.u.decim_rate())
            self.myform['fs@usb'].set_value(self.u.adc_freq() / self.u.decim_rate())
            self.myform['dbname'].set_value(self.subdev.name())
            self.myform['baseband'].set_value(0)
            self.myform['ddc'].set_value(0)

        if not(self.set_freq(options.freq)):
            self._set_status_msg("Failed to set initial frequency")
Esempio n. 54
0
def complex_to_mag(N):
    op = gr.complex_to_mag()
    tb = helper(N, op, gr.sizeof_gr_complex, gr.sizeof_float, 1, 1)
    return tb
Esempio n. 55
0
    def __init__(self,frame,panel,vbox,argv):
        stdgui2.std_top_block.__init__ (self,frame,panel,vbox,argv)

        usage="%prog: [options] [input_filename]. \n If you don't specify an input filename the usrp will be used as source\n " \
              "Make sure your input capture file containes interleaved shorts not complex floats"
        parser=OptionParser(option_class=eng_option)
        parser.add_option("-R", "--rx-subdev-spec", type="subdev", default=None,
                          help="select USRP Rx side A or B (default=A)")
        parser.add_option("-d", "--decim", type="int", default=64,
                          help="set fgpa decimation rate to DECIM [default=%default]")
        parser.add_option("-f", "--freq", type="eng_float", default=519.25e6,
                          help="set frequency to FREQ", metavar="FREQ")
        parser.add_option("-g", "--gain", type="eng_float", default=None,
                          help="set gain in dB (default is midpoint)")
        parser.add_option("-c", "--contrast", type="eng_float", default=1.0,
                          help="set contrast (default is 1.0)")
        parser.add_option("-b", "--brightness", type="eng_float", default=0.0,
                          help="set brightness (default is 0)")
        parser.add_option("-8", "--width-8", action="store_true", default=False,
                          help="Enable 8-bit samples across USB")
        parser.add_option("-p", "--pal", action="store_true", default=False,
                          help="PAL video format (this is the default)")
        parser.add_option("-n", "--ntsc", action="store_true", default=False,
                          help="NTSC video format")
        parser.add_option("-o", "--out-filename", type="string", default="sdl",
                          help="For example out_raw_uchar.gray. If you don't specify an output filename you will get a video_sink_sdl realtime output window. You then need to have gr-video-sdl installed)")
        parser.add_option("-r", "--repeat", action="store_false", default=True,
                          help="repeat file in a loop")
        parser.add_option("-N", "--no-hb", action="store_true", default=False,
                          help="don't use halfband filter in usrp")

        (options, args) = parser.parse_args()
        if not ((len(args) == 1) or (len(args) == 0)):
            parser.print_help()
            sys.exit(1)
        
        if len(args) == 1:
          filename = args[0]
        else:
          filename = None

        self.frame = frame
        self.panel = panel
        
        self.contrast = options.contrast
        self.brightness = options.brightness
        self.state = "FREQ"
        self.freq = 0

        # build graph

        self.u=None

        usrp_decim = options.decim # 32

        if not (options.out_filename=="sdl"):
          options.repeat=False

        if not ((filename is None) or (filename=="usrp")):
          self.filesource = gr.file_source(gr.sizeof_short,filename,options.repeat) # file is data source
          self.istoc = gr.interleaved_short_to_complex()
          self.connect(self.filesource,self.istoc)
          adc_rate=64e6
          self.src=self.istoc
          options.gain=0.0
          self.gain=0.0
        else:
          if options.no_hb or (options.decim<8):
            self.fpga_filename="std_4rx_0tx.rbf" #contains 4 Rx paths without halfbands and 0 tx paths
          else:
            self.fpga_filename="std_2rxhb_2tx.rbf" # contains 2 Rx paths with halfband filters and 2 tx paths (the default)
          self.u = usrp.source_c(0,fpga_filename=self.fpga_filename)                    # usrp is data source
          if options.width_8:
              sample_width = 8
              sample_shift = 8
              format = self.u.make_format(sample_width, sample_shift)
              r = self.u.set_format(format)
          adc_rate = self.u.adc_rate()                # 64 MS/s
          self.u.set_decim_rate(usrp_decim)
          if options.rx_subdev_spec is None:
            options.rx_subdev_spec = pick_subdevice(self.u)
          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(),)
          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.src=self.u

        usrp_rate = adc_rate / usrp_decim           # 320 kS/s

        f2uc=gr.float_to_uchar()
        # sdl window as final sink
        if not (options.pal or options.ntsc):
          options.pal=True #set default to PAL
        if options.pal:
          lines_per_frame=625.0
          frames_per_sec=25.0
          show_width=768
        elif options.ntsc:
          lines_per_frame=525.0
          frames_per_sec=29.97002997
          show_width=640
        width=int(usrp_rate/(lines_per_frame*frames_per_sec))
        height=int(lines_per_frame)

        if (options.out_filename=="sdl"):
          #Here comes the tv screen, you have to build and install gr-video-sdl for this (subproject of gnuradio, only in cvs for now)
          try:
            video_sink = video_sdl.sink_uc ( frames_per_sec, width, height,0,show_width,height)
          except:
            print "gr-video-sdl is not installed"
            print "realtime \"sdl\" video output window is not available"
            raise SystemExit, 1
          self.dst=video_sink
        else:
          print "You can use the imagemagick display tool to show the resulting imagesequence"
          print "use the following line to show the demodulated TV-signal:"
          print "display -depth 8 -size " +str(width)+ "x" + str(height) + " gray:" + options.out_filename
          print "(Use the spacebar to advance to next frames)" 
          options.repeat=False
          file_sink=gr.file_sink(gr.sizeof_char, options.out_filename)
          self.dst =file_sink 

        self.agc=gr.agc_cc(1e-7,1.0,1.0) #1e-7
        self.am_demod = gr.complex_to_mag ()
        self.set_blacklevel=gr.add_const_ff(0.0)
        self.invert_and_scale = gr.multiply_const_ff (0.0) #-self.contrast *128.0*255.0/(200.0)

        # now wire it all together
        #sample_rate=options.width*options.height*options.framerate

        process_type='do_no_sync'
        if process_type=='do_no_sync':
          self.connect (self.src, self.agc,self.am_demod,self.invert_and_scale, self.set_blacklevel,f2uc,self.dst)
        elif process_type=='do_tv_sync_adv':
          #defaults: gr.tv_sync_adv (double sampling_freq, unsigned int tv_format,bool output_active_video_only=false, bool do_invert=false, double wanted_black_level=0.0, double wanted_white_level=255.0, double avg_alpha=0.1, double initial_gain=1.0, double initial_offset=0.0,bool debug=false)
          self.tv_sync_adv=gr.tv_sync_adv(usrp_rate,0,False,False,0.0,255.0,0.01,1.0,0.0,False) #note, this block is not yet in cvs
          self.connect (self.src, self.am_demod,self.invert_and_scale,self.tv_sync_adv,s2f,f2uc,self.dst) 
        elif process_type=='do_nullsink':
          #self.connect (self.src, self.am_demod,self.invert_and_scale,f2uc,video_sink)
          c2r=gr.complex_to_real()
          nullsink=gr.null_sink(gr.sizeof_float)
          self.connect (self.src, c2r,nullsink) #video_sink)
        elif process_type=='do_tv_sync_corr':
          frame_size=width*height #int(usrp_rate/25.0)
          nframes=10# 32
          search_window=20*nframes 
          debug=False
          video_alpha=0.3 #0.1
          corr_alpha=0.3
          tv_corr=gr.tv_correlator_ff(frame_size,nframes, search_window, video_alpha, corr_alpha,debug) #Note: this block is not yet in cvs
          shift=gr.add_const_ff(-0.7)
          self.connect (self.src, self.agc,self.am_demod,tv_corr,self.invert_and_scale, self.set_blacklevel,f2uc,self.dst) #self.agc,
        else: # process_type=='do_test_image':
          src_vertical_bars = gr.sig_source_f (usrp_rate, gr.GR_SIN_WAVE, 10.0 *usrp_rate/320, 255,128)
          self.connect(src_vertical_bars,f2uc,self.dst)

        self._build_gui(vbox, usrp_rate, usrp_rate, usrp_rate)

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

        # set initial values
        self.set_gain(options.gain)
        self.set_contrast(self.contrast)
        self.set_brightness(options.brightness)
        if not(self.set_freq(options.freq)):
            self._set_status_msg("Failed to set initial frequency")
Esempio n. 56
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)
Esempio n. 57
0
    def __init__(self, fft_length, block_length, block_header, range, options):
        gr.hier_block2.__init__(
            self, "integer_fo_estimator",
            gr.io_signature3(3, 3, gr.sizeof_gr_complex, gr.sizeof_float,
                             gr.sizeof_char),
            gr.io_signature2(3, 3, gr.sizeof_float, gr.sizeof_char))

        raise NotImplementedError, "Obsolete class"

        self._range = range

        # threshold after integer part frequency offset estimation
        # if peak value below threshold, assume false triggering
        self._thr_lo = 0.4  #0.19 # empirically found threshold. see ioe_metric.float
        self._thr_hi = 0.4  #0.2

        # stuff to be removed after bugfix for hierblock2s
        self.input = gr.kludge_copy(gr.sizeof_gr_complex)
        self.time_sync = gr.kludge_copy(gr.sizeof_char)
        self.epsilon = (self, 1)
        self.connect((self, 0), self.input)
        self.connect((self, 2), self.time_sync)

        delay(gr.sizeof_char, block_header.schmidl_fine_sync[0] * block_length)

        # sample ofdm symbol (preamble 1 and 2)
        sampler_symbol1 = vector_sampler(gr.sizeof_gr_complex, fft_length)
        sampler_symbol2 = vector_sampler(gr.sizeof_gr_complex, fft_length)
        time_delay1 = delay(gr.sizeof_char,
                            block_length * block_header.schmidl_fine_sync[1])
        self.connect(self.input, (sampler_symbol1, 0))
        self.connect(self.input, (sampler_symbol2, 0))
        if block_header.schmidl_fine_sync[0] > 0:
            time_delay0 = delay(
                gr.sizeof_char,
                block_length * block_header.schmidl_fine_sync[0])
            self.connect(self.time_sync, time_delay0, (sampler_symbol1, 1))
        else:
            self.connect(self.time_sync, (sampler_symbol1, 1))
        self.connect(self.time_sync, time_delay1, (sampler_symbol2, 1))

        # negative fractional frequency offset estimate
        epsilon = gr.multiply_const_ff(-1.0)
        self.connect(self.epsilon, epsilon)

        # compensate for fractional frequency offset on per symbol base
        #  freq_shift: vector length, modulator sensitivity
        #  freq_shift third input: reset phase accumulator

        # symbol/preamble 1
        freq_shift_sym1 = frequency_shift_vcc(fft_length, 1.0 / fft_length)
        self.connect(sampler_symbol1, (freq_shift_sym1, 0))
        self.connect(epsilon, (freq_shift_sym1, 1))
        self.connect(gr.vector_source_b([1], True), (freq_shift_sym1, 2))

        # symbol/preamble 2
        freq_shift_sym2 = frequency_shift_vcc(fft_length, 1.0 / fft_length)
        self.connect(sampler_symbol2, (freq_shift_sym2, 0))
        self.connect(epsilon, (freq_shift_sym2, 1))
        self.connect(gr.vector_source_b([1], True), (freq_shift_sym2, 2))

        # fourier transfrom on both preambles
        fft_sym1 = gr.fft_vcc(fft_length, True, [],
                              True)  # Forward + Blockshift
        fft_sym2 = gr.fft_vcc(fft_length, True, [],
                              True)  # Forward + Blockshift

        # calculate schmidl's metric for estimation of freq. offset's integer part
        assert (hasattr(block_header, "schmidl_fine_sync"))
        pre1 = block_header.pilotsym_fd[block_header.schmidl_fine_sync[0]]
        pre2 = block_header.pilotsym_fd[block_header.schmidl_fine_sync[1]]
        diff_pn = concatenate(
            [[conjugate(math.sqrt(2) * pre2[2 * i] / pre1[2 * i]), 0.0j]
             for i in arange(len(pre1) / 2)])
        cfo_estimator = schmidl_cfo_estimator(fft_length, len(pre1),
                                              self._range, diff_pn)
        self.connect(freq_shift_sym1, fft_sym1,
                     (cfo_estimator, 0))  # preamble 1
        self.connect(freq_shift_sym2, fft_sym2,
                     (cfo_estimator, 1))  # preamble 2

        # search for maximum and its argument in interval [-range .. +range]
        #arg_max = arg_max_vff(2*self._range + 1)
        arg_max_s = gr.argmax_fs(2 * self._range + 1)
        arg_max = gr.short_to_float()
        ifo_max = gr.max_ff(2 * self._range + 1)  # vlen
        ifo_estimate = gr.add_const_ff(-self._range)
        self.connect(cfo_estimator, arg_max_s, arg_max, ifo_estimate)
        self.connect(cfo_estimator, ifo_max)
        self.connect((arg_max_s, 1), gr.null_sink(gr.sizeof_short))

        # threshold maximal value
        ifo_threshold = gr.threshold_ff(self._thr_lo, self._thr_hi, 0.0)
        ifo_thr_f2b = gr.float_to_char()
        self.connect(ifo_max, ifo_threshold, ifo_thr_f2b)

        # gating the streams ifo_estimate (integer part) and epsilon (frac. part)
        # if the metric's peak value was above the chosen threshold, assume to have
        # found a new burst. peak value below threshold results in blocking the
        # streams
        self.gate = gate_ff()
        self.connect(ifo_thr_f2b, (self.gate, 0))  # threshold stream
        self.connect(ifo_estimate, (self.gate, 1))
        self.connect(epsilon, (self.gate, 2))

        # peak filtering
        # resynchronize and suppress peaks that didn't match a preamble
        filtered_time_sync = peak_resync_bb(True)  # replace
        self.connect(self.time_sync, (filtered_time_sync, 0))
        self.connect(ifo_thr_f2b, (filtered_time_sync, 1))

        # find complete estimation for frequency offset
        # add together fractional and integer part
        freq_offset = gr.add_ff()
        self.connect((self.gate, 1), gr.multiply_const_ff(-1.0),
                     (freq_offset, 0))  # integer offset
        self.connect((self.gate, 2), (freq_offset, 1))  # frac offset

        # output connections
        self.connect(freq_offset, (self, 0))
        self.connect(filtered_time_sync, (self, 1))
        self.connect((self.gate, 0), (self, 2))  # used for frame trigger

        #########################################
        # debugging
        if options.log:
            self.epsilon2_sink = gr.vector_sink_f()
            self.connect(epsilon, self.epsilon2_sink)

            self.connect(
                cfo_estimator,
                gr.file_sink(gr.sizeof_float * (self._range * 2 + 1),
                             "data/ioe_metric.float"))

            # output joint stream
            preamble_stream = gr.streams_to_vector(
                fft_length * gr.sizeof_gr_complex, 2)
            self.connect(fft_sym1, (preamble_stream, 0))
            self.connect(fft_sym2, (preamble_stream, 1))
            self.connect(
                preamble_stream,
                gr.file_sink(gr.sizeof_gr_complex * 2 * fft_length,
                             "data/preambles.compl"))

            # output, preambles before and after correction, magnitude and complex spectrum
            self.connect(
                sampler_symbol1, gr.fft_vcc(fft_length, True, [], True),
                gr.file_sink(gr.sizeof_gr_complex * fft_length,
                             "data/pre1_bef.compl"))
            self.connect(
                sampler_symbol1, gr.fft_vcc(fft_length, True, [], True),
                gr.complex_to_mag(fft_length),
                gr.file_sink(gr.sizeof_float * fft_length,
                             "data/pre1_bef.float"))
            self.connect(
                sampler_symbol2, gr.fft_vcc(fft_length, True, [], True),
                gr.file_sink(gr.sizeof_gr_complex * fft_length,
                             "data/pre2_bef.compl"))
            self.connect(
                sampler_symbol2, gr.fft_vcc(fft_length, True, [], True),
                gr.complex_to_mag(fft_length),
                gr.file_sink(gr.sizeof_float * fft_length,
                             "data/pre2_bef.float"))
            self.connect(
                freq_shift_sym1, gr.fft_vcc(fft_length, True, [], True),
                gr.file_sink(gr.sizeof_gr_complex * fft_length,
                             "data/pre1.compl"))
            self.connect(
                freq_shift_sym1, gr.fft_vcc(fft_length, True, [], True),
                gr.complex_to_mag(fft_length),
                gr.file_sink(gr.sizeof_float * fft_length, "data/pre1.float"))
            self.connect(
                freq_shift_sym2, gr.fft_vcc(fft_length, True, [], True),
                gr.file_sink(gr.sizeof_gr_complex * fft_length,
                             "data/pre2.compl"))
            self.connect(
                freq_shift_sym2, gr.fft_vcc(fft_length, True, [], True),
                gr.complex_to_mag(fft_length),
                gr.file_sink(gr.sizeof_float * fft_length, "data/pre2.float"))

            # calculate epsilon from corrected source to check function
            test_cp = cyclic_prefixer(fft_length, block_length)
            test_eps = foe(fft_length)
            self.connect(freq_shift_sym1, test_cp, test_eps,
                         gr.file_sink(gr.sizeof_float, "data/eps_after.float"))

        try:
            gr.hier_block.update_var_names(self, "ifo_estimator", vars())
            gr.hier_block.update_var_names(self, "ifo_estimator", vars(self))
        except:
            pass
Esempio n. 58
0
    def __init__(self):
        gr.top_block.__init__(self)

        usage="%prog: [options] output_filename. \n Special output_filename \"sdl\" will use video_sink_sdl as realtime output window. " \
              "You then need to have gr-video-sdl installed. \n" \
              "Make sure your input capture file containes interleaved shorts not complex floats"
        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("-c",
                          "--contrast",
                          type="eng_float",
                          default=1.0,
                          help="set contrast (default is 1.0)")
        parser.add_option("-b",
                          "--brightness",
                          type="eng_float",
                          default=0.0,
                          help="set brightness (default is 0)")
        parser.add_option(
            "-d",
            "--decim",
            type="int",
            default=8,
            help="set fgpa decimation rate to DECIM [default=%default]")
        parser.add_option(
            "-i",
            "--in-filename",
            type="string",
            default=None,
            help=
            "Use input file as source. samples must be interleaved shorts \n "
            + "Use usrp_rx_file.py or usrp_rx_cfile.py --output-shorts. \n"
            "Special name \"usrp\"  results in realtime capturing and processing using usrp. \n"
            + "You then probably need a decimation factor of 64 or higher.")
        parser.add_option(
            "-f",
            "--freq",
            type="eng_float",
            default=None,
            help=
            "set frequency to FREQ.\nNote that the frequency of the video carrier is not at the middle of the TV channel",
            metavar="FREQ")
        parser.add_option("-g",
                          "--gain",
                          type="eng_float",
                          default=None,
                          help="set gain in dB (default is midpoint)")
        parser.add_option("-p",
                          "--pal",
                          action="store_true",
                          default=False,
                          help="PAL video format (this is the default)")
        parser.add_option("-n",
                          "--ntsc",
                          action="store_true",
                          default=False,
                          help="NTSC video format")
        parser.add_option("-r",
                          "--repeat",
                          action="store_false",
                          default=True,
                          help="repeat in_file in a loop")
        parser.add_option("-8",
                          "--width-8",
                          action="store_true",
                          default=False,
                          help="Enable 8-bit samples across USB")
        parser.add_option("-N",
                          "--nframes",
                          type="eng_float",
                          default=None,
                          help="number of frames to collect [default=+inf]")
        parser.add_option("--no-hb",
                          action="store_true",
                          default=False,
                          help="don't use halfband filter in usrp")
        (options, args) = parser.parse_args()
        if not (len(args) == 1):
            parser.print_help()
            sys.stderr.write('You must specify the output. FILENAME or sdl \n')
            sys.exit(1)

        filename = args[0]

        if options.in_filename is None:
            parser.print_help()
            sys.stderr.write(
                'You must specify the input -i FILENAME or -i usrp\n')
            raise SystemExit, 1

        if not (filename == "sdl"):
            options.repeat = False

        if not (options.in_filename == "usrp"):
            self.filesource = gr.file_source(
                gr.sizeof_short, options.in_filename, options.repeat
            )  # file is data source, capture with usr_rx_csfile.py
            self.istoc = gr.interleaved_short_to_complex()
            self.connect(self.filesource, self.istoc)
            self.adc_rate = 64e6
            self.src = self.istoc
        else:
            if options.freq is None:
                parser.print_help()
                sys.stderr.write(
                    'You must specify the frequency with -f FREQ\n')
                raise SystemExit, 1
            if abs(options.freq) < 1e6:
                options.freq *= 1e6
            if options.no_hb or (options.decim < 8):
                self.fpga_filename = "std_4rx_0tx.rbf"  #contains 4 Rx paths without halfbands and 0 tx paths
            else:
                self.fpga_filename = "std_2rxhb_2tx.rbf"  # contains 2 Rx paths with halfband filters and 2 tx paths (the default)

            # build the graph
            self.u = usrp.source_c(decim_rate=options.decim,
                                   fpga_filename=self.fpga_filename)
            self.src = self.u
            if options.width_8:
                sample_width = 8
                sample_shift = 8
                format = self.u.make_format(sample_width, sample_shift)
                r = self.u.set_format(format)
            self.adc_rate = self.u.adc_freq()
            if options.rx_subdev_spec is None:
                options.rx_subdev_spec = usrp.pick_rx_subdevice(self.u)
            self.u.set_mux(
                usrp.determine_rx_mux_value(self.u, options.rx_subdev_spec))
            # determine the daughterboard subdevice we're using
            self.subdev = usrp.selected_subdev(self.u, options.rx_subdev_spec)
            print "Using RX d'board %s" % (self.subdev.side_and_name(), )

            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.subdev.set_gain(options.gain)

            r = self.u.tune(0, self.subdev, options.freq)
            if not r:
                sys.stderr.write('Failed to set frequency\n')
                raise SystemExit, 1

        input_rate = self.adc_rate / options.decim
        print "video sample rate %s" % (eng_notation.num_to_str(input_rate))

        self.agc = gr.agc_cc(1e-7, 1.0, 1.0)  #1e-7
        self.am_demod = gr.complex_to_mag()
        self.set_blacklevel = gr.add_const_ff(options.brightness + 255.0)
        self.invert_and_scale = gr.multiply_const_ff(-options.contrast *
                                                     128.0 * 255.0 / (200.0))
        self.f2uc = gr.float_to_uchar()

        # sdl window as final sink
        if not (options.pal or options.ntsc):
            options.pal = True  #set default to PAL
        if options.pal:
            lines_per_frame = 625.0
            frames_per_sec = 25.0
            show_width = 768
        elif options.ntsc:
            lines_per_frame = 525.0
            frames_per_sec = 29.97002997
            show_width = 640
        width = int(input_rate / (lines_per_frame * frames_per_sec))
        height = int(lines_per_frame)

        if filename == "sdl":
            #Here comes the tv screen, you have to build and install gr-video-sdl for this (subproject of gnuradio, only in cvs for now)
            try:
                video_sink = video_sdl.sink_uc(frames_per_sec, width, height,
                                               0, show_width, height)
            except:
                print "gr-video-sdl is not installed"
                print "realtime \"sdl\" video output window is not available"
                raise SystemExit, 1
            self.dst = video_sink
        else:
            print "You can use the imagemagick display tool to show the resulting imagesequence"
            print "use the following line to show the demodulated TV-signal:"
            print "display -depth 8 -size " + str(width) + "x" + str(
                height) + " gray:" + filename
            print "(Use the spacebar to advance to next frames)"
            file_sink = gr.file_sink(gr.sizeof_char, filename)
            self.dst = file_sink

        if options.nframes is None:
            self.connect(self.src, self.agc)
        else:
            self.head = gr.head(gr.sizeof_gr_complex,
                                int(options.nframes * width * height))
            self.connect(self.src, self.head, self.agc)

        self.connect(self.agc, self.am_demod, self.invert_and_scale,
                     self.set_blacklevel, self.f2uc, self.dst)
Esempio n. 59
0
    def __init__(self, vlen):
        gr.hier_block2.__init__(
            self, "snr_estimator",
            gr.io_signature2(2, 2, gr.sizeof_gr_complex, gr.sizeof_char),
            gr.io_signature(1, 1, gr.sizeof_float))

        data_in = (self, 0)
        trig_in = (self, 1)
        snr_out = (self, 0)

        ## Preamble Extraction
        sampler = vector_sampler(gr.sizeof_gr_complex, vlen)
        self.connect(data_in, sampler)
        self.connect(trig_in, (sampler, 1))

        ## Algorithm implementation
        estim = sc_snr_estimator(vlen)
        self.connect(sampler, estim)
        self.connect(estim, snr_out)

        return

        ## Split block into two parts
        splitter = gr.vector_to_streams(gr.sizeof_gr_complex * vlen / 2, 2)
        self.connect(sampler, splitter)

        ## Conjugate first half block
        conj = gr.conjugate_cc(vlen / 2)
        self.connect(splitter, conj)

        ## Vector multiplication of both half blocks
        vmult = gr.multiply_vcc(vlen / 2)
        self.connect(conj, vmult)
        self.connect((splitter, 1), (vmult, 1))

        ## Sum of Products
        psum = vector_sum_vcc(vlen / 2)
        self.connect(vmult, psum)

        ## Magnitude of P(d)
        p_mag = gr.complex_to_mag()
        self.connect(psum, p_mag)

        ## Squared Magnitude of block
        r_magsqrd = gr.complex_to_mag_squared(vlen)
        self.connect(sampler, r_magsqrd)

        ## Sum of squared second half block
        r_sum = vector_sum_vff(vlen)
        self.connect(r_magsqrd, r_sum)

        ## Square Root of Metric
        m_sqrt = gr.divide_ff()
        self.connect(p_mag, (m_sqrt, 0))
        self.connect(r_sum, gr.multiply_const_ff(0.5), (m_sqrt, 1))

        ## Denominator of SNR estimate
        denom = gr.add_const_ff(1)
        neg_m_sqrt = gr.multiply_const_ff(-1.0)
        self.connect(m_sqrt, limit_vff(1, 1 - 2e-5, -1000), neg_m_sqrt, denom)

        ## SNR estimate
        snr_est = gr.divide_ff()
        self.connect(m_sqrt, (snr_est, 0))
        self.connect(denom, (snr_est, 1))

        ## Setup Output Connections
        self.connect(snr_est, self)