Exemplo n.º 1
0
    def set_frequency(self, freq):
        tune_request = uhd.tune_request(freq, self.profile.usrp_lo_offset)
        if self.profile.usrp_use_integerN_tuning:
            tune_request.args = uhd.device_addr('mode_n=integer')

        tune_result = self.usrp.set_center_freq(tune_request)
        print(tune_result.to_pp_string())
Exemplo n.º 2
0
	def __init__(self):
		gr.top_block.__init__(self)
		
		usage = "usage: %prog [options]"
		parser = OptionParser(option_class=eng_option, usage=usage)
		parser.add_option("-f", "--tx-freq", type="eng_float", default=None,
						  metavar="Hz", help="Transmit frequency [default=center_frequency]")

		(options, args) = parser.parse_args()

		args = "" #only supporting USB USRPs for now

		#find uhd devices

		d = uhd.find_devices(uhd.device_addr(args))

		if d:
			uhd_type = d[0].get('type')
			print "\nFound '%s'" % uhd_type
		else:
			print "\nNo device found"
			self.u_tx = None
			return

		#check version of USRP and set num_channels

		if uhd_type == "usrp":
			tx_nchan = 2
			rx_nchan = 2
		else:
			tx_nchan = 1
			rx_nchan = 1

		#setup transmit chain (usrp sink, signal source)
		
		#usrp sink
		stream_args = uhd.stream_args('fc32', channels = range(tx_nchan))
		self.u_tx = uhd.usrp_sink(device_addr=args, stream_args=stream_args)
		self.u_tx.set_samp_rate(MAX_RATE)

		#analog signal source - sig_source_c(sampling_freq,waveform, wave_freq, ampl, offset=0)
		self.tx_src0 = analog.sig_source_c(self.u_tx.get_samp_rate(), analog.GR_CONST_WAVE, 0, 1.0, 0)

		#check and output freq range, gain range, num_channels

		#gain range and max
		tx_gain_range = self.u_tx.get_gain_range()
		tx_gain_min = tx_gain_range.start()
		tx_gain_max = tx_gain_range.stop()

		#freq range
		tx_freq_range = self.u_tx.get_freq_range()
		tx_freq_low = tx_freq_range.start()
		tx_freq_high = tx_freq_range.stop()
		tx_freq_mid = (tx_freq_low + tx_freq_high) / 2.0

		if options.tx_freq is None:
			self.tx_freq = tx_freq_mid
		else:
			if options.tx_freq < 1e6:
				options.tx_freq *= 1e6
			self.tx_freq = options.tx_freq

		#output info
		print "\nDevice Info -\tType: %s\tFreq(MHz): (%d,%d,%d)\tGain(dB): (%f,%f)\n" % (uhd_type, (tx_freq_low/1e6), (tx_freq_mid/1e6), (tx_freq_high/1e6), tx_gain_min, tx_gain_max)		

		#set initial parameters 
		self.u_tx.set_center_freq(self.tx_freq)
		self.u_tx.set_gain(tx_gain_max)

		#connect blocks

		self.connect(self.tx_src0, self.u_tx)
Exemplo n.º 3
0
    def __init__(self, args, tx_enable, rx_enable):
        gr.top_block.__init__(self)

        d = uhd.find_devices(uhd.device_addr(args))
        uhd_type = d[0].get('type')

        print "\nFound '%s' at args '%s'" % \
            (uhd_type, args)

        # Test the type of USRP; if it's a USRP (v1), it has
        # 2 channels; otherwise, it has 1 channel
        if uhd_type == "usrp":
            tx_nchan = 2
            rx_nchan = 2
        else:
            tx_nchan = 1
            rx_nchan = 1
        
        if tx_enable:
            print "\nTRANSMIT CHAIN"
            self.u_tx = uhd.usrp_sink(device_addr=args,
                                      io_type=uhd.io_type.COMPLEX_FLOAT32,
                                      num_channels=tx_nchan)
            self.u_tx.set_samp_rate(MAX_RATE)

            self.tx_src0 = gr.sig_source_c(self.u_tx.get_samp_rate(),
                                           gr.GR_CONST_WAVE,
                                           0, 1.0, 0)

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

            # Get dboard freq range and select midpoint
            tx_freq_range = self.u_tx.get_freq_range()
            tx_freq_mid = (tx_freq_range.start() + tx_freq_range.stop())/2.0

            for i in xrange(tx_nchan):
                self.u_tx.set_center_freq (tx_freq_mid + i*1e6, i)
                self.u_tx.set_gain(tx_gain, i)

            print "\nTx Sample Rate: %ssps" % (n2s(self.u_tx.get_samp_rate()))
            for i in xrange(tx_nchan):
                print "Tx Channel %d: " % (i)
                print "\tFrequency = %sHz" % \
                    (n2s(self.u_tx.get_center_freq(i)))
                print "\tGain = %f dB" % (self.u_tx.get_gain(i))
            print ""

            self.connect (self.tx_src0, self.u_tx)

        if rx_enable:
            print "\nRECEIVE CHAIN"
            self.u_rx = uhd.usrp_source(device_addr=args,
                                        io_type=uhd.io_type.COMPLEX_FLOAT32,
                                        num_channels=rx_nchan)
            self.rx_dst0 = gr.null_sink (gr.sizeof_gr_complex)

            self.u_rx.set_samp_rate(MAX_RATE)

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

            # Get dboard freq range and select midpoint
            rx_freq_range = self.u_rx.get_freq_range()
            rx_freq_mid = (rx_freq_range.start() + rx_freq_range.stop())/2.0

            for i in xrange(tx_nchan):
                self.u_rx.set_center_freq (rx_freq_mid + i*1e6, i)
                self.u_rx.set_gain(rx_gain, i)

            print "\nRx Sample Rate: %ssps" % (n2s(self.u_rx.get_samp_rate()))
            for i in xrange(rx_nchan):
                print "Rx Channel %d: " % (i)
                print "\tFrequency = %sHz" % \
                    (n2s(self.u_rx.get_center_freq(i)))
                print "\tGain = %f dB" % (self.u_rx.get_gain(i))
            print ""

            self.connect (self.u_rx, self.rx_dst0)
