Пример #1
0
 def next_vector(self, seed, samp_rate, noise_amp, modulation, delay, samples_to_receive, freq, rx_id):
     timing_tag = gr.tag_t()
     timing_tag.offset = 0
     timing_tag.key = pmt.string_to_symbol('rx_time')
     timing_tag.value = pmt.to_pmt((float(seed), 0.6))
     timing_tag.srcid = pmt.string_to_symbol(str('gr uhd usrp source1'))
     # Rx freq tags:
     #print "In source emulation (before tag)" 
     #print freq
     rx_freq_tag = gr.tag_t()
     rx_freq_tag.offset = 0
     rx_freq_tag.key = pmt.string_to_symbol('rx_freq')
     rx_freq_tag.value = pmt.from_double(freq)
     rx_freq_tag.srcid = pmt.string_to_symbol(str('gr uhd usrp source1'))
     # Samp_rate tags:
     rx_rate_tag = gr.tag_t()
     rx_rate_tag.offset = 0
     rx_rate_tag.key = pmt.string_to_symbol('rx_rate')
     rx_rate_tag.value = pmt.from_double(samp_rate)
     rx_rate_tag.srcid = pmt.string_to_symbol(str('gr uhd usrp source1'))
     pulse_width = 4
     np.random.seed(seed=seed)
     tx_vector = np.reshape(np.matlib.repmat(np.random.randint(0,2,(5*samples_to_receive)/pulse_width)*2-1,pulse_width,1).T,[1,5*samples_to_receive])[0].tolist()
     # delay signal vector -> insert zeros at beginnig; nothing happens if signal has not reached the receiver:
     tx_vector_delayed = np.hstack((np.zeros(delay),tx_vector))
     #tx_vector_delayed = tx_vector_delayed[:600]
     print len(tx_vector_delayed)
     self.vector_source.set_data(tx_vector_delayed,(timing_tag, rx_freq_tag, rx_rate_tag)) 
     self.head.reset()
     self.vector_source.rewind()
Пример #2
0
 def test02(self):
     const = 123765
     x_pmt = pmt.from_double(const)
     x_int = pmt.to_double(x_pmt)
     x_float = pmt.to_float(x_pmt)
     self.assertEqual(x_int, const)
     self.assertEqual(x_float, const)
Пример #3
0
    def work(self, input_items, output_items):
        in0 = input_items[0]
        out = output_items[0]
        to_consume = len(in0)-self.history()
        
        if self.state == self.states["waiting_for_fcch_tag"]:
            fcch_tags = []
            
            start = self.nitems_written(0)
            stop = start + len(in0)
            key = pmt.string_to_symbol("fcch")
            fcch_tags = self.get_tags_in_range(0, start, stop, key)
            if fcch_tags:
                self.sch_offset = fcch_tags[0].offset + int(round(8*self.burst_size+0*self.guard_period)) #156.25 is number of GMSK symbols per timeslot, 
                                                                                       #8.25 is arbitrary safety margin in order to avoid cutting boundary of SCH burst
                self.state = self.states["reaching_sch_burst"]
            
        elif self.state == self.states["reaching_sch_burst"]:
            samples_left = self.sch_offset-self.nitems_written(0)
            if samples_left <= len(in0)-self.history():
                to_consume = samples_left
                self.state = self.states["sch_at_input_buffer"]

        elif self.state == self.states["sch_at_input_buffer"]:
            offset = self.nitems_written(0)
            key = pmt.string_to_symbol("sch")
            value =  pmt.from_double(0)
            self.add_item_tag(0,offset, key, value)
            self.state = self.states["waiting_for_fcch_tag"]
            self.sch_receiver.get_chan_imp_resp(in0[0:self.block_size+self.guard_period])
#            plot(unwrap(angle(in0[0:2*self.block_size])))
#            show()

        out[:] = in0[self.history()-1:]
        return to_consume
Пример #4
0
    def write_data(self, msg):
        snr = pmt.to_double(pmt.dict_ref(msg, pmt.intern("snr"), pmt.from_double(0)))
        encoding = pmt.to_long(pmt.dict_ref(msg, pmt.intern("encoding"), pmt.from_long(0)))

        time_now = time() * 1000
        delay = str(time_now - self.last_time)
        self.last_time = time_now


        if self.snr_file != "":
            f_snr = open(self.snr_file, 'a')
            f_snr.write(str(snr) + '\n')
            f_snr.close()

        if self.enc_file != "":
            f_enc = open(self.enc_file, 'a')    
            f_enc.write(str(encoding) + '\n')
            f_enc.close()

        if self.delay_file != "":
            f_delay = open(self.delay_file, 'a')
            f_delay.write(delay + '\n')
            f_delay.close()

        if self.debug:
            print("SNR:" + str(snr))
            print("Encoding:" + str(encoding))
            print("Delay in millis: " + delay)
Пример #5
0
    def handle_msg(self, msg):
        cell_id = pmt.to_long(msg)
        if self.cell_id == cell_id:
            return
        else:
            self.cell_id = cell_id
        print "received cell_id = " + str(cell_id)

        seqs = []

        seq = lte.encode_nrz(lte.generate_pn_sequence(1920, cell_id))

        pmt_list = pmt.list1(pmt.from_double(seq[0]))
        for i in range(len(seq) - 1):
            pmt_list = pmt.list_add(pmt_list, pmt.from_double(seq[i+1]))
        self.message_port_pub(self.msg_buf_out, pmt_list)
Пример #6
0
    def work(self, input_items, output_items):
        out = output_items[0]
        slpack = self._slClient.slconn.collect()
        try: 
            seqnum = slpack.getSequenceNumber()
            trace = slpack.getTrace()
        except:
            out[:] = []
            return 0

        # print "sending slpack(id:%d): %d samples, len(out)=%d" % \
        #     (seqnum, len(trace.data), len(out))
        out[:len(trace.data)] = numpy.float32(trace.data)

        # https://gnuradio.org/doc/doxygen/page_python_blocks.html
        # https://github.com/guruofquality/grextras/wiki/Blocks-Coding-Guide
        # add_item_tag(which_output, abs_offset, key, value, srcid)

        # add a packet length tag
        abs_offset = self.nitems_written + 0
        key = pmt.string_to_symbol("packet_len")
        value = pmt.from_long(len(trace.data))
        srcid = pmt.string_to_symbol(self._channel)
        self.add_item_tag(0, abs_offset, key, value, srcid)

        # add a tag to manage time
        abs_offset = self.nitems_written + 0
        key = pmt.string_to_symbol("rx_time")
        value = pmt.from_double(trace.stats['starttime'].timestamp)
        srcid = pmt.string_to_symbol(self._channel)
        self.add_item_tag(0, abs_offset, key, value, srcid)
        # print "starttime ", trace.stats['starttime'].timestamp

        # add a tag to manage sample rate change
        abs_offset = self.nitems_written + 0
        key = pmt.string_to_symbol("rx_rate")
        fech = 1./trace.stats['delta']
        value = pmt.from_double(fech)
        srcid = pmt.string_to_symbol(self._channel)
        self.add_item_tag(0, abs_offset, key, value, srcid)
        # print "fech ", 1./trace.stats['delta']

        self.samp_rate = fech
        self.nitems_written += len(trace.data)

        return len(trace.data)
    def handle_msg(self, msg):
        cell_id = pmt.to_long(msg)
        if self.cell_id == cell_id:
            return
        else:
            self.cell_id = cell_id
        print "received cell_id = " + str(cell_id)

        seqs = pmt.make_vector(10, pmt.make_vector(32, pmt.from_double(0.0)))
        for ns in range(10):
            scr = utils.get_pcfich_scrambling_sequence(cell_id, ns)
            scr = utils.encode_nrz(scr)
            pmt_seq = pmt.make_vector(len(scr), pmt.from_double(0.0))
            for i in range(len(scr)):
                pmt.vector_set(pmt_seq, i, pmt.from_double(scr[i]))
            pmt.vector_set(seqs, ns, pmt_seq)
        self.message_port_pub(self.msg_buf_out, seqs)
Пример #8
0
    def sched_pdu(self, pdu):
        sched_time = (self.nproduced_val + 10000); # pick a time in the future
        sched_time = sched_time - sched_time%5000; # round to nearest slot
        pdu = pdulib.pdu_arg_add(pdu, pmt.intern("event_time"), pmt.from_uint64(sched_time));
        pdu = pdulib.pdu_arg_add(pdu, pmt.intern("interp"), pmt.from_long(8));

        hop_offset = 10000;
        offset = (random.random()*self.fs-self.fs/2);
        offset = round(offset/hop_offset)*hop_offset; # quantize to nearest 1k offset
        pdu = pdulib.pdu_arg_add(pdu, pmt.intern("freq_offset"), pmt.from_double(offset));
        self.message_port_pub(pmt.intern("sched_pdu"), pdu);
Пример #9
0
    def work(self, input_items, output_items):
        in0=input_items[0]
        output_items[0][:] = in0[self.history()-1:]

        threshold = input_items[1][self.history()-1:]
        threshold_diff = diff(concatenate([[0],threshold]))
        up_to_high_indexes = nonzero(threshold_diff>0)[0]

        up_to_high_idx=[] 
        
        for up_to_high_idx in up_to_high_indexes:         #look for "high" value at the trigger
            if up_to_high_idx==0 and self.state==True:    #if it's not transition from "low" to "high"
                continue                                  #then continue
            self.state=True                               #if found - change state
        
        if self.state==True and up_to_high_idx and any(threshold_diff<0):          #and look for transition from high to low
            last_up_to_high_idx = up_to_high_idx
            last_high_to_low_idx = nonzero(threshold_diff<0)[0][-1]
            
            if last_high_to_low_idx-last_up_to_high_idx>0:
                coarse_idx = int(last_high_to_low_idx+self.history()-self.block_size)
                inst_freq = angle(in0[coarse_idx:coarse_idx+self.block_size]*in0[coarse_idx-self.OSR:coarse_idx+self.block_size-self.OSR].conj())/(2*pi)*self.symbol_rate #instantaneus frequency estimate
                precise_idx = self.find_best_position(inst_freq)
#                measured_freq = mean(inst_freq[precise_idx:precise_idx+self.processed_block_size])
                expected_freq = self.symbol_rate/4
                
                print "input_items:",len(in0)
                print "coarse_idx",coarse_idx
                print "coarse_idx+precise_idx",coarse_idx+precise_idx
                
                zoomed_spectrum = abs(self.zoomfft(in0[coarse_idx+precise_idx:coarse_idx+precise_idx+self.processed_block_size]))
                measured_freq = self.f_axis[argmax(zoomed_spectrum)]
                freq_offset = measured_freq - expected_freq
                offset = self.nitems_written(0) + coarse_idx + precise_idx - self.guard_period
                key = pmt.string_to_symbol("fcch")
                value =  pmt.from_double(freq_offset)
                self.add_item_tag(0,offset, key, value)
                self.state=False

#   Some additional plots and prints for debugging
#                print "coarse_idx+precise_idx",coarse_idx+precise_idx
#                print "offset-self.nitems_written(0):",offset-self.nitems_written(0)
                print offset-self.prev_offset
                self.prev_offset=offset
                print "freq offset", freq_offset
#                freq_offset = measured_freq - expected_freq
#                plot(self.f_axis, zoomed_spectrum)
#                show()
#                plot(inst_freq[precise_idx:precise_idx+self.burst_size])
#                show()
#                plot(unwrap(angle(in0[coarse_idx+precise_idx:coarse_idx+precise_idx+self.burst_size])))
#                show()
#                
        return len(output_items[0])
Пример #10
0
    def test_freq_msg(self):
        src = analog.sig_source_c(8, analog.GR_SIN_WAVE, 1.0, 1.0)
        op = blocks.head(gr.sizeof_gr_complex, 9)
        snk = blocks.vector_sink_c()
        self.tb.connect(src, op, snk)
        self.assertAlmostEqual(src.frequency(), 1.0)

        frequency = 3.0
        src._post(pmt.to_pmt('freq'), pmt.from_double(frequency))
        self.tb.run()

        self.assertAlmostEqual(src.frequency(), frequency)
Пример #11
0
 def process_measurement(self,msg):
     if pmt.is_tuple(msg):
         key = pmt.symbol_to_string(pmt.tuple_ref(msg,0))
         if key == "freq_offset":
             freq_offset = pmt.to_double(pmt.tuple_ref(msg,1))
             ppm = -freq_offset/self.fc*1.0e6
             state = pmt.symbol_to_string(pmt.tuple_ref(msg,2))
             
             self.last_state = state
             
             if abs(ppm) > 100: #safeguard against flawed measurements
                 ppm = 0
                 self.reset()
                 
             if state == "fcch_search":
                 msg_ppm = pmt.from_double(ppm)
                 self.message_port_pub(pmt.intern("ppm"), msg_ppm)
                 self.timer.cancel()
                 self.timer = Timer(0.5, self.timed_reset)
                 self.timer.start()
             elif state == "synchronized":
                 self.timer.cancel()
                 if self.first_measurement:
                     self.ppm_estimate = ppm
                     self.first_measurement = False
                 else:
                     self.ppm_estimate = (1-self.alfa)*self.ppm_estimate+self.alfa*ppm
                 
                 if self.counter == 5:
                     self.counter = 0
                     if abs(self.last_ppm_estimate-self.ppm_estimate) > 0.1:
                         msg_ppm = pmt.from_double(ppm)
                         self.message_port_pub(pmt.intern("ppm"), msg_ppm)
                         self.last_ppm_estimate = self.ppm_estimate
                 else:
                     self.counter=self.counter+1
             elif state == "sync_loss":
                 self.reset()
                 msg_ppm = pmt.from_double(0.0)
                 self.message_port_pub(pmt.intern("ppm"), msg_ppm)
Пример #12
0
    def handler(self, msg):
        meta = pmt.car(msg);
        samples = pmt.cdr(msg);
        
        x = numpy.array(pmt.c32vector_elements(samples), dtype=numpy.complex64)
        x_2 = numpy.real(x * x.conjugate())
        
        # smoothing filter
        x_2f = numpy.convolve(50*[1], x_2);

        # find max power to compute power thresh
        maxidx = numpy.argmax(x_2f);
        maxpow = x_2f[maxidx];
        thr = maxpow / 16; # 6db down

        # find where we are below thresh
        start_offset = 1000;
        idx = numpy.argmax(x_2f[start_offset:] < thr) + start_offset + 1000;
#        print "below = (%d, %f)"%(idx, x_2f[idx])

        # discard bursts where we dont find an end
        if idx == start_offset:
            print "WARNING: length detect: discarding burst"
            return

        # tack on some metadata
        meta = pmt.dict_add(meta, pmt.intern("est_len"), pmt.from_double(int(idx)));
        meta = pmt.dict_add(meta, pmt.intern("orig_len"), pmt.from_double(len(x)));
        
        # extract the useful signal
        x = x[0:idx];

        # send it on its way
        samples_out = pmt.init_c32vector(len(x), map(lambda i: complex(i), x))
        cpdu = pmt.cons(meta,samples_out)
        self.message_port_pub(pmt.intern("cpdus"), cpdu);
Пример #13
0
def update_timestamp(hdr,seg_size):
    if pmt.dict_has_key(hdr, pmt.string_to_symbol("rx_time")):
        r = pmt.dict_ref(hdr, pmt.string_to_symbol("rx_time"), pmt.PMT_NIL)
        secs = pmt.tuple_ref(r, 0)
        fracs = pmt.tuple_ref(r, 1)
        secs = float(pmt.to_uint64(secs))
        fracs = pmt.to_double(fracs)
        t = secs + fracs
    else:
        sys.stderr.write("Could not find key 'time': \
                invalid or corrupt data file.\n")
        sys.exit(1)
    new_hdr = pmt.dict_delete(hdr, pmt.intern("rx_time"))
    if pmt.dict_has_key(hdr, pmt.intern("rx_rate")):
        r = pmt.dict_ref(hdr, pmt.intern("rx_rate"), pmt.PMT_NIL)
        rate = pmt.to_double(r)
        new_t = t + float(seg_size)/rate
        new_secs = long(new_t)
        new_fracs = new_t - new_secs
        time_val = pmt.make_tuple(pmt.from_uint64(new_secs),
                             pmt.from_double(new_fracs))
        new_hdr = pmt.dict_add(new_hdr, pmt.intern("rx_time"), time_val)
        return new_hdr
Пример #14
0
    def handler(self, msg):
        # get input
        meta = pmt.car(msg);
        samples = pmt.cdr(msg);
        x = numpy.array(pmt.c32vector_elements(samples), dtype=numpy.complex64)
 
        # upsample and normalize power
        xi = signal.resample(x, len(x)* (self.N / self.T));
        # compute the symbol timing
        xt = numpy.real(xi*xi.conjugate()) * numpy.exp( (-1j*2.0*numpy.pi/self.N) * numpy.linspace(1,len(xi),len(xi)) );
        s = numpy.sum(x);    
        tau = (-self.T/(2*numpy.pi)) * numpy.arctan2(numpy.imag(s), numpy.real(s));
        
        # publish timing metric for debugging
        tm = pmt.init_c32vector(xt.size, map(lambda i: complex(i), xt))
        tm_cpdu = pmt.cons(meta,tm)
        self.message_port_pub(pmt.intern("timing_metric"), tm_cpdu);

        # extract symbols
        offset = round(self.N*tau/self.T);
        fo = (offset + self.N)%self.N;
        sym = xi[fo:-1:self.N];
        
        # normalize power to 1
        sym = sym / numpy.mean(numpy.real(sym * sym.conjugate()));

        # publish timing correct symbols (with frequency offset)
        sm = pmt.init_c32vector(sym.size, map(lambda i: complex(i), sym))
        sm_cpdu = pmt.cons(meta,sm)
        self.message_port_pub(pmt.intern("sym_timed"), sm_cpdu);

        # compute symbol frequency offset (linear phase offset within block)
        x_n = numpy.power(sym[200:1000], self.O);
        phase_ramp = numpy.unwrap(numpy.angle( x_n ));
        f_off_O = numpy.mean(numpy.diff(phase_ramp));
        goodstat = numpy.std(numpy.diff(phase_ramp));
        f_off = f_off_O / self.O;

        # check percentages
        self.nburst = self.nburst + 1;
        if(goodstat < 1.0):
            self.nburst_ok = self.nburst_ok + 1;
        else:
            print "WARNING: feedforward synchronizer discarding burst, goodness metric %f < 1.0 (likely poor timing recovery occurred, the CFO phase ramp looks like garbage)"%(goodstat)
            return
        print "sync: "+str((goodstat, self.nburst, self.nburst_ok, self.nburst_ok*100.0 / self.nburst));       

        # export phase ramp
        pr = pmt.init_f32vector(phase_ramp.size, map(lambda i: float(i), phase_ramp))
        pr_fpdu = pmt.cons(meta,pr)
        self.message_port_pub(pmt.intern("phase_ramp"), pr_fpdu);

        # apply frequency offset correction
        xc = numpy.multiply(sym, numpy.exp(-1j * f_off * numpy.linspace(1,sym.size,sym.size)));
        
        # compute and correct static symbol phase offset
        xcp = numpy.power(xc[400:1000], self.O);

# linear mean
        theta = numpy.mean( numpy.angle( xcp ) ) / self.O + numpy.pi/4;
# weighted mean
#        theta = numpy.sum(numpy.angle(xcp) * numpy.abs(xcp)) / numpy.sum(numpy.abs(xcp));
#        theta = theta / self.O + numpy.pi/4;

        xc = xc * numpy.exp(-1j*theta);

        # show time, frequency and phase estimates
        #print "tau = %f, f_off = %f, theta = %f"%(tau, f_off, theta);

        # add our estimates to the metadata dictionary
        meta = pmt.dict_add(meta, pmt.intern("tau"), pmt.from_double(tau));
        meta = pmt.dict_add(meta, pmt.intern("f_off"), pmt.from_double(f_off));
        meta = pmt.dict_add(meta, pmt.intern("theta"), pmt.from_double(theta));

        # publish freq corrected symbols
        xcm = pmt.init_c32vector(xc.size, map(lambda i: complex(i), xc))
        xcm_cpdu = pmt.cons(meta,xcm)
        self.message_port_pub(pmt.intern("cpdus"), xcm_cpdu);