Exemplo n.º 4
0
    def _usrp_setup(self):
        """Create, set up, and return USRP sink object."""
        op = self.op
        # create usrp sink block
        u = uhd.usrp_sink(
            device_addr=",".join(chain(op.mboard_strs, op.dev_args)),
            stream_args=uhd.stream_args(
                cpu_format="fc32",
                otw_format="sc16",
                channels=list(range(op.nchs)),
                args=",".join(op.stream_args),
            ),
        )

        # set clock and time source if synced
        if op.sync:
            try:
                u.set_clock_source(op.sync_source, uhd.ALL_MBOARDS)
                u.set_time_source(op.sync_source, uhd.ALL_MBOARDS)
            except RuntimeError:
                errstr = (
                    "Unknown sync_source option: '{0}'. Must be one of {1}."
                ).format(op.sync_source, u.get_clock_sources(0))
                raise ValueError(errstr)

        # check for ref lock
        mbnums_with_ref = [
            mb_num for mb_num in range(op.nmboards)
            if "ref_locked" in u.get_mboard_sensor_names(mb_num)
        ]
        if mbnums_with_ref:
            if op.verbose:
                sys.stdout.write("Waiting for reference lock...")
                sys.stdout.flush()
            timeout = 0
            while not all(
                    u.get_mboard_sensor("ref_locked", mb_num).to_bool()
                    for mb_num in mbnums_with_ref):
                if op.verbose:
                    sys.stdout.write(".")
                    sys.stdout.flush()
                time.sleep(1)
                timeout += 1
                if timeout > 30:
                    if op.verbose:
                        sys.stdout.write("failed\n")
                        sys.stdout.flush()
                    raise RuntimeError("Failed to lock to 10 MHz reference.")
            if op.verbose:
                sys.stdout.write("locked\n")
                sys.stdout.flush()

        # set mainboard options
        for mb_num in range(op.nmboards):
            u.set_subdev_spec(op.subdevs[mb_num], mb_num)
        # set global options
        # sample rate
        u.set_samp_rate(float(op.samplerate))
        # read back actual value
        samplerate = u.get_samp_rate()
        # calculate longdouble precision sample rate
        # (integer division of clock rate)
        cr = u.get_clock_rate()
        srdec = int(round(cr / samplerate))
        samplerate_ld = np.longdouble(cr) / srdec
        op.samplerate = samplerate_ld
        sr_rat = Fraction(cr).limit_denominator() / srdec
        op.samplerate_num = sr_rat.numerator
        op.samplerate_den = sr_rat.denominator

        # set per-channel options
        # set command time so settings are synced
        COMMAND_DELAY = 0.2
        cmd_time = u.get_time_now() + uhd.time_spec(COMMAND_DELAY)
        u.set_command_time(cmd_time, uhd.ALL_MBOARDS)
        for ch_num in range(op.nchs):
            # local oscillator sharing settings
            lo_source = op.lo_sources[ch_num]
            if lo_source:
                try:
                    u.set_lo_source(lo_source, uhd.ALL_LOS, ch_num)
                except RuntimeError:
                    errstr = (
                        "Unknown LO source option: '{0}'. Must be one of {1},"
                        " or it may not be possible to set the LO source on"
                        " this daughterboard.").format(
                            lo_source, u.get_lo_sources(uhd.ALL_LOS, ch_num))
                    raise ValueError(errstr)
            lo_export = op.lo_exports[ch_num]
            if lo_export is not None:
                if not lo_source:
                    errstr = (
                        "Channel {0}: must set an LO source in order to set"
                        " LO export.").format(ch_num)
                    raise ValueError(errstr)
                u.set_lo_export_enabled(lo_export, uhd.ALL_LOS, ch_num)
            # center frequency and tuning offset
            tune_res = u.set_center_freq(
                uhd.tune_request(
                    op.centerfreqs[ch_num],
                    op.lo_offsets[ch_num],
                    args=uhd.device_addr(",".join(op.tune_args)),
                ),
                ch_num,
            )
            # store actual values from tune result
            op.centerfreqs[
                ch_num] = tune_res.actual_rf_freq + tune_res.actual_dsp_freq
            op.lo_offsets[ch_num] = -tune_res.actual_dsp_freq
            # dc offset
            dc_offset = op.dc_offsets[ch_num]
            if dc_offset is not None:
                u.set_dc_offset(dc_offset, ch_num)
            # iq balance
            iq_balance = op.iq_balances[ch_num]
            if iq_balance is not None:
                u.set_iq_balance(iq_balance, ch_num)
            # gain
            u.set_gain(op.gains[ch_num], ch_num)
            # bandwidth
            bw = op.bandwidths[ch_num]
            if bw:
                u.set_bandwidth(bw, ch_num)
            # antenna
            ant = op.antennas[ch_num]
            if ant:
                try:
                    u.set_antenna(ant, ch_num)
                except RuntimeError:
                    errstr = (
                        "Unknown RX antenna option: '{0}'. Must be one of {1}."
                    ).format(ant, u.get_antennas(ch_num))
                    raise ValueError(errstr)

        # commands are done, clear time
        u.clear_command_time(uhd.ALL_MBOARDS)
        time.sleep(COMMAND_DELAY)

        # read back actual channel settings
        for ch_num in range(op.nchs):
            if op.lo_sources[ch_num]:
                op.lo_sources[ch_num] = u.get_lo_source(uhd.ALL_LOS, ch_num)
            if op.lo_exports[ch_num] is not None:
                op.lo_exports[ch_num] = u.get_lo_export_enabled(
                    uhd.ALL_LOS, ch_num)
            op.gains[ch_num] = u.get_gain(ch_num)
            op.bandwidths[ch_num] = u.get_bandwidth(chan=ch_num)
            op.antennas[ch_num] = u.get_antenna(chan=ch_num)

        if op.verbose:
            print("Using the following devices:")
            chinfostrs = [
                "Motherboard: {mb_id} ({mb_addr}) | Daughterboard: {db_name}",
                "Subdev: {sub} | Antenna: {ant} | Gain: {gain} | Rate: {sr}",
                "Frequency: {freq:.3f} ({lo_off:+.3f}) | Bandwidth: {bw}",
            ]
            if any(op.lo_sources) or any(op.lo_exports):
                chinfostrs.append(
                    "LO source: {lo_source} | LO export: {lo_export}")
            chinfo = "\n".join(["  " + l for l in chinfostrs])
            for ch_num in range(op.nchs):
                header = "---- {0} ".format(ch_num)
                header += "-" * (78 - len(header))
                print(header)
                usrpinfo = dict(u.get_usrp_info(chan=ch_num))
                info = {}
                info["mb_id"] = usrpinfo["mboard_id"]
                mba = op.mboards_bychan[ch_num]
                if mba == "default":
                    mba = usrpinfo["mboard_serial"]
                info["mb_addr"] = mba
                info["db_name"] = usrpinfo["tx_subdev_name"]
                info["sub"] = op.subdevs_bychan[ch_num]
                info["ant"] = op.antennas[ch_num]
                info["bw"] = op.bandwidths[ch_num]
                info["dc_offset"] = op.dc_offsets[ch_num]
                info["freq"] = op.centerfreqs[ch_num]
                info["gain"] = op.gains[ch_num]
                info["iq_balance"] = op.iq_balances[ch_num]
                info["lo_off"] = op.lo_offsets[ch_num]
                info["lo_source"] = op.lo_sources[ch_num]
                info["lo_export"] = op.lo_exports[ch_num]
                info["sr"] = op.samplerate
                print(chinfo.format(**info))
                print("-" * 78)

        return u
Exemplo n.º 5
0
    def __init__(self):
        gr.top_block.__init__(self)

        args = ""  #only supporting USB USRPs for now

        #find uhd devices

        d = uhd.find_devices(uhd.device_addr(args))
        if d:

            uhd_type = d[0].get('type')
            print "\nFound '%s'" % uhd_type
        else:
            print "\nNo device found"
            self.u_tx = None
            return

        #check version of USRP and set num_channels

        if uhd_type == "usrp":
            tx_nchan = 2
            rx_nchan = 2
        else:
            tx_nchan = 1
            rx_nchan = 1

        #setup transmit chain (usrp sink, signal source)

        #usrp sink
        stream_args = uhd.stream_args('fc32', channels=range(tx_nchan))
        self.u_tx = uhd.usrp_sink(device_addr=args, stream_args=stream_args)
        self.u_tx.set_samp_rate(MAX_RATE)

        #analog signal source - sig_source_c(sampling_freq,waveform, wave_freq, ampl, offset=0)
        self.tx_src0 = analog.sig_source_c(self.u_tx.get_samp_rate(),
                                           analog.GR_CONST_WAVE, 0, 1.0, 0)

        #check and output freq range, gain range, num_channels

        #gain range and max
        tx_gain_range = self.u_tx.get_gain_range()
        tx_gain_min = tx_gain_range.start()
        tx_gain_max = tx_gain_range.stop()

        #freq range
        tx_freq_range = self.u_tx.get_freq_range()
        tx_freq_low = tx_freq_range.start()
        tx_freq_high = tx_freq_range.stop()
        tx_freq_mid = (tx_freq_low + tx_freq_high) / 2.0

        #output info
        print "\nDevice Info"
        print "\n\tType: %s" % uhd_type

        print "\n\tMin Freq: %d MHz" % (tx_freq_low / 1e6)
        print "\tMax Freq: %d MHz" % (tx_freq_high / 1e6)
        print "\tMid Freq: %d MHz" % (tx_freq_mid / 1e6)

        print "\n\tMin Gain: %d dB" % tx_gain_min
        print "\tMax Gain: %d dB" % tx_gain_max

        #set initial parameters

        for i in xrange(tx_nchan):
            self.u_tx.set_center_freq(tx_freq_mid + i * 1e6, i)
            self.u_tx.set_gain(tx_gain_max, i)

        #connect blocks

        self.connect(self.tx_src0, self.u_tx)
Exemplo n.º 6
0
    def __init__(self):
        gr.top_block.__init__(self)

        usage = "%prog: [options] tx-freq0 tx-freq1"
        parser = OptionParser (option_class=eng_option, usage=usage)
        parser.add_option("-a", "--args", type="string", default="",
                          help="UHD device address args [default=%default]")
        parser.add_option("", "--spec", type="string", default=None,
	                  help="Subdevice of UHD device where appropriate")
        parser.add_option("-A", "--antenna", type="string", default=None,
                          help="select Rx Antenna where appropriate")
        parser.add_option("-s", "--samp-rate", type="eng_float", default=320e3,
                          help="set sample rate [default=%default]")
        parser.add_option("-g", "--gain", type="eng_float", default=None,
                          help="set gain in dB (default is midpoint)")
        (options, args) = parser.parse_args ()

        if len(args) != 2:
            parser.print_help()
            raise SystemExit
        else:
            freq0 = str_to_num(args[0])
            freq1 = str_to_num(args[1])

        # ----------------------------------------------------------------
        # Set up USRP to transmit on both daughterboards

        d = uhd.find_devices(uhd.device_addr(options.args))
        uhd_type = d[0].get('type')

        stream_args = uhd.stream_args('fc32', channels=range(2))
        self.u = uhd.usrp_sink(device_addr=options.args, stream_args=stream_args)

        # Set up USRP system based on type
        if(uhd_type == "usrp"):
            self.u.set_subdev_spec("A:0 B:0")
            tr0 = uhd.tune_request(freq0)
            tr1 = uhd.tune_request(freq1)

        else:
            if abs(freq0 - freq1) > 5.5e6:
                sys.stderr.write("\nError: When not using two separate d'boards, frequencies must bewithin 5.5MHz of each other.\n")
                raise SystemExit

            self.u.set_subdev_spec("A:0 A:0")

            mid_freq = (freq0 + freq1)/2.0
            tr0 = uhd.tune_request(freq0, rf_freq=mid_freq,
                                   rf_freq_policy=uhd.tune_request.POLICY_MANUAL)

            tr1 = uhd.tune_request(freq1, rf_freq=mid_freq,
                                   rf_freq_policy=uhd.tune_request.POLICY_MANUAL)

        # Use the tune requests to tune each channel
        self.set_freq(tr0, 0)
        self.set_freq(tr1, 1)

        self.usrp_rate  = options.samp_rate

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

        # ----------------------------------------------------------------
        # build two signal sources, interleave them, amplify and
        # connect them to usrp

        sig0 = example_signal_0(self.usrp_rate)
        sig1 = example_signal_1(self.usrp_rate)

        intl = blocks.interleave(gr.sizeof_gr_complex)
        self.connect(sig0, (intl, 0))
        self.connect(sig1, (intl, 1))

        # Correct for any difference in requested and actual rates
        rrate = self.usrp_rate / dev_rate
        resamp = filter.pfb.arb_resampler_ccf(rrate)

        # and wire them up
        self.connect(intl, resamp, self.u)

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

        self.set_gain(options.gain, 0)
        self.set_gain(options.gain, 1)

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

        # Set the antenna
        if(options.antenna):
            self.u.set_antenna(options.antenna, 0)
            self.u.set_antenna(options.antenna, 1)