Пример #15
0
    def __init__(self):
        gr.top_block.__init__(self, "Symbol Sync Test (Float)")
        Qt.QWidget.__init__(self)
        self.setWindowTitle("Symbol Sync Test (Float)")
        qtgui.util.check_set_qss()
        try:
            self.setWindowIcon(Qt.QIcon.fromTheme('gnuradio-grc'))
        except:
            pass
        self.top_scroll_layout = Qt.QVBoxLayout()
        self.setLayout(self.top_scroll_layout)
        self.top_scroll = Qt.QScrollArea()
        self.top_scroll.setFrameStyle(Qt.QFrame.NoFrame)
        self.top_scroll_layout.addWidget(self.top_scroll)
        self.top_scroll.setWidgetResizable(True)
        self.top_widget = Qt.QWidget()
        self.top_scroll.setWidget(self.top_widget)
        self.top_layout = Qt.QVBoxLayout(self.top_widget)
        self.top_grid_layout = Qt.QGridLayout()
        self.top_layout.addLayout(self.top_grid_layout)

        self.settings = Qt.QSettings("GNU Radio", "symbol_sync_test_float")
        self.restoreGeometry(self.settings.value("geometry").toByteArray())

        ##################################################
        # Variables
        ##################################################
        self.zeta = zeta = 1.0
        self.omega_n_norm = omega_n_norm = 0.125
        self.ted_gain = ted_gain = 0.28365
        self.omega_d_norm = omega_d_norm = omega_n_norm * math.sqrt(
            (zeta * zeta - 1.0) if zeta > 1.0 else (1.0 - zeta * zeta))
        self.proportional_gain = proportional_gain = 2.0 / ted_gain * math.exp(
            -zeta * omega_n_norm) * math.sinh(zeta * omega_n_norm)
        self.integral_gain = integral_gain = 2.0 / ted_gain * (
            1.0 - math.exp(-zeta * omega_n_norm) *
            (math.sinh(zeta * omega_n_norm) +
             (math.cosh(omega_d_norm)
              if zeta > 1.0 else math.cos(omega_d_norm))))
        self.sps = sps = 7
        self.proportional_gain_label = proportional_gain_label = "%8.6f" % proportional_gain
        self.packet_time_est_tag = packet_time_est_tag = gr.tag_utils.python_to_tag(
            (9, pmt.intern("test"), pmt.from_double(0.0),
             pmt.intern("packet_vector_source")))
        self.osps = osps = 1
        self.integral_gain_label = integral_gain_label = "%8.6f" % integral_gain
        self.data_src = data_src = (0, 0, 0, 0, 1)
        self.baud_rate = baud_rate = 1200.0

        ##################################################
        # Blocks
        ##################################################
        self._zeta_range = Range(0.1, 5.0, 0.1, 1.0, 200)
        self._zeta_win = RangeWidget(self._zeta_range, self.set_zeta,
                                     'Damping Factor', "counter_slider", float)
        self.top_grid_layout.addWidget(self._zeta_win, 0, 1, 1, 1)
        for r in range(0, 1):
            self.top_grid_layout.setRowStretch(r, 1)
        for c in range(1, 2):
            self.top_grid_layout.setColumnStretch(c, 1)
        self._ted_gain_range = Range(0.05, 5.0, 0.01, 0.28365, 200)
        self._ted_gain_win = RangeWidget(self._ted_gain_range,
                                         self.set_ted_gain,
                                         'Expected TED Gain', "counter_slider",
                                         float)
        self.top_grid_layout.addWidget(self._ted_gain_win, 1, 0, 1, 1)
        for r in range(1, 2):
            self.top_grid_layout.setRowStretch(r, 1)
        for c in range(0, 1):
            self.top_grid_layout.setColumnStretch(c, 1)
        self._omega_n_norm_range = Range(0.0, 2.0 * math.pi * 0.25, 0.001,
                                         0.125, 200)
        self._omega_n_norm_win = RangeWidget(self._omega_n_norm_range,
                                             self.set_omega_n_norm,
                                             'Normalized Bandwidth',
                                             "counter_slider", float)
        self.top_grid_layout.addWidget(self._omega_n_norm_win, 1, 1, 1, 1)
        for r in range(1, 2):
            self.top_grid_layout.setRowStretch(r, 1)
        for c in range(1, 2):
            self.top_grid_layout.setColumnStretch(c, 1)
        self._data_src_options = (
            (1, 0, 0, 0, 0),
            (0, 1, 0, 0, 0),
            (0, 0, 1, 0, 0),
            (0, 0, 0, 1, 0),
            (0, 0, 0, 0, 1),
        )
        self._data_src_labels = (
            'Random',
            'Low freq',
            'Dot Pattern',
            'Pulse',
            'Packets',
        )
        self._data_src_tool_bar = Qt.QToolBar(self)
        self._data_src_tool_bar.addWidget(Qt.QLabel('Data Source' + ": "))
        self._data_src_combo_box = Qt.QComboBox()
        self._data_src_tool_bar.addWidget(self._data_src_combo_box)
        for label in self._data_src_labels:
            self._data_src_combo_box.addItem(label)
        self._data_src_callback = lambda i: Qt.QMetaObject.invokeMethod(
            self._data_src_combo_box, "setCurrentIndex",
            Qt.Q_ARG("int", self._data_src_options.index(i)))
        self._data_src_callback(self.data_src)
        self._data_src_combo_box.currentIndexChanged.connect(
            lambda i: self.set_data_src(self._data_src_options[i]))
        self.top_grid_layout.addWidget(self._data_src_tool_bar, 0, 0, 1, 1)
        for r in range(0, 1):
            self.top_grid_layout.setRowStretch(r, 1)
        for c in range(0, 1):
            self.top_grid_layout.setColumnStretch(c, 1)
        self.rational_resampler_xxx_0 = filter.rational_resampler_fff(
            interpolation=10,
            decimation=21,
            taps=None,
            fractional_bw=0.45,
        )
        self.qtgui_time_sink_x_0_1_0 = qtgui.time_sink_f(
            1024 * 3,  #size
            baud_rate * sps,  #samp_rate
            "",  #name
            1  #number of inputs
        )
        self.qtgui_time_sink_x_0_1_0.set_update_time(0.10)
        self.qtgui_time_sink_x_0_1_0.set_y_axis(-1.5, 1.5)

        self.qtgui_time_sink_x_0_1_0.set_y_label('Amplitude', "")

        self.qtgui_time_sink_x_0_1_0.enable_tags(-1, True)
        self.qtgui_time_sink_x_0_1_0.set_trigger_mode(qtgui.TRIG_MODE_NORM,
                                                      qtgui.TRIG_SLOPE_POS,
                                                      0.1, 0.01, 0, '')
        self.qtgui_time_sink_x_0_1_0.enable_autoscale(False)
        self.qtgui_time_sink_x_0_1_0.enable_grid(True)
        self.qtgui_time_sink_x_0_1_0.enable_axis_labels(True)
        self.qtgui_time_sink_x_0_1_0.enable_control_panel(False)
        self.qtgui_time_sink_x_0_1_0.enable_stem_plot(False)

        if not True:
            self.qtgui_time_sink_x_0_1_0.disable_legend()

        labels = ['', '', '', '', 'Baseband', 'Abs(Corr)', '', '', '', '']
        widths = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
        colors = [
            "blue", "red", "green", "black", "dark green", "magenta", "yellow",
            "dark red", "dark green", "blue"
        ]
        styles = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
        markers = [-1, -1, -1, -1, -1, -1, -1, -1, -1, -1]
        alphas = [1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0]

        for i in xrange(1):
            if len(labels[i]) == 0:
                self.qtgui_time_sink_x_0_1_0.set_line_label(
                    i, "Data {0}".format(i))
            else:
                self.qtgui_time_sink_x_0_1_0.set_line_label(i, labels[i])
            self.qtgui_time_sink_x_0_1_0.set_line_width(i, widths[i])
            self.qtgui_time_sink_x_0_1_0.set_line_color(i, colors[i])
            self.qtgui_time_sink_x_0_1_0.set_line_style(i, styles[i])
            self.qtgui_time_sink_x_0_1_0.set_line_marker(i, markers[i])
            self.qtgui_time_sink_x_0_1_0.set_line_alpha(i, alphas[i])

        self._qtgui_time_sink_x_0_1_0_win = sip.wrapinstance(
            self.qtgui_time_sink_x_0_1_0.pyqwidget(), Qt.QWidget)
        self.top_grid_layout.addWidget(self._qtgui_time_sink_x_0_1_0_win, 3, 0,
                                       1, 1)
        for r in range(3, 4):
            self.top_grid_layout.setRowStretch(r, 1)
        for c in range(0, 1):
            self.top_grid_layout.setColumnStretch(c, 1)
        self.qtgui_time_sink_x_0_0_0_0_0 = qtgui.time_sink_f(
            256 * osps,  #size
            baud_rate * osps,  #samp_rate
            'Symbol Synched Output and Debug',  #name
            4  #number of inputs
        )
        self.qtgui_time_sink_x_0_0_0_0_0.set_update_time(0.1)
        self.qtgui_time_sink_x_0_0_0_0_0.set_y_axis(-1.5, sps + 2)

        self.qtgui_time_sink_x_0_0_0_0_0.set_y_label('Amplitude', "")

        self.qtgui_time_sink_x_0_0_0_0_0.enable_tags(-1, True)
        self.qtgui_time_sink_x_0_0_0_0_0.set_trigger_mode(
            qtgui.TRIG_MODE_NORM, qtgui.TRIG_SLOPE_POS, 0.1, 0.01, 0,
            "time_est")
        self.qtgui_time_sink_x_0_0_0_0_0.enable_autoscale(False)
        self.qtgui_time_sink_x_0_0_0_0_0.enable_grid(False)
        self.qtgui_time_sink_x_0_0_0_0_0.enable_axis_labels(True)
        self.qtgui_time_sink_x_0_0_0_0_0.enable_control_panel(False)
        self.qtgui_time_sink_x_0_0_0_0_0.enable_stem_plot(False)

        if not True:
            self.qtgui_time_sink_x_0_0_0_0_0.disable_legend()

        labels = [
            'Soft Bits', 'Error', 'Instantaneous Period', 'Average Period', '',
            '', '', '', '', ''
        ]
        widths = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
        colors = [
            "blue", "red", "green", "black", "cyan", "magenta", "yellow",
            "dark red", "dark green", "blue"
        ]
        styles = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
        markers = [0, -1, -1, -1, -1, -1, -1, -1, -1, -1]
        alphas = [1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0]

        for i in xrange(4):
            if len(labels[i]) == 0:
                self.qtgui_time_sink_x_0_0_0_0_0.set_line_label(
                    i, "Data {0}".format(i))
            else:
                self.qtgui_time_sink_x_0_0_0_0_0.set_line_label(i, labels[i])
            self.qtgui_time_sink_x_0_0_0_0_0.set_line_width(i, widths[i])
            self.qtgui_time_sink_x_0_0_0_0_0.set_line_color(i, colors[i])
            self.qtgui_time_sink_x_0_0_0_0_0.set_line_style(i, styles[i])
            self.qtgui_time_sink_x_0_0_0_0_0.set_line_marker(i, markers[i])
            self.qtgui_time_sink_x_0_0_0_0_0.set_line_alpha(i, alphas[i])

        self._qtgui_time_sink_x_0_0_0_0_0_win = sip.wrapinstance(
            self.qtgui_time_sink_x_0_0_0_0_0.pyqwidget(), Qt.QWidget)
        self.top_grid_layout.addWidget(self._qtgui_time_sink_x_0_0_0_0_0_win,
                                       3, 1, 1, 2)
        for r in range(3, 4):
            self.top_grid_layout.setRowStretch(r, 1)
        for c in range(1, 3):
            self.top_grid_layout.setColumnStretch(c, 1)
        self._proportional_gain_label_tool_bar = Qt.QToolBar(self)

        if None:
            self._proportional_gain_label_formatter = None
        else:
            self._proportional_gain_label_formatter = lambda x: str(x)

        self._proportional_gain_label_tool_bar.addWidget(
            Qt.QLabel('Proportional Gain' + ": "))
        self._proportional_gain_label_label = Qt.QLabel(
            str(
                self._proportional_gain_label_formatter(
                    self.proportional_gain_label)))
        self._proportional_gain_label_tool_bar.addWidget(
            self._proportional_gain_label_label)
        self.top_grid_layout.addWidget(self._proportional_gain_label_tool_bar,
                                       1, 2, 1, 1)
        for r in range(1, 2):
            self.top_grid_layout.setRowStretch(r, 1)
        for c in range(2, 3):
            self.top_grid_layout.setColumnStretch(c, 1)
        self._integral_gain_label_tool_bar = Qt.QToolBar(self)

        if None:
            self._integral_gain_label_formatter = None
        else:
            self._integral_gain_label_formatter = lambda x: str(x)

        self._integral_gain_label_tool_bar.addWidget(
            Qt.QLabel('Integral Gain' + ": "))
        self._integral_gain_label_label = Qt.QLabel(
            str(self._integral_gain_label_formatter(self.integral_gain_label)))
        self._integral_gain_label_tool_bar.addWidget(
            self._integral_gain_label_label)
        self.top_grid_layout.addWidget(self._integral_gain_label_tool_bar, 0,
                                       2, 1, 1)
        for r in range(0, 1):
            self.top_grid_layout.setRowStretch(r, 1)
        for c in range(2, 3):
            self.top_grid_layout.setColumnStretch(c, 1)
        self.fir_filter_xxx_0_1_0_0_0 = filter.fir_filter_fff(
            1, ([1.0 / float(sps)] * sps))
        self.fir_filter_xxx_0_1_0_0_0.declare_sample_delay(
            int((sps - 1.0) / 2.0) + 4)
        self.epy_block_0 = epy_block_0.ConstMap()
        self.digital_symbol_sync_xx_0 = digital.symbol_sync_ff(
            digital.TED_MUELLER_AND_MULLER, sps, omega_n_norm, zeta, ted_gain,
            1.5, osps,
            digital.constellation_bpsk().base(), digital.IR_MMSE_8TAP, 128,
            ([]))
        self.blocks_vector_source_x_0_0_1_0 = blocks.vector_source_f(
            [1, 0] * (4 * 12 * 0) + [1, 1, 0, 1, 0, 1, 0, 1] * 12 +
            [1, 0, 1, 1, 1, 1, 1, 0, 0, 1] + [1, 1, 1, 1, 0, 1, 1, 0, 0, 1] +
            [1, 0, 1, 1, 1, 1, 1, 0, 0, 1] + [0, 1, 1, 1, 0, 1, 1, 0, 1, 0] +
            [0, 0, 0, 0, 0, 1, 0, 1, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0] +
            [2] * 128, True, 1, [packet_time_est_tag])
        self.blocks_vector_source_x_0_0_1 = blocks.vector_source_f(
            [1] + [0] * 7, True, 1, [])
        self.blocks_vector_source_x_0_0_0 = blocks.vector_source_f(
            (0, 0, 0, 0, 1, 1, 1, 1), True, 1, [])
        self.blocks_vector_source_x_0_0 = blocks.vector_source_f(
            (0, 1, 0, 1, 0, 1, 0, 1), True, 1, [])
        self.blocks_throttle_0 = blocks.throttle(gr.sizeof_float * 1,
                                                 baud_rate * 10, True)
        self.blocks_short_to_float_1 = blocks.short_to_float(1, 1)
        self.blocks_repeat_0 = blocks.repeat(gr.sizeof_float * 1, sps * 2)
        self.blocks_multiply_matrix_xx_0 = blocks.multiply_matrix_ff(
            (data_src, ), gr.TPP_ALL_TO_ALL)
        self.analog_random_source_x_0 = blocks.vector_source_s(
            map(int, numpy.random.randint(0, 2, 16384)), True)

        ##################################################
        # Connections
        ##################################################
        self.connect((self.analog_random_source_x_0, 0),
                     (self.blocks_short_to_float_1, 0))
        self.connect((self.blocks_multiply_matrix_xx_0, 0),
                     (self.blocks_throttle_0, 0))
        self.connect((self.blocks_repeat_0, 0),
                     (self.rational_resampler_xxx_0, 0))
        self.connect((self.blocks_short_to_float_1, 0),
                     (self.blocks_multiply_matrix_xx_0, 0))
        self.connect((self.blocks_throttle_0, 0), (self.epy_block_0, 0))
        self.connect((self.blocks_vector_source_x_0_0, 0),
                     (self.blocks_multiply_matrix_xx_0, 2))
        self.connect((self.blocks_vector_source_x_0_0_0, 0),
                     (self.blocks_multiply_matrix_xx_0, 1))
        self.connect((self.blocks_vector_source_x_0_0_1, 0),
                     (self.blocks_multiply_matrix_xx_0, 3))
        self.connect((self.blocks_vector_source_x_0_0_1_0, 0),
                     (self.blocks_multiply_matrix_xx_0, 4))
        self.connect((self.digital_symbol_sync_xx_0, 3),
                     (self.qtgui_time_sink_x_0_0_0_0_0, 3))
        self.connect((self.digital_symbol_sync_xx_0, 2),
                     (self.qtgui_time_sink_x_0_0_0_0_0, 2))
        self.connect((self.digital_symbol_sync_xx_0, 1),
                     (self.qtgui_time_sink_x_0_0_0_0_0, 1))
        self.connect((self.digital_symbol_sync_xx_0, 0),
                     (self.qtgui_time_sink_x_0_0_0_0_0, 0))
        self.connect((self.epy_block_0, 0), (self.blocks_repeat_0, 0))
        self.connect((self.fir_filter_xxx_0_1_0_0_0, 0),
                     (self.digital_symbol_sync_xx_0, 0))
        self.connect((self.fir_filter_xxx_0_1_0_0_0, 0),
                     (self.qtgui_time_sink_x_0_1_0, 0))
        self.connect((self.rational_resampler_xxx_0, 0),
                     (self.fir_filter_xxx_0_1_0_0_0, 0))
Пример #16
0
def make_header(options, filename):
    extras_present = False
    if options.freq is not None:
        extras_present = True
    # Open the file and make the header
    hdr_filename = filename + '.hdr'
    hdr_file = open(hdr_filename, 'wb')
    header = pmt.make_dict()
    # Fill in header vals
    # TODO - Read this from blocks.METADATA_VERSION
    ver_val = pmt.from_long(long(0))
    rate_val = pmt.from_double(options.sample_rate)
    time_val = pmt.make_tuple(pmt.from_uint64(options.time_sec),
                             pmt.from_double(options.time_fsec))
    ft_to_sz = parse_file_metadata.ftype_to_size
    # Map shortname to properties
    enum_type = SNAME_TO_ENUM[options.format]
    type_props = SNAME_DEFS[enum_type]
    size_val = pmt.from_long(type_props[0])
    cplx_val = pmt.from_bool(type_props[1])
    type_val = pmt.from_long(type_props[2])
    fmt = type_props[2]
    file_samp_len = long(options.length)
    seg_size = long(options.seg_size)
    bytes_per_sample = type_props[0]
    bytes_val = pmt.from_uint64(long(seg_size*bytes_per_sample))
    # Set header vals
    header = pmt.dict_add(header, pmt.intern("version"), ver_val)
    header = pmt.dict_add(header, pmt.intern("size"), size_val)
    header = pmt.dict_add(header, pmt.intern("type"), type_val)
    header = pmt.dict_add(header, pmt.intern("cplx"), cplx_val)
    header = pmt.dict_add(header, pmt.intern("rx_time"), time_val)
    header = pmt.dict_add(header, pmt.intern("rx_rate"), rate_val)
    header = pmt.dict_add(header, pmt.intern("bytes"), bytes_val)

    if extras_present:
        freq_key = pmt.intern("rx_freq")
        freq_val = pmt.from_double(options.freq)
        extras = pmt.make_dict()
        extras = pmt.dict_add(extras, freq_key, freq_val)
        extras_str = pmt.serialize_str(extras)
        start_val = pmt.from_uint64(blocks.METADATA_HEADER_SIZE
                + len(extras_str))
    else:
        start_val = pmt.from_uint64(blocks.METADATA_HEADER_SIZE)
    header = pmt.dict_add(header, pmt.intern("strt"), start_val)
    num_segments = file_samp_len/seg_size
    if options.verbose:
        print "Wrote %d headers to: %s (Version %d)" % (num_segments,
                hdr_filename,pmt.to_long(ver_val))
    for x in range(0,num_segments-1,1):
        # Serialize and write out file
        if extras_present:
            header_str = pmt.serialize_str(header) + extras_str
        else:
            header_str = pmt.serialize_str(header)
        hdr_file.write(header_str)
        # Update header based on sample rate and segment size
        header = update_timestamp(header,seg_size)
    
    # Last header is special b/c file size is probably not mult. of seg_size
    header = pmt.dict_delete(header,pmt.intern("bytes"))
    bytes_remaining = bytes_per_sample*(file_samp_len - (num_segments-1)*long(seg_size))
    bytes_val = pmt.from_uint64(bytes_remaining)
    header = pmt.dict_add(header,pmt.intern("bytes"),bytes_val)
    # Serialize and write out file
    if extras_present:
        header_str = pmt.serialize_str(header) + extras_str
    else:
        header_str = pmt.serialize_str(header)
    hdr_file.write(header_str)
    hdr_file.close()
Пример #17
0
    def test_001(self):
        N = 1000
        outfile = "test_out.dat"

        detached = False
        samp_rate = 200000
        key = pmt.intern("samp_rate")
        val = pmt.from_double(samp_rate)
        extras = pmt.make_dict()
        extras = pmt.dict_add(extras, key, val)

        data = sig_source_c(samp_rate, 1000, 1, N)
        src = blocks.vector_source_c(data)
        fsnk = blocks.file_meta_sink(gr.sizeof_gr_complex, outfile, samp_rate,
                                     1, blocks.GR_FILE_FLOAT, True, 1000000,
                                     extras, detached)
        fsnk.set_unbuffered(True)

        self.tb.connect(src, fsnk)
        self.tb.run()
        fsnk.close()

        handle = open(outfile, "rb")
        header_str = handle.read(parse_file_metadata.HEADER_LENGTH)
        if (len(header_str) == 0):
            self.assertFalse()

        try:
            header = pmt.deserialize_str(header_str)
        except RuntimeError:
            self.assertFalse()

        info = parse_file_metadata.parse_header(header, False)

        extra_str = handle.read(info["extra_len"])
        self.assertEqual(len(extra_str) > 0, True)

        handle.close()

        try:
            extra = pmt.deserialize_str(extra_str)
        except RuntimeError:
            self.assertFalse()

        extra_info = parse_file_metadata.parse_extra_dict(extra, info, False)

        self.assertEqual(info['rx_rate'], samp_rate)
        self.assertEqual(pmt.to_double(extra_info['samp_rate']), samp_rate)

        # Test file metadata source
        src.rewind()
        fsrc = blocks.file_meta_source(outfile, False)
        vsnk = blocks.vector_sink_c()
        tsnk = blocks.tag_debug(gr.sizeof_gr_complex, "QA")
        ssnk = blocks.vector_sink_c()
        self.tb.disconnect(src, fsnk)
        self.tb.connect(fsrc, vsnk)
        self.tb.connect(fsrc, tsnk)
        self.tb.connect(src, ssnk)
        self.tb.run()

        fsrc.close()
        # Test to make sure tags with 'samp_rate' and 'rx_rate' keys
        # were generated and received correctly.
        tags = tsnk.current_tags()
        for t in tags:
            if (pmt.eq(t.key, pmt.intern("samp_rate"))):
                self.assertEqual(pmt.to_double(t.value), samp_rate)
            elif (pmt.eq(t.key, pmt.intern("rx_rate"))):
                self.assertEqual(pmt.to_double(t.value), samp_rate)

        # Test that the data portion was extracted and received correctly.
        self.assertComplexTuplesAlmostEqual(vsnk.data(), ssnk.data(), 5)

        os.remove(outfile)