Exemplo n.º 7
0
    def __init__(self):
        gr.top_block.__init__(self)

        usage="%prog: [options] tx-freq0 tx-freq1"
        parser = OptionParser (option_class=eng_option, usage=usage)
        parser.add_option("-a", "--args", type="string", default="",
                          help="UHD device address args [default=%default]")
        parser.add_option("", "--spec", type="string", default=None,
	                  help="Subdevice of UHD device where appropriate")
        parser.add_option("-A", "--antenna", type="string", default=None,
                          help="select Rx Antenna where appropriate")
        parser.add_option("-s", "--samp-rate", type="eng_float", default=320e3,
                          help="set sample rate [default=%default]")
        parser.add_option("-g", "--gain", type="eng_float", default=None,
                          help="set gain in dB (default is midpoint)")
        (options, args) = parser.parse_args ()

        if len(args) != 2:
            parser.print_help()
            raise SystemExit
        else:
            freq0 = str_to_num(args[0])
            freq1 = str_to_num(args[1])

        # ----------------------------------------------------------------
        # Set up USRP to transmit on both daughterboards

        d = uhd.find_devices(uhd.device_addr(options.args))
        uhd_type = d[0].get('type')

        stream_args = uhd.stream_args('fc32', channels=range(2))
        self.u = uhd.usrp_sink(device_addr=options.args, stream_args=stream_args)

        # Set up USRP system based on type
        if(uhd_type == "usrp"):
            self.u.set_subdev_spec("A:0 B:0")
            tr0 = uhd.tune_request(freq0)
            tr1 = uhd.tune_request(freq1)

        else:
            if abs(freq0 - freq1) > 5.5e6:
                sys.stderr.write("\nError: When not using two separate d'boards, frequencies must bewithin 5.5MHz of each other.\n")
                raise SystemExit

            self.u.set_subdev_spec("A:0 A:0")

            mid_freq = (freq0 + freq1)/2.0
            tr0 = uhd.tune_request(freq0, rf_freq=mid_freq,
                                   rf_freq_policy=uhd.tune_request.POLICY_MANUAL)

            tr1 = uhd.tune_request(freq1, rf_freq=mid_freq,
                                   rf_freq_policy=uhd.tune_request.POLICY_MANUAL)

        # Use the tune requests to tune each channel
        self.set_freq(tr0, 0)
        self.set_freq(tr1, 1)

        self.usrp_rate  = options.samp_rate

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

        # ----------------------------------------------------------------
        # build two signal sources, interleave them, amplify and
        # connect them to usrp

        sig0 = example_signal_0(self.usrp_rate)
        sig1 = example_signal_1(self.usrp_rate)

        intl = gr.interleave(gr.sizeof_gr_complex)
        self.connect(sig0, (intl, 0))
        self.connect(sig1, (intl, 1))

        # Correct for any difference in requested and actual rates
        rrate = self.usrp_rate / dev_rate
        resamp = blks2.pfb_arb_resampler_ccf(rrate)

        # and wire them up
        self.connect(intl, resamp, self.u)

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

        self.set_gain(options.gain, 0)
        self.set_gain(options.gain, 1)

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

        # Set the antenna
        if(options.antenna):
            self.u.set_antenna(options.antenna, 0)
            self.u.set_antenna(options.antenna, 1)
Exemplo n.º 8
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))
Exemplo n.º 9
0
    def __init__(self, args, tx_enable, rx_enable):
        gr.top_block.__init__(self)

        d = uhd.find_devices(uhd.device_addr(args))
        print(d)
        uhd_type = d[0].get('type')

        print "\nFound '%s' at args '%s'" % \
            (uhd_type, args)

        # Test the type of USRP; if it's a USRP (v1), it has
        # 2 channels; otherwise, it has 1 channel
        if uhd_type == "usrp":
            tx_nchan = 2
            rx_nchan = 2
        else:
            tx_nchan = 1
            rx_nchan = 1

        if tx_enable:
            print "\nTRANSMIT CHAIN"
            stream_args = uhd.stream_args('fc32', channels=range(tx_nchan))
            self.u_tx = uhd.usrp_sink(device_addr=args,
                                      stream_args=stream_args)
            self.u_tx.set_samp_rate(MAX_RATE)

            self.tx_src0 = analog.sig_source_c(self.u_tx.get_samp_rate(),
                                               analog.GR_CONST_WAVE, 0, 1.0, 0)

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

            # Get dboard freq range and select midpoint
            tx_freq_range = self.u_tx.get_freq_range()
            tx_freq_mid = (tx_freq_range.start() + tx_freq_range.stop()) / 2.0

            for i in xrange(tx_nchan):
                self.u_tx.set_center_freq(tx_freq_mid + i * 1e6, i)
                self.u_tx.set_gain(tx_gain, i)

            print "\nTx Sample Rate: %ssps" % (n2s(self.u_tx.get_samp_rate()))
            for i in xrange(tx_nchan):
                print "Tx Channel %d: " % (i)
                print "\tFrequency = %sHz" % \
                    (n2s(self.u_tx.get_center_freq(i)))
                print "\tGain = %f dB" % (self.u_tx.get_gain(i))
            print ""

            self.connect(self.tx_src0, self.u_tx)

        if rx_enable:
            print "\nRECEIVE CHAIN"
            self.u_rx = uhd.usrp_source(device_addr=args,
                                        io_type=uhd.io_type.COMPLEX_FLOAT32,
                                        num_channels=rx_nchan)
            self.rx_dst0 = blocks.null_sink(gr.sizeof_gr_complex)

            self.u_rx.set_samp_rate(MAX_RATE)

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

            # Get dboard freq range and select midpoint
            rx_freq_range = self.u_rx.get_freq_range()
            rx_freq_mid = (rx_freq_range.start() + rx_freq_range.stop()) / 2.0

            for i in xrange(tx_nchan):
                self.u_rx.set_center_freq(rx_freq_mid + i * 1e6, i)
                self.u_rx.set_gain(rx_gain, i)

            print "\nRx Sample Rate: %ssps" % (n2s(self.u_rx.get_samp_rate()))
            for i in xrange(rx_nchan):
                print "Rx Channel %d: " % (i)
                print "\tFrequency = %sHz" % \
                    (n2s(self.u_rx.get_center_freq(i)))
                print "\tGain = %f dB" % (self.u_rx.get_gain(i))
            print ""

            self.connect(self.u_rx, self.rx_dst0)