Пример #18
0
    def __init__(self, seed, samp_rate, noise_amp, modulation, delay, samples_to_receive, freq, rx_id):
        gr.hier_block2.__init__(self, "ModulatorBlock",
                       gr.io_signature(0, 0, 0),
                       gr.io_signature(1, 1, gr.sizeof_gr_complex))

        # Timing tag: This is preserved and updated:
        timing_tag = gr.tag_t()
        timing_tag.offset = 0
        timing_tag.key = pmt.string_to_symbol('rx_time')
        timing_tag.value = pmt.to_pmt((float(seed), 0.6))
        timing_tag.srcid = pmt.string_to_symbol(str('gr uhd usrp source1'))
        # Rx freq tags:
        #print "In source emulation (before tag)" 
        #print freq
        rx_freq_tag = gr.tag_t()
        rx_freq_tag.offset = 0
        rx_freq_tag.key = pmt.string_to_symbol('rx_freq')
        rx_freq_tag.value = pmt.from_double(freq)
        rx_freq_tag.srcid = pmt.string_to_symbol(str('gr uhd usrp source1'))
        # Samp_rate tags:
        rx_rate_tag = gr.tag_t()
        rx_rate_tag.offset = 0
        rx_rate_tag.key = pmt.string_to_symbol('rx_rate')
        rx_rate_tag.value = pmt.from_double(samp_rate)
        rx_rate_tag.srcid = pmt.string_to_symbol(str('gr uhd usrp source1'))

        add = blocks.add_vcc(1, )

        tag_debug = blocks.tag_debug(gr.sizeof_gr_complex*1, "", "")
        tag_debug.set_display(True)
    
        #if modulation == "bpsk":
        #    mod = digital.psk.psk_mod(
        #      constellation_points=2,
        #      mod_code="none",
        #      differential=True,
        #      samples_per_symbol=2,
        #      excess_bw=0.1,
        #      verbose=False,
        #      log=False,
        #      )
        #else:
        #    mod = grc_blks2.packet_mod_b(digital.ofdm_mod(
        #                    options=grc_blks2.options(
        #                            modulation="qpsk",
        #                            fft_length=4096,
        #                            occupied_tones=200,
        #                            cp_length=0,
        #                            pad_for_usrp=False,
        #                            log=None,
        #                            verbose=None,
        #                    ),
        #            ),
        #            payload_length=0,
        #    )
        #print "in source emulation(after_tag)"
        #print  pmt.to_double(rx_freq_tag.value)
        pulse_width = 4
        np.random.seed(seed=seed)
        
        tx_vector = np.reshape(np.matlib.repmat(np.random.randint(0,2,(5*samples_to_receive)/pulse_width)*2-1,pulse_width,1).T,[1,5*samples_to_receive])[0].tolist()
        # delay signal vector -> insert zeros at beginnig; nothing happens if signal has not reached the receiver:
        tx_vector_delayed = np.hstack((np.zeros(delay),tx_vector))
        #tx_vector_delayed = tx_vector_delayed[:600]
        self.vector_source = blocks.vector_source_c(tx_vector_delayed, False, 1, (timing_tag, rx_freq_tag, rx_rate_tag)) 
        #clip first 600 samples
        self.head = blocks.head(gr.sizeof_gr_complex*1, samples_to_receive + 300)
        # skiphead= blocks.skiphead(gr.sizeof_gr_complex*1,delay)
        throttle = blocks.throttle(gr.sizeof_gr_complex*1, samp_rate,True)
        noise = analog.noise_source_c(analog.GR_GAUSSIAN, noise_amp, -seed)
        # connects
        #self.connect(vector_source, mod, (add,0))
        self.connect(self.vector_source, (add,0))
        self.connect(noise, (add,1))
        self.connect(add, throttle, self.head, self)
        self.connect(add, tag_debug)
        '''
Пример #19
0
    def calcLQE(self):  # Calcula LQE e envia a estimativa

        #Range do RSSI
        minRSSI = self.minRSSI
        maxRSSI = self.maxRSSI

        rangeRSSI = maxRSSI - minRSSI

        tempRssi = self.emaRssi

        # print "RSSI suavizado: "
        # print tempRssi

        if tempRssi < minRSSI:
            tempRssi = minRSSI
        elif tempRssi > maxRSSI:
            tempRssi = maxRSSI

        tempKalmanRssi = self.kRssi

        if tempKalmanRssi < minRSSI:
            tempKalmanRssi = minRSSI
        elif tempKalmanRssi > maxRSSI:
            tempKalmanRssi = maxRSSI

        # print "RSSI suavizado: "
        # print tempKalmanRssi

        self.estimRssi = float(1 - (tempRssi - minRSSI) / rangeRSSI)

        # print "RSSI Estim: "
        # print self.estimRssi

        self.estimRssiKalman = float(1 -
                                     (tempKalmanRssi - minRSSI) / rangeRSSI)

        # print "RSSI Estim Kalman: "
        # print self.estimRssiKalman

        # RSSI Instantaneo + Kalman kRssi
        # See calibration in datasheet of AD9361 (Analog Device of B210):
        # http://www.analog.com/media/en/technical-documentation/user-guides/AD9361_Reference_Manual_UG-570.pdf
        # https://www.analog.com/media/en/technical-documentation/data-sheets/AD9361.pdf

        self.estimPRR = float(self.geralPRR)
        self.estimPRR_Rssi = float(min(self.geralPRR,
                                       self.estimRssi))  # PRR + RSSI

        self.estimPRR2levels = float(min(
            self.geralPRR, self.geralLPRR))  # PRR with 2 levels without RSSI
        self.estimPRR2 = float(
            min(self.geralPRR, self.geralLPRR, self.estimRssi))  # PRR2 Full
        # print "# DEBUG---------- IMPRIMINDO SERIE-ESTIM-PRR2 desmembrada -----------"
        # print(self.geralPRR)
        # print(self.geralLPRR)
        # print(self.estimRssi)

        if self.method == 1:
            #####################################################
            # No estimator - constant gain - maximum gain
            #####################################################
            #print "No estimator in use - the tx gain is constant"
            aux1 = 0.0
            self.message_port_pub(pmt.intern("estimation"),
                                  pmt.from_double(aux1))

        elif self.method == 2:
            #####################################################
            # Estimator using ONLY RSSI:
            #####################################################

            if self.filter == 2:  #EMA
                self.message_port_pub(pmt.intern("estimation"),
                                      pmt.from_double(self.estimRssi))
                # print " DEBUG ---------- RSSI EMA  -----------"
                # print(self.estimRssi)

            elif self.filter == 3:  #Kalman
                self.message_port_pub(pmt.intern("estimation"),
                                      pmt.from_double(self.estimRssiKalman))

                # print " DEBUG ---------- RSSI KALMAN -----------"
                # print(self.estimRssiKalman)

            #print "RSSI method in use"
            #This sets the gain
            # FIXME
            # aux = float(self.emaRssi)
            #print "RSSI ------------ %2.4f\n" % (float(aux))
            # self.message_port_pub(pmt.intern("estimation"), pmt.from_double(self.gainTx))

        elif self.method == 3:
            #####################################################
            # Estimator using ONLY traditional PRR:
            #####################################################

            if self.filter == 3:  #Kalman
                print "\n--- WARNING: Kalman filter only for RSSI. Using EMA --- \n"

            # self.gainTx = self.holtwinters(self.serie, self.alphaHW, self.betaHW, self.gammaHW, 4)
            # if self.geralPRR < 0.699:
            # 	self.gainTx = 89
            # else:
            # 	self.gainTx = 89 - (self.geralPRR-0.7)*100

            # self.estim = self.geralPRR

            #print "PRR method in use"
            #This sets the gain
            # est=float(self.estim)
            self.message_port_pub(pmt.intern("estimation"),
                                  pmt.from_double(self.estimPRR))

        elif self.method == 4:
            #####################################################
            # PRR 2 levels + RSSI (FULL)
            #####################################################

            # if self.geralPRR < 0.699 or self.geralLPRR < 0.699:
            # 	self.estim = 0
            # else:
            #self.gainTx = max(89 - min((self.geralPRR-0.7)*100,(self.geralLPRR-0.7)*100),(170+int(self.emaRssi)+72)*0.46)

            # self.estim = float(min(self.geralPRR,self.geralLPRR, self.emaRssi))
            # self.geralPRR2 = self.estim

            #print "Proposed mode in use - under development - the tx gain is constant"
            #This sets the gain
            #gTx=float(self.gainTx)
            if self.treinaML == True:  # setado na linha 58
                self.message_port_pub(pmt.intern("estimation"),
                                      pmt.from_double(
                                          self.forcaLQE))  #setar aqui o valor
            else:
                self.message_port_pub(pmt.intern("estimation"),
                                      pmt.from_double(self.estimPRR2))

        elif self.method == 5:
            #####################################################
            # PRR 2 levels without RSSI
            #####################################################

            # self.estim = float(min(self.geralPRR,self.geralLPRR))
            # self.geralPRR2modif = self.estim

            self.message_port_pub(pmt.intern("estimation"),
                                  pmt.from_double(self.estimPRR2levels))

            #print "Dynamic mode in use - under development - the tx gain is constant"

        elif self.method == 6:
            #####################################################
            # Traditional PRR + RSSI
            #####################################################
            self.message_port_pub(pmt.intern("estimation"),
                                  pmt.from_double(self.estimPRR_Rssi))

        elif self.method == 7:
            pass
            #####################################################
            # LQL - Link Quality Learning --- era Foresee 4C (like)
            # [REF:] Di Caro, Gianni A., et al. "Online supervised incremental learning of link quality estimates
            # in wireless networks." Ad Hoc Networking Workshop (MED-HOC-NET), 2013 12th Annual Mediterranean. IEEE, 2013.
            #####################################################

            # if len(self.serieLQL) >= 40: # Arbitrary value to training
            # 	del(self.serieLQL[0])
            # 	# del(self.tempML[0])
            # 	del(self.serieTargetLQL[0])

            # # if (self.adwin.update(self.emaRssi)): # SE DETECTAR CONCEPT DRIFT
            # # 	self.serieLQL = []
            # # 	self.serieTargetLQL = []
            # # 	self.treinar = True
            # # 	self.contaConceptDrift += 1

            # if len(self.serieLQL)>=10 :
            # 	if (self.geralSends%10==0 and len(Self.serieLQL)<=40): # So habilita para treinar e retreinar a cada 10 entradas e ate o tam max 40
            # 		self.treinar = True								# depois so retreina se houver detecção de concept drift
            # 	else:
            # 		self.treinar = False

            # # if len(self.serieLQL)>=10 :
            # # 	if (self.geralSends%30==0): # So habilita para treinar e retreinar a cada 30 entradas
            # # 		self.treinar = True
            # # 	else:
            # # 		self.treinar = False

            # #self.tempLQL.append(self.estimPRR)
            # self.tempLQL.append(self.estimRssi)
            # self.tempLQL.append(self.mediaSNR)
            # self.serieLQL.append(list(self.tempLQL))
            # #self.serieLQL.append(list(self.tempLQL)) # Duplicar append para ter dois targets com as mesmas entradas
            # self.tempLQL=[]
            # self.serieTargetLQL.append(self.estimPRR) # Target 1
            # #self.serieTarget.append(self.estimPRR2) # Target 2
            # self.finalSerieLQL = numpy.array(self.serieLQL)

            # #SVMR

            # # print "DEBUG: ---------- IMPRIMINDO SERIE-LQL -----------"
            # # print(self.serieLQL)
            # #print "DEBUG: ---------- IMPRIMINDO SERIE-TARGET-LQL -----------"
            # #print(self.serieTargetLQL)
            # # estimSVMRLQL = 0.0 #
            # if len(self.serieLQL) >= 5:
            # 	self.finalSerieLQL=numpy.array(self.serieLQL)
            # 	# print "---------- IMPRIMINDO SERIE-ML-ARRAY -----------"
            # 	# print(self.finalSerieLQL)

            # 	# print "---------- IMPRIMINDO SERIE-TARGET-ML-ARRAY -----------"
            # 	# print(self.serieTargetLQL)

            # 	if self.treinar == True :
            # 		self.contaTreinos +=1
            # 		self.reg.fit(self.serieLQL[:-1],self.serieTargetLQL[:-1]) # Treina com todos os dados da serie, exceto o último
            # 	self.finalSerieLQL = self.serieLQL[-1]
            # 	self.finalSerieLQL = numpy.arange(2).reshape(1,-1) # Para duas entradas, usar 	self.finalSerieML = numpy.arange(2).reshape(1,-1)
            # 	self.estimSVMRLQL = float(self.reg.predict(self.finalSerieLQL)) # Predizer somente o ultimo valor da serie
            # 	erroSVMRLQL = numpy.abs(self.estimSVMRLQL - self.serieTargetLQL[-1])
            # 	self.serieErroSVMRLQL.append(erroSVMRLQL)
            # 	# print "DEBUG - ESTIMATIVA GERADA PELA ML-SVMR-LQL: %f" %self.estimSVMRLQL
            # 	# print "DEBUG - ERRO do SVMR: %f" %erroSVMRLQL

            # # print "ESTIMATIVA GERADA PELA ML-SVMR: %f" %self.estimSVMRLQL
            # self.message_port_pub(pmt.intern("estimation"),pmt.from_double(self.estimSVMRLQL))

        #@profile # TODO: Testar o Memory_profile (0) Pode limitar tam arvore
        elif self.method == 8:
            print "Ok"
Пример #20
0
 def test_pmt_from_double(self):
     b = pmt.from_double(123765)
     self.assertEqual(pmt.to_python(b), 123765)
     t = pmt.to_pmt(list(range(5)))
Пример #21
0
    def calcLQE(self):  # Calcula LQE e envia a estimativa

        #Range do RSSI
        minRSSI = self.minRSSI
        maxRSSI = self.maxRSSI

        rangeRSSI = maxRSSI - minRSSI

        tempRssi = self.emaRssi

        # print "RSSI suavizado: "
        # print tempRssi

        if tempRssi < minRSSI:
            tempRssi = minRSSI
        elif tempRssi > maxRSSI:
            tempRssi = maxRSSI

        tempKalmanRssi = self.kRssi

        if tempKalmanRssi < minRSSI:
            tempKalmanRssi = minRSSI
        elif tempKalmanRssi > maxRSSI:
            tempKalmanRssi = maxRSSI

        # print "RSSI suavizado: "
        # print tempKalmanRssi

        self.estimRssi = float(1 - (tempRssi - minRSSI) / rangeRSSI)

        # print "RSSI Estim: "
        # print self.estimRssi

        self.estimRssiKalman = float(1 -
                                     (tempKalmanRssi - minRSSI) / rangeRSSI)

        # print "RSSI Estim Kalman: "
        # print self.estimRssiKalman

        # RSSI Instantaneo + Kalman kRssi
        # See calibration in datasheet of AD9361 (Analog Device of B210):
        # http://www.analog.com/media/en/technical-documentation/user-guides/AD9361_Reference_Manual_UG-570.pdf
        # https://www.analog.com/media/en/technical-documentation/data-sheets/AD9361.pdf

        self.estimPRR = float(self.geralPRR)
        self.estimPRR_Rssi = float(min(self.geralPRR,
                                       self.estimRssi))  # PRR + RSSI

        self.estimPRR2levels = float(min(
            self.geralPRR, self.geralLPRR))  # PRR with 2 levels without RSSI
        self.estimPRR2 = float(
            min(self.geralPRR, self.geralLPRR, self.estimRssi))  # PRR2 Full
        # print "# DEBUG---------- IMPRIMINDO SERIE-ESTIM-PRR2 desmembrada -----------"
        # print(self.geralPRR)
        # print(self.geralLPRR)
        # print(self.estimRssi)

        if self.method == 1:
            #####################################################
            # No estimator - constant gain - maximum gain
            #####################################################

            print "No estimator in use - the tx gain is constant"
            aux1 = 0.0  # Poor quality, maximum gain
            self.message_port_pub(pmt.intern("estimation"),
                                  pmt.from_double(aux1))

        elif self.method == 2:
            #####################################################
            # Estimator using ONLY RSSI:
            #####################################################

            if self.filter == 2:  #EMA
                self.message_port_pub(pmt.intern("estimation"),
                                      pmt.from_double(self.estimRssi))
                # print " DEBUG ---------- RSSI EMA  -----------"
                # print(self.estimRssi)

            elif self.filter == 3:  #Kalman
                self.message_port_pub(pmt.intern("estimation"),
                                      pmt.from_double(self.estimRssiKalman))

                # print " DEBUG ---------- RSSI KALMAN -----------"
                # print(self.estimRssiKalman)

            print "RSSI method in use"
            # aux = float(self.emaRssi)
            # print "RSSI ------------ %2.4f\n" % (float(aux))
            # self.message_port_pub(pmt.intern("estimation"), pmt.from_double(self.gainTx))

        elif self.method == 3:
            #####################################################
            # Estimator using ONLY traditional PRR:
            #####################################################

            if self.filter == 3:  #Kalman
                print "\n--- WARNING: Kalman filter only for RSSI. Using EMA --- \n"

            #print "PRR method in use"

            self.message_port_pub(pmt.intern("estimation"),
                                  pmt.from_double(self.estimPRR))

        elif self.method == 4:
            #####################################################
            # PRR 2 levels + RSSI (FULL)
            #####################################################

            #print "Proposed mode in use - under development - the tx gain is constant"
            #This sets the gain
            #gTx=float(self.gainTx)
            if self.treinaML == True:  # setado na linha 118
                self.message_port_pub(pmt.intern("estimation"),
                                      pmt.from_double(
                                          self.forcaLQE))  #seta o valor
            else:
                self.message_port_pub(pmt.intern("estimation"),
                                      pmt.from_double(self.estimPRR2))

        elif self.method == 5:
            #####################################################
            # NOTE: ETX -  Expected Transmission Count (ETX) --- Previously: PRR 2 levels without RSSI
            # COUTO, D. S. J. D., AGUAYO, D., BICKET, J., AND MORRIS, R. 2003. A high-throughput path metric for multihop
            # wireless routing. In Proceedings of the 9th Annual International Conference on Mobile Computing and
            # Networking (MobiCom ’03). ACM, 134–146.
            # https://pdos.lcs.mit.edu/papers/grid:decouto-phd/thesis.pdf
            # https://en.wikipedia.org/wiki/Expected_transmission_count
            #####################################################

            #self.message_port_pub(pmt.intern("estimation"),pmt.from_double(self.estimPRR2levels)) # Previously: PRR 2 levels without RSSI
            if self.ackCount > 0:
                self.ETX = float(self.geralSends) / self.ackCount
            else:
                self.ETX = 6
            estimETX = (self.ETX - 6) / (-5.0)  # Convertion to 0 --- 1 range
            print "ETX raw value ----- : %6.2f" % (self.ETX)
            print "ETX estimation ----- : %6.2f" % (estimETX)
            self.message_port_pub(pmt.intern("estimation"),
                                  pmt.from_double(estimETX))

        elif self.method == 6:
            #####################################################
            # Traditional PRR + RSSI
            #####################################################
            self.message_port_pub(pmt.intern("estimation"),
                                  pmt.from_double(self.estimPRR_Rssi))

        elif self.method == 7:
            #####################################################
            # LQL - Link Quality Learning --- era Foresee 4C (like)
            # [REF:] Di Caro, Gianni A., et al. "Online supervised incremental learning of link quality estimates
            # in wireless networks." Ad Hoc Networking Workshop (MED-HOC-NET), 2013 12th Annual Mediterranean. IEEE, 2013.
            # - NÃO RETREINA
            #####################################################

            maxValue = 40  # MAX value to serie to training

            if len(self.serieLQL
                   ) >= maxValue:  # Arbitrary MAX value to training
                del (self.serieLQL[0])
                del (self.serieTargetLQL[0])

            if (self.geralSends % 20 == 0 and self.geralSends >= 20):
                if (
                        self.geralSends % 10 == 0
                        and len(self.serieLQL) <= maxValue
                ):  # So habilita para treinar e retreinar a cada 10 entradas e ate o MaxValue
                    self.treinar = True
                else:
                    self.treinar = False

            self.tempLQL.append(self.estimPRR)
            self.tempLQL.append(self.estimRssi)
            self.tempLQL.append(self.mediaSNR)
            self.serieLQL.append(list(self.tempLQL))
            self.tempLQL = []
            self.serieTargetLQL.append(self.estimPRR)  # Target
            self.finalSerieLQL = numpy.array(self.serieLQL)

            if len(self.serieLQL
                   ) >= 20:  # Somente usado para treinar a primeira vez
                self.finalSerieLQL = numpy.array(self.serieLQL)

                if self.treinar == True:
                    self.contaTreinos += 1
                    self.reg.fit(
                        self.serieLQL[:-1], self.serieTargetLQL[:-1]
                    )  # Treina com todos os dados da serie, exceto o último
                self.finalSerieLQL = self.serieLQL[-1]
                self.finalSerieLQL = numpy.arange(3).reshape(
                    1, -1
                )  # Para duas entradas, usar 	self.finalSerieML = numpy.arange(2).reshape(1,-1)
                self.estimSVMRLQL = float(
                    self.reg.predict(self.finalSerieLQL)
                )  # Predizer somente o ultimo valor da serie
                erroSVMRLQL = numpy.abs(self.estimSVMRLQL -
                                        self.serieTargetLQL[-1])
                self.serieErroSVMRLQL.append(erroSVMRLQL)

                # self.timestr = time.strftime("%Y%m%d-%H%M%S") # Se quiser salvar o arquivo de treinamento .joblib
                # filename = "fileTrainLQL"+self.itmestr+".joblib"
                filename = "fileTrainLQL2.joblib"
                joblib.dump(self.reg, filename)

            # self.finalSerieLQL = self.serieLQL[-1] # Descomentar essas 3 linhas se o grande if anterior estiver comentado
            # self.finalSerieLQL = numpy.arange(3).reshape(1,-1) # Para duas entradas, usar 	self.finalSerieML = numpy.arange(2).reshape(1,-1)
            # self.estimSVMRLQL = float(self.reg.predict(self.finalSerieLQL))
            self.message_port_pub(pmt.intern("estimation"),
                                  pmt.from_double(self.estimSVMRLQL))

        elif self.method == 8 or self.method == 9:  # 8 with Concept drift ---- 9 without concept drift

            ###########################################################
            # #													    # #
            # #													    # #
            # # NOTE: PROPOSTA - Machine Learning - LQM3	        # #
            # # Link Quality Estimator using M.L. with triple input # #
            # # NOTE: Usar .format								    # #
            # #													    # #
            ###########################################################

            self.split = time.time()
            elapsed = self.split - self.startT

            # TIME CONTROL : RECURSO DE REDUÇÃO TEMPORAL DA SERIE - Usado opcionalmente
            timeControl = True  #True para ativar ou False para desativar
            #
            # if timeControl :
            # 	if elapsed > self.timeoutML: # se decorridos mais de xx segundo, a serie eh reduzida pela metade, apagando as entradas mais antigas
            # 		self.serieML = self.serieML[-(len(self.serieML)/2):]
            # 		self.serieTarget = self.serieTarget[-(len(self.serieTarget)/2):]
            # 		self.contaReducao += 1
            #

            if len(self.serieML) >= 20:
                if (
                        self.geralSends % 20 == 0 and self.geralSends <= 40
                ):  # So habilita para treinar e retreinar a cada 20 entradas e ate o tam max 40
                    # self.treinar = True								  # e depois so retreina se houver detecção de concept drift
                    pass
                else:
                    self.treinar = False

                if len(self.serieML) >= 41:  # Arbitrary MAX value to training
                    del (self.serieML[0])  # Apaga a entrada mais antiga
                    del (self.serieTarget[0])  # Apaga a entrada mais antiga
            else:
                self.treinar = False

            # NOTE: CONCEPT DRIFT - Se detectar, retreina a ML

            if self.method == 8:
                concDrift = True
            elif self.method == 9:
                concDrift = False

            if concDrift == True:
                if (self.adwin.update(self.emaRssi)):
                    self.treinar = True
                    self.contaConceptDrift += 1

            # if len(self.serieML)>=10 : # Usado apenas para treinamento inicial (depois faz o load .joblib e retreina quando detecta concept drift)
            # 	if (self.geralSends%30==0): # So habilita para treinar e retreinar a cada 30 entradas
            # 		self.treinar = True
            # 	else:
            # 		self.treinar = False

            # -------------------------
            # INPUTS:
            # -------------------------

            #['rssi','prr','snr','latencia-ms','relacao'] # inputs

            self.tempML.append(self.estimPRR)
            self.tempML.append(self.estimRssi)
            self.tempML.append(float(self.mediaSNR))

            if self.diffTempo == 0.0 or self.diffTempo == 999:
                self.tempML.append(self.diffTempo)
            else:
                self.tempML.append(self.diffTempo.microseconds /
                                   1000.0)  # miliseconds
            self.diffTempo = 999  #para evitar leituras de tempo repetidas

            if self.ackCount > 0:
                calcRel = self.geralSends / (self.ackCount * 1.0
                                             )  # to force float
            else:
                calcRel = 0.0
            self.tempML.append(calcRel)  # Relacao

            self.serieML.append(list(self.tempML))
            self.tempML = []
            self.serieTarget.append(self.estimPRR2)  # Target
            self.finalSerieML = numpy.array(self.serieML)

            if len(self.serieML) >= 20:
                self.finalSerieML = numpy.array(self.serieML)

                if self.treinar == True:  # TODO: Liberado para treinar o LQM3
                    self.contaTreinos += 1
                    tempo1 = datetime.datetime.now()
                    self.clf.fit(
                        self.serieML[:-1], self.serieTarget[:-1]
                    )  # Treina com todos os dados da serie, exceto o último
                    self.treinado = True  # para identificar que já houve 1 treinamento
                    # self.profund = self.clf.get_depth() # Python3
                    self.profund.append(self.clf.tree_.max_depth)
                    # self.folhas = self.clf.get_n_leaves() #P ython3
                    folhas = numpy.sum(
                        numpy.logical_and(self.clf.tree_.children_left == -1,
                                          self.clf.tree_.children_right == -1))
                    self.folhas.append(folhas)
                    # self.timestr = time.strftime("%Y%m%d-%H%M%S") # Se quiser salvar o arquivo de treinamento .joblib
                    # filename = "fileTrain"+self.timestr+".joblib"
                    # joblib.dump(self.clf,filename)

                    tempo2 = datetime.datetime.now()
                    diferenca = tempo2 - tempo1  # para calcular o tempo de treinamento da ML
                    print "Diferenca tempo -----------"
                    print diferenca
                    print(diferenca.seconds, ":", diferenca.microseconds)
                    # self.serieTempoML.append((diferenca.microseconds/1000.0)) #adiciona o tempo na serie em miliseconds
                    self.serieTempoML.append(
                        diferenca)  #adiciona o tempo na serie em miliseconds

                erroML = numpy.abs(self.estimSVMR - self.serieTarget[-1])
                self.serieErroLQM3.append(erroML)
                self.startT = time.time()

            self.finalSerieML = self.serieML[-1]
            self.finalSerieML = numpy.arange(5).reshape(
                1, -1
            )  # Para duas entradas, usar self.finalSerieML = numpy.arange(2).reshape(1,-1)
            self.estimSVMR = float(self.clf.predict(
                self.finalSerieML))  # Predizer somente o ultimo valor da serie
            self.message_port_pub(pmt.intern("estimation"),
                                  pmt.from_double(self.estimSVMR))
Пример #22
0
#!/usr/bin/env python

import sys
import pmt
from gnuradio.ctrlport.GNURadioControlPortClient import GNURadioControlPortClient

args = sys.argv
if(len(args) < 4):
    sys.stderr.write('Not enough arguments: usrp_source_controller.py <host> <port> <command> <value>\n')
    sys.stderr.write('See the "UHD Interface" section of the manual for available commands.\n\n')
    sys.exit(1)

alias = 'usrp_source0'
port = 'command'

hostname = args[1]
portnum = int(args[2])
cmd = args[3].lower()

if(cmd == "antenna"):
    val = pmt.intern(args[4])
else:
    val = pmt.from_double(float(args[4]))

argv = [None, hostname, portnum]
radiosys = GNURadioControlPortClient(argv=argv, rpcmethod='thrift')
radio = radiosys.client

radio.postMessage(alias, port, pmt.cons(pmt.intern(cmd), val))
Пример #23
0
 def test02(self):
     const = 123765
     x_pmt = pmt.from_double(const)
     x_int = pmt.to_double(x_pmt)
     self.assertEqual(x_int, const)
 def send_seq(self, msg):
     x = self.chan_spacing * random.randint(-self.nchans / 2,
                                            self.nchans / 2 - 1)
     self.message_port_pub(pmt.intern("seq"), pmt.from_double(x))
Пример #25
0
	def handle(self, msg):
		meta = pmt.to_python(msg)
		if not isinstance(meta, dict):
			print "Unexpected type:", meta
			return

		period = meta['period']

		new_ratio = period / self.target_period

		if self.limit is not None:
			if (new_ratio > (self.init_ratio * (1.0 + self.limit))) or (new_ratio < (self.init_ratio * (1.0 - self.limit))):
				if self.verbose:
					print "Exceeds limit: {} ({})".format(period, new_ratio)
				return

		ratio_diff = abs((new_ratio / self.ratio) - 1.0)

		avg_ratio = (self.alpha * new_ratio) + ((1.0 - self.alpha) * self.ratio)

		# if self.verbose:
		# 	print "Period: {}, ratio: {}, ratio diff: {}".format(period, new_ratio, ratio_diff)

		if self.jump_ratio is not None and ratio_diff >= self.jump_ratio:
			print "Jumping to ratio: {}", new_ratio
			self.ratio = new_ratio
			if self.locked:
				print "Unlocked"
			self.locked = False
			self.window = []
		elif not self.locked:
			self.ratio = avg_ratio

		if len(self.window) >= self.window_length:
			self.window = self.window[(len(self.window) - self.window_length + 1):]

		self.window.append(avg_ratio)

		_sum = sum(self.window)
		_count = float(len(self.window))
		_ave = _sum / _count
		_sum_squared = sum([x*x for x in self.window])

		_var = ( _sum_squared + (_ave  * ((_ave * _count) - 2.0 * _sum) ) ) / _count
		if _var < 0: # Due to floating point error
			# print "Var negative: {}".format(_var)
			_var = 0
		_sd = math.sqrt(_var)

		if self.lock_sd is not None:
			if len(self.window) == self.window_length:
				if not self.locked:
					if _sd <= self.lock_sd:
						self.locked = True
						print "Locked"

		new_ratio_ppb = self.ratio * 1e9
		if self.verbose:
			print "New ratio: {} (#{}, SD: {}), reported period: {} (ratio: {}), ratio diff: {}, locked: {}".format(self.ratio, len(self.window), _sd, period, new_ratio, ratio_diff, self.locked)
		new_ratio_int = int(new_ratio_ppb)
		new_ratio_frac = new_ratio_ppb - new_ratio_int
		#self.message_port_pub(pmt.intern('out'), pmt.from_double(float(self.ratio)))
		self.message_port_pub(pmt.intern('out'), pmt.cons(pmt.from_long(new_ratio_int), pmt.from_double(float(new_ratio_frac))))
Пример #26
0
    def work(self, input_items, output_items):
        in0 = input_items[0][self.history() - 1:]
        out = output_items[0]

        consumed = 0

        #print "work", len(in0), self.integer_offset, self.nitems_read(0), self.nitems_written(0)

        while True:
            #print self.state
            self.integer_offset = self.nitems_read(0) + consumed
            if self.state == INIT:
                self.state = SKIP_SAMPLES
                self.skip_samples_count = (int(self.frame_length * 10.1), 0)
                self.next_state = PREPARE_FIND_START
                key = pmt.string_to_symbol("sync")
                value = pmt.from_double(0)
                self.add_item_tag(0, self.integer_offset, key, value)

            elif self.state == PREPARE_FIND_START:
                self.state = GET_SAMPLES
                self.count = self.frame_length
                self.samples = numpy.array([], dtype=numpy.complex64)
                self.next_state = FIND_START

            elif self.state == FIND_START:
                #start = 0
                #while start == 0:
                #    start = find_start.find_start(signal, self.sample_rate)
                #    signal = reader.read(f, count=self.frame_length)
                rough_start = find_start.find_start(self.samples,
                                                    self.sample_rate)

                if rough_start == 0:
                    self.state = INIT
                    continue

                signal = self.samples[rough_start:]
                if len(signal) < self.prs_len:
                    self.state = PREPARE_FIND_START
                    continue
                fine_freq_offset = auto_correlate.auto_correlate(
                    signal, self.dp, self.sample_rate)

                fine_start, rough_freq_offset = self.correlator.find_rough_freq_offset(
                    signal, -fine_freq_offset)
                signal = signal[fine_start:]
                start = rough_start + fine_start

                freq_offset = rough_freq_offset - fine_freq_offset

                self.shift_signal = numpy.exp(
                    complex(0, -1) * numpy.arange(self.prs_len) * 2 *
                    numpy.pi * freq_offset / float(self.sample_rate))

                self.error_acc = 0

                self.state = SKIP_SAMPLES
                self.skip_samples_count = (start + self.frame_length *
                                           (self.step - 1), 0)
                self.next_state = GET_PRS

            elif self.state == GET_PRS:
                self.state = GET_SAMPLES
                self.count = self.prs_len
                self.samples = numpy.array([], dtype=numpy.complex64)
                self.next_state = PROCESS_PRS
                print "get prs at", self.integer_offset

            elif self.state == PROCESS_PRS:
                signal = self.samples * self.shift_signal
                '''
                fine_freq_offset = auto_correlate.auto_correlate(signal, self.dp, self.sample_rate)
                fine_shift_signal = numpy.exp(complex(0,-1)*numpy.arange(len(signal))*2*numpy.pi*-fine_freq_offset/float(self.sample_rate))
                signal = signal * fine_shift_signal
                '''

                error, cor, phase = self.correlator.estimate_prs_fine(
                    signal[:len(self.prs)], self.fract_offset)
                #print "error:", error
                absolute_start = self.integer_offset + self.fract_offset / 1000. + error
                if self.fract_offset / 1000. + error < 0:
                    print "================================================================"

                self.error_acc += error
                estimated_frame_length = self.frame_length + self.I * self.error_acc + self.P * error
                ppm = (estimated_frame_length -
                       self.frame_length) / self.frame_length * 1e6
                print "estimated_frame_length:", estimated_frame_length, "(", ppm, "ppm)"
                print "absolute_start:", absolute_start
                print "consumed:", self.nitems_read(0)
                print absolute_start + self.history() - 1 - self.nitems_read(0)

                if abs(ppm) > 100:
                    self.state = INIT
                    continue

                key = pmt.string_to_symbol("start_prs")
                fract_offset = (self.fract_offset / 1000. + error) % 1
                value = pmt.from_double(fract_offset)
                self.add_item_tag(0, int(absolute_start), key, value)

                skip = estimated_frame_length * self.step - self.prs_len

                self.state = SKIP_SAMPLES
                self.skip_samples_count = (int(skip),
                                           int((skip - int(skip)) * 1000))
                self.next_state = GET_PRS

            elif self.state == GET_SAMPLES:
                n_input_items = len(in0[consumed:])
                to_consume = min(n_input_items, self.count - len(self.samples))
                self.samples = numpy.concatenate(
                    (self.samples, in0[consumed:consumed + to_consume]))
                consumed += to_consume

                if len(self.samples) < self.count:
                    break

                #self.samples = delay(self.samples, float(self.fract_offset) / self.fract)
                self.state = self.next_state

            elif self.state == SKIP_SAMPLES:
                current_integer_offset = self.nitems_read(0) + consumed
                current_fract_offset = self.fract_offset

                integer_count = self.skip_samples_count[0]
                fract_count = self.skip_samples_count[1]
                assert fract_count < self.fract

                target_integer_offset = current_integer_offset + integer_count + (
                    current_fract_offset + fract_count) / self.fract
                target_fract_offset = (current_fract_offset +
                                       fract_count) % self.fract

                self.count = target_integer_offset - current_integer_offset
                self.fract_offset = target_fract_offset

                self.state = SKIP_SAMPLES_INTERNAL

            elif self.state == SKIP_SAMPLES_INTERNAL:
                n_input_items = len(in0[consumed:])
                to_consume = min(n_input_items, self.count)
                self.count -= to_consume
                consumed += to_consume

                if self.count > 0:
                    break

                self.state = self.next_state

        #XXX: We always consume everything...
        #out0 = in0[:consumed]
        #return consumed

        if self.history() > 1:
            out[:] = input_items[0][:-self.history() + 1]
            #out[:] = in0[self.history()-1:]
        else:
            out0 = in0[:consumed]
        return len(out)
Пример #27
0
    def handler(self, msg):
        meta = pmt.car(msg)
        bits = pmt.cdr(msg)

        self.npkt = self.npkt + 1

        # convert pmt -> int list (of bits)
        data = pmt.u8vector_elements(bits)
        ba = bitarray.bitarray(data)
        datab = ba.tobytes()

        #        print map(lambda x: hex(ord(x)), datab[0:4]);
        #        print 'Received Len Bits= ' + str(len(datab)*8)

        #        print "Rx Packet:" + str(data[0:10]);
        #        print "Rx Packet: "+":".join("{:02x}".format(ord(c)) for c in datab[0:8])
        try:
            (prefix, pktlen) = struct.unpack('<hh', datab[0:4])
            pprint.pprint({
                "prefix": hex(prefix),
                "pktlen": pktlen,
                "pktlen_bytes": pktlen / 8
            })
            if (not (prefix == 0x1337)):
                print "Deframer: BAD PREFIX!"
                return

            # check header crc
            c2 = binascii.crc32(datab[0:4])
            hcrc = struct.unpack('i', datab[4:8])[0]
            #        print "CRC: " + str((c2,hcrc))
            if not (c2 == hcrc):
                print "Deframer: bad header crc"
                return
            self.npkt_hok = self.npkt_hok + 1

            # make sure we got enough bits for the given header len
            if (len(data) < (pktlen / 8 + 8 + 4)):
                print "Deframer: not enough bits received for full payload!"
                print "Deframer: pktlen field = %d, received = %d\n" % (
                    pktlen, len(data))
                return

            if (not (pktlen % 8 == 0)):
                print "Deframer: payload should be a multiple of 8"
                return

            # extract header bytes
            c1 = binascii.crc32(datab[0:8 + pktlen / 8])
            payload = datab[8:8 + pktlen / 8]
            #print "RX Payload len = %d"%(len(payload))
            #print  ":".join("{:02x}".format(ord(c)) for c in datab)
            #        print payload;
            ex_crc2 = datab[(8 + pktlen / 8):(8 + pktlen / 8 + 4)]
        except:
            print 'Not enough data to read! dropping'
            return
        try:
            c1h = struct.unpack('i', ex_crc2)[0]
            #print "rx payload CRC = %d (%s)"%(c1h, ":".join("{:02x}".format(ord(c)) for c in ex_crc2))
        except:
            print "shortened packet length dropping"
            return
#        print "CRC2:" + str((c1, c1h));
        if (not c1 == c1h):
            print "Failed payload CRC"
            return

#        print "BURST OK!"
        self.npkt_ok = self.npkt_ok + 1
        pct_ok = 100.0 * self.npkt_ok / self.npkt
        pct_hok = 100.0 * self.npkt_hok / self.npkt
        print "Deframer: Percent ok = %f (%f header)%%" % (pct_ok, pct_hok)

        # send it on its way
        payload = numpy.fromstring(payload, dtype=numpy.uint8)
        v = pmt.to_pmt(payload)
        meta = pmt.dict_add(meta, pmt.intern("timestamp"),
                            pmt.from_double(time.time()))
        meta = pmt.dict_add(meta, pmt.intern("npkt"), pmt.from_long(self.npkt))
        meta = pmt.dict_add(meta, pmt.intern("npkt_hok"),
                            pmt.from_long(self.npkt_hok))
        meta = pmt.dict_add(meta, pmt.intern("npkt_ok"),
                            pmt.from_long(self.npkt_ok))
        meta = pmt.dict_add(meta, pmt.intern("header_pass_rate"),
                            pmt.from_double(pct_hok))
        meta = pmt.dict_add(meta, pmt.intern("payload_pass_rate"),
                            pmt.from_double(pct_ok))
        pdu = pmt.cons(meta, v)
        self.message_port_pub(pmt.intern("pdus"), pdu)
 def test_003_t (self):
     """
     Like test 1, but twice, plus one fail
     """
     ### Tx Data
     n_zeros = 5
     header = (1, 2, 3)
     header_fail = (-1, -2, -4) # Contents don't really matter
     payload1 = tuple(range(5, 20))
     payload2 = (42,)
     sampling_rate = 2
     data_signal = (0,) * n_zeros + header + payload1
     trigger_signal = [0,] * len(data_signal) * 2
     trigger_signal[n_zeros] = 1
     trigger_signal[len(data_signal)] = 1
     trigger_signal[len(data_signal)+len(header_fail)+n_zeros] = 1
     tx_signal = data_signal + header_fail + (0,) * n_zeros + header + payload2 + (0,) * 1000
     # Timing tag: This is preserved and updated:
     timing_tag = gr.tag_t()
     timing_tag.offset = 0
     timing_tag.key = pmt.string_to_symbol('rx_time')
     timing_tag.value = pmt.to_pmt((0, 0))
     # Rx freq tags:
     rx_freq_tag1 = gr.tag_t()
     rx_freq_tag1.offset = 0
     rx_freq_tag1.key = pmt.string_to_symbol('rx_freq')
     rx_freq_tag1.value = pmt.from_double(1.0)
     rx_freq_tag2 = gr.tag_t()
     rx_freq_tag2.offset = 29
     rx_freq_tag2.key = pmt.string_to_symbol('rx_freq')
     rx_freq_tag2.value = pmt.from_double(1.5)
     rx_freq_tag3 = gr.tag_t()
     rx_freq_tag3.offset = 30
     rx_freq_tag3.key = pmt.string_to_symbol('rx_freq')
     rx_freq_tag3.value = pmt.from_double(2.0)
     ### Flow graph
     data_src = blocks.vector_source_f(
         tx_signal, False,
         tags=(timing_tag, rx_freq_tag1, rx_freq_tag2, rx_freq_tag3)
     )
     trigger_src = blocks.vector_source_b(trigger_signal, False)
     hpd = digital.header_payload_demux(
         header_len=len(header),
         items_per_symbol=1,
         guard_interval=0,
         length_tag_key="frame_len",
         trigger_tag_key="detect",
         output_symbols=False,
         itemsize=gr.sizeof_float,
         timing_tag_key='rx_time',
         samp_rate=sampling_rate,
         special_tags=('rx_freq',),
     )
     self.assertEqual(pmt.length(hpd.message_ports_in()), 2) #extra system port defined for you
     header_sink = blocks.vector_sink_f()
     payload_sink = blocks.vector_sink_f()
     self.tb.connect(data_src,    (hpd, 0))
     self.tb.connect(trigger_src, (hpd, 1))
     self.tb.connect((hpd, 0), header_sink)
     self.tb.connect((hpd, 1), payload_sink)
     self.tb.start()
     time.sleep(.2) # Need this, otherwise, the next message is ignored
     hpd.to_basic_block()._post(
             pmt.intern('header_data'),
             pmt.from_long(len(payload1))
     )
     while len(payload_sink.data()) < len(payload1):
         time.sleep(.2)
     hpd.to_basic_block()._post(
             pmt.intern('header_data'),
             pmt.PMT_F
     )
     # This next command is a bit of a showstopper, but there's no condition to check upon
     # to see if the previous msg handling is finished
     time.sleep(.7)
     hpd.to_basic_block()._post(
             pmt.intern('header_data'),
             pmt.from_long(len(payload2))
     )
     while len(payload_sink.data()) < len(payload1) + len(payload2):
         time.sleep(.2)
     self.tb.stop()
     self.tb.wait()
     # Signal description:
     # 0:  5 zeros
     # 5:  header 1
     # 8:  payload 1 (length: 15)
     # 23: header 2 (fail)
     # 26: 5 zeros
     # 31: header 3
     # 34: payload 2 (length 1)
     # 35: 1000 zeros
     self.assertEqual(header_sink.data(),  header + header_fail + header)
     self.assertEqual(payload_sink.data(), payload1 + payload2)
     tags_payload = [gr.tag_to_python(x) for x in payload_sink.tags()]
     tags_payload = sorted([(x.offset, x.key, x.value) for x in tags_payload])
     tags_expected_payload = [
         (0,             'frame_len', len(payload1)),
         (len(payload1), 'frame_len', len(payload2)),
     ]
     tags_header = [gr.tag_to_python(x) for x in header_sink.tags()]
     tags_header = sorted([(x.offset, x.key, x.value) for x in tags_header])
     tags_expected_header = [
         (0,             'rx_freq', 1.0),
         (0,             'rx_time', (2, 0.5)), # Hard coded time value :( Is n_zeros/sampling_rate
         (len(header),   'rx_freq', 1.0),
         (len(header),   'rx_time', (11, .5)), # Hard coded time value :(. See above.
         (2*len(header), 'rx_freq', 2.0),
         (2*len(header), 'rx_time', (15, .5)), # Hard coded time value :(. See above.
     ]
     self.assertEqual(tags_header, tags_expected_header)
     self.assertEqual(tags_payload, tags_expected_payload)
Пример #29
0
 def test01(self):
     a = pmt.intern("a")
     b = pmt.from_double(123765)
     d1 = pmt.make_dict()
     d2 = pmt.dict_add(d1, a, b)
     print d2
Пример #30
0
def channel_states_tag_create(phase_offset, freq_offset, channel_states):
    return pmt.make_tuple(
        pmt.from_double(phase_offset), pmt.from_double(freq_offset),
        pmt.init_c32vector(len(channel_states), channel_states))
Пример #31
0
 def set_distant_tx_target(self, distant_tx_target):
     self.distant_tx_target = distant_tx_target
     self._distant_tx_target_callback(self.distant_tx_target)
     self.blocks_message_strobe_0_2_0.set_msg(pmt.from_double(self.distant_tx_target))
Пример #32
0
    def handler(self, msg):
        # get input
        meta = pmt.car(msg);
        x = pmt.to_python(pmt.cdr(msg))

        if( self.sps == None and len(self.sps_samps) < 10):
            # compute the cross correlation metric first peak (to find baud rate)
            (clen, ncut) = (500,500)
            e = numpy.zeros(clen*2-1)
            for i in range(1,ncut):
                c = x[i:i+clen]
                d = numpy.correlate(c,c, mode='full')
                e += d

            # upsample to xcorr to interpolate fractional sym rate
            e = e[clen-1:]
            e_upsamp = signal.resample(e, self.upsample_rate*len(e))
            e_upsamp = e_upsamp[:len(e_upsamp)/2]
            #e_upsamp = e_upsamp[0:len(e_upsamp)/2]
            self.message_port_pub(pmt.intern("autocorr"), pmt.cons(meta, pmt.to_pmt(e_upsamp)))
    
            # locate first minimum and next peak (need to see how generalizable this is ... )
            firstmin = numpy.argmin(e_upsamp)
            firstmax = firstmin + numpy.argmax(e_upsamp[firstmin:])

            # determine samples per symbol
            sps = firstmax/self.upsample_rate
            self.sps_samps.append(sps)
            self.sps = numpy.mean(self.sps_samps)
        else:
            sps = self.sps

        meta = pmt.dict_add(meta, pmt.intern("meta"), pmt.from_double(sps));
        print "sps = %f"%(sps)
        
        ovf = []
        ovals = {}
        n_offsets = float(self.n_offsets)
        nsyms = (len(x)/sps)-1
        best = 0
        best_syms = None
        for o in numpy.arange(0,sps,sps/n_offsets):
            syms = signal.resample(x[o:o+nsyms*sps], len(x[o:])*10/(sps))
            syms = syms[0:len(syms)-len(syms)%10]
            syms = syms.reshape( [len(syms)/10, 10] )
            #syms = syms[:,4]
            syms = syms[:,3:7].mean(1)
            dist = numpy.mean(numpy.abs(syms))
            if dist > best:
                best = dist
                best_syms = syms
            ovals[o] = dist
            ovf.append(dist)

        # output timing metric (should look sinusoidal-ish)
        self.message_port_pub(pmt.intern("timing"), pmt.cons(meta, pmt.to_pmt(ovf)))
        best_offset = ovals.keys()[ numpy.argmax(ovals.values()) ]
        meta = pmt.dict_add(meta, pmt.intern("tau"), pmt.from_double(best_offset));

        # publish our recovered symbols
        self.message_port_pub(pmt.intern("pdus"), pmt.cons(meta, pmt.to_pmt(best_syms)))
Пример #33
0
import pmt
import socket
import random

pmt_to_send = pmt.make_dict()

attributes = pmt.make_dict()
attributes = pmt.dict_add(attributes, pmt.string_to_symbol("center_freq"),
                          pmt.from_double(15e6))
attributes = pmt.dict_add(attributes, pmt.string_to_symbol("occ"),
                          pmt.from_double(random.random()))
attributes = pmt.dict_add(attributes, pmt.string_to_symbol("bandwidth"),
                          pmt.from_double(2e6))

psd_list = []
for i in range(0, 10):
    psd_list.append(random.random())

attributes = pmt.dict_add(attributes, pmt.string_to_symbol("psd"),
                          pmt.init_f32vector(10, psd_list))

command = pmt.make_dict()
command = pmt.dict_add(command, pmt.string_to_symbol("table"),
                       pmt.string_to_symbol("spectruminfo"))
command = pmt.dict_add(command, pmt.string_to_symbol("attributes"), attributes)

pmt_to_send = pmt.dict_add(pmt_to_send, pmt.string_to_symbol("INSERT"),
                           command)

attributes = pmt.make_dict()
attributes = pmt.dict_add(attributes, pmt.string_to_symbol("nodeID"),
Пример #34
0
    def __init__(self, args1, args2):
        gr.top_block.__init__(self)

        ##############################
        # TRANSMIT CHAIN
        ##############################
        print "\nTRANSMIT CHAIN"

        ##USRP transmits repeating file generated in MATLAB
        #self.tx_src = blocks.file_source(gr.sizeof_gr_complex, "iq_in.dat", True)

        #USRP transmits a repeating vector generated here...
        tx_list = [
            0.2363 + 0.0741j, 0.0733 - 0.2865j, -0.1035 - 0.2663j,
            -0.0853 + 0.1909j, -0.0736 + 0.2699j, 0.0773 + 0.1481j,
            -0.0336 + 0.2079j, -0.0644 - 0.2244j, 0.0396 + 0.2822j,
            -0.0595 - 0.2416j, 0.1379 + 0.2658j, -0.0449 - 0.2539j,
            0.0593 + 0.2946j, 0.0221 - 0.0113j, -0.1303 + 0.2762j,
            -0.1351 - 0.2598j, -0.0275 - 0.2617j, 0.2157 + 0.1021j,
            0.0332 - 0.0383j, -0.1369 - 0.2680j
        ]
        self.vec_tx_src = blocks.vector_source_c(tuple(tx_list), True,
                                                 SIGNAL_LEN, [])
        self.tx_src = blocks.vector_to_stream(gr.sizeof_gr_complex, SIGNAL_LEN)

        #Find USRP with device characteristics specified by args1
        d1 = uhd.find_devices(uhd.device_addr(args1))
        uhd_type1 = d1[0].get('type')
        print "\nFound '%s' at args '%s'" % \
            (uhd_type1, args1)

        stream_args = uhd.stream_args('fc32')
        self.u_tx = uhd.usrp_sink(device_addr=args1, stream_args=stream_args)
        self.u_tx.set_samp_rate(SAMPLE_RATE)
        self.u_tx.set_clock_source("external")
        self.center_freq = END_FREQ - STEP_FREQ
        self.tr = uhd.tune_request(self.center_freq)
        self.tr.args = uhd.device_addr_t("mode_n=integer")
        self.u_tx.set_center_freq(self.tr)
        self.u_tx.set_bandwidth(SAMPLE_RATE * 1.5)

        # Get dboard gain range and select maximum
        tx_gain_range = self.u_tx.get_gain_range()
        tx_gain = tx_gain_range.stop()
        self.u_tx.set_gain(tx_gain - 9)

        self.connect(self.vec_tx_src, self.tx_src, self.u_tx)

        ##############################
        # RECEIVE CHAIN
        ##############################
        print "\nRECEIVE CHAIN"

        #USRP logs IQ data to file
        #This PMT dictionary stuff is stupid, however it's required otherwise the header will become corrupted...
        key = pmt.intern("rx_freq")
        val = pmt.from_double(0)
        extras = pmt.make_dict()
        extras = pmt.dict_add(extras, key, val)
        extras = pmt.serialize_str(extras)

        self.tag_debug = None
        self.u_rxs = []

        for usrp_addr in args2.split(","):
            kv = usrp_addr.split("=")
            rx_dst = blocks.file_meta_sink(
                gr.sizeof_gr_complex * SIGNAL_LEN,
                "iq_out_{}.dat".format(kv[1]),
                SAMPLE_RATE,
                extra_dict=extras)  #, detached_header=True)
            #rx_dst = blocks.file_sink(gr.sizeof_gr_complex*SIGNAL_LEN, "iq_out.dat")

            # Accumulate repeating sequences using custom block
            rx_accum = slocalization.accumulator_vcvc(SIGNAL_LEN, int(1e3))

            #Find USRP with device characteristics specified by args1
            d2 = uhd.find_devices(uhd.device_addr(usrp_addr))
            uhd_type2 = d2[0].get('type')
            print "\nFound '%s' at args '%s'" % \
                (uhd_type2, usrp_addr)

            u_rx = uhd.usrp_source(device_addr=usrp_addr,
                                   io_type=uhd.io_type.COMPLEX_FLOAT32,
                                   num_channels=1)
            u_rx.set_samp_rate(SAMPLE_RATE)
            u_rx.set_bandwidth(SAMPLE_RATE * 1.5)
            u_rx.set_clock_source("external")
            u_rx.set_center_freq(self.tr)
            self.u_rxs.append(u_rx)

            # Get dboard gain range and select maximum
            rx_gain_range = u_rx.get_gain_range()
            rx_gain = rx_gain_range.stop()
            u_rx.set_gain(rx_gain, 0)

            # Convert stream to vector
            s_to_v = blocks.stream_to_vector(gr.sizeof_gr_complex, SIGNAL_LEN)

            self.connect(u_rx, s_to_v, rx_accum, rx_dst)
            #self.connect (u_rx, s_to_v, rx_dst)

            if not self.tag_debug:
                # DEBUG: Monitor incoming tags...
                self.tag_debug = blocks.tag_debug(
                    gr.sizeof_gr_complex * SIGNAL_LEN, "tag_debugger", "")
                self.connect(rx_accum, self.tag_debug)

            # Synchronize both USRPs' timebases
            u_rx.set_time_now(uhd.time_spec(0.0))

        # Synchronize both USRPs' timebases
        self.u_tx.set_time_now(uhd.time_spec(0.0))
Пример #35
0
def propagate_headers(options,args):
    infile = args[0]
    outfile = args[1]
    infile_hdr = infile + '.hdr'
    outfile_hdr = outfile + '.hdr'
    sample_cnt_end = 0
    sample_offset = long(options.start)
        # Open input header
    try:
        handle_in = open(infile_hdr, "rb")
    except IOError:
        sys.stderr.write("Unable to open input file header\n")
        sys.exit(1)
    # Open output header
    try:
        handle_out = open(outfile_hdr, "wb")
    except IOError:
        sys.stderr.write("Unable to open output file header\n")
        sys.exit(1)

    # Read first header separately to get file type
    hdr_in, hdr_extra_in, handle_in = read_single_header(handle_in)
    info_in = parse_file_metadata.parse_header(hdr_in,False)
    sample_cnt_end += info_in["nitems"]
    # Parse file type - ensure support for it
    shortname_intype = find_shortname(info_in['cplx'], info_in['type'],
                info_in['size'])
    if shortname_intype == SNAME_TO_ENUM["unknown"]:
        sys.stderr.write("Unsupported data type\n")
        sys.exit(1)
    if options.output_type == 'unknown':
        shortname_outtype = shortname_intype
    else:
        shortname_outtype = SNAME_TO_ENUM[options.output_type]

    # Calc sample_len from file size if not specified
    if options.nsamples is not None:
        sample_len = long(options.nsamples)
	final_index = sample_offset + sample_len
    else:
        sample_len = os.path.getsize(infile)/SNAME_DEFS[shortname_intype][0]
	final_index = sample_len

    # Search input headers until we find the correct one
    while sample_cnt_end <= sample_offset:
        hdr_in, hdr_extra_in, handle_in = read_single_header(handle_in)
        info_in = parse_file_metadata.parse_header(hdr_in,False)
        sample_cnt_end += info_in["nitems"]
    time_in = info_in["rx_time"]
    # Starting sample of current segment
    sample_cnt_start = sample_cnt_end - info_in["nitems"]
    # Interpolate new timestamp
    delta = sample_offset - sample_cnt_start
    new_ts = time_in + delta/info_in["rx_rate"]
    # Calc new segment size (samples)
    if sample_cnt_end > final_index:
        first_seg_len = final_index - sample_offset
    else:
        first_seg_len = sample_cnt_end - sample_offset
    
    # Write the first output header
    hdr_out = hdr_in
    new_secs = long(new_ts)
    new_fracs = new_ts - new_secs
    time_val = pmt.make_tuple(pmt.from_uint64(new_secs),
            pmt.from_double(new_fracs))
    size_val = pmt.from_long(SNAME_DEFS[shortname_outtype][0])
    bytes_val = pmt.from_uint64(first_seg_len*SNAME_DEFS[shortname_outtype][0])
    type_val = pmt.from_long(SNAME_DEFS[shortname_outtype][2])
    hdr_out = pmt.dict_add(hdr_out, pmt.intern("rx_time"), time_val)
    hdr_out = pmt.dict_add(hdr_out, pmt.intern("bytes"), bytes_val)
    hdr_out = pmt.dict_add(hdr_out, pmt.intern("type"), type_val)
    hdr_out = pmt.dict_add(hdr_out, pmt.intern("size"), size_val)
    hdr_out_str = pmt.serialize_str(hdr_out) + pmt.serialize_str(hdr_extra_in)    
    handle_out.write(hdr_out_str)

    # Continue reading headers, modifying, and writing 
    last_seg_len = info_in['nitems']
    print "sample_cnt_end=%d,final_index=%d" % (sample_cnt_end,final_index)
    # Iterate through remaining headers
    while sample_cnt_end < final_index:
        hdr_in, hdr_extra_in, handle_in = read_single_header(handle_in)
        info_in = parse_file_metadata.parse_header(hdr_in,False)
        nitems = info_in["nitems"]
        sample_cnt_start = sample_cnt_end
        sample_cnt_end += nitems
        hdr_out = hdr_in
        # For last header, adjust segment length accordingly
        if sample_cnt_end > final_index:
            last_seg_len = final_index - sample_cnt_start
        else:
            last_seg_len = nitems
        size_val = pmt.from_long(SNAME_DEFS[shortname_outtype][0])
        bytes_val = pmt.from_uint64(last_seg_len*SNAME_DEFS[shortname_outtype][0])
        type_val = pmt.from_long(SNAME_DEFS[shortname_outtype][2])
        hdr_out = pmt.dict_add(hdr_out, pmt.intern("bytes"), bytes_val)
        hdr_out = pmt.dict_add(hdr_out, pmt.intern("type"), type_val)
        hdr_out = pmt.dict_add(hdr_out, pmt.intern("size"), size_val)
        hdr_out_str = pmt.serialize_str(hdr_out) + pmt.serialize_str(hdr_extra_in)
        handle_out.write(hdr_out_str)
        
    if options.verbose:
        print 'Input File:' + infile
        print 'Input Header:' + infile_hdr
        print 'Input Type:' + ENUM_TO_SNAME[shortname_intype]
        print 'Output File:' + outfile
        print 'Output File Length (Samples):%d' % (final_index-sample_offset)
        print 'Output Header:' + outfile_hdr
        print 'File subsection: [%d,%d]' % (sample_offset,final_index)
        print 'Output Type:' + ENUM_TO_SNAME[shortname_outtype]
        print 'First Segment Length: %e samples' % first_seg_len
        print 'Last Segment Length: %e samples' % last_seg_len
        print 'delta=%f,new ts=%f' % (delta,new_ts)

    # Clean up
    handle_in.close()
    handle_out.close()

    # Return header info
    return {'infile':infile,'intype':shortname_intype,'outfile':outfile,
            'outtype':shortname_outtype,'sample_offset':sample_offset,
            'sample_len':sample_len}
Пример #36
0
 def test_003_t(self):
     """
     Like test 1, but twice, plus one fail
     """
     ### Tx Data
     n_zeros = 5
     header = (1, 2, 3)
     header_fail = (-1, -2, -4)  # Contents don't really matter
     payload1 = tuple(range(5, 20))
     payload2 = (42, )
     sampling_rate = 2
     data_signal = (0, ) * n_zeros + header + payload1
     trigger_signal = [
         0,
     ] * len(data_signal) * 2
     trigger_signal[n_zeros] = 1
     trigger_signal[len(data_signal)] = 1
     trigger_signal[len(data_signal) + len(header_fail) + n_zeros] = 1
     tx_signal = data_signal + header_fail + (
         0, ) * n_zeros + header + payload2 + (0, ) * 1000
     # Timing tag: This is preserved and updated:
     timing_tag = gr.tag_t()
     timing_tag.offset = 0
     timing_tag.key = pmt.string_to_symbol('rx_time')
     timing_tag.value = pmt.to_pmt((0, 0))
     # Rx freq tags:
     rx_freq_tag1 = gr.tag_t()
     rx_freq_tag1.offset = 0
     rx_freq_tag1.key = pmt.string_to_symbol('rx_freq')
     rx_freq_tag1.value = pmt.from_double(1.0)
     rx_freq_tag2 = gr.tag_t()
     rx_freq_tag2.offset = 29
     rx_freq_tag2.key = pmt.string_to_symbol('rx_freq')
     rx_freq_tag2.value = pmt.from_double(1.5)
     rx_freq_tag3 = gr.tag_t()
     rx_freq_tag3.offset = 30
     rx_freq_tag3.key = pmt.string_to_symbol('rx_freq')
     rx_freq_tag3.value = pmt.from_double(2.0)
     ### Flow graph
     data_src = blocks.vector_source_f(tx_signal,
                                       False,
                                       tags=(timing_tag, rx_freq_tag1,
                                             rx_freq_tag2, rx_freq_tag3))
     trigger_src = blocks.vector_source_b(trigger_signal, False)
     hpd = digital.header_payload_demux(
         header_len=len(header),
         items_per_symbol=1,
         guard_interval=0,
         length_tag_key="frame_len",
         trigger_tag_key="detect",
         output_symbols=False,
         itemsize=gr.sizeof_float,
         timing_tag_key='rx_time',
         samp_rate=sampling_rate,
         special_tags=('rx_freq', ),
     )
     self.assertEqual(pmt.length(hpd.message_ports_in()),
                      2)  #extra system port defined for you
     header_sink = blocks.vector_sink_f()
     payload_sink = blocks.vector_sink_f()
     self.tb.connect(data_src, (hpd, 0))
     self.tb.connect(trigger_src, (hpd, 1))
     self.tb.connect((hpd, 0), header_sink)
     self.tb.connect((hpd, 1), payload_sink)
     self.tb.start()
     time.sleep(.2)  # Need this, otherwise, the next message is ignored
     hpd.to_basic_block()._post(pmt.intern('header_data'),
                                pmt.from_long(len(payload1)))
     while len(payload_sink.data()) < len(payload1):
         time.sleep(.2)
     hpd.to_basic_block()._post(pmt.intern('header_data'), pmt.PMT_F)
     # This next command is a bit of a showstopper, but there's no condition to check upon
     # to see if the previous msg handling is finished
     time.sleep(.7)
     hpd.to_basic_block()._post(pmt.intern('header_data'),
                                pmt.from_long(len(payload2)))
     while len(payload_sink.data()) < len(payload1) + len(payload2):
         time.sleep(.2)
     self.tb.stop()
     self.tb.wait()
     # Signal description:
     # 0:  5 zeros
     # 5:  header 1
     # 8:  payload 1 (length: 15)
     # 23: header 2 (fail)
     # 26: 5 zeros
     # 31: header 3
     # 34: payload 2 (length 1)
     # 35: 1000 zeros
     self.assertEqual(header_sink.data(), header + header_fail + header)
     self.assertEqual(payload_sink.data(), payload1 + payload2)
     tags_payload = [gr.tag_to_python(x) for x in payload_sink.tags()]
     tags_payload = sorted([(x.offset, x.key, x.value)
                            for x in tags_payload])
     tags_expected_payload = [
         (0, 'frame_len', len(payload1)),
         (len(payload1), 'frame_len', len(payload2)),
     ]
     tags_header = [gr.tag_to_python(x) for x in header_sink.tags()]
     tags_header = sorted([(x.offset, x.key, x.value) for x in tags_header])
     tags_expected_header = [
         (0, 'rx_freq', 1.0),
         (0, 'rx_time',
          (2, 0.5)),  # Hard coded time value :( Is n_zeros/sampling_rate
         (len(header), 'rx_freq', 1.0),
         (len(header), 'rx_time',
          (11, .5)),  # Hard coded time value :(. See above.
         (2 * len(header), 'rx_freq', 2.0),
         (2 * len(header), 'rx_time',
          (15, .5)),  # Hard coded time value :(. See above.
     ]
     self.assertEqual(tags_header, tags_expected_header)
     self.assertEqual(tags_payload, tags_expected_payload)
Пример #37
0
 def test01(self):
     a = pmt.intern("a")
     b = pmt.from_double(123765)
     d1 = pmt.make_dict()
     d2 = pmt.dict_add(d1, a, b)
     print(d2)
Пример #38
0
    def __init__(self):
        gr.top_block.__init__(self, "Test Shift And Measure")
        Qt.QWidget.__init__(self)
        self.setWindowTitle("Test Shift And Measure")
        try:
            self.setWindowIcon(Qt.QIcon.fromTheme("gnuradio-grc"))
        except:
            pass
        self.top_scroll_layout = Qt.QVBoxLayout()
        self.setLayout(self.top_scroll_layout)
        self.top_scroll = Qt.QScrollArea()
        self.top_scroll.setFrameStyle(Qt.QFrame.NoFrame)
        self.top_scroll_layout.addWidget(self.top_scroll)
        self.top_scroll.setWidgetResizable(True)
        self.top_widget = Qt.QWidget()
        self.top_scroll.setWidget(self.top_widget)
        self.top_layout = Qt.QVBoxLayout(self.top_widget)
        self.top_grid_layout = Qt.QGridLayout()
        self.top_layout.addLayout(self.top_grid_layout)

        self.settings = Qt.QSettings("GNU Radio", "test_shift_and_measure")
        self.restoreGeometry(self.settings.value("geometry").toByteArray())

        ##################################################
        # Variables
        ##################################################
        self.samp_rate = samp_rate = 100000000 / 64
        self.cal_tone_freq = cal_tone_freq = 1024
        self.vec_size = vec_size = int(2 ** (numpy.ceil(numpy.log(samp_rate / cal_tone_freq) / numpy.log(2))))
        self.variable_qtgui_range_0_0 = variable_qtgui_range_0_0 = 0
        self.variable_qtgui_range_0 = variable_qtgui_range_0 = 0
        self.variable_qtgui_chooser_0_1_0 = variable_qtgui_chooser_0_1_0 = 1

        ##################################################
        # Blocks
        ##################################################
        self._variable_qtgui_chooser_0_1_0_options = (1, 0)
        self._variable_qtgui_chooser_0_1_0_labels = ("Stop", "Running")
        self._variable_qtgui_chooser_0_1_0_tool_bar = Qt.QToolBar(self)
        self._variable_qtgui_chooser_0_1_0_tool_bar.addWidget(Qt.QLabel("Sync System" + ": "))
        self._variable_qtgui_chooser_0_1_0_combo_box = Qt.QComboBox()
        self._variable_qtgui_chooser_0_1_0_tool_bar.addWidget(self._variable_qtgui_chooser_0_1_0_combo_box)
        for label in self._variable_qtgui_chooser_0_1_0_labels:
            self._variable_qtgui_chooser_0_1_0_combo_box.addItem(label)
        self._variable_qtgui_chooser_0_1_0_callback = lambda i: Qt.QMetaObject.invokeMethod(
            self._variable_qtgui_chooser_0_1_0_combo_box,
            "setCurrentIndex",
            Qt.Q_ARG("int", self._variable_qtgui_chooser_0_1_0_options.index(i)),
        )
        self._variable_qtgui_chooser_0_1_0_callback(self.variable_qtgui_chooser_0_1_0)
        self._variable_qtgui_chooser_0_1_0_combo_box.currentIndexChanged.connect(
            lambda i: self.set_variable_qtgui_chooser_0_1_0(self._variable_qtgui_chooser_0_1_0_options[i])
        )
        self.top_layout.addWidget(self._variable_qtgui_chooser_0_1_0_tool_bar)
        self._variable_qtgui_range_0_0_range = Range(-800, 800, 1, 0, 200)
        self._variable_qtgui_range_0_0_win = RangeWidget(
            self._variable_qtgui_range_0_0_range,
            self.set_variable_qtgui_range_0_0,
            "variable_qtgui_range_0_0",
            "counter_slider",
            int,
        )
        self.top_layout.addWidget(self._variable_qtgui_range_0_0_win)
        self._variable_qtgui_range_0_range = Range(-800, 800, 1, 0, 200)
        self._variable_qtgui_range_0_win = RangeWidget(
            self._variable_qtgui_range_0_range,
            self.set_variable_qtgui_range_0,
            "variable_qtgui_range_0",
            "counter_slider",
            int,
        )
        self.top_layout.addWidget(self._variable_qtgui_range_0_win)
        self.qtgui_time_sink_x_0_0 = qtgui.time_sink_f(1000, 1, "", 2)  # size  # samp_rate  # name  # number of inputs
        self.qtgui_time_sink_x_0_0.set_update_time(0.10)
        self.qtgui_time_sink_x_0_0.set_y_axis(-0.003, 0.003)

        self.qtgui_time_sink_x_0_0.set_y_label("Amplitude", "")

        self.qtgui_time_sink_x_0_0.enable_tags(-1, True)
        self.qtgui_time_sink_x_0_0.set_trigger_mode(qtgui.TRIG_MODE_AUTO, qtgui.TRIG_SLOPE_POS, 0.0, 0, 0, "")
        self.qtgui_time_sink_x_0_0.enable_autoscale(True)
        self.qtgui_time_sink_x_0_0.enable_grid(False)
        self.qtgui_time_sink_x_0_0.enable_control_panel(True)

        if not True:
            self.qtgui_time_sink_x_0_0.disable_legend()

        labels = ["", "", "", "", "", "", "", "", "", ""]
        widths = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
        colors = ["blue", "red", "green", "black", "cyan", "magenta", "yellow", "dark red", "dark green", "blue"]
        styles = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
        markers = [-1, -1, -1, -1, -1, -1, -1, -1, -1, -1]
        alphas = [1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0]

        for i in xrange(2):
            if len(labels[i]) == 0:
                self.qtgui_time_sink_x_0_0.set_line_label(i, "Data {0}".format(i))
            else:
                self.qtgui_time_sink_x_0_0.set_line_label(i, labels[i])
            self.qtgui_time_sink_x_0_0.set_line_width(i, widths[i])
            self.qtgui_time_sink_x_0_0.set_line_color(i, colors[i])
            self.qtgui_time_sink_x_0_0.set_line_style(i, styles[i])
            self.qtgui_time_sink_x_0_0.set_line_marker(i, markers[i])
            self.qtgui_time_sink_x_0_0.set_line_alpha(i, alphas[i])

        self._qtgui_time_sink_x_0_0_win = sip.wrapinstance(self.qtgui_time_sink_x_0_0.pyqwidget(), Qt.QWidget)
        self.top_layout.addWidget(self._qtgui_time_sink_x_0_0_win)
        self.qtgui_time_sink_x_0 = qtgui.time_sink_f(
            1024, samp_rate, "", 1  # size  # samp_rate  # name  # number of inputs
        )
        self.qtgui_time_sink_x_0.set_update_time(0.10)
        self.qtgui_time_sink_x_0.set_y_axis(-1, 1)

        self.qtgui_time_sink_x_0.set_y_label("Amplitude", "")

        self.qtgui_time_sink_x_0.enable_tags(-1, True)
        self.qtgui_time_sink_x_0.set_trigger_mode(qtgui.TRIG_MODE_FREE, qtgui.TRIG_SLOPE_POS, 0.0, 0, 0, "")
        self.qtgui_time_sink_x_0.enable_autoscale(False)
        self.qtgui_time_sink_x_0.enable_grid(False)
        self.qtgui_time_sink_x_0.enable_control_panel(False)

        if not True:
            self.qtgui_time_sink_x_0.disable_legend()

        labels = ["", "", "", "", "", "", "", "", "", ""]
        widths = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
        colors = ["blue", "red", "green", "black", "cyan", "magenta", "yellow", "dark red", "dark green", "blue"]
        styles = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
        markers = [-1, -1, -1, -1, -1, -1, -1, -1, -1, -1]
        alphas = [1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0]

        for i in xrange(1):
            if len(labels[i]) == 0:
                self.qtgui_time_sink_x_0.set_line_label(i, "Data {0}".format(i))
            else:
                self.qtgui_time_sink_x_0.set_line_label(i, labels[i])
            self.qtgui_time_sink_x_0.set_line_width(i, widths[i])
            self.qtgui_time_sink_x_0.set_line_color(i, colors[i])
            self.qtgui_time_sink_x_0.set_line_style(i, styles[i])
            self.qtgui_time_sink_x_0.set_line_marker(i, markers[i])
            self.qtgui_time_sink_x_0.set_line_alpha(i, alphas[i])

        self._qtgui_time_sink_x_0_win = sip.wrapinstance(self.qtgui_time_sink_x_0.pyqwidget(), Qt.QWidget)
        self.top_layout.addWidget(self._qtgui_time_sink_x_0_win)
        self.delay_correct_hier_1 = delay_correct_hier(cal_tone_freq=1024 * 10, mu=0.0001, samp_rate=samp_rate)
        self.top_layout.addWidget(self.delay_correct_hier_1)
        self.blocks_throttle_0_0 = blocks.throttle(gr.sizeof_gr_complex * 1, samp_rate / 1000, True)
        self.blocks_throttle_0 = blocks.throttle(gr.sizeof_gr_complex * 1, samp_rate / 1000, True)
        self.blocks_message_strobe_0 = blocks.message_strobe(pmt.from_double(variable_qtgui_chooser_0_1_0), 1000)
        self.blocks_file_source_0_0 = blocks.file_source(
            gr.sizeof_gr_complex * 1,
            "/home/travis/Dropbox/PHD/WiFiUS/doa/gnuradio/gr-wifius/data/channel0_complex_1_6_2015.bin",
            True,
        )
        self.blocks_file_source_0 = blocks.file_source(
            gr.sizeof_gr_complex * 1,
            "/home/travis/Dropbox/PHD/WiFiUS/doa/gnuradio/gr-wifius/data/channel1_complex_1_6_2015.bin",
            True,
        )
        self.blocks_complex_to_real_0_0 = blocks.complex_to_real(1)
        self.blocks_complex_to_real_0 = blocks.complex_to_real(1)

        ##################################################
        # Connections
        ##################################################
        self.msg_connect((self.blocks_message_strobe_0, "strobe"), (self.delay_correct_hier_1, "enable_sync"))
        self.connect((self.blocks_complex_to_real_0, 0), (self.qtgui_time_sink_x_0_0, 1))
        self.connect((self.blocks_complex_to_real_0_0, 0), (self.qtgui_time_sink_x_0_0, 0))
        self.connect((self.blocks_file_source_0, 0), (self.blocks_throttle_0, 0))
        self.connect((self.blocks_file_source_0_0, 0), (self.blocks_throttle_0_0, 0))
        self.connect((self.blocks_throttle_0, 0), (self.delay_correct_hier_1, 0))
        self.connect((self.blocks_throttle_0_0, 0), (self.blocks_complex_to_real_0_0, 0))
        self.connect((self.blocks_throttle_0_0, 0), (self.delay_correct_hier_1, 1))
        self.connect((self.delay_correct_hier_1, 0), (self.blocks_complex_to_real_0, 0))
        self.connect((self.delay_correct_hier_1, 1), (self.qtgui_time_sink_x_0, 0))
Пример #39
0
context = zmq.Context()
socket = context.socket(zmq.PUB)
socket.bind("tcp://127.0.0.1:50001")

# Note: this number is still being refined, and depends on the baseline.
# Note: it can jump by 100ns due to PPS/10MHz phase drift
fixed_delay = {}
fixed_delay[('1a', '4g')] = -750.8 * u.ns
fixed_delay[('1c', '4g')] = -750.8 * u.ns - 147.2 * u.ns
fixed_delay[('1h', '4g')] = -750.8 * u.ns + 26.6 * u.ns
fixed_delay[('2b', '4g')] = 33.46 * 20 * u.ns

source = SkyCoord(ra=float(sys.argv[1]) * u.deg,
                  dec=float(sys.argv[2]) * u.deg)
ant_a = sys.argv[3].lower()
ant_b = sys.argv[4].lower()

baseline = EarthLocation((ant_pos[ant_b][0] - ant_pos[ant_a][0]) * u.m,
                         (ant_pos[ant_b][1] - ant_pos[ant_a][1]) * u.m,
                         (ant_pos[ant_b][2] - ant_pos[ant_a][2]) * u.m)

while True:
    obstime = Time.now()
    baseline_projected = \
        baseline.get_gcrs(obstime).cartesian.xyz.T.dot(source.cartesian.xyz)
    delay = baseline_projected / c + fixed_delay[(ant_b, ant_a)]
    msg = pmt.cons(pmt.intern("delay"), pmt.from_double(delay.value))
    sb = pmt.serialize_str(msg)
    socket.send(sb)
    time.sleep(0.5)
Пример #40
0
 def __init__(
         self,
         n_bursts, n_channels,
         freq_delta, base_freq, dsp_tuning,
         burst_length, base_time, hop_time,
         post_tuning=False,
         tx_gain=0,
         verbose=False
     ):
     gr.hier_block2.__init__(
         self, "FrequencyHopperSrc",
         gr.io_signature(1, 1, gr.sizeof_gr_complex),
         gr.io_signature(1, 1, gr.sizeof_gr_complex),
     )
     n_samples_total = n_bursts * burst_length
     lowest_frequency = base_freq - numpy.floor(n_channels/2) * freq_delta
     self.hop_sequence = [lowest_frequency + n * freq_delta for n in range(n_channels)]
     numpy.random.shuffle(self.hop_sequence)
     # Repeat that:
     self.hop_sequence = [self.hop_sequence[x % n_channels] for x in range(n_bursts)]
     if verbose:
         print("Hop Frequencies  | Hop Pattern")
         print("=================|================================")
         for f in self.hop_sequence:
             print("{:6.3f} MHz      |  ".format(f/1e6), end='')
             if n_channels < 50:
                 print(" " * int((f - base_freq) / freq_delta) + "#")
             else:
                 print("\n")
         print("=================|================================")
     # There's no real point in setting the gain via tag for this application,
     # but this is an example to show you how to do it.
     gain_tag = gr.tag_t()
     gain_tag.offset = 0
     gain_tag.key = pmt.string_to_symbol('tx_command')
     gain_tag.value = pmt.to_pmt({'gain': tx_gain})
     tag_list = [gain_tag,]
     for i in range(len(self.hop_sequence)):
         time = pmt.cons(
             pmt.from_uint64(int(base_time + i * hop_time+0.01)),
             pmt.from_double((base_time + i * hop_time+0.01) % 1),
         )
         tune_tag = gr.tag_t()
         tune_tag.offset = i * burst_length
         # TODO dsp_tuning should also be able to do post_tuning
         if i > 0 and post_tuning and not dsp_tuning:
             tune_tag.offset -= 1 # Move it to last sample of previous burst
         if dsp_tuning:
             tune_tag.key = pmt.string_to_symbol('tx_command')
             tune_tag.value = pmt.to_pmt({'lo_freq': base_freq, 'dsp_freq': base_freq - self.hop_sequence[i]})
             tune_tag.value = pmt.dict_add(tune_tag.value, pmt.intern("time"),time)
         else:
             tune_tag.key = pmt.string_to_symbol('tx_command')
             tune_tag.value = pmt.to_pmt({'freq': self.hop_sequence[i]})
             tune_tag.value = pmt.dict_add(tune_tag.value, pmt.intern('time'), time)
         tag_list.append(tune_tag)
         length_tag = gr.tag_t()
         length_tag.offset = i * burst_length
         length_tag.key = pmt.string_to_symbol('packet_len')
         length_tag.value = pmt.from_long(burst_length)
         tag_list.append(length_tag)
         time_tag = gr.tag_t()
         time_tag.offset = i * burst_length
         time_tag.key = pmt.string_to_symbol('tx_time')
         time_tag.value = pmt.make_tuple(
                 pmt.car(time),
                 pmt.cdr(time)
         )
         tag_list.append(time_tag)
     tag_source = blocks.vector_source_c((1.0,) * n_samples_total, repeat=False, tags=tag_list)
     mult = blocks.multiply_cc()
     self.connect(self, mult, self)
     self.connect(tag_source, (mult, 1))
Пример #41
0
    sys.stderr.write(
        'Not enough arguments: usrp_source_controller.py [options] <command> <value>\n'
    )
    sys.stderr.write(
        'See the "UHD Interface" section of the manual for available commands.\n\n'
    )
    sys.exit(1)

port = 'command'
alias = options.alias
hostname = options.host
portnum = options.port
cmd = args[0]
val = args[1]

if (cmd == "tune" or cmd == "time"):
    sys.stderr.write(
        "This application currently does not support the 'tune' or 'time' UHD "
        "message commands.\n\n")
    sys.exit(1)
if (cmd == "antenna"):
    val = pmt.intern(val)
else:
    val = pmt.from_double(float(val))

argv = [None, hostname, portnum]
radiosys = GNURadioControlPortClient(argv=argv, rpcmethod='thrift')
radio = radiosys.client

radio.postMessage(alias, port, pmt.cons(pmt.intern(cmd), val))
Пример #42
0
    def test_009_dual_tags_nostore(self):
        '''
        This test has 2 sources each with tags 
        '''
        src_tag1 = gr.tag_utils.python_to_tag([
            0,
            pmt.intern("sam"),
            pmt.from_double(10000),
            pmt.intern("test_003_tags")
        ])
        src_tag2 = gr.tag_utils.python_to_tag([
            1,
            pmt.intern("peter"),
            pmt.from_double(1000),
            pmt.intern("test_003_tags")
        ])
        src_tag3 = gr.tag_utils.python_to_tag([
            2,
            pmt.intern("jacob"),
            pmt.from_double(100),
            pmt.intern("test_003_tags")
        ])
        src_tag4 = gr.tag_utils.python_to_tag([
            2,
            pmt.intern("chip"),
            pmt.from_double(10),
            pmt.intern("test_003_tags")
        ])
        src_tag5 = gr.tag_utils.python_to_tag([
            2,
            pmt.intern("josh"),
            pmt.from_double(1),
            pmt.intern("test_003_tags")
        ])

        src_data = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
        src1 = blocks.vector_source_i(src_data, False, 1,
                                      [src_tag1, src_tag2, src_tag3])
        src2 = blocks.vector_source_i(src_data, False, 1, [src_tag4, src_tag5])
        dut = sandia_utils.sandia_tag_debug(gr.sizeof_int, "tag QA", "", False)
        self.tb.connect(src1, (dut, 0))
        self.tb.connect(src2, (dut, 1))

        self.tb.run()

        self.assertEqual(5, dut.num_tags())

        tag0 = dut.get_tag(0)
        tag1 = dut.get_tag(1)
        tag2 = dut.get_tag(2)
        tag3 = dut.get_tag(3)
        tag4 = dut.get_tag(4)

        self.assertTrue(pmt.eq(tag0.key, pmt.intern("sam")))
        self.assertAlmostEqual(10000, pmt.to_double(tag0.value))

        self.assertTrue(pmt.eq(tag1.key, pmt.intern("peter")))
        self.assertAlmostEqual(1000, pmt.to_double(tag1.value))

        self.assertTrue(pmt.eq(tag2.key, pmt.intern("jacob")))
        self.assertAlmostEqual(100, pmt.to_double(tag2.value))

        self.assertTrue(pmt.eq(tag3.key, pmt.intern("chip")))
        self.assertAlmostEqual(10, pmt.to_double(tag3.value))

        self.assertTrue(pmt.eq(tag4.key, pmt.intern("josh")))
        self.assertAlmostEqual(1, pmt.to_double(tag4.value))

        self.tb.stop()
        self.tb.wait()
Пример #43
0
parser = ArgumentParser()
parser.add_argument("-H", "--host", default="localhost",
                  help="Hostname to connect to (default=%(default)r)")
parser.add_argument("-p", "--port", type=int, default=9090,
                  help="Port of Controlport instance on host (default=%(default)r)")
parser.add_argument("-a", "--alias", default="gr uhd usrp sink0",
                  help="The UHD block's alias to control (default=%(default)r)")
parser.add_argument("command", metavar="COMMAND")
parser.add_argument("value", metavar="VALUE")
args = parser.parse_args()

port = 'command'
cmd = args.command
val = args.value

if(cmd == "tune" or cmd == "time"):
    sys.stderr.write("This application currently does not support the 'tune' or 'time' UHD "
                     "message commands.\n\n")
    sys.exit(1)
elif(cmd == "antenna"):
    val = pmt.intern(val)
else:
    val = pmt.from_double(float(val))

argv = [None, args.host, args.port]
radiosys = GNURadioControlPortClient(argv=argv, rpcmethod='thrift')
radio = radiosys.client

radio.postMessage(args.alias, port, pmt.cons(pmt.intern(cmd), val))
Пример #44
0
import pmt
from gnuradio.ctrlport.GNURadioControlPortClient import GNURadioControlPortClient

args = sys.argv
if (len(args) < 4):
    sys.stderr.write(
        'Not enough arguments: usrp_source_controller.py <host> <port> <command> <value>\n'
    )
    sys.stderr.write(
        'See the "UHD Interface" section of the manual for available commands.\n\n'
    )
    sys.exit(1)

alias = 'usrp_source0'
port = 'command'

hostname = args[1]
portnum = int(args[2])
cmd = args[3].lower()

if (cmd == "antenna"):
    val = pmt.intern(args[4])
else:
    val = pmt.from_double(float(args[4]))

argv = [None, hostname, portnum]
radiosys = GNURadioControlPortClient(argv=argv, rpcmethod='thrift')
radio = radiosys.client

radio.postMessage(alias, port, pmt.cons(pmt.intern(cmd), val))
Пример #45
0
    def __init__(
        self,
        channel_dir,
        start=None,
        end=None,
        repeat=False,
        gapless=False,
        min_chunksize=None,
    ):
        """Read a channel of data from a Digital RF directory.

        In addition to outputting samples from Digital RF format data, this
        block also emits a 'properties' message containing inherent channel
        properties and adds stream tags using the channel's accompanying
        Digital Metadata. See the Notes section for details on what the
        messages and stream tags contain.


        Parameters
        ----------
        channel_dir : string | list of strings
            Either a single channel directory containing 'drf_properties.h5'
            and timestamped subdirectories with Digital RF files, or a list of
            such. A directory can be a file system path or a url, where the url
            points to a channel directory. Each must be a local path, or start
            with 'http://'', 'file://'', or 'ftp://''.


        Other Parameters
        ----------------
        start : None | int | float | string, optional
            A value giving the start of the channel's playback.
            If None or '', the start of the channel's available data is used.
            If an integer, it is interpreted as a sample index given in the
            number of samples since the epoch (time_since_epoch*sample_rate).
            If a float, it is interpreted as a UTC timestamp (seconds since
            epoch).
            If a string, four forms are permitted:
                1) a string which can be evaluated to an integer/float and
                    interpreted as above,
                2) a string beginning with '+' and followed by an integer
                    (float) expression, interpreted as samples (seconds) from
                    the start of the data, and
                3) a time in ISO8601 format, e.g. '2016-01-01T16:24:00Z'
                4) 'now' ('nowish'), indicating the current time (rounded up)

        end : None | int | float | string, optional
            A value giving the end of the channel's playback.
            If None or '', the end of the channel's available data is used.
            See `start` for a description of how this value is interpreted.

        repeat : bool, optional
            If True, loop the data continuously from the start after the end
            is reached. If False, stop after the data is read once.

        gapless : bool, optional
            If True, output default-filled samples for any missing data between
            start and end. If False, skip missing samples and add an `rx_time`
            stream tag to indicate the gap.

        min_chunksize : None | int, optional
            Minimum number of samples to output at once. This value can be used
            to adjust the source's performance to reduce underruns and
            processing time. If None, a sensible default will be used.


        Notes
        -----
        A channel directory must contain subdirectories/files in the format:
            [YYYY-MM-DDTHH-MM-SS]/rf@[seconds].[%03i milliseconds].h5

        Each directory provided is considered the same channel. An error is
        raised if their sample rates differ, or if their time periods overlap.

        Upon start, this block sends a 'properties' message on its output
        message port that contains a dictionary with one key, the channel's
        name, and a value which is a dictionary of properties found in the
        channel's 'drf_properties.h5' file.

        This block emits the following stream tags at the appropriate sample
        for each of the channel's accompanying Digital Metadata samples:

            rx_time : (int secs, float frac) tuple
                Time since epoch of the sample.

            rx_rate : float
                Sample rate in Hz.

            rx_freq : float | 1-D array of floats
                Center frequency or frequencies of the subchannels based on
                the 'center_frequencies' metadata field.

            metadata : dict
                Any additional Digital Metadata fields are added to this
                dictionary tag of metadata.

        """
        if isinstance(channel_dir, six.string_types):
            channel_dir = [channel_dir]
        # eventually, we should re-factor DigitalRFReader and associated so
        # that reading from a list of channel directories is possible
        # with a DigitalRFChannelReader class or similar
        # until then, split the path and use existing DigitalRFReader
        top_level_dirs = []
        chs = set()
        for ch_dir in channel_dir:
            top_level_dir, ch = os.path.split(ch_dir)
            top_level_dirs.append(top_level_dir)
            chs.add(ch)
        if len(chs) == 1:
            ch = chs.pop()
        else:
            raise ValueError("Channel directories must have the same name.")
        self._ch = ch

        self._Reader = DigitalRFReader(top_level_dirs)
        self._properties = self._Reader.get_properties(self._ch)

        typeclass = self._properties["H5Tget_class"]
        itemsize = self._properties["H5Tget_size"]
        is_complex = self._properties["is_complex"]
        vlen = self._properties["num_subchannels"]
        sr = self._properties["samples_per_second"]

        self._itemsize = itemsize
        self._sample_rate = sr
        self._sample_rate_pmt = pmt.from_double(float(sr))

        # determine output signature from HDF5 type metadata
        typedict = get_h5type(typeclass, itemsize, is_complex)
        self._outtype = typedict["name"]
        self._itemtype = typedict["dtype"]
        self._missingvalue = np.zeros((), dtype=self._itemtype)
        self._missingvalue[()] = typedict["missingvalue"]
        self._fillvalue = np.zeros((), dtype=self._itemtype)
        if np.issubdtype(self._itemtype, np.inexact) and np.isnan(
                self._missingvalue):
            self._ismissing = lambda a: np.isnan(a)
        else:
            self._ismissing = lambda a: a == self._missingvalue
        if vlen == 1:
            out_sig = [self._itemtype]
        else:
            out_sig = [(self._itemtype, vlen)]

        gr.sync_block.__init__(self,
                               name="digital_rf_channel_source",
                               in_sig=None,
                               out_sig=out_sig)

        self.message_port_register_out(pmt.intern("properties"))
        self._id = pmt.intern(self._ch)
        self._tag_queue = {}

        self._start = start
        self._end = end
        self._repeat = repeat
        self._gapless = gapless
        if min_chunksize is None:
            # FIXME: it shouldn't have to be quite this high
            self._min_chunksize = int(sr)
        else:
            self._min_chunksize = min_chunksize

        # reduce CPU usage and underruns by setting a minimum number of samples
        # to handle at once
        # (really want to set_min_noutput_items, but no way to do that from
        #  Python)
        try:
            self.set_output_multiple(self._min_chunksize)
        except RuntimeError:
            traceback.print_exc()
            errstr = "Failed to set source block min_chunksize to {min_chunksize}."
            if min_chunksize is None:
                errstr += (
                    " This value was calculated automatically based on the sample rate."
                    " You may have to specify min_chunksize manually.")
            raise ValueError(errstr.format(min_chunksize=self._min_chunksize))

        try:
            self._DMDReader = self._Reader.get_digital_metadata(self._ch)
        except IOError:
            self._DMDReader = None
Пример #46
0
 def send_tune(self, freq):
     cmd = pmt.cons(pmt.intern("set_center_freq"),
             pmt.list2(pmt.from_double(freq), pmt.from_uint64(0)))
     #print "tune to", freq
     self.message_port_pub(pmt.intern('command'), cmd)
Пример #47
0
    def test_005_multiWork(self):
        '''
        This test is testing multiple calls to the sandia_tag_debug::work function 
        to ensure tags are all being saved. 
        '''
        src_tag1 = gr.tag_utils.python_to_tag([
            0,
            pmt.intern("sam"),
            pmt.from_double(10000),
            pmt.intern("test_003_tags")
        ])
        src_tag2 = gr.tag_utils.python_to_tag([
            1,
            pmt.intern("peter"),
            pmt.from_double(1000),
            pmt.intern("test_003_tags")
        ])
        src_tag3 = gr.tag_utils.python_to_tag([
            2,
            pmt.intern("jacob"),
            pmt.from_double(100),
            pmt.intern("test_003_tags")
        ])
        src_tag4 = gr.tag_utils.python_to_tag([
            2,
            pmt.intern("chip"),
            pmt.from_double(10),
            pmt.intern("test_003_tags")
        ])
        src_tag5 = gr.tag_utils.python_to_tag([
            2,
            pmt.intern("josh"),
            pmt.from_double(1),
            pmt.intern("test_003_tags")
        ])

        src_data = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
        src = blocks.vector_source_i(src_data, False, 1,
                                     [src_tag1, src_tag2, src_tag3])
        dut = sandia_utils.sandia_tag_debug(gr.sizeof_int, "tag QA")
        self.tb.connect(src, dut)

        #Run one of the TB
        self.tb.run()

        self.assertEqual(3, dut.num_tags())

        tag0 = dut.get_tag(0)
        tag1 = dut.get_tag(1)
        tag2 = dut.get_tag(2)

        self.assertTrue(pmt.eq(tag0.key, pmt.intern("sam")))
        self.assertAlmostEqual(10000, pmt.to_double(tag0.value))

        self.assertTrue(pmt.eq(tag1.key, pmt.intern("peter")))
        self.assertAlmostEqual(1000, pmt.to_double(tag1.value))

        self.assertTrue(pmt.eq(tag2.key, pmt.intern("jacob")))
        self.assertAlmostEqual(100, pmt.to_double(tag2.value))

        self.tb.stop()
        self.tb.wait()

        #Run two of the TB
        src.set_data(src_data, [src_tag4, src_tag5])
        self.tb.run()

        self.assertEqual(5, dut.num_tags())

        tag3 = dut.get_tag(3)
        tag4 = dut.get_tag(4)

        self.assertTrue(pmt.eq(tag0.key, pmt.intern("sam")))
        self.assertAlmostEqual(10000, pmt.to_double(tag0.value))

        self.assertTrue(pmt.eq(tag1.key, pmt.intern("peter")))
        self.assertAlmostEqual(1000, pmt.to_double(tag1.value))

        self.assertTrue(pmt.eq(tag2.key, pmt.intern("jacob")))
        self.assertAlmostEqual(100, pmt.to_double(tag2.value))

        self.assertTrue(pmt.eq(tag3.key, pmt.intern("chip")))
        self.assertAlmostEqual(10, pmt.to_double(tag3.value))

        self.assertTrue(pmt.eq(tag4.key, pmt.intern("josh")))
        self.assertAlmostEqual(1, pmt.to_double(tag4.value))

        self.tb.stop()
        self.tb.wait()
Пример #48
0
 def __init__(
         self,
         n_bursts, n_channels,
         freq_delta, base_freq, dsp_tuning,
         burst_length, base_time, hop_time,
         post_tuning=False,
         tx_gain=0,
         verbose=False
     ):
     gr.hier_block2.__init__(
         self, "FrequencyHopperSrc",
         gr.io_signature(1, 1, gr.sizeof_gr_complex),
         gr.io_signature(1, 1, gr.sizeof_gr_complex),
     )
     n_samples_total = n_bursts * burst_length
     lowest_frequency = base_freq - numpy.floor(n_channels/2) * freq_delta
     self.hop_sequence = [lowest_frequency + n * freq_delta for n in range(n_channels)]
     numpy.random.shuffle(self.hop_sequence)
     # Repeat that:
     self.hop_sequence = [self.hop_sequence[x % n_channels] for x in range(n_bursts)]
     if verbose:
         print("Hop Frequencies  | Hop Pattern")
         print("=================|================================")
         for f in self.hop_sequence:
             print("{:6.3f} MHz      |  ".format(f/1e6), end='')
             if n_channels < 50:
                 print(" " * int((f - base_freq) / freq_delta) + "#")
             else:
                 print("\n")
         print("=================|================================")
     # There's no real point in setting the gain via tag for this application,
     # but this is an example to show you how to do it.
     gain_tag = gr.tag_t()
     gain_tag.offset = 0
     gain_tag.key = pmt.string_to_symbol('tx_command')
     gain_tag.value = pmt.to_pmt({'gain': tx_gain})
     tag_list = [gain_tag,]
     for i in range(len(self.hop_sequence)):
         time = pmt.cons(
             pmt.from_uint64(int(base_time + i * hop_time+0.01)),
             pmt.from_double((base_time + i * hop_time+0.01) % 1),
         )
         tune_tag = gr.tag_t()
         tune_tag.offset = i * burst_length
         # TODO dsp_tuning should also be able to do post_tuning
         if i > 0 and post_tuning and not dsp_tuning:
             tune_tag.offset -= 1 # Move it to last sample of previous burst
         if dsp_tuning:
             tune_tag.key = pmt.string_to_symbol('tx_command')
             tune_tag.value = pmt.to_pmt({'lo_freq': base_freq, 'dsp_freq': base_freq - self.hop_sequence[i]})
             tune_tag.value = pmt.dict_add(tune_tag.value, pmt.intern("time"),time)
         else:
             tune_tag.key = pmt.string_to_symbol('tx_command')
             tune_tag.value = pmt.to_pmt({'freq': self.hop_sequence[i]})
             tune_tag.value = pmt.dict_add(tune_tag.value, pmt.intern('time'), time)
         tag_list.append(tune_tag)
         length_tag = gr.tag_t()
         length_tag.offset = i * burst_length
         length_tag.key = pmt.string_to_symbol('packet_len')
         length_tag.value = pmt.from_long(burst_length)
         tag_list.append(length_tag)
         time_tag = gr.tag_t()
         time_tag.offset = i * burst_length
         time_tag.key = pmt.string_to_symbol('tx_time')
         time_tag.value = pmt.make_tuple(
                 pmt.car(time),
                 pmt.cdr(time)
         )
         tag_list.append(time_tag)
     tag_source = blocks.vector_source_c((1.0,) * n_samples_total, repeat=False, tags=tag_list)
     mult = blocks.multiply_cc()
     self.connect(self, mult, self)
     self.connect(tag_source, (mult, 1))
Пример #49
0
    def __init__(self, seed, samp_rate, noise_amp, modulation, delay,
                 samples_to_receive, freq, rx_id):
        gr.hier_block2.__init__(self, "ModulatorBlock",
                                gr.io_signature(0, 0, 0),
                                gr.io_signature(1, 1, gr.sizeof_gr_complex))

        # Timing tag: This is preserved and updated:
        timing_tag = gr.tag_t()
        timing_tag.offset = 0
        timing_tag.key = pmt.string_to_symbol('rx_time')
        timing_tag.value = pmt.to_pmt((float(seed), 0.6))
        timing_tag.srcid = pmt.string_to_symbol(str('gr uhd usrp source1'))
        # Rx freq tags:
        #print "In source emulation (before tag)"
        #print freq
        rx_freq_tag = gr.tag_t()
        rx_freq_tag.offset = 0
        rx_freq_tag.key = pmt.string_to_symbol('rx_freq')
        rx_freq_tag.value = pmt.from_double(freq)
        rx_freq_tag.srcid = pmt.string_to_symbol(str('gr uhd usrp source1'))
        # Samp_rate tags:
        rx_rate_tag = gr.tag_t()
        rx_rate_tag.offset = 0
        rx_rate_tag.key = pmt.string_to_symbol('rx_rate')
        rx_rate_tag.value = pmt.from_double(samp_rate)
        rx_rate_tag.srcid = pmt.string_to_symbol(str('gr uhd usrp source1'))

        add = blocks.add_vcc(1, )

        tag_debug = blocks.tag_debug(gr.sizeof_gr_complex * 1, "", "")
        tag_debug.set_display(True)

        #if modulation == "bpsk":
        #    mod = digital.psk.psk_mod(
        #      constellation_points=2,
        #      mod_code="none",
        #      differential=True,
        #      samples_per_symbol=2,
        #      excess_bw=0.1,
        #      verbose=False,
        #      log=False,
        #      )
        #else:
        #    mod = grc_blks2.packet_mod_b(digital.ofdm_mod(
        #                    options=grc_blks2.options(
        #                            modulation="qpsk",
        #                            fft_length=4096,
        #                            occupied_tones=200,
        #                            cp_length=0,
        #                            pad_for_usrp=False,
        #                            log=None,
        #                            verbose=None,
        #                    ),
        #            ),
        #            payload_length=0,
        #    )
        #print "in source emulation(after_tag)"
        #print  pmt.to_double(rx_freq_tag.value)
        pulse_width = 4
        np.random.seed(seed=seed)

        tx_vector = np.reshape(
            np.matlib.repmat(
                np.random.randint(0, 2,
                                  (5 * samples_to_receive) / pulse_width) * 2 -
                1, pulse_width, 1).T, [1, 5 * samples_to_receive])[0].tolist()
        # delay signal vector -> insert zeros at beginnig; nothing happens if signal has not reached the receiver:
        tx_vector_delayed = np.hstack((np.zeros(delay), tx_vector))
        #tx_vector_delayed = tx_vector_delayed[:600]
        self.vector_source = blocks.vector_source_c(
            tx_vector_delayed, False, 1,
            (timing_tag, rx_freq_tag, rx_rate_tag))
        #clip first 600 samples
        self.head = blocks.head(gr.sizeof_gr_complex * 1,
                                samples_to_receive + 300)
        # skiphead= blocks.skiphead(gr.sizeof_gr_complex*1,delay)
        throttle = blocks.throttle(gr.sizeof_gr_complex * 1, samp_rate, True)
        noise = analog.noise_source_c(analog.GR_GAUSSIAN, noise_amp, -seed)
        # connects
        #self.connect(vector_source, mod, (add,0))
        self.connect(self.vector_source, (add, 0))
        self.connect(noise, (add, 1))
        self.connect(add, throttle, self.head, self)
        self.connect(add, tag_debug)
        '''
 def set_variable_qtgui_chooser_0_1_1(self, variable_qtgui_chooser_0_1_1):
     self.variable_qtgui_chooser_0_1_1 = variable_qtgui_chooser_0_1_1
     self._variable_qtgui_chooser_0_1_1_callback(self.variable_qtgui_chooser_0_1_1)
     self.blocks_message_strobe_0_0.set_msg(pmt.from_double(self.variable_qtgui_chooser_0_1_1))