Exemplo n.º 10
0
    def __init__(self):
        gr.top_block.__init__(self)

        usage = "usage: %prog [options] min_freq max_freq"
        parser = OptionParser(option_class=eng_option, usage=usage)
        parser.add_option("-a",
                          "--args",
                          type="string",
                          default="",
                          help="UHD device address args [default=%default]")
        parser.add_option("",
                          "--spec",
                          type="string",
                          default=None,
                          help="Subdevice of UHD device where appropriate")
        parser.add_option("-R",
                          "--rx-antenna",
                          type="string",
                          default="RX2",
                          help="select RX antenna where appropriate")
        parser.add_option("-T",
                          "--tx-antenna",
                          type="string",
                          default="TX/RX",
                          help="select TX antenna where appropriate")
        parser.add_option("-s",
                          "--samp-rate",
                          type="eng_float",
                          default=1e6,
                          help="set sample rate [default=%default]")
        parser.add_option("-g",
                          "--gain",
                          type="eng_float",
                          default=None,
                          help="set gain in dB (default is midpoint)")
        parser.add_option(
            "",
            "--tune-delay",
            type="eng_float",
            default=0.25,
            metavar="SECS",
            help=
            "time to delay (in seconds) after changing frequency [default=%default]"
        )
        parser.add_option(
            "",
            "--dwell-delay",
            type="eng_float",
            default=0.25,
            metavar="SECS",
            help=
            "time to delay (in seconds) at a given frequency [default=%default]"
        )
        parser.add_option(
            "-b",
            "--channel-bandwidth",
            type="eng_float",
            default=6.25e3,
            metavar="Hz",
            help="channel bandwidth of fft bins in Hz [default=%default]")
        parser.add_option("-l",
                          "--lo-offset",
                          type="eng_float",
                          default=0,
                          metavar="Hz",
                          help="lo_offset in Hz [default=%default]")
        parser.add_option("-q",
                          "--squelch-threshold",
                          type="eng_float",
                          default=None,
                          metavar="dB",
                          help="squelch threshold in dB [default=%default]")
        parser.add_option(
            "-F",
            "--fft-size",
            type="int",
            default=None,
            help="specify the number of FFT bins [default=samp_rate/channel_bw]"
        )
        parser.add_option("",
                          "--real-time",
                          action="store_true",
                          default=False,
                          help="Attempt to enable real-time scheduling")
        parser.add_option(
            "-w",
            "--tx-bandwidth",
            type="eng_float",
            default=6e6,
            metavar="Hz",
            help="transmit frequency bandwidth [default=%default]")

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

        self.channel_bandwidth = options.channel_bandwidth  #fft channel bandwidth
        self.tx_bandwidth = options.tx_bandwidth

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

        if self.min_freq < 1e6: self.min_freq *= 1e6
        if self.max_freq < 1e6: self.max_freq *= 1e6

        self.n_channel_grps = 5  #number of channel groups
        self.curr_channel_grp = 0
        self.n_channels = 5  #number of channels / channel group
        self.curr_channel = 0

        self.tx_guard_band = 4e6

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

        self.channel_grp_bw = (self.max_freq -
                               self.min_freq) / self.n_channel_grps
        self.tx_channel_bw = self.channel_grp_bw / self.n_channels  # tx channel bw

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

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

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

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

        self.u_rx.set_samp_rate(options.samp_rate)
        self.usrp_rate = usrp_rate = self.u_rx.get_samp_rate()

        self.lo_offset = options.lo_offset

        if options.fft_size is None:
            self.fft_size = int(self.usrp_rate / self.channel_bandwidth)
        else:
            self.fft_size = options.fft_size

        print "FFT Size: %d, USRP Samp Rate: %d, Channel Bandwidth: %d" % (
            self.fft_size, self.usrp_rate, self.channel_bandwidth)

        self.squelch_threshold = options.squelch_threshold

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

        mywindow = filter.window.blackmanharris(self.fft_size)
        ffter = fft.fft_vcc(self.fft_size, True, mywindow, True)

        c2mag = blocks.complex_to_mag_squared(self.fft_size)

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

        self.msgq = gr.msg_queue(1)
        self._tune_callback = tune(
            self)  #hang on to this to keep it from being GC'd

        stats = blocks.bin_statistics_f(self.fft_size, self.msgq,
                                        self._tune_callback, tune_delay,
                                        dwell_delay)

        self.connect(self.u_rx, s2v, ffter, c2mag, stats)

        #transmit chain

        d = uhd.find_devices(uhd.device_addr(options.args))
        if d:

            uhd_type = d[0].get('type')
            print "\nFound '%s'" % uhd_type
        else:
            print "\nNo device found"
            self.u_tx = None
            return

        #check version of USRP and set num_channels

        if uhd_type == "usrp":
            tx_nchan = 2
            rx_nchan = 2
        else:
            tx_nchan = 1
            rx_nchan = 1

        #setup transmit chain (usrp sink, signal source)

        #usrp sink
        stream_args = uhd.stream_args('fc32', channels=range(tx_nchan))
        self.u_tx = uhd.usrp_sink(device_addr=options.args,
                                  stream_args=stream_args)
        self.u_tx.set_samp_rate(self.usrp_rate)

        if options.tx_antenna:
            self.u_tx.set_antenna(options.tx_antenna, 0)

#analog signal source - sig_source_c(sampling_freq,waveform, wave_freq, ampl, offset=0)
        self.tx_src0 = analog.sig_source_c(self.u_tx.get_samp_rate(),
                                           analog.GR_CONST_WAVE, 0, 1.0, 0)

        #connect blocks

        self.connect(self.tx_src0, self.u_tx)

        if options.gain is None:
            # if no gain was specified use the midpoint in dB
            g = self.u_rx.get_gain_range()
            options.gain = float(g.start() + g.stop()) / 2.0

        self.set_gain(options.gain)
        print "gain =", options.gain

        #initialize transmission parameters
        self.set_channel_group(3)
        self.step_count = 0