Пример #51
0
    def __init__(
            self,
            n_bursts, n_channels,
            freq_delta, base_freq, dsp_tuning,
            burst_length, base_time, hop_time,
            seed,rate,
	    post_tuning=False, 
            tx_gain=0,
            verbose=False
        ):
        gr.hier_block2.__init__(self,
            "Hopping",
            gr.io_signature(1, 1, gr.sizeof_gr_complex),
            gr.io_signature(1, 1, gr.sizeof_gr_complex),
        )
        n_samples_total = n_bursts * burst_length
        lowest_frequency = base_freq - numpy.floor(n_channels/2) * freq_delta
        self.hop_sequence = [lowest_frequency + n * freq_delta for n in xrange(n_channels)]
	random.seed(seed)	
	lam = random.random()        
	random.shuffle(self.hop_sequence, lambda: lam)
        # Repeat that:
        self.hop_sequence = [self.hop_sequence[x % n_channels] for x in xrange(n_bursts)]
        if verbose:
            print "Hop Frequencies  | Hop Pattern"
            print "=================|================================"
            for f in self.hop_sequence:
                print "{:6.3f} MHz      |  ".format(f/1e6),
                if n_channels < 50:
                    print " " * int((f - base_freq) / freq_delta) + "#"
                else:
                    print "\n"
            print "=================|================================"
        # There's no real point in setting the gain via tag for this application,
        # but this is an example to show you how to do it.
        gain_tag = gr.tag_t()
        gain_tag.offset = 0
        gain_tag.key = pmt.string_to_symbol('tx_command')
        gain_tag.value = pmt.to_pmt({'gain': tx_gain})
        tag_list = [gain_tag,]
        for i in xrange(len(self.hop_sequence)):
            tune_tag = gr.tag_t()
            tune_tag.offset = i * burst_length
            if i > 0 and post_tuning and not dsp_tuning: # TODO dsp_tuning should also be able to do post_tuning
                tune_tag.offset -= 1 # Move it to last sample of previous burst
            if dsp_tuning:
                tune_tag.key = pmt.string_to_symbol('tx_command')
                tune_tag.value = pmt.to_pmt({'rf_freq_policy': int(ord('N')), 'lo_freq': base_freq, 'dsp_freq_policy': int(ord('M')),'dsp_freq': base_freq - self.hop_sequence[i] })
            else:
                tune_tag.key = pmt.string_to_symbol('tx_freq')
                tune_tag.value = pmt.to_pmt(self.hop_sequence[i])
            tag_list.append(tune_tag)
            length_tag = gr.tag_t()
            length_tag.offset = i * burst_length
            length_tag.key = pmt.string_to_symbol('packet_len')
            length_tag.value = pmt.from_long(burst_length)
            tag_list.append(length_tag)	
            time_tag = gr.tag_t()
            time_tag.offset = i * burst_length
            time_tag.key = pmt.string_to_symbol("tx_time")
            time_tag.value = pmt.make_tuple(
                    pmt.from_uint64(int(base_time + i * hop_time)),
                    pmt.from_double((base_time + i * hop_time) % 1),
            )
            tag_list.append(time_tag)
        #############################################
        # Old Version
        #############################################
        tag_source = blocks.vector_source_c((1.0,) * n_samples_total, repeat= True, tags=tag_list)
        mult = blocks.multiply_cc()
        self.connect(self, mult, self)
        self.connect(tag_source, (mult, 1))
Пример #52
0
    def __init__(self,
                 fname='',
                 has_header=True,
                 data_type='uint8',
                 period=1000,
                 start_delay=0,
                 repeat=True):
        gr.sync_block.__init__(self, "CSV Reader", in_sig=None, out_sig=None)
        self.file = fname
        self.has_header = has_header
        self.data_type = data_type
        self.period = period
        self.repeat = repeat
        self.start_delay = start_delay

        # setup logger
        logger_name = 'gr_log.' + self.to_basic_block().alias()
        if logger_name in gr.logger_get_names():
            self.log = gr.logger(logger_name)
        else:
            self.log = gr.logger('log')

        # metadata field mappings
        self.metadata_mappings = {
            'string':
            lambda x: pmt.intern(x),
            'bool':
            lambda x: pmt.from_bool(bool(x)),
            'long':
            lambda x: pmt.from_long(int(x)),
            'uint64':
            lambda x: pmt.from_uint64(int(x)),
            'float':
            lambda x: pmt.from_float(float(x)),
            'double':
            lambda x: pmt.from_double(float(x)),
            'complex':
            lambda x: pmt.from_complex(complex(x)),
            'time':
            lambda x: pmt.cons(pmt.from_uint64(int(math.modf(float(x))[1])),
                               pmt.from_double(math.modf(float(x))[0])),
            'time_tuple':
            lambda x: pmt.make_tuple(
                pmt.from_uint64(int(math.modf(float(x))[1])),
                pmt.from_double(math.modf(float(x))[0]))
        }

        self.data_type_mappings = {
            'uint8':
            lambda x: pmt.init_u8vector(len(x), [int(y) for y in x]),
            'int8':
            lambda x: pmt.init_s8vector(len(x), [int(y) for y in x]),
            'uint16':
            lambda x: pmt.init_u16vector(len(x), [int(y) for y in x]),
            'int16':
            lambda x: pmt.init_s16vector(len(x), [int(y) for y in x]),
            'uint32':
            lambda x: pmt.init_u32vector(len(x), [int(y) for y in x]),
            'int32':
            lambda x: pmt.init_s32vector(len(x), [int(y) for y in x]),
            'float':
            lambda x: pmt.init_f32vector(len(x), [float(y) for y in x]),
            'complex float':
            lambda x: pmt.init_c32vector(len(x), [complex(y) for y in x]),
            'double':
            lambda x: pmt.init_f64vector(len(x), [float(y) for y in x]),
            'complex double':
            lambda x: pmt.init_c64vector(len(x), [complex(y) for y in x])
        }

        # ensure valid data type
        if self.data_type not in self.data_type_mappings.keys():
            raise ValueError('Invalid data type {}'.format(data_type))

        # set file name
        self.set_fname(self.file)

        self.message_port_name = pmt.intern('out')
        self.message_port_register_out(self.message_port_name)

        # flag for when to stop
        self.stop_signal_called = False

        # no timer yet
        self.timer = None

        # file lock
        self.lock = threading.Lock()