Exemplo n.º 11
0
    def _usrp_setup(self):
        """Create, set up, and return USRP sink object."""
        op = self.op
        # create usrp sink block
        usrp = uhd.usrp_sink(
            device_addr=','.join(chain(op.mboard_strs, op.dev_args)),
            stream_args=uhd.stream_args(cpu_format='fc32',
                                        otw_format='sc16',
                                        channels=range(op.nchs),
                                        args=','.join(op.stream_args)))

        # set clock and time source if synced
        if op.sync:
            try:
                usrp.set_clock_source(op.sync_source, uhd.ALL_MBOARDS)
                usrp.set_time_source(op.sync_source, uhd.ALL_MBOARDS)
            except RuntimeError:
                errstr = (
                    "Unknown sync_source option: '{0}'. Must be one of {1}."
                ).format(op.sync_source, usrp.get_clock_sources(0))
                raise ValueError(errstr)

        # check for ref lock
        mbnums_with_ref = [
            mb_num for mb_num in range(op.nmboards)
            if 'ref_locked' in usrp.get_mboard_sensor_names(mb_num)
        ]
        if mbnums_with_ref:
            if op.verbose:
                sys.stdout.write('Waiting for reference lock...')
                sys.stdout.flush()
            timeout = 0
            while not all(
                    usrp.get_mboard_sensor('ref_locked', mb_num).to_bool()
                    for mb_num in mbnums_with_ref):
                if op.verbose:
                    sys.stdout.write('.')
                    sys.stdout.flush()
                time.sleep(1)
                timeout += 1
                if timeout > 30:
                    if op.verbose:
                        sys.stdout.write('failed\n')
                        sys.stdout.flush()
                    raise RuntimeError('Failed to lock to 10 MHz reference.')
            if op.verbose:
                sys.stdout.write('locked\n')
                sys.stdout.flush()

        # set mainboard options
        for mb_num in range(op.nmboards):
            usrp.set_subdev_spec(op.subdevs[mb_num], mb_num)
        # set global options
        # sample rate
        usrp.set_samp_rate(float(op.samplerate))
        # read back actual value
        samplerate = usrp.get_samp_rate()
        # calculate longdouble precision sample rate
        # (integer division of clock rate)
        cr = usrp.get_clock_rate()
        srdec = int(round(cr / samplerate))
        samplerate_ld = np.longdouble(cr) / srdec
        op.samplerate = samplerate_ld
        sr_rat = Fraction(cr).limit_denominator() / srdec
        op.samplerate_num = sr_rat.numerator
        op.samplerate_den = sr_rat.denominator

        # Set device time using the onboard GPS
        freq_stepper.set_dev_time(usrp)

        # set per-channel options
        # set command time so settings are synced
        gpstime = datetime.utcfromtimestamp(usrp.get_mboard_sensor("gps_time"))
        gpstime_secs = (pytz.utc.localize(gpstime) -
                        drf.util.epoch).total_seconds()
        COMMAND_DELAY = 0.2
        cmd_time_secs = gpstime_secs + COMMAND_DELAY

        usrp.set_command_time(
            uhd.time_spec(float(cmd_time_secs)),
            uhd.ALL_MBOARDS,
        )

        for ch_num in range(op.nchs):
            # local oscillator sharing settings
            lo_source = op.lo_sources[ch_num]
            if lo_source:
                try:
                    usrp.set_lo_source(lo_source, uhd.ALL_LOS, ch_num)
                except RuntimeError:
                    errstr = (
                        "Unknown LO source option: '{0}'. Must be one of {1},"
                        " or it may not be possible to set the LO source on"
                        " this daughterboard.").format(
                            lo_source,
                            usrp.get_lo_sources(uhd.ALL_LOS, ch_num))
                    raise ValueError(errstr)
            lo_export = op.lo_exports[ch_num]
            if lo_export is not None:
                if not lo_source:
                    errstr = (
                        'Channel {0}: must set an LO source in order to set'
                        ' LO export.').format(ch_num)
                    raise ValueError(errstr)
                usrp.set_lo_export_enabled(lo_export, uhd.ALL_LOS, ch_num)
            # center frequency and tuning offset
            tune_res = usrp.set_center_freq(
                uhd.tune_request(
                    op.centerfreqs[ch_num],
                    op.lo_offsets[ch_num],
                    args=uhd.device_addr(','.join(op.tune_args)),
                ),
                ch_num,
            )
            # store actual values from tune result
            op.centerfreqs[ch_num] = (tune_res.actual_rf_freq +
                                      tune_res.actual_dsp_freq)
            op.lo_offsets[ch_num] = -tune_res.actual_dsp_freq
            # dc offset
            dc_offset = op.dc_offsets[ch_num]
            if dc_offset is not None:
                usrp.set_dc_offset(dc_offset, ch_num)
            # iq balance
            iq_balance = op.iq_balances[ch_num]
            if iq_balance is not None:
                usrp.set_iq_balance(iq_balance, ch_num)
            # gain
            usrp.set_gain(op.gains[ch_num], ch_num)
            # bandwidth
            bw = op.bandwidths[ch_num]
            if bw:
                usrp.set_bandwidth(bw, ch_num)
            # antenna
            ant = op.antennas[ch_num]
            if ant:
                try:
                    usrp.set_antenna(ant, ch_num)
                except RuntimeError:
                    errstr = (
                        "Unknown RX antenna option: '{0}'. Must be one of {1}."
                    ).format(ant, usrp.get_antennas(ch_num))
                    raise ValueError(errstr)

        # commands are done, clear time
        usrp.clear_command_time(uhd.ALL_MBOARDS)
        time.sleep(COMMAND_DELAY)

        # read back actual channel settings
        for ch_num in range(op.nchs):
            if op.lo_sources[ch_num]:
                op.lo_sources[ch_num] = usrp.get_lo_source(uhd.ALL_LOS, ch_num)
            if op.lo_exports[ch_num] is not None:
                op.lo_exports[ch_num] = usrp.get_lo_export_enabled(
                    uhd.ALL_LOS,
                    ch_num,
                )
            op.gains[ch_num] = usrp.get_gain(ch_num)
            op.bandwidths[ch_num] = usrp.get_bandwidth(chan=ch_num)
            op.antennas[ch_num] = usrp.get_antenna(chan=ch_num)

        if op.verbose:
            print('Using the following devices:')
            chinfostrs = [
                'Motherboard: {mb_id} ({mb_addr}) | Daughterboard: {db_name}',
                'Subdev: {sub} | Antenna: {ant} | Gain: {gain} | Rate: {sr}',
                'Frequency: {freq:.3f} ({lo_off:+.3f}) | Bandwidth: {bw}',
            ]
            if any(op.lo_sources) or any(op.lo_exports):
                chinfostrs.append(
                    'LO source: {lo_source} | LO export: {lo_export}')
            chinfo = '\n'.join(['  ' + l for l in chinfostrs])
            for ch_num in range(op.nchs):
                header = '---- {0} '.format(ch_num)
                header += '-' * (78 - len(header))
                print(header)
                usrpinfo = dict(usrp.get_usrp_info(chan=ch_num))
                info = {}
                info['mb_id'] = usrpinfo['mboard_id']
                mba = op.mboards_bychan[ch_num]
                if mba == 'default':
                    mba = usrpinfo['mboard_serial']
                info['mb_addr'] = mba
                info['db_name'] = usrpinfo['tx_subdev_name']
                info['sub'] = op.subdevs_bychan[ch_num]
                info['ant'] = op.antennas[ch_num]
                info['bw'] = op.bandwidths[ch_num]
                info['dc_offset'] = op.dc_offsets[ch_num]
                info['freq'] = op.centerfreqs[ch_num]
                info['gain'] = op.gains[ch_num]
                info['iq_balance'] = op.iq_balances[ch_num]
                info['lo_off'] = op.lo_offsets[ch_num]
                info['lo_source'] = op.lo_sources[ch_num]
                info['lo_export'] = op.lo_exports[ch_num]
                info['sr'] = op.samplerate
                print(chinfo.format(**info))
                print('-' * 78)

        return usrp