Пример #53
0
    def __init__(self):
        gr.top_block.__init__(self, "Calibration Example")
        Qt.QWidget.__init__(self)
        self.setWindowTitle("Calibration Example")
        try:
            self.setWindowIcon(Qt.QIcon.fromTheme('gnuradio-grc'))
        except:
            pass
        self.top_scroll_layout = Qt.QVBoxLayout()
        self.setLayout(self.top_scroll_layout)
        self.top_scroll = Qt.QScrollArea()
        self.top_scroll.setFrameStyle(Qt.QFrame.NoFrame)
        self.top_scroll_layout.addWidget(self.top_scroll)
        self.top_scroll.setWidgetResizable(True)
        self.top_widget = Qt.QWidget()
        self.top_scroll.setWidget(self.top_widget)
        self.top_layout = Qt.QVBoxLayout(self.top_widget)
        self.top_grid_layout = Qt.QGridLayout()
        self.top_layout.addLayout(self.top_grid_layout)

        self.settings = Qt.QSettings("GNU Radio", "calibration_example_gui")
        self.restoreGeometry(self.settings.value("geometry").toByteArray())

        ##################################################
        # Variables
        ##################################################
        self.antenna_spacing_inches = antenna_spacing_inches = 6.25
        self.speed_of_light = speed_of_light = 299792458
        self.gain_rx_array = gain_rx_array = 3
        self.antenna_spacing = antenna_spacing = antenna_spacing_inches*0.0254
        self.window = window = 1024
        self.variable_qtgui_chooser_0_1_1 = variable_qtgui_chooser_0_1_1 = 1
        self.variable_qtgui_chooser_0_0 = variable_qtgui_chooser_0_0 = 0
        self.sync = sync = pmt.PMT_F
        self.snapshots = snapshots = 4096
        self._samples_to_save_config = ConfigParser.ConfigParser()
        self._samples_to_save_config.read("/home/travis/Dropbox/PHD/WiFiUS/doa/gnuradio/gr-matlab/config.gr")
        try: samples_to_save = self._samples_to_save_config.getfloat("rx", "samples_to_save")
        except: samples_to_save = 2**18
        self.samples_to_save = samples_to_save
        self.samp_rate = samp_rate = 100000000/64
        self.pi = pi = 3.14159265359
        self.phase_c3 = phase_c3 = 0
        self.phase_c2 = phase_c2 = 0
        self.phase_c1 = phase_c1 = 0
        self.phase_c0 = phase_c0 = 0
        self.offset = offset = 0
        self.label2 = label2 = "Check To Enable"
        self.label = label = "Check To Enable"
        self.gain_tx2 = gain_tx2 = 20
        self.gain_tx1 = gain_tx1 = 20
        self.gain_rx = gain_rx = gain_rx_array
        self.distant_tx_target = distant_tx_target = 1
        self.distant_tx = distant_tx = 1
        self.center_freq = center_freq = speed_of_light/(2*antenna_spacing)
        self.cal_freq = cal_freq = 10000
        self.ant_cal_enable = ant_cal_enable = 1

        ##################################################
        # Blocks
        ##################################################
        _variable_qtgui_chooser_0_1_1_check_box = Qt.QCheckBox("Trigger Data Save")
        self._variable_qtgui_chooser_0_1_1_choices = {True: 0, False: 1}
        self._variable_qtgui_chooser_0_1_1_choices_inv = dict((v,k) for k,v in self._variable_qtgui_chooser_0_1_1_choices.iteritems())
        self._variable_qtgui_chooser_0_1_1_callback = lambda i: Qt.QMetaObject.invokeMethod(_variable_qtgui_chooser_0_1_1_check_box, "setChecked", Qt.Q_ARG("bool", self._variable_qtgui_chooser_0_1_1_choices_inv[i]))
        self._variable_qtgui_chooser_0_1_1_callback(self.variable_qtgui_chooser_0_1_1)
        _variable_qtgui_chooser_0_1_1_check_box.stateChanged.connect(lambda i: self.set_variable_qtgui_chooser_0_1_1(self._variable_qtgui_chooser_0_1_1_choices[bool(i)]))
        self.top_grid_layout.addWidget(_variable_qtgui_chooser_0_1_1_check_box, 4,0)
        _variable_qtgui_chooser_0_0_check_box = Qt.QCheckBox("Connected Sync Tx")
        self._variable_qtgui_chooser_0_0_choices = {True: 0, False: 1}
        self._variable_qtgui_chooser_0_0_choices_inv = dict((v,k) for k,v in self._variable_qtgui_chooser_0_0_choices.iteritems())
        self._variable_qtgui_chooser_0_0_callback = lambda i: Qt.QMetaObject.invokeMethod(_variable_qtgui_chooser_0_0_check_box, "setChecked", Qt.Q_ARG("bool", self._variable_qtgui_chooser_0_0_choices_inv[i]))
        self._variable_qtgui_chooser_0_0_callback(self.variable_qtgui_chooser_0_0)
        _variable_qtgui_chooser_0_0_check_box.stateChanged.connect(lambda i: self.set_variable_qtgui_chooser_0_0(self._variable_qtgui_chooser_0_0_choices[bool(i)]))
        self.top_grid_layout.addWidget(_variable_qtgui_chooser_0_0_check_box, 3,0)
        self._phase_c1_range = Range(-180, 180, 1, 0, 200)
        self._phase_c1_win = RangeWidget(self._phase_c1_range, self.set_phase_c1, "Phase Channel1", "counter_slider", float)
        self.top_layout.addWidget(self._phase_c1_win)
        self._phase_c0_range = Range(-180, 180, 1, 0, 200)
        self._phase_c0_win = RangeWidget(self._phase_c0_range, self.set_phase_c0, "Phase Channel0", "counter_slider", float)
        self.top_layout.addWidget(self._phase_c0_win)
        self._gain_tx2_range = Range(0, 30, 1, 20, 200)
        self._gain_tx2_win = RangeWidget(self._gain_tx2_range, self.set_gain_tx2, "Gain DRTX 2", "counter", float)
        self.top_grid_layout.addWidget(self._gain_tx2_win, 4,1)
        self._gain_tx1_range = Range(0, 30, 1, 20, 200)
        self._gain_tx1_win = RangeWidget(self._gain_tx1_range, self.set_gain_tx1, "Gain DRTX 1", "counter", float)
        self.top_grid_layout.addWidget(self._gain_tx1_win, 3,1)
        _distant_tx_target_check_box = Qt.QCheckBox("Distant TX Target")
        self._distant_tx_target_choices = {True: 0, False: 1}
        self._distant_tx_target_choices_inv = dict((v,k) for k,v in self._distant_tx_target_choices.iteritems())
        self._distant_tx_target_callback = lambda i: Qt.QMetaObject.invokeMethod(_distant_tx_target_check_box, "setChecked", Qt.Q_ARG("bool", self._distant_tx_target_choices_inv[i]))
        self._distant_tx_target_callback(self.distant_tx_target)
        _distant_tx_target_check_box.stateChanged.connect(lambda i: self.set_distant_tx_target(self._distant_tx_target_choices[bool(i)]))
        self.top_grid_layout.addWidget(_distant_tx_target_check_box, 2,0)
        _distant_tx_check_box = Qt.QCheckBox("Distant TX Ref")
        self._distant_tx_choices = {True: 0, False: 1}
        self._distant_tx_choices_inv = dict((v,k) for k,v in self._distant_tx_choices.iteritems())
        self._distant_tx_callback = lambda i: Qt.QMetaObject.invokeMethod(_distant_tx_check_box, "setChecked", Qt.Q_ARG("bool", self._distant_tx_choices_inv[i]))
        self._distant_tx_callback(self.distant_tx)
        _distant_tx_check_box.stateChanged.connect(lambda i: self.set_distant_tx(self._distant_tx_choices[bool(i)]))
        self.top_grid_layout.addWidget(_distant_tx_check_box, 1,0)
        self.wifius_gen_music_spectrum_vcvf_0 = wifius.gen_music_spectrum_vcvf(2, 1, -90, 90, 1, 0.5, snapshots)
        self.wifius_antenna_array_calibration_cf_0 = wifius.antenna_array_calibration_cf(90, 0.5, 2, 4096)
        self.uhd_usrp_source_0_0 = uhd.usrp_source(
        	",".join(("addr0=192.168.20.2,addr1=192.168.30.2", "")),
        	uhd.stream_args(
        		cpu_format="fc32",
        		channels=range(2),
        	),
        )
        self.uhd_usrp_source_0_0.set_clock_source("external", 0)
        self.uhd_usrp_source_0_0.set_time_source("external", 0)
        self.uhd_usrp_source_0_0.set_clock_source("external", 1)
        self.uhd_usrp_source_0_0.set_time_source("external", 1)
        self.uhd_usrp_source_0_0.set_time_now(uhd.time_spec(time.time()), uhd.ALL_MBOARDS)
        self.uhd_usrp_source_0_0.set_samp_rate(samp_rate)
        self.uhd_usrp_source_0_0.set_center_freq(center_freq, 0)
        self.uhd_usrp_source_0_0.set_gain(10, 0)
        self.uhd_usrp_source_0_0.set_antenna("RX2", 0)
        self.uhd_usrp_source_0_0.set_center_freq(center_freq, 1)
        self.uhd_usrp_source_0_0.set_gain(10, 1)
        self.uhd_usrp_source_0_0.set_antenna("RX2", 1)
        self.target_tx_hier_0_0 = target_tx_hier(
            addr0="addr=192.168.90.2",
            cal_freq=10e3,
            center_freq=center_freq,
            gain_tx2=gain_tx1,
            samp_rate=samp_rate,
            tone_type="Real",
        )
        self.target_tx_hier_0 = target_tx_hier(
            addr0="addr=192.168.80.2",
            cal_freq=10e3,
            center_freq=center_freq,
            gain_tx2=gain_tx2,
            samp_rate=samp_rate,
            tone_type="Real",
        )
        self.tab = Qt.QTabWidget()
        self.tab_widget_0 = Qt.QWidget()
        self.tab_layout_0 = Qt.QBoxLayout(Qt.QBoxLayout.TopToBottom, self.tab_widget_0)
        self.tab_grid_layout_0 = Qt.QGridLayout()
        self.tab_layout_0.addLayout(self.tab_grid_layout_0)
        self.tab.addTab(self.tab_widget_0, "Input")
        self.tab_widget_1 = Qt.QWidget()
        self.tab_layout_1 = Qt.QBoxLayout(Qt.QBoxLayout.TopToBottom, self.tab_widget_1)
        self.tab_grid_layout_1 = Qt.QGridLayout()
        self.tab_layout_1.addLayout(self.tab_grid_layout_1)
        self.tab.addTab(self.tab_widget_1, "Post Phase Correct")
        self.tab_widget_2 = Qt.QWidget()
        self.tab_layout_2 = Qt.QBoxLayout(Qt.QBoxLayout.TopToBottom, self.tab_widget_2)
        self.tab_grid_layout_2 = Qt.QGridLayout()
        self.tab_layout_2.addLayout(self.tab_grid_layout_2)
        self.tab.addTab(self.tab_widget_2, "Angle of Arrival")
        self.tab_widget_3 = Qt.QWidget()
        self.tab_layout_3 = Qt.QBoxLayout(Qt.QBoxLayout.TopToBottom, self.tab_widget_3)
        self.tab_grid_layout_3 = Qt.QGridLayout()
        self.tab_layout_3.addLayout(self.tab_grid_layout_3)
        self.tab.addTab(self.tab_widget_3, "MuSIC Spectrum")
        self.top_layout.addWidget(self.tab)
        self.sync_tx_hier_0 = sync_tx_hier(
            addr0="addr=192.168.60.2",
            cal_freq=1e3,
            center_freq=center_freq,
            gain_tx2=10,
            samp_rate=samp_rate,
            tone_type="Complex",
        )
        _sync_check_box = Qt.QCheckBox("Enable Sync Adaption")
        self._sync_choices = {True: pmt.PMT_T, False: pmt.PMT_F}
        self._sync_choices_inv = dict((v,k) for k,v in self._sync_choices.iteritems())
        self._sync_callback = lambda i: Qt.QMetaObject.invokeMethod(_sync_check_box, "setChecked", Qt.Q_ARG("bool", self._sync_choices_inv[i]))
        self._sync_callback(self.sync)
        _sync_check_box.stateChanged.connect(lambda i: self.set_sync(self._sync_choices[bool(i)]))
        self.top_grid_layout.addWidget(_sync_check_box, 1,1)
        self.qtgui_vector_sink_f_0 = qtgui.vector_sink_f(
            180,
            -90,
            1.0,
            "Offset",
            "dB",
            "MuSIC Spectrum",
            1 # Number of inputs
        )
        self.qtgui_vector_sink_f_0.set_update_time(0.10)
        self.qtgui_vector_sink_f_0.set_y_axis(-140, 10)
        self.qtgui_vector_sink_f_0.enable_autoscale(True)
        self.qtgui_vector_sink_f_0.enable_grid(True)
        self.qtgui_vector_sink_f_0.set_x_axis_units("")
        self.qtgui_vector_sink_f_0.set_y_axis_units("")
        self.qtgui_vector_sink_f_0.set_ref_level(0)
        
        labels = ["", "", "", "", "",
                  "", "", "", "", ""]
        widths = [1, 1, 1, 1, 1,
                  1, 1, 1, 1, 1]
        colors = ["blue", "red", "green", "black", "cyan",
                  "magenta", "yellow", "dark red", "dark green", "dark blue"]
        alphas = [1.0, 1.0, 1.0, 1.0, 1.0,
                  1.0, 1.0, 1.0, 1.0, 1.0]
        for i in xrange(1):
            if len(labels[i]) == 0:
                self.qtgui_vector_sink_f_0.set_line_label(i, "Data {0}".format(i))
            else:
                self.qtgui_vector_sink_f_0.set_line_label(i, labels[i])
            self.qtgui_vector_sink_f_0.set_line_width(i, widths[i])
            self.qtgui_vector_sink_f_0.set_line_color(i, colors[i])
            self.qtgui_vector_sink_f_0.set_line_alpha(i, alphas[i])
        
        self._qtgui_vector_sink_f_0_win = sip.wrapinstance(self.qtgui_vector_sink_f_0.pyqwidget(), Qt.QWidget)
        self.top_layout.addWidget(self._qtgui_vector_sink_f_0_win)
        self.qtgui_time_sink_x_0 = qtgui.time_sink_f(
        	2000, #size
        	samp_rate, #samp_rate
        	"", #name
        	2 #number of inputs
        )
        self.qtgui_time_sink_x_0.set_update_time(0.10)
        self.qtgui_time_sink_x_0.set_y_axis(-1, 1)
        
        self.qtgui_time_sink_x_0.set_y_label("Amplitude", "")
        
        self.qtgui_time_sink_x_0.enable_tags(-1, True)
        self.qtgui_time_sink_x_0.set_trigger_mode(qtgui.TRIG_MODE_FREE, qtgui.TRIG_SLOPE_POS, 0.0, 0, 0, "")
        self.qtgui_time_sink_x_0.enable_autoscale(False)
        self.qtgui_time_sink_x_0.enable_grid(False)
        self.qtgui_time_sink_x_0.enable_control_panel(True)
        
        if not True:
          self.qtgui_time_sink_x_0.disable_legend()
        
        labels = ["", "", "", "", "",
                  "", "", "", "", ""]
        widths = [1, 1, 1, 1, 1,
                  1, 1, 1, 1, 1]
        colors = ["blue", "red", "green", "black", "cyan",
                  "magenta", "yellow", "dark red", "dark green", "blue"]
        styles = [1, 1, 1, 1, 1,
                  1, 1, 1, 1, 1]
        markers = [-1, -1, -1, -1, -1,
                   -1, -1, -1, -1, -1]
        alphas = [1.0, 1.0, 1.0, 1.0, 1.0,
                  1.0, 1.0, 1.0, 1.0, 1.0]
        
        for i in xrange(2):
            if len(labels[i]) == 0:
                self.qtgui_time_sink_x_0.set_line_label(i, "Data {0}".format(i))
            else:
                self.qtgui_time_sink_x_0.set_line_label(i, labels[i])
            self.qtgui_time_sink_x_0.set_line_width(i, widths[i])
            self.qtgui_time_sink_x_0.set_line_color(i, colors[i])
            self.qtgui_time_sink_x_0.set_line_style(i, styles[i])
            self.qtgui_time_sink_x_0.set_line_marker(i, markers[i])
            self.qtgui_time_sink_x_0.set_line_alpha(i, alphas[i])
        
        self._qtgui_time_sink_x_0_win = sip.wrapinstance(self.qtgui_time_sink_x_0.pyqwidget(), Qt.QWidget)
        self.top_layout.addWidget(self._qtgui_time_sink_x_0_win)
        self._phase_c3_range = Range(-180, 180, 1, 0, 200)
        self._phase_c3_win = RangeWidget(self._phase_c3_range, self.set_phase_c3, "Phase Channel3", "counter_slider", float)
        self.top_layout.addWidget(self._phase_c3_win)
        self._phase_c2_range = Range(-180, 180, 1, 0, 200)
        self._phase_c2_win = RangeWidget(self._phase_c2_range, self.set_phase_c2, "Phase Channel2", "counter_slider", float)
        self.top_layout.addWidget(self._phase_c2_win)
        self._offset_range = Range(-90, 90, 1, 0, 10)
        self._offset_win = RangeWidget(self._offset_range, self.set_offset, "Bias Angle", "counter", float)
        self.top_grid_layout.addWidget(self._offset_win, 2,1)
        self._label2_tool_bar = Qt.QToolBar(self)
        
        if None:
          self._label2_formatter = None
        else:
          self._label2_formatter = lambda x: x
        
        self._label2_tool_bar.addWidget(Qt.QLabel("Algorithm  Control"+": "))
        self._label2_label = Qt.QLabel(str(self._label2_formatter(self.label2)))
        self._label2_tool_bar.addWidget(self._label2_label)
        self.top_grid_layout.addWidget(self._label2_tool_bar, 0,1)
          
        self._label_tool_bar = Qt.QToolBar(self)
        
        if None:
          self._label_formatter = None
        else:
          self._label_formatter = lambda x: x
        
        self._label_tool_bar.addWidget(Qt.QLabel("Transmitter Control"+": "))
        self._label_label = Qt.QLabel(str(self._label_formatter(self.label)))
        self._label_tool_bar.addWidget(self._label_label)
        self.top_grid_layout.addWidget(self._label_tool_bar, 0,0)
          
        self._gain_rx_array_range = Range(0, 30, 1, 3, 200)
        self._gain_rx_array_win = RangeWidget(self._gain_rx_array_range, self.set_gain_rx_array, "Gain RX Array", "counter", float)
        self.top_grid_layout.addWidget(self._gain_rx_array_win, 5,1)
        self.blocks_stream_to_vector_0_0 = blocks.stream_to_vector(gr.sizeof_gr_complex*1, snapshots)
        self.blocks_stream_to_vector_0 = blocks.stream_to_vector(gr.sizeof_gr_complex*1, snapshots)
        self.blocks_multiply_const_vxx_0_0 = blocks.multiply_const_vcc((numpy.exp(-1j*phase_c1*pi/180), ))
        self.blocks_multiply_const_vxx_0 = blocks.multiply_const_vcc((numpy.exp(-1j*phase_c0*pi/180), ))
        self.blocks_message_strobe_0_2_0 = blocks.message_strobe(pmt.from_double(distant_tx_target), 1000)
        self.blocks_message_strobe_0_2 = blocks.message_strobe(pmt.from_double(distant_tx), 1000)
        self.blocks_message_strobe_0_0 = blocks.message_strobe(pmt.from_double(variable_qtgui_chooser_0_1_1), 1000)
        self.blocks_message_strobe_0 = blocks.message_strobe(pmt.from_double(variable_qtgui_chooser_0_0), 1000)
        self.blocks_complex_to_real_1 = blocks.complex_to_real(1)
        self.blocks_complex_to_real_0 = blocks.complex_to_real(1)
        _ant_cal_enable_check_box = Qt.QCheckBox("Enable Antenna Calibration")
        self._ant_cal_enable_choices = {True: 0, False: 1}
        self._ant_cal_enable_choices_inv = dict((v,k) for k,v in self._ant_cal_enable_choices.iteritems())
        self._ant_cal_enable_callback = lambda i: Qt.QMetaObject.invokeMethod(_ant_cal_enable_check_box, "setChecked", Qt.Q_ARG("bool", self._ant_cal_enable_choices_inv[i]))
        self._ant_cal_enable_callback(self.ant_cal_enable)
        _ant_cal_enable_check_box.stateChanged.connect(lambda i: self.set_ant_cal_enable(self._ant_cal_enable_choices[bool(i)]))
        self.top_grid_layout.addWidget(_ant_cal_enable_check_box, 1,4)

        ##################################################
        # Connections
        ##################################################
        self.msg_connect((self.blocks_message_strobe_0, 'strobe'), (self.sync_tx_hier_0, 'Trigger'))    
        self.msg_connect((self.blocks_message_strobe_0_0, 'strobe'), (self.wifius_antenna_array_calibration_cf_0, 'enable_hold'))    
        self.msg_connect((self.blocks_message_strobe_0_2, 'strobe'), (self.target_tx_hier_0, 'Trigger'))    
        self.msg_connect((self.blocks_message_strobe_0_2_0, 'strobe'), (self.target_tx_hier_0_0, 'Trigger'))    
        self.connect((self.blocks_complex_to_real_0, 0), (self.qtgui_time_sink_x_0, 0))    
        self.connect((self.blocks_complex_to_real_1, 0), (self.qtgui_time_sink_x_0, 1))    
        self.connect((self.blocks_multiply_const_vxx_0, 0), (self.blocks_complex_to_real_0, 0))    
        self.connect((self.blocks_multiply_const_vxx_0, 0), (self.blocks_stream_to_vector_0, 0))    
        self.connect((self.blocks_multiply_const_vxx_0, 0), (self.wifius_antenna_array_calibration_cf_0, 0))    
        self.connect((self.blocks_multiply_const_vxx_0_0, 0), (self.blocks_complex_to_real_1, 0))    
        self.connect((self.blocks_multiply_const_vxx_0_0, 0), (self.blocks_stream_to_vector_0_0, 0))    
        self.connect((self.blocks_multiply_const_vxx_0_0, 0), (self.wifius_antenna_array_calibration_cf_0, 1))    
        self.connect((self.blocks_stream_to_vector_0, 0), (self.wifius_gen_music_spectrum_vcvf_0, 2))    
        self.connect((self.blocks_stream_to_vector_0_0, 0), (self.wifius_gen_music_spectrum_vcvf_0, 3))    
        self.connect((self.uhd_usrp_source_0_0, 0), (self.blocks_multiply_const_vxx_0, 0))    
        self.connect((self.uhd_usrp_source_0_0, 1), (self.blocks_multiply_const_vxx_0_0, 0))    
        self.connect((self.wifius_antenna_array_calibration_cf_0, 0), (self.wifius_gen_music_spectrum_vcvf_0, 0))    
        self.connect((self.wifius_antenna_array_calibration_cf_0, 1), (self.wifius_gen_music_spectrum_vcvf_0, 1))    
        self.connect((self.wifius_gen_music_spectrum_vcvf_0, 0), (self.qtgui_vector_sink_f_0, 0))    