Exemplo n.º 12
0
    def _usrp_setup(self):
        """Create, set up, and return USRP source object."""
        op = self.op
        # create usrp source block
        if op.dec > 1:
            op.cpu_format = 'fc32'
        else:
            op.cpu_format = 'sc16'
        op.otw_format = 'sc16'
        u = uhd.usrp_source(
            device_addr=','.join(chain(op.mboard_strs, op.dev_args)),
            stream_args=uhd.stream_args(cpu_format=op.cpu_format,
                                        otw_format=op.otw_format,
                                        channels=range(len(op.chs)),
                                        args=','.join(op.stream_args)),
        )

        # set clock and time source if synced
        if op.sync:
            try:
                u.set_clock_source(op.sync_source, uhd.ALL_MBOARDS)
                u.set_time_source(op.sync_source, uhd.ALL_MBOARDS)
            except RuntimeError:
                errstr = (
                    "Unknown sync_source option: '{0}'. Must be one of {1}."
                ).format(op.sync_source, u.get_clock_sources(0))
                raise ValueError(errstr)

        # set mainboard options
        for mb_num in range(op.nmboards):
            u.set_subdev_spec(op.subdevs[mb_num], mb_num)
        # set global options
        # sample rate
        u.set_samp_rate(float(op.samplerate))
        # read back actual value
        samplerate = u.get_samp_rate()
        # calculate longdouble precision sample rate
        # (integer division of clock rate)
        cr = u.get_clock_rate()
        srdec = int(round(cr / samplerate))
        samplerate_ld = np.longdouble(cr) / srdec
        op.samplerate = samplerate_ld
        sr_rat = Fraction(cr).limit_denominator() / srdec
        op.samplerate_num = sr_rat.numerator
        op.samplerate_den = sr_rat.denominator

        # set per-channel options
        # set command time so settings are synced
        COMMAND_DELAY = 0.2
        cmd_time = u.get_time_now() + uhd.time_spec(COMMAND_DELAY)
        u.set_command_time(cmd_time, uhd.ALL_MBOARDS)
        for ch_num in range(op.nchs):
            # local oscillator sharing settings
            lo_source = op.lo_sources[ch_num]
            if lo_source:
                try:
                    u.set_lo_source(lo_source, uhd.ALL_LOS, ch_num)
                except RuntimeError:
                    errstr = (
                        "Unknown LO source option: '{0}'. Must be one of {1},"
                        " or it may not be possible to set the LO source on"
                        " this daughterboard.").format(
                            lo_source, u.get_lo_sources(uhd.ALL_LOS, ch_num))
                    raise ValueError(errstr)
            lo_export = op.lo_exports[ch_num]
            if lo_export is not None:
                if not lo_source:
                    errstr = (
                        'Channel {0}: must set an LO source in order to set'
                        ' LO export.').format(ch_num)
                    raise ValueError(errstr)
                u.set_lo_export_enabled(lo_export, uhd.ALL_LOS, ch_num)
            # center frequency and tuning offset
            tune_res = u.set_center_freq(
                uhd.tune_request(
                    op.centerfreqs[ch_num],
                    op.lo_offsets[ch_num],
                    args=uhd.device_addr(','.join(op.tune_args)),
                ),
                ch_num,
            )
            # store actual values from tune result
            op.centerfreqs[ch_num] = (tune_res.actual_rf_freq -
                                      tune_res.actual_dsp_freq)
            op.lo_offsets[ch_num] = tune_res.actual_dsp_freq
            # gain
            u.set_gain(op.gains[ch_num], ch_num)
            # bandwidth
            bw = op.bandwidths[ch_num]
            if bw:
                u.set_bandwidth(bw, ch_num)
            # antenna
            ant = op.antennas[ch_num]
            if ant:
                try:
                    u.set_antenna(ant, ch_num)
                except RuntimeError:
                    errstr = (
                        "Unknown RX antenna option: '{0}'. Must be one of {1}."
                    ).format(ant, u.get_antennas(ch_num))
                    raise ValueError(errstr)

        # commands are done, clear time
        u.clear_command_time(uhd.ALL_MBOARDS)
        time.sleep(COMMAND_DELAY)

        # read back actual channel settings
        for ch_num in range(op.nchs):
            if op.lo_sources[ch_num]:
                op.lo_sources[ch_num] = u.get_lo_source(uhd.ALL_LOS, ch_num)
            if op.lo_exports[ch_num] is not None:
                op.lo_exports[ch_num] = u.get_lo_export_enabled(
                    uhd.ALL_LOS,
                    ch_num,
                )
            op.gains[ch_num] = u.get_gain(ch_num)
            op.bandwidths[ch_num] = u.get_bandwidth(chan=ch_num)
            op.antennas[ch_num] = u.get_antenna(chan=ch_num)

        if op.verbose:
            print('Using the following devices:')
            chinfostrs = [
                'Motherboard: {mb_id} ({mb_addr}) | Daughterboard: {db_name}',
                'Subdev: {sub} | Antenna: {ant} | Gain: {gain} | Rate: {sr}',
                'Frequency: {freq:.3f} ({lo_off:+.3f}) | Bandwidth: {bw}',
            ]
            if any(op.lo_sources) or any(op.lo_exports):
                chinfostrs.append(
                    'LO source: {lo_source} | LO export: {lo_export}')
            chinfo = '\n'.join(['  ' + l for l in chinfostrs])
            for ch_num in range(op.nchs):
                header = '---- {0} '.format(op.chs[ch_num])
                header += '-' * (78 - len(header))
                print(header)
                usrpinfo = dict(u.get_usrp_info(chan=ch_num))
                info = {}
                info['mb_id'] = usrpinfo['mboard_id']
                mba = op.mboards_bychan[ch_num]
                if mba == 'default':
                    mba = usrpinfo['mboard_serial']
                info['mb_addr'] = mba
                info['db_name'] = usrpinfo['rx_subdev_name']
                info['sub'] = op.subdevs_bychan[ch_num]
                info['ant'] = op.antennas[ch_num]
                info['bw'] = op.bandwidths[ch_num]
                info['freq'] = op.centerfreqs[ch_num]
                info['gain'] = op.gains[ch_num]
                info['lo_off'] = op.lo_offsets[ch_num]
                info['lo_source'] = op.lo_sources[ch_num]
                info['lo_export'] = op.lo_exports[ch_num]
                info['sr'] = op.samplerate
                print(chinfo.format(**info))
                print('-' * 78)

        return u
Exemplo n.º 13
0
def step(
    usrp,
    op,
    ch_num=0,
    sleeptime=0.1,
    freq_list_fname=None,
    flog_fname=None,
    lock_fname=None,
    time_source='GPS',
    timestr='%Y/%b/%d %H:%M:%S',
):
    """ Step the USRP's oscillator through a list of frequencies """
    if freq_list_fname:
        freq_list = get_freq_list(
            freq_list_fname) if freq_list_fname else set_freq_list()
    else:
        freq_list = set_freq_list()

    print('Starting freq_stepper')

    prev_lock = False
    # Check for GPS lock
    while not usrp.get_mboard_sensor("gps_locked", 0).to_bool():
        print("waiting for gps lock...")
        time.sleep(5)
    assert usrp.get_mboard_sensor("gps_locked",
                                  0).to_bool(), "GPS still not locked"

    # Begin infinite transmission loop
    freq = 0
    while 1:

        # Set USRP time (necessary to know what sample number we shifted frequencies at)
        usrptime_secs = usrp.get_time_now().get_real_secs()

        if time_source == 'GPS':
            # Set GPS time (necessary to sync operations between the transmitter and receiver)
            gpstime = datetime.utcfromtimestamp(
                usrp.get_mboard_sensor("gps_time"))
            time_next = pytz.utc.localize(gpstime) + timedelta(seconds=1)
        elif time_source == 'USRP':
            time_next = drf.util.epoch + timedelta(seconds=usrptime_secs + 1)

        # Calculate the samplerate
        try:
            ch_samplerate_frac = op.ch_samplerates_frac[ch_num]
            ch_samplerate_ld = (np.longdouble(ch_samplerate_frac.numerator) /
                                np.longdouble(ch_samplerate_frac.denominator))
        except:
            ch_samplerate_ld = op.samplerate

        # Frequency shifting block
        #    Change frequency each time we hit a new time in the list, otherwise hold the existing note
        if ((time_next.second)
                in freq_list.keys()) and (freq != freq_list[time_next.second]):
            tune_time = time_next
            freq = freq_list[time_next.second]

            # Specify USRP tune time on the first exact sample after listed time
            # tune_time_secs = (tune_time - drf.util.epoch).total_seconds()
            tune_time_secs = usrp.get_time_last_pps().get_real_secs() + 1
            tune_time_rsamples = np.ceil(tune_time_secs * op.samplerate)
            tune_time_secs = tune_time_rsamples / op.samplerate

            gps_lock = usrp.get_mboard_sensor("gps_locked").to_bool()
            print('GPS lock status: %s' % gps_lock)
            timestr = tune_time.strftime('%Y/%m/%d-%H:%M:%S')
            if lock_fname:
                if gps_lock != prev_lock:
                    with open(tune_time.strftime(lock_fname), 'a+') as f:
                        f.write('GPS lock status: %s at %s' %
                                (gps_lock, timestr))
                prev_lock = gps_lock

            # Optionally write out the shift samples of each frequency
            tune_sample = int(np.uint64(tune_time_secs * ch_samplerate_ld))
            if flog_fname:
                # Change to 'a' to append
                with open(tune_time.strftime(flog_fname), 'w') as f:
                    f.write('%s %s %i\n' %
                            (timestr, str(freq).rjust(4), tune_sample))

            usrp.set_command_time(
                uhd.time_spec(float(tune_time_secs)),
                uhd.ALL_MBOARDS,
            )

            # Tune to the next frequency in the list
            tune_res = usrp.set_center_freq(
                            uhd.tune_request(freq * 1E6, op.lo_offsets[ch_num], \
                                 args=uhd.device_addr(','.join(op.tune_args)),
                            ),
                            ch_num,
            )

            usrp.clear_command_time(uhd.ALL_MBOARDS)
            if op.verbose:
                print('Tuned to %s MHz at %s (sample %i)' % \
                        (str(freq).rjust(4),
                        tune_time.strftime(timestr),
                        tune_sample,
                        )
                )
                """
                gpstime = datetime.utcfromtimestamp(usrp.get_mboard_sensor("gps_time"))
                usrptime = drf.util.epoch + timedelta(seconds=usrp.get_time_now().get_real_secs())
                print('GPS tune time:  %s\nUSRP tune time: %s' %
                    (gpstime.strftime(timestr),
                    usrptime.strftime(timestr))
                )
                """
        time.sleep(sleeptime)