Пример #54
0
 def __init__(self,
              n_bursts,
              n_channels,
              freq_delta,
              base_freq,
              burst_length,
              base_time,
              hop_time,
              post_tuning=True,
              tx_gain=0,
              verbose=False):
     gr.hier_block2.__init__(
         self,
         "FrequencyHopperSrc",
         gr.io_signature(1, 1, gr.sizeof_gr_complex),
         gr.io_signature(1, 1, gr.sizeof_gr_complex),
     )
     n_samples_total = n_bursts * burst_length
     #  self.hop_sequence = numpy.arange(base_freq, base_freq + n_channels * freq_delta, freq_delta)
     self.hop_sequence = 2440000000, 2450000000, 2435000000, 2430000000, 2445000000, 2420000000, 2425000000
     #  numpy.random.shuffle(self.hop_sequence)  #this randomly shuffels frequencies in the specified range
     #  self.hop_sequence = [self.hop_sequence[x % n_channels] for x in xrange(n_bursts)]
     self.hop_sequence = [
         self.hop_sequence[x % 7] for x in xrange(n_bursts)
     ]
     if verbose:
         print "Hop Frequencies  | Hop Pattern"
         print "=================|================================"
         for f in self.hop_sequence:
             print "{:6.3f} MHz      |  ".format(f / 1e6),
             if n_channels < 50:
                 print " " * int((f - base_freq) / freq_delta) + "#"
             else:
                 print "\n"
         print "=================|================================"
     # There's no real point in setting the gain via tag for this application,
     # but this is an example to show you how to do it.
     gain_tag = gr.tag_t()
     gain_tag.offset = 0
     gain_tag.key = pmt.string_to_symbol('tx_command')
     gain_tag.value = pmt.cons(
         pmt.intern("gain"),
         # These are both valid:
         #pmt.from_double(tx_gain)
         pmt.cons(pmt.to_pmt(0), pmt.to_pmt(tx_gain)))
     tag_list = [
         gain_tag,
     ]
     for i in xrange(n_bursts):
         tune_tag = gr.tag_t()
         tune_tag.offset = i * burst_length
         if i > 0 and post_tuning:
             tune_tag.offset -= 1  # Move it to last sample of previous burst
         tune_tag.key = pmt.string_to_symbol('tx_freq')
         tune_tag.value = pmt.to_pmt(self.hop_sequence[i])
         tag_list.append(tune_tag)
         length_tag = gr.tag_t()
         length_tag.offset = i * burst_length
         length_tag.key = pmt.string_to_symbol('packet_len')
         length_tag.value = pmt.from_long(burst_length)
         tag_list.append(length_tag)
         time_tag = gr.tag_t()
         time_tag.offset = i * burst_length
         time_tag.key = pmt.string_to_symbol('tx_time')
         time_tag.value = pmt.make_tuple(
             pmt.from_uint64(int(base_time + i * hop_time)),
             pmt.from_double((base_time + i * hop_time) % 1),
         )
         tag_list.append(time_tag)
     tag_source = blocks.vector_source_c((1.0, ) * n_samples_total,
                                         repeat=False,
                                         tags=tag_list)
     mult = blocks.multiply_cc()
     self.connect(self, mult, self)
     self.connect(tag_source, (mult, 1))
Пример #55
0
 def set_distant_tx(self, distant_tx):
     self.distant_tx = distant_tx
     self._distant_tx_callback(self.distant_tx)
     self.blocks_message_strobe_0_2.set_msg(pmt.from_double(self.distant_tx))
Пример #56
0
    def timed_reset(self):
        if self.last_state != "synchronized":
#            print "conditional reset"
            self.reset()
            msg_ppm = pmt.from_double(0.0)
            self.message_port_pub(pmt.intern("ppm"), msg_ppm)
Пример #57
0
def make_header(options, filename):
    extras_present = False
    if options.freq is not None:
        extras_present = True
    # Open the file and make the header
    hdr_filename = filename + '.hdr'
    hdr_file = open(hdr_filename, 'wb')
    header = pmt.make_dict()
    # Fill in header vals
    # TODO - Read this from blocks.METADATA_VERSION
    ver_val = pmt.from_long(long(0))
    rate_val = pmt.from_double(options.sample_rate)
    time_val = pmt.make_tuple(pmt.from_uint64(options.time_sec),
                             pmt.from_double(options.time_fsec))
    ft_to_sz = parse_file_metadata.ftype_to_size
    # Map shortname to properties
    enum_type = SNAME_TO_ENUM[options.format]
    type_props = SNAME_DEFS[enum_type]
    size_val = pmt.from_long(type_props[0])
    cplx_val = pmt.from_bool(type_props[1])
    type_val = pmt.from_long(type_props[2])
    fmt = type_props[2]
    file_samp_len = long(options.length)
    seg_size = long(options.seg_size)
    bytes_val = pmt.from_uint64(long(seg_size*ft_to_sz[fmt]))
    # Set header vals
    header = pmt.dict_add(header, pmt.intern("version"), ver_val)
    header = pmt.dict_add(header, pmt.intern("size"), size_val)
    header = pmt.dict_add(header, pmt.intern("type"), type_val)
    header = pmt.dict_add(header, pmt.intern("cplx"), cplx_val)
    header = pmt.dict_add(header, pmt.intern("rx_time"), time_val)
    header = pmt.dict_add(header, pmt.intern("rx_rate"), rate_val)
    header = pmt.dict_add(header, pmt.intern("bytes"), bytes_val)

    if extras_present:
        freq_key = pmt.intern("rx_freq")
        freq_val = pmt.from_double(options.freq)
        extras = pmt.make_dict()
        extras = pmt.dict_add(extras, freq_key, freq_val)
        extras_str = pmt.serialize_str(extras)
        start_val = pmt.from_uint64(blocks.METADATA_HEADER_SIZE
                + len(extras_str))
    else:
        start_val = pmt.from_uint64(blocks.METADATA_HEADER_SIZE)
    header = pmt.dict_add(header, pmt.intern("strt"), start_val)
    num_segments = file_samp_len/seg_size
    if options.verbose:
        print "Wrote %d headers to: %s (Version %d)" % (num_segments+1,
                hdr_filename,pmt.to_long(ver_val))
    for x in range(0,num_segments,1):
        # Serialize and write out file
        if extras_present:
            header_str = pmt.serialize_str(header) + extras_str
        else:
            header_str = pmt.serialize_str(header)
        hdr_file.write(header_str)
        # Update header based on sample rate and segment size
        header = update_timestamp(header,seg_size)
    
    # Last header is special b/c file size is probably not mult. of seg_size
    header = pmt.dict_delete(header,pmt.intern("bytes"))
    bytes_remaining = ft_to_sz[fmt]*(file_samp_len - num_segments*long(seg_size))
    bytes_val = pmt.from_uint64(bytes_remaining)
    header = pmt.dict_add(header,pmt.intern("bytes"),bytes_val)
    # Serialize and write out file
    if extras_present:
        header_str = pmt.serialize_str(header) + extras_str
    else:
        header_str = pmt.serialize_str(header)
    hdr_file.write(header_str)
    hdr_file.close()
Пример #58
0
    def work(self, input_items, output_items):
        in0 = input_items[0]
        output_items[0][:] = in0[self.history() - 1:]

        threshold = input_items[1][self.history() - 1:]
        threshold_diff = diff(concatenate([[0], threshold]))
        up_to_high_indexes = nonzero(threshold_diff > 0)[0]

        up_to_high_idx = []

        for up_to_high_idx in up_to_high_indexes:  #look for "high" value at the trigger
            if up_to_high_idx == 0 and self.state == True:  #if it's not transition from "low" to "high"
                continue  #then continue
            self.state = True  #if found - change state

        if self.state == True and up_to_high_idx and any(
                threshold_diff < 0):  #and look for transition from high to low
            last_up_to_high_idx = up_to_high_idx
            last_high_to_low_idx = nonzero(threshold_diff < 0)[0][-1]

            if last_high_to_low_idx - last_up_to_high_idx > 0:
                coarse_idx = int(last_high_to_low_idx + self.history() -
                                 self.block_size)
                inst_freq = angle(
                    in0[coarse_idx:coarse_idx + self.block_size] *
                    in0[coarse_idx - self.OSR:coarse_idx + self.block_size -
                        self.OSR].conj()) / (
                            2 * pi
                        ) * self.symbol_rate  #instantaneus frequency estimate
                precise_idx = self.find_best_position(inst_freq)
                #                measured_freq = mean(inst_freq[precise_idx:precise_idx+self.processed_block_size])
                expected_freq = self.symbol_rate / 4

                print "input_items:", len(in0)
                print "coarse_idx", coarse_idx
                print "coarse_idx+precise_idx", coarse_idx + precise_idx

                zoomed_spectrum = abs(
                    self.zoomfft(in0[coarse_idx + precise_idx:coarse_idx +
                                     precise_idx + self.processed_block_size]))
                measured_freq = self.f_axis[argmax(zoomed_spectrum)]
                freq_offset = measured_freq - expected_freq
                offset = self.nitems_written(
                    0) + coarse_idx + precise_idx - self.guard_period
                key = pmt.string_to_symbol("fcch")
                value = pmt.from_double(freq_offset)
                self.add_item_tag(0, offset, key, value)
                self.state = False

                #   Some additional plots and prints for debugging
                #                print "coarse_idx+precise_idx",coarse_idx+precise_idx
                #                print "offset-self.nitems_written(0):",offset-self.nitems_written(0)
                print offset - self.prev_offset
                self.prev_offset = offset
                print "freq offset", freq_offset
#                freq_offset = measured_freq - expected_freq
#                plot(self.f_axis, zoomed_spectrum)
#                show()
#                plot(inst_freq[precise_idx:precise_idx+self.burst_size])
#                show()
#                plot(unwrap(angle(in0[coarse_idx+precise_idx:coarse_idx+precise_idx+self.burst_size])))
#                show()
#
        return len(output_items[0])
    def __init__(self):
        gr.top_block.__init__(self, "Calibration Example")
        Qt.QWidget.__init__(self)
        self.setWindowTitle("Calibration Example")
        try:
             self.setWindowIcon(Qt.QIcon.fromTheme('gnuradio-grc'))
        except:
             pass
        self.top_scroll_layout = Qt.QVBoxLayout()
        self.setLayout(self.top_scroll_layout)
        self.top_scroll = Qt.QScrollArea()
        self.top_scroll.setFrameStyle(Qt.QFrame.NoFrame)
        self.top_scroll_layout.addWidget(self.top_scroll)
        self.top_scroll.setWidgetResizable(True)
        self.top_widget = Qt.QWidget()
        self.top_scroll.setWidget(self.top_widget)
        self.top_layout = Qt.QVBoxLayout(self.top_widget)
        self.top_grid_layout = Qt.QGridLayout()
        self.top_layout.addLayout(self.top_grid_layout)

        self.settings = Qt.QSettings("GNU Radio", "calibration_example_gui_manual")
        self.restoreGeometry(self.settings.value("geometry").toByteArray())

        ##################################################
        # Variables
        ##################################################
        self.speed_of_light = speed_of_light = 299792458
        self.antenna_spacing = antenna_spacing = 0.1
        self.variable_qtgui_chooser_0_1_1 = variable_qtgui_chooser_0_1_1 = 1
        self.variable_qtgui_chooser_0_1_0 = variable_qtgui_chooser_0_1_0 = 0
        self.variable_qtgui_chooser_0_0_0 = variable_qtgui_chooser_0_0_0 = 1
        self.variable_qtgui_chooser_0_0 = variable_qtgui_chooser_0_0 = 0
        self.samp_rate = samp_rate = 100000000/64
        self.gain_rx = gain_rx = 0
        self.center_freq = center_freq = speed_of_light/(2*antenna_spacing)
        self.cal_freq = cal_freq = 1024
        self.Shift_1 = Shift_1 = -4
        self.Shift_0 = Shift_0 = -4
        self.Shift = Shift = -4

        ##################################################
        # Blocks
        ##################################################
        self._variable_qtgui_chooser_0_1_1_options = (1, 0, )
        self._variable_qtgui_chooser_0_1_1_labels = ("Not Started", "Start Save", )
        self._variable_qtgui_chooser_0_1_1_group_box = Qt.QGroupBox("Trigger Data Save")
        self._variable_qtgui_chooser_0_1_1_box = Qt.QHBoxLayout()
        class variable_chooser_button_group(Qt.QButtonGroup):
            def __init__(self, parent=None):
                Qt.QButtonGroup.__init__(self, parent)
            @pyqtSlot(int)
            def updateButtonChecked(self, button_id):
                self.button(button_id).setChecked(True)
        self._variable_qtgui_chooser_0_1_1_button_group = variable_chooser_button_group()
        self._variable_qtgui_chooser_0_1_1_group_box.setLayout(self._variable_qtgui_chooser_0_1_1_box)
        for i, label in enumerate(self._variable_qtgui_chooser_0_1_1_labels):
        	radio_button = Qt.QRadioButton(label)
        	self._variable_qtgui_chooser_0_1_1_box.addWidget(radio_button)
        	self._variable_qtgui_chooser_0_1_1_button_group.addButton(radio_button, i)
        self._variable_qtgui_chooser_0_1_1_callback = lambda i: Qt.QMetaObject.invokeMethod(self._variable_qtgui_chooser_0_1_1_button_group, "updateButtonChecked", Qt.Q_ARG("int", self._variable_qtgui_chooser_0_1_1_options.index(i)))
        self._variable_qtgui_chooser_0_1_1_callback(self.variable_qtgui_chooser_0_1_1)
        self._variable_qtgui_chooser_0_1_1_button_group.buttonClicked[int].connect(
        	lambda i: self.set_variable_qtgui_chooser_0_1_1(self._variable_qtgui_chooser_0_1_1_options[i]))
        self.top_layout.addWidget(self._variable_qtgui_chooser_0_1_1_group_box)
        self._variable_qtgui_chooser_0_0_0_options = (0, 1, )
        self._variable_qtgui_chooser_0_0_0_labels = ("Enable", "Disable", )
        self._variable_qtgui_chooser_0_0_0_group_box = Qt.QGroupBox("Distant Transmitter Enable")
        self._variable_qtgui_chooser_0_0_0_box = Qt.QHBoxLayout()
        class variable_chooser_button_group(Qt.QButtonGroup):
            def __init__(self, parent=None):
                Qt.QButtonGroup.__init__(self, parent)
            @pyqtSlot(int)
            def updateButtonChecked(self, button_id):
                self.button(button_id).setChecked(True)
        self._variable_qtgui_chooser_0_0_0_button_group = variable_chooser_button_group()
        self._variable_qtgui_chooser_0_0_0_group_box.setLayout(self._variable_qtgui_chooser_0_0_0_box)
        for i, label in enumerate(self._variable_qtgui_chooser_0_0_0_labels):
        	radio_button = Qt.QRadioButton(label)
        	self._variable_qtgui_chooser_0_0_0_box.addWidget(radio_button)
        	self._variable_qtgui_chooser_0_0_0_button_group.addButton(radio_button, i)
        self._variable_qtgui_chooser_0_0_0_callback = lambda i: Qt.QMetaObject.invokeMethod(self._variable_qtgui_chooser_0_0_0_button_group, "updateButtonChecked", Qt.Q_ARG("int", self._variable_qtgui_chooser_0_0_0_options.index(i)))
        self._variable_qtgui_chooser_0_0_0_callback(self.variable_qtgui_chooser_0_0_0)
        self._variable_qtgui_chooser_0_0_0_button_group.buttonClicked[int].connect(
        	lambda i: self.set_variable_qtgui_chooser_0_0_0(self._variable_qtgui_chooser_0_0_0_options[i]))
        self.top_layout.addWidget(self._variable_qtgui_chooser_0_0_0_group_box)
        self._variable_qtgui_chooser_0_0_options = (0, 1, )
        self._variable_qtgui_chooser_0_0_labels = ("Enable", "Disable", )
        self._variable_qtgui_chooser_0_0_group_box = Qt.QGroupBox("Source Enable")
        self._variable_qtgui_chooser_0_0_box = Qt.QHBoxLayout()
        class variable_chooser_button_group(Qt.QButtonGroup):
            def __init__(self, parent=None):
                Qt.QButtonGroup.__init__(self, parent)
            @pyqtSlot(int)
            def updateButtonChecked(self, button_id):
                self.button(button_id).setChecked(True)
        self._variable_qtgui_chooser_0_0_button_group = variable_chooser_button_group()
        self._variable_qtgui_chooser_0_0_group_box.setLayout(self._variable_qtgui_chooser_0_0_box)
        for i, label in enumerate(self._variable_qtgui_chooser_0_0_labels):
        	radio_button = Qt.QRadioButton(label)
        	self._variable_qtgui_chooser_0_0_box.addWidget(radio_button)
        	self._variable_qtgui_chooser_0_0_button_group.addButton(radio_button, i)
        self._variable_qtgui_chooser_0_0_callback = lambda i: Qt.QMetaObject.invokeMethod(self._variable_qtgui_chooser_0_0_button_group, "updateButtonChecked", Qt.Q_ARG("int", self._variable_qtgui_chooser_0_0_options.index(i)))
        self._variable_qtgui_chooser_0_0_callback(self.variable_qtgui_chooser_0_0)
        self._variable_qtgui_chooser_0_0_button_group.buttonClicked[int].connect(
        	lambda i: self.set_variable_qtgui_chooser_0_0(self._variable_qtgui_chooser_0_0_options[i]))
        self.top_layout.addWidget(self._variable_qtgui_chooser_0_0_group_box)
        self.tab = Qt.QTabWidget()
        self.tab_widget_0 = Qt.QWidget()
        self.tab_layout_0 = Qt.QBoxLayout(Qt.QBoxLayout.TopToBottom, self.tab_widget_0)
        self.tab_grid_layout_0 = Qt.QGridLayout()
        self.tab_layout_0.addLayout(self.tab_grid_layout_0)
        self.tab.addTab(self.tab_widget_0, "Input")
        self.tab_widget_1 = Qt.QWidget()
        self.tab_layout_1 = Qt.QBoxLayout(Qt.QBoxLayout.TopToBottom, self.tab_widget_1)
        self.tab_grid_layout_1 = Qt.QGridLayout()
        self.tab_layout_1.addLayout(self.tab_grid_layout_1)
        self.tab.addTab(self.tab_widget_1, "Post Gain Correct")
        self.tab_widget_2 = Qt.QWidget()
        self.tab_layout_2 = Qt.QBoxLayout(Qt.QBoxLayout.TopToBottom, self.tab_widget_2)
        self.tab_grid_layout_2 = Qt.QGridLayout()
        self.tab_layout_2.addLayout(self.tab_grid_layout_2)
        self.tab.addTab(self.tab_widget_2, "Post Phase Correct")
        self.top_layout.addWidget(self.tab)
        self._Shift_1_range = Range(-4, 4, 0.01, -4, 200)
        self._Shift_1_win = RangeWidget(self._Shift_1_range, self.set_Shift_1, "Shift", "counter_slider", float)
        self.top_layout.addWidget(self._Shift_1_win)
        self._Shift_0_range = Range(-4, 4, 0.01, -4, 200)
        self._Shift_0_win = RangeWidget(self._Shift_0_range, self.set_Shift_0, "Shift", "counter_slider", float)
        self.top_layout.addWidget(self._Shift_0_win)
        self._Shift_range = Range(-4, 4, 0.01, -4, 200)
        self._Shift_win = RangeWidget(self._Shift_range, self.set_Shift, "Shift", "counter_slider", float)
        self.top_layout.addWidget(self._Shift_win)
        self._variable_qtgui_chooser_0_1_0_options = (1, 0, )
        self._variable_qtgui_chooser_0_1_0_labels = ("Stop", "Running", )
        self._variable_qtgui_chooser_0_1_0_group_box = Qt.QGroupBox("Sync System")
        self._variable_qtgui_chooser_0_1_0_box = Qt.QHBoxLayout()
        class variable_chooser_button_group(Qt.QButtonGroup):
            def __init__(self, parent=None):
                Qt.QButtonGroup.__init__(self, parent)
            @pyqtSlot(int)
            def updateButtonChecked(self, button_id):
                self.button(button_id).setChecked(True)
        self._variable_qtgui_chooser_0_1_0_button_group = variable_chooser_button_group()
        self._variable_qtgui_chooser_0_1_0_group_box.setLayout(self._variable_qtgui_chooser_0_1_0_box)
        for i, label in enumerate(self._variable_qtgui_chooser_0_1_0_labels):
        	radio_button = Qt.QRadioButton(label)
        	self._variable_qtgui_chooser_0_1_0_box.addWidget(radio_button)
        	self._variable_qtgui_chooser_0_1_0_button_group.addButton(radio_button, i)
        self._variable_qtgui_chooser_0_1_0_callback = lambda i: Qt.QMetaObject.invokeMethod(self._variable_qtgui_chooser_0_1_0_button_group, "updateButtonChecked", Qt.Q_ARG("int", self._variable_qtgui_chooser_0_1_0_options.index(i)))
        self._variable_qtgui_chooser_0_1_0_callback(self.variable_qtgui_chooser_0_1_0)
        self._variable_qtgui_chooser_0_1_0_button_group.buttonClicked[int].connect(
        	lambda i: self.set_variable_qtgui_chooser_0_1_0(self._variable_qtgui_chooser_0_1_0_options[i]))
        self.top_layout.addWidget(self._variable_qtgui_chooser_0_1_0_group_box)
        self.uhd_usrp_source_0_0 = uhd.usrp_source(
        	",".join(("addr0=192.168.70.2,addr1=192.168.20.2,addr2=192.168.30.2,addr3=192.168.50.2", "")),
        	uhd.stream_args(
        		cpu_format="fc32",
        		channels=range(4),
        	),
        )
        self.uhd_usrp_source_0_0.set_clock_source("external", 0)
        self.uhd_usrp_source_0_0.set_time_source("external", 0)
        self.uhd_usrp_source_0_0.set_clock_source("external", 1)
        self.uhd_usrp_source_0_0.set_time_source("external", 1)
        self.uhd_usrp_source_0_0.set_clock_source("external", 2)
        self.uhd_usrp_source_0_0.set_time_source("external", 2)
        self.uhd_usrp_source_0_0.set_clock_source("external", 3)
        self.uhd_usrp_source_0_0.set_time_source("external", 3)
        self.uhd_usrp_source_0_0.set_time_unknown_pps(uhd.time_spec())
        self.uhd_usrp_source_0_0.set_samp_rate(samp_rate)
        self.uhd_usrp_source_0_0.set_center_freq(center_freq, 0)
        self.uhd_usrp_source_0_0.set_gain(gain_rx, 0)
        self.uhd_usrp_source_0_0.set_center_freq(center_freq, 1)
        self.uhd_usrp_source_0_0.set_gain(gain_rx, 1)
        self.uhd_usrp_source_0_0.set_center_freq(center_freq, 2)
        self.uhd_usrp_source_0_0.set_gain(gain_rx, 2)
        self.uhd_usrp_source_0_0.set_center_freq(center_freq, 3)
        self.uhd_usrp_source_0_0.set_gain(gain_rx, 3)
        self.uhd_usrp_sink_0_0_0 = uhd.usrp_sink(
        	",".join(("addr=192.168.80.2", "")),
        	uhd.stream_args(
        		cpu_format="fc32",
        		channels=range(1),
        	),
        )
        self.uhd_usrp_sink_0_0_0.set_time_now(uhd.time_spec(time.time()), uhd.ALL_MBOARDS)
        self.uhd_usrp_sink_0_0_0.set_samp_rate(samp_rate)
        self.uhd_usrp_sink_0_0_0.set_center_freq(center_freq, 0)
        self.uhd_usrp_sink_0_0_0.set_gain(30, 0)
        self.uhd_usrp_sink_0_0 = uhd.usrp_sink(
        	",".join(("addr=192.168.40.2", "")),
        	uhd.stream_args(
        		cpu_format="fc32",
        		channels=range(1),
        	),
        )
        self.uhd_usrp_sink_0_0.set_clock_source("mimo", 0)
        self.uhd_usrp_sink_0_0.set_time_source("mimo", 0)
        self.uhd_usrp_sink_0_0.set_time_now(uhd.time_spec(time.time()), uhd.ALL_MBOARDS)
        self.uhd_usrp_sink_0_0.set_samp_rate(samp_rate)
        self.uhd_usrp_sink_0_0.set_center_freq(center_freq, 0)
        self.uhd_usrp_sink_0_0.set_gain(10, 0)
        self.save_data_hier_0 = save_data_hier(
            keep=1,
            samples=2**22,
            skips=2**18,
            vec_size=1,
        )
        self.real_time_scope_hier_0_0_0 = real_time_scope_hier(
            npoints=3000,
            samp_rate=samp_rate,
        )
        self.tab_layout_2.addWidget(self.real_time_scope_hier_0_0_0)
        self.real_time_scope_hier_0 = real_time_scope_hier(
            npoints=3000,
            samp_rate=samp_rate,
        )
        self.tab_layout_0.addWidget(self.real_time_scope_hier_0)
        self.blocks_multiply_const_vxx_0_2 = blocks.multiply_const_vcc((complex(numpy.cos(Shift_1),numpy.sin(Shift_1)), ))
        self.blocks_multiply_const_vxx_0_1 = blocks.multiply_const_vcc((complex(numpy.cos(Shift_0),numpy.sin(Shift_0)), ))
        self.blocks_multiply_const_vxx_0_0 = blocks.multiply_const_vcc((complex(numpy.cos(Shift),numpy.sin(Shift)), ))
        self.blocks_message_strobe_0_0 = blocks.message_strobe(pmt.from_double(variable_qtgui_chooser_0_1_1), 1000)
        self.blks2_valve_0_0 = grc_blks2.valve(item_size=gr.sizeof_gr_complex*1, open=bool(variable_qtgui_chooser_0_0_0))
        self.blks2_valve_0 = grc_blks2.valve(item_size=gr.sizeof_gr_complex*1, open=bool(variable_qtgui_chooser_0_0))
        self.analog_sig_source_x_0_0 = analog.sig_source_c(samp_rate, analog.GR_COS_WAVE, cal_freq, 1, 0)
        self.analog_sig_source_x_0 = analog.sig_source_c(samp_rate, analog.GR_COS_WAVE, cal_freq, 1, 0)

        ##################################################
        # Connections
        ##################################################
        self.msg_connect((self.blocks_message_strobe_0_0, 'strobe'), (self.save_data_hier_0, 'Trigger'))    
        self.connect((self.analog_sig_source_x_0, 0), (self.blks2_valve_0, 0))    
        self.connect((self.analog_sig_source_x_0_0, 0), (self.blks2_valve_0_0, 0))    
        self.connect((self.blks2_valve_0, 0), (self.uhd_usrp_sink_0_0, 0))    
        self.connect((self.blks2_valve_0_0, 0), (self.uhd_usrp_sink_0_0_0, 0))    
        self.connect((self.blocks_multiply_const_vxx_0_0, 0), (self.real_time_scope_hier_0_0_0, 1))    
        self.connect((self.blocks_multiply_const_vxx_0_0, 0), (self.save_data_hier_0, 1))    
        self.connect((self.blocks_multiply_const_vxx_0_1, 0), (self.real_time_scope_hier_0_0_0, 2))    
        self.connect((self.blocks_multiply_const_vxx_0_1, 0), (self.save_data_hier_0, 2))    
        self.connect((self.blocks_multiply_const_vxx_0_2, 0), (self.real_time_scope_hier_0_0_0, 3))    
        self.connect((self.blocks_multiply_const_vxx_0_2, 0), (self.save_data_hier_0, 3))    
        self.connect((self.uhd_usrp_source_0_0, 1), (self.blocks_multiply_const_vxx_0_0, 0))    
        self.connect((self.uhd_usrp_source_0_0, 2), (self.blocks_multiply_const_vxx_0_1, 0))    
        self.connect((self.uhd_usrp_source_0_0, 3), (self.blocks_multiply_const_vxx_0_2, 0))    
        self.connect((self.uhd_usrp_source_0_0, 0), (self.real_time_scope_hier_0, 0))    
        self.connect((self.uhd_usrp_source_0_0, 1), (self.real_time_scope_hier_0, 1))    
        self.connect((self.uhd_usrp_source_0_0, 2), (self.real_time_scope_hier_0, 2))    
        self.connect((self.uhd_usrp_source_0_0, 3), (self.real_time_scope_hier_0, 3))    
        self.connect((self.uhd_usrp_source_0_0, 0), (self.real_time_scope_hier_0_0_0, 0))    
        self.connect((self.uhd_usrp_source_0_0, 0), (self.save_data_hier_0, 0))    
Пример #60
0
    def __init__(self):
        gr.top_block.__init__(self, "Calibration Example")
        Qt.QWidget.__init__(self)
        self.setWindowTitle("Calibration Example")
        try:
             self.setWindowIcon(Qt.QIcon.fromTheme('gnuradio-grc'))
        except:
             pass
        self.top_scroll_layout = Qt.QVBoxLayout()
        self.setLayout(self.top_scroll_layout)
        self.top_scroll = Qt.QScrollArea()
        self.top_scroll.setFrameStyle(Qt.QFrame.NoFrame)
        self.top_scroll_layout.addWidget(self.top_scroll)
        self.top_scroll.setWidgetResizable(True)
        self.top_widget = Qt.QWidget()
        self.top_scroll.setWidget(self.top_widget)
        self.top_layout = Qt.QVBoxLayout(self.top_widget)
        self.top_grid_layout = Qt.QGridLayout()
        self.top_layout.addLayout(self.top_grid_layout)

        self.settings = Qt.QSettings("GNU Radio", "calibration_example_gui")
        self.restoreGeometry(self.settings.value("geometry").toByteArray())

        ##################################################
        # Variables
        ##################################################
        self.speed_of_light = speed_of_light = 299792458
        self.antenna_spacing = antenna_spacing = 0.06
        self.variable_qtgui_chooser_0_1_1 = variable_qtgui_chooser_0_1_1 = 1
        self.variable_qtgui_chooser_0_1_0 = variable_qtgui_chooser_0_1_0 = 1
        self.variable_qtgui_chooser_0_0_0 = variable_qtgui_chooser_0_0_0 = 1
        self.variable_qtgui_chooser_0_0 = variable_qtgui_chooser_0_0 = 0
        self.samp_rate = samp_rate = 100000000/256
        self.gain_rx = gain_rx = 0
        self.center_freq = center_freq = speed_of_light/(2*antenna_spacing)
        self.cal_freq = cal_freq = 1024

        ##################################################
        # Blocks
        ##################################################
        self._variable_qtgui_chooser_0_1_1_options = (1, 0, )
        self._variable_qtgui_chooser_0_1_1_labels = ("Not Started", "Start Save", )
        self._variable_qtgui_chooser_0_1_1_group_box = Qt.QGroupBox("Trigger Data Save")
        self._variable_qtgui_chooser_0_1_1_box = Qt.QHBoxLayout()
        class variable_chooser_button_group(Qt.QButtonGroup):
            def __init__(self, parent=None):
                Qt.QButtonGroup.__init__(self, parent)
            @pyqtSlot(int)
            def updateButtonChecked(self, button_id):
                self.button(button_id).setChecked(True)
        self._variable_qtgui_chooser_0_1_1_button_group = variable_chooser_button_group()
        self._variable_qtgui_chooser_0_1_1_group_box.setLayout(self._variable_qtgui_chooser_0_1_1_box)
        for i, label in enumerate(self._variable_qtgui_chooser_0_1_1_labels):
        	radio_button = Qt.QRadioButton(label)
        	self._variable_qtgui_chooser_0_1_1_box.addWidget(radio_button)
        	self._variable_qtgui_chooser_0_1_1_button_group.addButton(radio_button, i)
        self._variable_qtgui_chooser_0_1_1_callback = lambda i: Qt.QMetaObject.invokeMethod(self._variable_qtgui_chooser_0_1_1_button_group, "updateButtonChecked", Qt.Q_ARG("int", self._variable_qtgui_chooser_0_1_1_options.index(i)))
        self._variable_qtgui_chooser_0_1_1_callback(self.variable_qtgui_chooser_0_1_1)
        self._variable_qtgui_chooser_0_1_1_button_group.buttonClicked[int].connect(
        	lambda i: self.set_variable_qtgui_chooser_0_1_1(self._variable_qtgui_chooser_0_1_1_options[i]))
        self.top_layout.addWidget(self._variable_qtgui_chooser_0_1_1_group_box)
        self._variable_qtgui_chooser_0_1_0_options = (1, 0, )
        self._variable_qtgui_chooser_0_1_0_labels = ("Stop", "Running", )
        self._variable_qtgui_chooser_0_1_0_tool_bar = Qt.QToolBar(self)
        self._variable_qtgui_chooser_0_1_0_tool_bar.addWidget(Qt.QLabel("Sync System"+": "))
        self._variable_qtgui_chooser_0_1_0_combo_box = Qt.QComboBox()
        self._variable_qtgui_chooser_0_1_0_tool_bar.addWidget(self._variable_qtgui_chooser_0_1_0_combo_box)
        for label in self._variable_qtgui_chooser_0_1_0_labels: self._variable_qtgui_chooser_0_1_0_combo_box.addItem(label)
        self._variable_qtgui_chooser_0_1_0_callback = lambda i: Qt.QMetaObject.invokeMethod(self._variable_qtgui_chooser_0_1_0_combo_box, "setCurrentIndex", Qt.Q_ARG("int", self._variable_qtgui_chooser_0_1_0_options.index(i)))
        self._variable_qtgui_chooser_0_1_0_callback(self.variable_qtgui_chooser_0_1_0)
        self._variable_qtgui_chooser_0_1_0_combo_box.currentIndexChanged.connect(
        	lambda i: self.set_variable_qtgui_chooser_0_1_0(self._variable_qtgui_chooser_0_1_0_options[i]))
        self.top_layout.addWidget(self._variable_qtgui_chooser_0_1_0_tool_bar)
        self._variable_qtgui_chooser_0_0_0_options = (0, 1, )
        self._variable_qtgui_chooser_0_0_0_labels = ("Enable", "Disable", )
        self._variable_qtgui_chooser_0_0_0_group_box = Qt.QGroupBox("Transmitter Enable")
        self._variable_qtgui_chooser_0_0_0_box = Qt.QVBoxLayout()
        class variable_chooser_button_group(Qt.QButtonGroup):
            def __init__(self, parent=None):
                Qt.QButtonGroup.__init__(self, parent)
            @pyqtSlot(int)
            def updateButtonChecked(self, button_id):
                self.button(button_id).setChecked(True)
        self._variable_qtgui_chooser_0_0_0_button_group = variable_chooser_button_group()
        self._variable_qtgui_chooser_0_0_0_group_box.setLayout(self._variable_qtgui_chooser_0_0_0_box)
        for i, label in enumerate(self._variable_qtgui_chooser_0_0_0_labels):
        	radio_button = Qt.QRadioButton(label)
        	self._variable_qtgui_chooser_0_0_0_box.addWidget(radio_button)
        	self._variable_qtgui_chooser_0_0_0_button_group.addButton(radio_button, i)
        self._variable_qtgui_chooser_0_0_0_callback = lambda i: Qt.QMetaObject.invokeMethod(self._variable_qtgui_chooser_0_0_0_button_group, "updateButtonChecked", Qt.Q_ARG("int", self._variable_qtgui_chooser_0_0_0_options.index(i)))
        self._variable_qtgui_chooser_0_0_0_callback(self.variable_qtgui_chooser_0_0_0)
        self._variable_qtgui_chooser_0_0_0_button_group.buttonClicked[int].connect(
        	lambda i: self.set_variable_qtgui_chooser_0_0_0(self._variable_qtgui_chooser_0_0_0_options[i]))
        self.top_layout.addWidget(self._variable_qtgui_chooser_0_0_0_group_box)
        self._variable_qtgui_chooser_0_0_options = (0, 1, )
        self._variable_qtgui_chooser_0_0_labels = ("Enable", "Disable", )
        self._variable_qtgui_chooser_0_0_group_box = Qt.QGroupBox("Source Enable")
        self._variable_qtgui_chooser_0_0_box = Qt.QVBoxLayout()
        class variable_chooser_button_group(Qt.QButtonGroup):
            def __init__(self, parent=None):
                Qt.QButtonGroup.__init__(self, parent)
            @pyqtSlot(int)
            def updateButtonChecked(self, button_id):
                self.button(button_id).setChecked(True)
        self._variable_qtgui_chooser_0_0_button_group = variable_chooser_button_group()
        self._variable_qtgui_chooser_0_0_group_box.setLayout(self._variable_qtgui_chooser_0_0_box)
        for i, label in enumerate(self._variable_qtgui_chooser_0_0_labels):
        	radio_button = Qt.QRadioButton(label)
        	self._variable_qtgui_chooser_0_0_box.addWidget(radio_button)
        	self._variable_qtgui_chooser_0_0_button_group.addButton(radio_button, i)
        self._variable_qtgui_chooser_0_0_callback = lambda i: Qt.QMetaObject.invokeMethod(self._variable_qtgui_chooser_0_0_button_group, "updateButtonChecked", Qt.Q_ARG("int", self._variable_qtgui_chooser_0_0_options.index(i)))
        self._variable_qtgui_chooser_0_0_callback(self.variable_qtgui_chooser_0_0)
        self._variable_qtgui_chooser_0_0_button_group.buttonClicked[int].connect(
        	lambda i: self.set_variable_qtgui_chooser_0_0(self._variable_qtgui_chooser_0_0_options[i]))
        self.top_layout.addWidget(self._variable_qtgui_chooser_0_0_group_box)
        self.wifius_find_scale_factor_0_0 = wifius.find_scale_factor(samp_rate,cal_freq)
        self.wifius_find_scale_factor_0 = wifius.find_scale_factor(samp_rate,cal_freq)
        self.wifius_divide_by_message_0_0 = wifius.divide_by_message()
        self.wifius_divide_by_message_0 = wifius.divide_by_message()
        self.wifius_blocker_0 = wifius.blocker(True)
        self.uhd_usrp_source_0_0 = uhd.usrp_source(
        	",".join(("addr0=192.168.20.2,addr1=192.168.50.2", "")),
        	uhd.stream_args(
        		cpu_format="fc32",
        		channels=range(2),
        	),
        )
        self.uhd_usrp_source_0_0.set_clock_source("external", 0)
        self.uhd_usrp_source_0_0.set_time_source("external", 0)
        self.uhd_usrp_source_0_0.set_clock_source("external", 1)
        self.uhd_usrp_source_0_0.set_time_source("external", 1)
        self.uhd_usrp_source_0_0.set_time_unknown_pps(uhd.time_spec())
        self.uhd_usrp_source_0_0.set_samp_rate(samp_rate)
        self.uhd_usrp_source_0_0.set_center_freq(center_freq, 0)
        self.uhd_usrp_source_0_0.set_gain(gain_rx, 0)
        self.uhd_usrp_source_0_0.set_center_freq(center_freq, 1)
        self.uhd_usrp_source_0_0.set_gain(gain_rx, 1)
        self.uhd_usrp_sink_0_0_0 = uhd.usrp_sink(
        	",".join(("addr=192.168.90.2", "")),
        	uhd.stream_args(
        		cpu_format="fc32",
        		channels=range(1),
        	),
        )
        self.uhd_usrp_sink_0_0_0.set_time_now(uhd.time_spec(time.time()), uhd.ALL_MBOARDS)
        self.uhd_usrp_sink_0_0_0.set_samp_rate(samp_rate)
        self.uhd_usrp_sink_0_0_0.set_center_freq(center_freq, 0)
        self.uhd_usrp_sink_0_0_0.set_gain(30, 0)
        self.uhd_usrp_sink_0_0 = uhd.usrp_sink(
        	",".join(("addr=192.168.40.2", "")),
        	uhd.stream_args(
        		cpu_format="fc32",
        		channels=range(1),
        	),
        )
        self.uhd_usrp_sink_0_0.set_clock_source("mimo", 0)
        self.uhd_usrp_sink_0_0.set_time_source("mimo", 0)
        self.uhd_usrp_sink_0_0.set_time_now(uhd.time_spec(time.time()), uhd.ALL_MBOARDS)
        self.uhd_usrp_sink_0_0.set_samp_rate(samp_rate)
        self.uhd_usrp_sink_0_0.set_center_freq(center_freq, 0)
        self.uhd_usrp_sink_0_0.set_gain(10, 0)
        self.tab = Qt.QTabWidget()
        self.tab_widget_0 = Qt.QWidget()
        self.tab_layout_0 = Qt.QBoxLayout(Qt.QBoxLayout.TopToBottom, self.tab_widget_0)
        self.tab_grid_layout_0 = Qt.QGridLayout()
        self.tab_layout_0.addLayout(self.tab_grid_layout_0)
        self.tab.addTab(self.tab_widget_0, "Input")
        self.tab_widget_1 = Qt.QWidget()
        self.tab_layout_1 = Qt.QBoxLayout(Qt.QBoxLayout.TopToBottom, self.tab_widget_1)
        self.tab_grid_layout_1 = Qt.QGridLayout()
        self.tab_layout_1.addLayout(self.tab_grid_layout_1)
        self.tab.addTab(self.tab_widget_1, "Post Gain Correct")
        self.tab_widget_2 = Qt.QWidget()
        self.tab_layout_2 = Qt.QBoxLayout(Qt.QBoxLayout.TopToBottom, self.tab_widget_2)
        self.tab_grid_layout_2 = Qt.QGridLayout()
        self.tab_layout_2.addLayout(self.tab_grid_layout_2)
        self.tab.addTab(self.tab_widget_2, "Post Phase Correct")
        self.top_layout.addWidget(self.tab)
        self.qtgui_time_sink_x_1 = qtgui.time_sink_f(
        	1024, #size
        	samp_rate, #samp_rate
        	"", #name
        	1 #number of inputs
        )
        self.qtgui_time_sink_x_1.set_update_time(0.10)
        self.qtgui_time_sink_x_1.set_y_axis(-1, 1)
        
        self.qtgui_time_sink_x_1.set_y_label("Amplitude", "")
        
        self.qtgui_time_sink_x_1.enable_tags(-1, True)
        self.qtgui_time_sink_x_1.set_trigger_mode(qtgui.TRIG_MODE_FREE, qtgui.TRIG_SLOPE_POS, 0.0, 0, 0, "")
        self.qtgui_time_sink_x_1.enable_autoscale(True)
        self.qtgui_time_sink_x_1.enable_grid(False)
        self.qtgui_time_sink_x_1.enable_control_panel(True)
        
        if not True:
          self.qtgui_time_sink_x_1.disable_legend()
        
        labels = ["", "", "", "", "",
                  "", "", "", "", ""]
        widths = [1, 1, 1, 1, 1,
                  1, 1, 1, 1, 1]
        colors = ["blue", "red", "green", "black", "cyan",
                  "magenta", "yellow", "dark red", "dark green", "blue"]
        styles = [1, 1, 1, 1, 1,
                  1, 1, 1, 1, 1]
        markers = [-1, -1, -1, -1, -1,
                   -1, -1, -1, -1, -1]
        alphas = [1.0, 1.0, 1.0, 1.0, 1.0,
                  1.0, 1.0, 1.0, 1.0, 1.0]
        
        for i in xrange(1):
            if len(labels[i]) == 0:
                self.qtgui_time_sink_x_1.set_line_label(i, "Data {0}".format(i))
            else:
                self.qtgui_time_sink_x_1.set_line_label(i, labels[i])
            self.qtgui_time_sink_x_1.set_line_width(i, widths[i])
            self.qtgui_time_sink_x_1.set_line_color(i, colors[i])
            self.qtgui_time_sink_x_1.set_line_style(i, styles[i])
            self.qtgui_time_sink_x_1.set_line_marker(i, markers[i])
            self.qtgui_time_sink_x_1.set_line_alpha(i, alphas[i])
        
        self._qtgui_time_sink_x_1_win = sip.wrapinstance(self.qtgui_time_sink_x_1.pyqwidget(), Qt.QWidget)
        self.top_layout.addWidget(self._qtgui_time_sink_x_1_win)
        self.qtgui_time_sink_x_0 = qtgui.time_sink_f(
        	1024, #size
        	samp_rate, #samp_rate
        	"", #name
        	2 #number of inputs
        )
        self.qtgui_time_sink_x_0.set_update_time(0.10)
        self.qtgui_time_sink_x_0.set_y_axis(-1, 1)
        
        self.qtgui_time_sink_x_0.set_y_label("Amplitude", "")
        
        self.qtgui_time_sink_x_0.enable_tags(-1, True)
        self.qtgui_time_sink_x_0.set_trigger_mode(qtgui.TRIG_MODE_AUTO, qtgui.TRIG_SLOPE_POS, 0.0, 0, 0, "")
        self.qtgui_time_sink_x_0.enable_autoscale(False)
        self.qtgui_time_sink_x_0.enable_grid(False)
        self.qtgui_time_sink_x_0.enable_control_panel(True)
        
        if not True:
          self.qtgui_time_sink_x_0.disable_legend()
        
        labels = ["", "", "", "", "",
                  "", "", "", "", ""]
        widths = [1, 1, 1, 1, 1,
                  1, 1, 1, 1, 1]
        colors = ["blue", "red", "green", "black", "cyan",
                  "magenta", "yellow", "dark red", "dark green", "blue"]
        styles = [1, 1, 1, 1, 1,
                  1, 1, 1, 1, 1]
        markers = [-1, -1, -1, -1, -1,
                   -1, -1, -1, -1, -1]
        alphas = [1.0, 1.0, 1.0, 1.0, 1.0,
                  1.0, 1.0, 1.0, 1.0, 1.0]
        
        for i in xrange(2):
            if len(labels[i]) == 0:
                self.qtgui_time_sink_x_0.set_line_label(i, "Data {0}".format(i))
            else:
                self.qtgui_time_sink_x_0.set_line_label(i, labels[i])
            self.qtgui_time_sink_x_0.set_line_width(i, widths[i])
            self.qtgui_time_sink_x_0.set_line_color(i, colors[i])
            self.qtgui_time_sink_x_0.set_line_style(i, styles[i])
            self.qtgui_time_sink_x_0.set_line_marker(i, markers[i])
            self.qtgui_time_sink_x_0.set_line_alpha(i, alphas[i])
        
        self._qtgui_time_sink_x_0_win = sip.wrapinstance(self.qtgui_time_sink_x_0.pyqwidget(), Qt.QWidget)
        self.top_layout.addWidget(self._qtgui_time_sink_x_0_win)
        self.delay_correct_hier_0 = delay_correct_hier(
            cal_tone_freq=cal_freq,
            mu=0.001,
            samp_rate=samp_rate,
        )
        self.blocks_message_strobe_0_1 = blocks.message_strobe(pmt.from_double(variable_qtgui_chooser_0_1_1), 1000)
        self.blocks_message_strobe_0 = blocks.message_strobe(pmt.from_double(variable_qtgui_chooser_0_1_0), 1000)
        self.blocks_complex_to_real_1 = blocks.complex_to_real(1)
        self.blocks_complex_to_real_0 = blocks.complex_to_real(1)
        self.blks2_valve_0_0 = grc_blks2.valve(item_size=gr.sizeof_gr_complex*1, open=bool(variable_qtgui_chooser_0_0_0))
        self.blks2_valve_0 = grc_blks2.valve(item_size=gr.sizeof_gr_complex*1, open=bool(variable_qtgui_chooser_0_0))
        self.analog_sig_source_x_0_0 = analog.sig_source_c(samp_rate, analog.GR_COS_WAVE, cal_freq, 1, 0)
        self.analog_sig_source_x_0 = analog.sig_source_c(samp_rate, analog.GR_COS_WAVE, cal_freq, 1, 0)

        ##################################################
        # Connections
        ##################################################
        self.msg_connect((self.blocks_message_strobe_0, 'strobe'), (self.delay_correct_hier_0, 'enable_sync'))    
        self.msg_connect((self.blocks_message_strobe_0_1, 'strobe'), (self.wifius_blocker_0, 'enable_stop'))    
        self.msg_connect((self.wifius_find_scale_factor_0, 'message'), (self.wifius_divide_by_message_0, 'set_divisor'))    
        self.msg_connect((self.wifius_find_scale_factor_0_0, 'message'), (self.wifius_divide_by_message_0_0, 'set_divisor'))    
        self.connect((self.analog_sig_source_x_0, 0), (self.blks2_valve_0, 0))    
        self.connect((self.analog_sig_source_x_0_0, 0), (self.blks2_valve_0_0, 0))    
        self.connect((self.blks2_valve_0, 0), (self.uhd_usrp_sink_0_0, 0))    
        self.connect((self.blks2_valve_0_0, 0), (self.uhd_usrp_sink_0_0_0, 0))    
        self.connect((self.blocks_complex_to_real_0, 0), (self.qtgui_time_sink_x_0, 1))    
        self.connect((self.blocks_complex_to_real_1, 0), (self.qtgui_time_sink_x_0, 0))    
        self.connect((self.delay_correct_hier_0, 0), (self.blocks_complex_to_real_1, 0))    
        self.connect((self.delay_correct_hier_0, 1), (self.qtgui_time_sink_x_1, 0))    
        self.connect((self.uhd_usrp_source_0_0, 0), (self.wifius_blocker_0, 0))    
        self.connect((self.uhd_usrp_source_0_0, 1), (self.wifius_blocker_0, 1))    
        self.connect((self.uhd_usrp_source_0_0, 0), (self.wifius_divide_by_message_0, 0))    
        self.connect((self.uhd_usrp_source_0_0, 1), (self.wifius_divide_by_message_0_0, 0))    
        self.connect((self.wifius_blocker_0, 0), (self.wifius_find_scale_factor_0, 0))    
        self.connect((self.wifius_blocker_0, 1), (self.wifius_find_scale_factor_0_0, 0))    
        self.connect((self.wifius_divide_by_message_0, 0), (self.delay_correct_hier_0, 0))    
        self.connect((self.wifius_divide_by_message_0_0, 0), (self.blocks_complex_to_real_0, 0))    
        self.connect((self.wifius_divide_by_message_0_0, 0), (self.delay_correct_hier_0, 1))