def __init__( self, parent, msgq, size=DEFAULT_WIN_SIZE, ): wx.Panel.__init__( self, parent, size=size, style=wx.SIMPLE_BORDER, ) self.text_ctrl = wx.TextCtrl( self, wx.ID_ANY, value="", size=size, style=wx.TE_MULTILINE | wx.TE_READONLY, ) main_sizer = wx.BoxSizer(wx.VERTICAL) main_sizer.Add(self.text_ctrl, 1, wx.EXPAND) self.SetSizerAndFit(main_sizer) EVT_APPEND_EVENT(self, self.evt_append) self.runner = gru.msgq_runner(msgq, self.handle_msg)
def __init__(self, parent, msgq, size=DEFAULT_WIN_SIZE, ): wx.Panel.__init__(self, parent, size=size, style=wx.SIMPLE_BORDER, ) self.text_ctrl = wx.TextCtrl(self, wx.ID_ANY, value="", size=size, style=wx.TE_MULTILINE|wx.TE_READONLY, ) main_sizer = wx.BoxSizer(wx.VERTICAL) main_sizer.Add(self.text_ctrl, 1, wx.EXPAND) self.SetSizerAndFit(main_sizer) EVT_APPEND_EVENT(self, self.evt_append) self.runner = gru.msgq_runner(msgq, self.handle_msg)
def _setup_usrpx(self, options): self._u = uhd.usrp_sink(device_addr=options.args, stream_args=uhd.stream_args('fc32')) self._u.set_samp_rate(options.samp_rate) # Set the subdevice spec if(options.spec): self._u.set_subdev_spec(options.spec, 0) # Set the gain on the usrp from options if(options.gain): self._u.set_gain(options.gain) # Set the antenna if(options.antenna): self._u.set_antenna(options.antenna, 0) self.publish(DESC_KEY, lambda: str(self._u)) self.publish(FREQ_RANGE_KEY, self._u.get_freq_range) self.publish(GAIN_RANGE_KEY, self._u.get_gain_range) self.publish(GAIN_KEY, self._u.get_gain) if self._verbose: print str(self._u) # Direct asynchronous notifications to callback function if options.show_async_msg: self.async_msgq = gr.msg_queue(0) self.async_src = uhd.amsg_source("", self.async_msgq) self.async_rcv = gru.msgq_runner(self.async_msgq, self.async_callback)
def _setup_usrpx(self, options): self._u = uhd.usrp_sink(device_addr=options.args, stream_args=uhd.stream_args('fc32')) self._u.set_samp_rate(options.samp_rate) # Set the subdevice spec if (options.spec): self._u.set_subdev_spec(options.spec, 0) # Set the gain on the usrp from options if (options.gain): self._u.set_gain(options.gain) # Set the antenna if (options.antenna): self._u.set_antenna(options.antenna, 0) # Setup USRP Configuration value try: usrp_info = self._u.get_usrp_info() mboard_id = usrp_info.get("mboard_id") mboard_serial = usrp_info.get("mboard_serial") if mboard_serial == "": mboard_serial = "no serial" dboard_subdev_name = usrp_info.get("tx_subdev_name") dboard_serial = usrp_info.get("tx_serial") if dboard_serial == "": dboard_serial = "no serial" subdev = self._u.get_subdev_spec() antenna = self._u.get_antenna() desc_key_str = "Motherboard: %s [%s]\n" % (mboard_id, mboard_serial) if "B200" in mboard_id or "B210" in mboard_id: desc_key_str += "Daughterboard: %s\n" % dboard_subdev_name else: desc_key_str += "Daughterboard: %s [%s]\n" % ( dboard_subdev_name, dboard_serial) desc_key_str += "Subdev: %s\n" % subdev desc_key_str += "Antenna: %s" % antenna except: desc_key_str = "USRP configuration output not implemented in this version" self.publish(DESC_KEY, lambda: desc_key_str) self.publish(FREQ_RANGE_KEY, self._u.get_freq_range) self.publish(GAIN_RANGE_KEY, self._u.get_gain_range) self.publish(GAIN_KEY, self._u.get_gain) print "UHD Signal Generator" print "Version: %s" % uhd.get_version_string() print "\nUsing USRP configuration:" print desc_key_str + "\n" # Direct asynchronous notifications to callback function if options.show_async_msg: self.async_msgq = gr.msg_queue(0) self.async_src = uhd.amsg_source("", self.async_msgq) self.async_rcv = gru.msgq_runner(self.async_msgq, self.async_callback)
def __init__(self, mode='MODE-S', input_rate=0, context=None): assert input_rate > 0 gr.hier_block2.__init__( self, type(self).__name__, gr.io_signature(1, 1, gr.sizeof_gr_complex * 1), gr.io_signature(0, 0, 0)) demod_rate = 2000000 transition_width = 500000 hex_msg_queue = gr.msg_queue(100) self.__band_filter = MultistageChannelFilter( input_rate=input_rate, output_rate=demod_rate, cutoff_freq=demod_rate / 2, transition_width=transition_width) # TODO optimize filter band self.__demod = air_modes.rx_path( rate=demod_rate, threshold=7.0, # default used in air-modes code but not exposed queue=hex_msg_queue, use_pmf=False, use_dcblock=True) self.connect(self, self.__band_filter, self.__demod) self.__messages_seen = 0 self.__message_rate_calc = LazyRateCalculator( lambda: self.__messages_seen, min_interval=2) # Parsing # TODO: These bits are mimicking gr-air-modes toplevel code. Figure out if we can have less glue. # Note: gr pubsub is synchronous -- subscribers are called on the publisher's thread parser_output = gr.pubsub.pubsub() parser = air_modes.make_parser(parser_output) cpr_decoder = air_modes.cpr_decoder( my_location=None) # TODO: get position info from device air_modes.output_print(cpr_decoder, parser_output) def msq_runner_callback(msg): # called on msgq_runner's thread # pylint: disable=broad-except try: reactor.callFromThread(parser, msg.to_string()) except Exception: print(traceback.format_exc()) self.__msgq_runner = gru.msgq_runner(hex_msg_queue, msq_runner_callback) def parsed_callback(msg): timestamp = time.time() self.__messages_seen += 1 context.output_message( ModeSMessageWrapper(msg, cpr_decoder, timestamp)) for i in six.moves.range(0, 2**5): parser_output.subscribe('type%i_dl' % i, parsed_callback)
def __init__(self, mode='MODE-S', input_rate=0, mode_s_information=None, context=None): assert input_rate > 0 gr.hier_block2.__init__( self, 'Mode S/ADS-B/1090 demodulator', gr.io_signature(1, 1, gr.sizeof_gr_complex * 1), gr.io_signature(0, 0, 0)) self.mode = mode self.input_rate = input_rate if mode_s_information is not None: self.__information = mode_s_information else: self.__information = ModeSInformation() hex_msg_queue = gr.msg_queue(100) band_filter = MultistageChannelFilter( input_rate=input_rate, output_rate=demod_rate, cutoff_freq=demod_rate / 2, transition_width=transition_width) # TODO optimize filter band self.__demod = air_modes.rx_path( rate=demod_rate, threshold=7.0, # default used in air-modes code but not exposed queue=hex_msg_queue, use_pmf=False, use_dcblock=True) self.connect( self, band_filter, self.__demod) self.__messages_seen = 0 self.__message_rate_calc = LazyRateCalculator(lambda: self.__messages_seen, min_interval=2) # Parsing # TODO: These bits are mimicking gr-air-modes toplevel code. Figure out if we can have less glue. # Note: gr pubsub is synchronous -- subscribers are called on the publisher's thread parser_output = gr.pubsub.pubsub() parser = air_modes.make_parser(parser_output) cpr_decoder = air_modes.cpr_decoder(my_location=None) # TODO: get position info from device air_modes.output_print(cpr_decoder, parser_output) def callback(msg): # called on msgq_runner's thrad # pylint: disable=broad-except try: reactor.callFromThread(parser, msg.to_string()) except Exception: print traceback.format_exc() self.__msgq_runner = gru.msgq_runner(hex_msg_queue, callback) def parsed_callback(msg): self.__messages_seen += 1 self.__information.receive(msg, cpr_decoder) for i in xrange(0, 2 ** 5): parser_output.subscribe('type%i_dl' % i, parsed_callback)
def __init__(self, mode='MODE-S', input_rate=0, mode_s_information=None, context=None): assert input_rate > 0 gr.hier_block2.__init__( self, 'Mode S/ADS-B/1090 demodulator', gr.io_signature(1, 1, gr.sizeof_gr_complex * 1), gr.io_signature(0, 0, 0)) self.mode = mode self.input_rate = input_rate if mode_s_information is not None: self.__information = mode_s_information else: self.__information = ModeSInformation() hex_msg_queue = gr.msg_queue(100) band_filter = MultistageChannelFilter( input_rate=input_rate, output_rate=demod_rate, cutoff_freq=demod_rate / 2, transition_width=transition_width) # TODO optimize filter band self.__demod = air_modes.rx_path( rate=demod_rate, threshold=7.0, # default used in air-modes code but not exposed queue=hex_msg_queue, use_pmf=False, use_dcblock=True) self.connect(self, band_filter, self.__demod) # Parsing # TODO: These bits are mimicking gr-air-modes toplevel code. Figure out if we can have less glue. # Note: gr pubsub is synchronous -- subscribers are called on the publisher's thread parser_output = gr.pubsub.pubsub() parser = air_modes.make_parser(parser_output) cpr_decoder = air_modes.cpr_decoder( my_location=None) # TODO: get position info from device air_modes.output_print(cpr_decoder, parser_output) def callback(msg): # called on msgq_runner's thrad # pylint: disable=broad-except try: reactor.callFromThread(parser, msg.to_string()) except Exception: print traceback.format_exc() self.__msgq_runner = gru.msgq_runner(hex_msg_queue, callback) def parsed_callback(msg): self.__information.receive(msg, cpr_decoder) for i in xrange(0, 2**5): parser_output.subscribe('type%i_dl' % i, parsed_callback)
def _setup_usrpx(self, options): self._u = uhd.usrp_sink(device_addr=options.args, stream_args=uhd.stream_args('fc32')) self._u.set_samp_rate(options.samp_rate) # Set the subdevice spec if(options.spec): self._u.set_subdev_spec(options.spec, 0) # Set the gain on the usrp from options if(options.gain): self._u.set_gain(options.gain) # Set the antenna if(options.antenna): self._u.set_antenna(options.antenna, 0) # Setup USRP Configuration value try: usrp_info = self._u.get_usrp_info() mboard_id = usrp_info["mboard_id"] mboard_serial = usrp_info["mboard_serial"] if mboard_serial == "": mboard_serial = "no serial" dboard_subdev_name = usrp_info["tx_subdev_name"] dboard_serial = usrp_info["tx_serial"] if dboard_serial == "": dboard_serial = "no serial" subdev = self._u.get_subdev_spec() antenna = self._u.get_antenna() desc_key_str = "Motherboard: %s [%s]\n" % (mboard_id, mboard_serial) if "B200" in mboard_id or "B210" in mboard_id: desc_key_str += "Daughterboard: %s\n" % dboard_subdev_name else: desc_key_str += "Daughterboard: %s [%s]\n" % (dboard_subdev_name, dboard_serial) desc_key_str += "Subdev: %s\n" % subdev desc_key_str += "Antenna: %s" % antenna except: desc_key_str = "USRP configuration output not implemented in this version" self.publish(DESC_KEY, lambda: desc_key_str) self.publish(FREQ_RANGE_KEY, self._u.get_freq_range) self.publish(GAIN_RANGE_KEY, self._u.get_gain_range) self.publish(GAIN_KEY, self._u.get_gain) print "UHD Signal Generator" print "Version: %s" % uhd.get_version_string() print "\nUsing USRP configuration:" print desc_key_str + "\n" # Direct asynchronous notifications to callback function if options.show_async_msg: self.async_msgq = gr.msg_queue(0) self.async_src = uhd.amsg_source("", self.async_msgq) self.async_rcv = gru.msgq_runner(self.async_msgq, self.async_callback)
def __init__(self, options, context): gr.top_block.__init__(self) pubsub.__init__(self) self._options = options self._queue = gr.msg_queue() self._rate = int(options.rate) self._resample = None self._setup_source(options) if self._rate < 4e6: self._resample = pfb.arb_resampler_ccf(4.e6 / self._rate) self._rx_rate = 4e6 else: self._rx_rate = self._rate self._rx_path = air_modes.rx_path(self._rx_rate, options.threshold, self._queue, options.pmf, options.dcblock) #now subscribe to set various options via pubsub self.subscribe("freq", self.set_freq) self.subscribe("gain", self.set_gain) self.subscribe("rate", self.set_rate) self.subscribe("rate", self._rx_path.set_rate) self.subscribe("threshold", self._rx_path.set_threshold) self.subscribe("pmf", self._rx_path.set_pmf) self.publish("freq", self.get_freq) self.publish("gain", self.get_gain) self.publish("rate", self.get_rate) self.publish("threshold", self._rx_path.get_threshold) self.publish("pmf", self._rx_path.get_pmf) if self._resample is not None: self.connect(self._u, self._resample, self._rx_path) else: self.connect(self._u, self._rx_path) #Publish messages when they come back off the queue server_addr = ["inproc://modes-radio-pub"] if options.tcp is not None: server_addr += ["tcp://*:%i" % options.tcp] self._sender = air_modes.zmq_pubsub_iface(context, subaddr=None, pubaddr=server_addr) self._async_sender = gru.msgq_runner(self._queue, self.send)
def __init__(self, options, context): gr.top_block.__init__(self) pubsub.__init__(self) self._options = options self._queue = gr.msg_queue() self._rate = int(options.rate) self._resample = None self._setup_source(options) if self._rate < 4e6: self._resample = pfb.arb_resampler_ccf(4.e6/self._rate) self._rx_rate = 4e6 else: self._rx_rate = self._rate self._rx_path = air_modes.rx_path(self._rx_rate, options.threshold, self._queue, options.pmf, options.dcblock) #now subscribe to set various options via pubsub self.subscribe("freq", self.set_freq) self.subscribe("gain", self.set_gain) self.subscribe("rate", self.set_rate) self.subscribe("rate", self._rx_path.set_rate) self.subscribe("threshold", self._rx_path.set_threshold) self.subscribe("pmf", self._rx_path.set_pmf) self.publish("freq", self.get_freq) self.publish("gain", self.get_gain) self.publish("rate", self.get_rate) self.publish("threshold", self._rx_path.get_threshold) self.publish("pmf", self._rx_path.get_pmf) if self._resample is not None: self.connect(self._u, self._resample, self._rx_path) else: self.connect(self._u, self._rx_path) #Publish messages when they come back off the queue server_addr = ["inproc://modes-radio-pub"] if options.tcp is not None: server_addr += ["tcp://*:%i" % options.tcp] self._sender = air_modes.zmq_pubsub_iface(context, subaddr=None, pubaddr=server_addr) self._async_sender = gru.msgq_runner(self._queue, self.send)
def __init__(self, rate): #TODO pass in chanlist gr.hier_block2.__init__(self, "smartnet_ctrl_rx", gr.io_signature(1,1,gr.sizeof_gr_complex), gr.io_signature(0,0,0)) self.set_assign_callback(None) self._queue = gr.msg_queue() self._async_sender = gru.msgq_runner(self._queue, self.msg_handler) self._syms_per_sec = 3600. self._sps = rate / self._syms_per_sec self._demod = scanner.fsk_demod(self._sps, 0.1) self._sof = digital.correlate_access_code_tag_bb("10101100", 0, "smartnet_preamble") self._deinterleave = scanner.deinterleave() self._crc = scanner.crc(self._queue) self.connect(self, self._demod, self._sof, self._deinterleave, self._crc)
def __init__(self, rate): #TODO pass in chanlist gr.hier_block2.__init__(self, "edacs_ctrl_rx", gr.io_signature(1,1,gr.sizeof_gr_complex), gr.io_signature(0,0,0)) self.set_assign_callback(None) self._queue = gr.msg_queue() self._async_sender = gru.msgq_runner(self._queue, self.msg_handler) self._syms_per_sec = 9600. self._sps = rate / self._syms_per_sec self._demod = scanner.fsk_demod(self._sps, 0.575) self._invert = scanner.invert() self._sof = digital.correlate_access_code_tag_bb("010101010101010101010111000100100101010101010101", 0, "edacs_preamble") self._rx = scanner.edacs_pkt_rx(self._queue) self.connect(self, self._demod, self._invert, self._sof, self._rx)
def __init__(self, options): gr.top_block.__init__(self) pubsub.__init__(self) self._options = options self._queue = gr.msg_queue() self._u = self._setup_source(options) self._rate = self.get_rate() print "Rate is %i" % (self._rate,) self._rx_path1 = ais_rx(161.975e6 - 162.0e6, options.rate, "A", self._queue, options.viterbi) self._rx_path2 = ais_rx(162.025e6 - 162.0e6, options.rate, "B", self._queue, options.viterbi) self.connect(self._u, self._rx_path1) self.connect(self._u, self._rx_path2) #now subscribe to set various options via pubsub self.subscribe("gain", self.set_gain) self.subscribe("rate", self.set_rate) self.publish("gain", self.get_gain) self.publish("rate", self.get_rate) self._async_sender = gru.msgq_runner(self._queue, self.send)
def __init__(self, frame, panel, vbox, argv): stdgui2.std_top_block.__init__(self, frame, panel, vbox, argv) self.frame = frame self.panel = panel parser = OptionParser(option_class=eng_option) parser.add_option("-a", "--args", type="string", default="", help="UHD device address args , [default=%default]") parser.add_option("", "--spec", type="string", default=None, help="Subdevice of UHD device where appropriate") parser.add_option("-A", "--antenna", type="string", default=None, help="select Rx Antenna where appropriate") parser.add_option("-s", "--samp-rate", type="eng_float", default=1e6, help="set sample rate (bandwidth) [default=%default]") parser.add_option("-f", "--freq", type="eng_float", default=None, help="set frequency to FREQ", metavar="FREQ") parser.add_option("-g", "--gain", type="eng_float", default=None, help="set gain in dB (default is midpoint)") parser.add_option("-W", "--waterfall", action="store_true", default=False, help="Enable waterfall display") parser.add_option("-S", "--oscilloscope", action="store_true", default=False, help="Enable oscilloscope display") parser.add_option("", "--avg-alpha", type="eng_float", default=1e-1, help="Set fftsink averaging factor, default=[%default]") parser.add_option ("", "--averaging", action="store_true", default=False, help="Enable fftsink averaging, default=[%default]") parser.add_option("", "--ref-scale", type="eng_float", default=1.0, help="Set dBFS=0dB input value, default=[%default]") parser.add_option("", "--fft-size", type="int", default=1024, help="Set number of FFT bins [default=%default]") parser.add_option("", "--fft-rate", type="int", default=30, help="Set FFT update rate, [default=%default]") parser.add_option("", "--wire-format", type="string", default="sc16", help="Set wire format from USRP [default=%default]") parser.add_option("", "--scalar", type="int", default=1024, help="Set scalar multiplier value sc8 wire format [default=%default]") parser.add_option("", "--show-async-msg", action="store_true", default=False, help="Show asynchronous message notifications from UHD [default=%default]") (options, args) = parser.parse_args() if len(args) != 0: parser.print_help() sys.exit(1) self.options = options self.show_debug_info = True scalar="scalar="+str(options.scalar) self.u = uhd.usrp_source(device_addr=options.args, stream_args=uhd.stream_args(cpu_format='fc32', otw_format=options.wire_format, args=scalar)) # Set the subdevice spec if(options.spec): self.u.set_subdev_spec(options.spec, 0) # Set the antenna if(options.antenna): self.u.set_antenna(options.antenna, 0) self.u.set_samp_rate(options.samp_rate) input_rate = self.u.get_samp_rate() if options.waterfall: self.scope = \ waterfallsink2.waterfall_sink_c (panel, fft_size=1024, sample_rate=input_rate) self.frame.SetMinSize((800, 420)) elif options.oscilloscope: self.scope = scopesink2.scope_sink_c(panel, sample_rate=input_rate) self.frame.SetMinSize((800, 600)) else: self.scope = fftsink2.fft_sink_c (panel, fft_size=options.fft_size, sample_rate=input_rate, ref_scale=options.ref_scale, ref_level=20.0, y_divs = 12, average=options.averaging, avg_alpha=options.avg_alpha, fft_rate=options.fft_rate) self.frame.SetMinSize((800, 420)) self.connect(self.u, self.scope) self._build_gui(vbox) self._setup_events() # set initial values if options.gain is None: # if no gain was specified, use the mid-point in dB g = self.u.get_gain_range() options.gain = float(g.start()+g.stop())/2 if options.freq is None: # if no freq was specified, use the mid-point r = self.u.get_freq_range() options.freq = float(r.start()+r.stop())/2 self.set_gain(options.gain) if self.show_debug_info: self.myform['samprate'].set_value(self.u.get_samp_rate()) self.myform['rffreq'].set_value(0) self.myform['dspfreq'].set_value(0) if not(self.set_freq(options.freq)): self._set_status_msg("Failed to set initial frequency") # Direct asynchronous notifications to callback function if self.options.show_async_msg: self.async_msgq = gr.msg_queue(0) self.async_src = uhd.amsg_source("", self.async_msgq) self.async_rcv = gru.msgq_runner(self.async_msgq, self.async_callback)
def __init__(self, options): gr.top_block.__init__(self) self.options = options (dev_rate, channel_rate, audio_rate, channel_pass, channel_stop, demod) = demod_params[options.modulation] DEV = uhd_src(options.args, # UHD device address options.spec, # device subdev spec options.antenna, # device antenna dev_rate, # device sample rate options.gain, # Receiver gain options.calibration) # Frequency offset DEV.tune(options.frequency) if_rate = DEV.rate() channel_decim = int(if_rate // channel_rate) audio_decim = int(channel_rate // audio_rate) CHAN_taps = optfir.low_pass(1.0, # Filter gain if_rate, # Sample rate channel_pass, # One sided modulation bandwidth channel_stop, # One sided channel bandwidth 0.1, # Passband ripple 60) # Stopband attenuation CHAN = gr.freq_xlating_fir_filter_ccf(channel_decim, # Decimation rate CHAN_taps, # Filter taps 0.0, # Offset frequency if_rate) # Sample rate RFSQL = gr.pwr_squelch_cc(options.rf_squelch, # Power threshold 125.0/channel_rate, # Time constant int(channel_rate/20), # 50ms rise/fall False) # Zero, not gate output AGC = gr.agc_cc(1.0/channel_rate, # Time constant 1.0, # Reference power 1.0, # Initial gain 1.0) # Maximum gain DEMOD = demod(channel_rate, audio_decim) # From RF to audio #self.connect(DEV, CHAN, RFSQL, AGC, DEMOD) self.connect(DEV, CHAN, DEMOD) # Optionally add CTCSS and RSAMP if needed tail = DEMOD if options.ctcss != None and options.ctcss > 60.0: CTCSS = gr.ctcss_squelch_ff(audio_rate, # Sample rate options.ctcss) # Squelch tone self.connect(DEMOD, CTCSS) tail = CTCSS if options.output_rate != audio_rate: out_lcm = gru.lcm(audio_rate, options.output_rate) out_interp = int(out_lcm // audio_rate) out_decim = int(out_lcm // options.output_rate) RSAMP = blks2.rational_resampler_fff(out_interp, out_decim) self.connect(tail, RSAMP) tail = RSAMP # Send to audio output device AUDIO = audio.sink(int(options.output_rate), options.audio_output) self.connect(tail, AUDIO) # Direct asynchronous notifications to callback function if self.options.show_async_msg: self.async_msgq = gr.msg_queue(0) self.async_src = uhd.amsg_source("", self.async_msgq) self.async_rcv = gru.msgq_runner(self.async_msgq, self.async_callback)
def setup_usrp(self, ctor, args, cpu_format='fc32'): """ Instantiate a USRP object; takes care of all kinds of corner cases and settings. Pop it and some args onto the class that calls this. """ self.channels = args.channels self.cpu_format = cpu_format # Create a UHD device object: self.usrp = ctor( device_addr=args.args, stream_args=uhd.stream_args( cpu_format, args.otw_format, args=args.stream_args, channels=self.channels, ) ) # Set the subdevice spec: self.spec = self.normalize_sel("mboards", "subdev", self.usrp.get_num_mboards(), args.spec) if self.spec: for mb_idx in xrange(self.usrp.get_num_mboards()): self.usrp.set_subdev_spec(self.spec[mb_idx], mb_idx) # Set the clock and/or time source: if args.clock_source is not None: self.clock_source = self.normalize_sel("mboards", "clock-source", self.usrp.get_num_mboards(), args.clock_source) for mb_idx in xrange(self.usrp.get_num_mboards()): self.usrp.set_clock_source(self.clock_source[mb_idx], mb_idx) if args.time_source is not None: self.time_source = self.normalize_sel("mboards", "time-source", self.usrp.get_num_mboards(), args.time_source) for mb_idx in xrange(self.usrp.get_num_mboards()): self.usrp.set_time_source(self.time_source[mb_idx], mb_idx) # Sampling rate: self.usrp.set_samp_rate(args.samp_rate) self.samp_rate = self.usrp.get_samp_rate() self.vprint("Using sampling rate: {rate}".format(rate=self.samp_rate)) # Set the antenna: self.antenna = self.normalize_sel("channels", "antenna", len(args.channels), args.antenna) if self.antenna is not None: for i, chan in enumerate(self.channels): if not self.antenna[i] in self.usrp.get_antennas(i): print("[ERROR] {} is not a valid antenna name for this USRP device!".format(self.antenna[i])) exit(1) self.usrp.set_antenna(self.antenna[i], i) self.vprint("[{prefix}] Channel {chan}: Using antenna {ant}.".format( prefix=self.prefix, chan=chan, ant=self.usrp.get_antenna(i) )) self.antenna = self.usrp.get_antenna(0) # Set receive daughterboard gain: self.set_gain(args.gain) self.gain_range = self.usrp.get_gain_range(0) # Set frequency (tune request takes lo_offset): if hasattr(args, 'lo_offset') and args.lo_offset is not None: treq = uhd.tune_request(args.freq, args.lo_offset) else: treq = uhd.tune_request(args.freq) self.has_lo_sensor = 'lo_locked' in self.usrp.get_sensor_names() # Set LO export and LO source operation if (args.lo_export is not None) and (args.lo_source is not None): self.lo_source = self.normalize_sel("channels", "lo-source", len(self.channels), args.lo_source) self.lo_export = self.normalize_sel("channels", "lo-export", len(self.channels), args.lo_export) for chan, lo_source, lo_export in zip(self.channels, self.lo_source, self.lo_export): if (lo_source == "None") or (lo_export == "None"): continue if lo_export == "True": #If channel is LO source set frequency and store response self.usrp.set_lo_export_enabled(True, uhd.ALL_LOS, chan) if lo_source == "internal": self.lo_source_channel = chan tune_resp = self.usrp.set_center_freq(treq,chan) self.usrp.set_lo_source(lo_source, uhd.ALL_LOS,chan) # Use lo source tune response to tune dsp_freq on remaining channels if getattr(args, 'lo_offset', None) is not None: treq = uhd.tune_request(target_freq=args.freq, rf_freq=args.freq+args.lo_offset, rf_freq_policy=uhd.tune_request.POLICY_MANUAL, dsp_freq=tune_resp.actual_dsp_freq, dsp_freq_policy=uhd.tune_request.POLICY_MANUAL) else: treq = uhd.tune_request(target_freq=args.freq, rf_freq=args.freg, rf_freq_policy=uhd.tune_request.POLICY_MANUAL, dsp_freq=tune_resp.actual_dsp_freq, dsp_freq_policy=uhd.tune_request.POLICY_MANUAL) for chan in args.channels: if chan == self.lo_source_channel: continue self.usrp.set_center_freq(treq,chan) # Make sure tuning is synched: command_time_set = False if len(self.channels) > 1: if args.sync == 'pps': self.usrp.set_time_unknown_pps(uhd.time_spec()) cmd_time = self.usrp.get_time_now() + uhd.time_spec(COMMAND_DELAY) try: for mb_idx in xrange(self.usrp.get_num_mboards()): self.usrp.set_command_time(cmd_time, mb_idx) command_time_set = True except RuntimeError: sys.stderr.write('[{prefix}] [WARNING] Failed to set command times.\n'.format(prefix=self.prefix)) for i, chan in enumerate(self.channels): self.tr = self.usrp.set_center_freq(treq, i) if self.tr == None: sys.stderr.write('[{prefix}] [ERROR] Failed to set center frequency on channel {chan}\n'.format( prefix=self.prefix, chan=chan )) exit(1) if command_time_set: for mb_idx in xrange(self.usrp.get_num_mboards()): self.usrp.clear_command_time(mb_idx) self.vprint("Syncing channels...".format(prefix=self.prefix)) time.sleep(COMMAND_DELAY) self.freq = self.usrp.get_center_freq(0) if args.show_async_msg: self.async_msgq = gr.msg_queue(0) self.async_src = uhd.amsg_source("", self.async_msgq) self.async_rcv = gru.msgq_runner(self.async_msgq, self.async_callback)
def __init__(self, modulator, demodulator, options, ll_logging, dev_log, start_tb_time, time_cal_timeout, start_controller_time): gr.top_block.__init__(self) # Get the modulation's bits_per_symbol args = modulator.extract_kwargs_from_options(options) symbol_rate = options.modulation_bitrate / modulator(**args).bits_per_symbol() # all subsequent code expects list of ints, so convert from # comma separated string sink_addresses = options.sink_mac_addresses options.sink_mac_addresses = [int(x) for x in sink_addresses.split(',')] # Direct asynchronous notifications to callback function if True:#self.options.show_async_msg: self.async_msgq = gr.msg_queue(0) self.async_src = uhd.amsg_source("", self.async_msgq) self.async_rcv = gru.msgq_runner(self.async_msgq, self.async_callback) self.dev_log = dev_log # how much time should be spent calibrating time sync? self.cal_time = time_cal_timeout self.rx_channelizer = channelizer.rx_channelizer(options, dev_log) self.tx_channelizer = channelizer.tx_channelizer(options, dev_log) self.rx_channelizer.set_beacon_channel(options.gpsbug_cal_channel) upsampled_symbol_rate = symbol_rate*options.digital_freq_hop_num_channels upsample_factor_usrp = options.digital_freq_hop_num_channels #setting up USRP RX self.source = uhd_receiver(options.usrp_args, upsampled_symbol_rate, options.modulation_samples_per_symbol, options.rf_rx_freq, options.rf_rx_gain, options.usrp_spec, "RX2", options.verbose) #setting up USRP TX self.sink = uhd_transmitter(options.usrp_args, upsampled_symbol_rate, options.modulation_samples_per_symbol, options.rf_tx_freq, options.rf_tx_gain, options.usrp_spec, "TX/RX", options.verbose) if self.source._sps != options.modulation_samples_per_symbol: self.dev_log.warning("The USRP does not support the requested sample rate of %f. Using %f instead", options.modulation_samples_per_symbol*upsampled_symbol_rate, self.source._sps*upsampled_symbol_rate) options.modulation_samples_per_symbol = self.source._sps self.digital_scaling = gr.multiply_const_vcc((options.digital_scale_factor,)) # moved down here (after reassignment of self.source._sps so we can use # the actual sample rate the UHD is using self.fs = options.modulation_samples_per_symbol*upsampled_symbol_rate/upsample_factor_usrp self.pmt_rpc = digital_ll.pmt_rpc(obj=self,result_msg=False) self.start_tb_time = start_tb_time self.start_controller_time = start_controller_time # this helps control dc tone problem (Use to be burst_gate now eob_shifter) # TODO: Only programmed for GMSK. Other modulations will need additional work. upsample_factor = 8*options.modulation_samples_per_symbol*options.digital_freq_hop_num_channels self.eob = digital_ll.eob_shifter(upsample_factor) num_d_chans = options.digital_freq_hop_num_channels if options.tx_access_code == '0': tx_access_code = None elif options.tx_access_code == '1': tx_access_code = '0000010000110001010011110100011100100101101110110011010101111110' elif options.tx_access_code == '2': tx_access_code = '1110001100101100010110110001110101100000110001011101000100001110' else: tx_access_code = options.tx_access_code print 'tx access code: %s' % tx_access_code self.packet_framer = digital_ll.packet_framer( fs=self.fs, samples_per_symbol=options.modulation_samples_per_symbol, bits_per_symbol=1, access_code=tx_access_code, number_digital_channels=num_d_chans ) if options.node_role == "tdma_base": self.tdma_mac_sm = tdma_base_sm(options, self.sink, self.source, self.packet_framer.num_bytes_to_num_samples) self.frame_sched = parse_frame_file(options.frame_file,start_controller_time, self.fs) for k, slot in enumerate(self.frame_sched["slots"]): self.frame_sched["slots"][k] = slot._replace() # replace the rf_freq field with the value of tx_freq from the ini or # command line for the slots transmitted by the base if (slot.type == "downlink") or (slot.type == "beacon"): self.frame_sched["slots"][k] = slot._replace(rf_freq=options.rf_tx_freq, tx_gain=options.rf_tx_gain, bw=self.fs) # replace the rf_freq field with the value of rx_freq from the ini or # command line for the slots received by the base elif slot.type == "uplink": self.frame_sched["slots"][k] = slot._replace(rf_freq=options.rf_rx_freq, tx_gain=options.rf_tx_gain, bw=self.fs) else: self.tdma_mac_sm = tdma_mobile_sm(options, self.sink, self.source, self.packet_framer.num_bytes_to_num_samples) self.frame_sched = None if self.tdma_mac_sm.is_base(): manage_slots = base_slot_manager_ber_feedback(tdma_types_to_ints, initial_schedule=self.frame_sched, options=options, tdma_mac = self.tdma_mac_sm,) else: manage_slots = mobile_slot_manager_ber_feedback(tdma_types_to_ints, options=options, tdma_mac = self.tdma_mac_sm,) self.dev_log.info("starting at time %s", start_tb_time) self.tdma_controller = tdma_controller(options=options, mac_sm=self.tdma_mac_sm, manage_slots=manage_slots, fs=self.fs, mux_name="scheduled_mux", rx_channelizer_name="rx_channelizer", fhss_flag=1, start_time=start_controller_time, ) if options.traffic_generation == "infinite": self.traffic = Infinite_Backlog_PDU_Streamer( options, self.tdma_controller.app_queue_size ) self.msg_connect(self.traffic, "out_pkt_port", self.tdma_controller,'from_app') elif options.traffic_generation == "tunnel": self.traffic = Tunnel_Handler_PDU_Streamer(options) self.msg_connect(self.traffic, "out_pkt_port", self.tdma_controller,'from_app') self.msg_connect(self.tdma_controller,'to_app', self.traffic, "in_pkt_port") else: self.traffic = None self.tdma_logger = tdma_logger(ll_logging, upsample_factor_usrp) # set up receive path packet_rx_callback = self.tdma_controller.incoming_packet_callback self.rx_path = receive_path_gmsk(demodulator, packet_rx_callback, options, log_index=-2, use_new_pkt=True) self.gmsk_mod = digital_ll.gmsk_mod( samples_per_symbol=options.modulation_samples_per_symbol, bt=options.bt, verbose=False, log=False, ) # declare time tag shifters is_receive = True self.rx_time_tag_shifter = time_tag_shifter(is_receive, gr.sizeof_gr_complex) self.tx_time_tag_shifter = time_tag_shifter(not is_receive, gr.sizeof_gr_complex) # handle base node specific setup if self.tdma_mac_sm.is_base(): t0 = time.time() t0_int = int(t0)-10 t0_frac = t0-t0_int beacon_sched = (1,1,0,(t0_int, t0_frac),(t0_int, t0_frac)) self.scheduled_mux = digital_ll.scheduled_mux(gr.sizeof_gr_complex,1, self.fs, [beacon_sched]) self.connect(self.source, self.rx_time_tag_shifter, self.rx_channelizer,self.scheduled_mux,self.rx_path) # handle mobile node specific setup else: t0 = time.time() t0_int = int(t0)-10 t0_frac = t0-t0_int beacon_sched = (2.0,2.0,0,(t0_int, t0_frac),(t0_int, t0_frac)) self.scheduled_mux = digital_ll.scheduled_mux(gr.sizeof_gr_complex,2,self.fs) self.rx_channelizer.switch_channels(options.gpsbug_cal_channel) # Set up receive path for beacon # set up beacon consumer self.beacon_consumer = beacon_consumer(options, overwrite_metadata=True) beacon_rx_callback = self.beacon_consumer.beacon_callback self.beacon_rx_path = receive_path_gmsk(demodulator, beacon_rx_callback, options,log_index=-1,use_new_pkt=True) self.connect(self.source, self.rx_time_tag_shifter,self.rx_channelizer,self.scheduled_mux,self.beacon_consumer) self.connect(self.scheduled_mux,self.beacon_rx_path) self.connect((self.scheduled_mux,1),self.rx_path) self.msg_connect(self.beacon_consumer, "sched_out", self.tdma_controller, "sched_in") # add in time tag shifter block message connections self.msg_connect(self.beacon_consumer, 'time_cal_out', self.rx_time_tag_shifter, 'time_tag_shift') self.msg_connect(self.beacon_consumer, 'time_cal_out', self.tx_time_tag_shifter, 'time_tag_shift') self.msg_connect(self.beacon_consumer, 'time_cal_out', self.tdma_mac_sm.cq_manager, 'time_tag_shift') self.connect(self.rx_channelizer,self.tdma_controller) self.connect(self.packet_framer, self.gmsk_mod, self.digital_scaling, self.tx_channelizer, self.tx_time_tag_shifter, self.eob, self.sink) #self.connect(self.gmsk_mod, self.tdma_logger) self.connect(self.eob, self.tdma_logger) self.msg_connect(self.tdma_controller, "command_out", self.pmt_rpc, "in") self.msg_connect(self.tdma_controller, "outgoing_pkt", self.packet_framer, "in") # store off params for logging self.get_usrp_params(options)
def __init__(self, frame, panel, vbox, argv): stdgui2.std_top_block.__init__(self, frame, panel, vbox, argv) self.frame = frame self.panel = panel parser = OptionParser(option_class=eng_option) parser.add_option("-a", "--args", type="string", default="", help="UHD device address args , [default=%default]") parser.add_option("", "--spec", type="string", default=None, help="Subdevice of UHD device where appropriate") parser.add_option("-A", "--antenna", type="string", default=None, help="select Rx Antenna where appropriate") parser.add_option("-s", "--samp-rate", type="eng_float", default=1e6, help="set sample rate (bandwidth) [default=%default]") parser.add_option("-f", "--freq", type="eng_float", default=None, help="set frequency to FREQ", metavar="FREQ") parser.add_option("-g", "--gain", type="eng_float", default=None, help="set gain in dB (default is midpoint)") parser.add_option("-W", "--waterfall", action="store_true", default=False, help="Enable waterfall display") parser.add_option("-S", "--oscilloscope", action="store_true", default=False, help="Enable oscilloscope display") parser.add_option("", "--avg-alpha", type="eng_float", default=1e-1, help="Set fftsink averaging factor, default=[%default]") parser.add_option ("", "--averaging", action="store_true", default=False, help="Enable fftsink averaging, default=[%default]") parser.add_option("", "--ref-scale", type="eng_float", default=1.0, help="Set dBFS=0dB input value, default=[%default]") parser.add_option("", "--fft-size", type="int", default=1024, help="Set number of FFT bins [default=%default]") parser.add_option("", "--fft-rate", type="int", default=30, help="Set FFT update rate, [default=%default]") parser.add_option("", "--wire-format", type="string", default="sc16", help="Set wire format from USRP [default=%default]") parser.add_option("", "--stream-args", type="string", default="", help="Set additional stream args [default=%default]") parser.add_option("", "--show-async-msg", action="store_true", default=False, help="Show asynchronous message notifications from UHD [default=%default]") parser.add_option("-b", "--bandwidth", type="eng_float", default=1e6, help="set bandpass filter setting on the RF frontend") parser.add_option("-n", "--nsamples", type="eng_float", default=1024, help="set number of samples which will be saved") parser.add_option("-N", "--samp-avg", type="eng_float", default=10, help="set number of FFT samples which are averaged") (options, args) = parser.parse_args() if len(args) != 0: parser.print_help() sys.exit(1) self.options = options self.show_debug_info = True #Create USRP object self.u = uhd.usrp_source(device_addr=options.args, stream_args=uhd.stream_args(cpu_format='fc32', otw_format=options.wire_format, args=options.stream_args)) #Create USRP object to transmit data to B200 (LO signal) self.u_lo = uhd.usrp_sink( ",".join(("", "")), uhd.stream_args( cpu_format="fc32", channels=range(1), ), ) self.u_lo.set_samp_rate(320000) self.u_lo.set_center_freq(25000000, 0) self.u_lo.set_gain(0, 0) # Create signal source self.sig_lo= analog.sig_source_c(320000, analog.GR_SIN_WAVE, 25000000, 0.316, 0) #(sample_rate, type, frequency, amplitude, offset) #Valve controls the streaming of LO self.valve = grc_blks2.valve(item_size=gr.sizeof_gr_complex*1, open=True) self.fft_size=options.fft_size # 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) # Set sample rate self.u.set_samp_rate(options.samp_rate) input_rate = self.u.get_samp_rate() # What kind of display will be shown if options.waterfall: self.scope = \ waterfallsink2.waterfall_sink_c (panel, fft_size=1024, sample_rate=input_rate) self.frame.SetMinSize((800, 420)) elif options.oscilloscope: self.scope = scopesink2.scope_sink_c(panel, sample_rate=input_rate) self.frame.SetMinSize((800, 600)) else: self.scope = fftsink2_.fft_sink_c (panel, fft_size=options.fft_size, sample_rate=input_rate, ref_scale=options.ref_scale, ref_level=20.0, y_divs = 12, average=options.averaging, avg_alpha=options.avg_alpha, fft_rate=options.fft_rate) def fftsink_callback(x, y): self.set_freq(x) self.scope.set_callback(fftsink_callback) self.frame.SetMinSize((800, 420)) self.connect(self.u, self.scope) self.connect(self.sig_lo,self.valve, self.u_lo) self._build_gui(vbox) self._setup_events() # set initial values # Get gain 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 #Get frequency if options.freq is None: # if no freq was specified, use the mid-point r = self.u.get_freq_range()#possible frequency range options.freq = float(r.start()+r.stop())/2#middle of the tunable frequency #Following lines must be after defining myform because set_freq, set_nsamples and set_gain need it # Set number of samples to store self.set_nsamples(options.nsamples) # Set bandwidth (passband filter on the RF frontend) self.set_bw(options.bandwidth) # Set gain self.set_gain(options.gain) # Set default LO frequency self.set_lo_freq(25000000)# LO frequency will be 25MHz, by default if self.show_debug_info: self.myform['samprate'].set_value(self.u.get_samp_rate()) self.myform['rffreq'].set_value(0) self.myform['dspfreq'].set_value(0) if not(self.set_freq(options.freq)): self._set_status_msg("Failed to set initial frequency") else: self.set_filename("Data_nsam_"+str(self.nsamp)+"_samprate_"+str(input_rate)+ "_bw_"+str(self.bandwidth)+"_cfreq_"+str(self.u.get_center_freq())+"_.txt") # Direct asynchronous notifications to callback function if self.options.show_async_msg: self.async_msgq = gr.msg_queue(0) self.async_src = uhd.amsg_source("", self.async_msgq) self.async_rcv = gru.msgq_runner(self.async_msgq, self.async_callback)
def __init__(self, options, filename): gr.top_block.__init__(self) scalar="scalar="+str(options.scalar) # Create a UHD device source if options.output_shorts: self._u = uhd.usrp_source(device_addr=options.args, stream_args=uhd.stream_args('sc16', options.wire_format, args=scalar)) self._sink = gr.file_sink(gr.sizeof_short*2, filename) else: self._u = uhd.usrp_source(device_addr=options.args, stream_args=uhd.stream_args('fc32', options.wire_format, args=scalar)) self._sink = gr.file_sink(gr.sizeof_gr_complex, filename) # 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) # Set receiver sample rate self._u.set_samp_rate(options.samp_rate) # Set receive daughterboard gain if options.gain is None: g = self._u.get_gain_range() options.gain = float(g.start()+g.stop())/2 print "Using mid-point gain of", options.gain, "(", g.start(), "-", g.stop(), ")" self._u.set_gain(options.gain) # Set frequency (tune request takes lo_offset) if(options.lo_offset is not None): treq = uhd.tune_request(options.freq, options.lo_offset) else: treq = uhd.tune_request(options.freq) tr = self._u.set_center_freq(treq) if tr == None: sys.stderr.write('Failed to set center frequency\n') raise SystemExit, 1 # Create head block if needed and wire it up if options.nsamples is None: self.connect(self._u, self._sink) else: if options.output_shorts: self._head = gr.head(gr.sizeof_short*2, int(options.nsamples)) else: self._head = gr.head(gr.sizeof_gr_complex, int(options.nsamples)) self.connect(self._u, self._head, self._sink) input_rate = self._u.get_samp_rate() if options.verbose: print "Args: ", options.args print "Rx gain:", options.gain print "Rx baseband frequency:", n2s(tr.actual_rf_freq) print "Rx DDC frequency:", n2s(tr.actual_dsp_freq) print "Rx Sample Rate:", n2s(input_rate) if options.nsamples is None: print "Receiving samples until Ctrl-C" else: print "Receving", n2s(options.nsamples), "samples" if options.output_shorts: print "Writing 16-bit complex shorts" else: print "Writing 32-bit complex floats" print "Output filename:", filename # Direct asynchronous notifications to callback function if options.show_async_msg: self.async_msgq = gr.msg_queue(0) self.async_src = uhd.amsg_source("", self.async_msgq) self.async_rcv = gru.msgq_runner(self.async_msgq, self.async_callback)
def __init__(self, filenames, dev_addrs, dual, onebit, iq, noise, mix, gain, fs, fc, unint, sync_pps): gr.top_block.__init__(self) if mix: raise NotImplementedError("TODO: Hilbert remix mode not implemented.") if dual: channels = [0, 1] else: channels = [0] uhd_sinks = [ uhd.usrp_sink(",".join( [addr, "send_frame_size=32768,num_send_frames=128"]), uhd.stream_args( cpu_format="fc32", otwformat="sc8", channels=channels)) for addr in dev_addrs] for sink in uhd_sinks: a = sink.get_usrp_info() for each in a.keys(): print each + " : " + a.get(each) sink.set_clock_rate(fs, uhd.ALL_MBOARDS) sink.set_samp_rate(fs) sink.set_center_freq(fc, 0) sink.set_gain(gain, 0) if dual: sink.set_center_freq(fc, 1) sink.set_gain(gain, 1) sink.set_subdev_spec("A:B A:A", 0) # TODO Use offset tuning? if sync_pps: sink.set_clock_source("external") # 10 MHz sink.set_time_source("external") # PPS if unint: if noise or onebit or not iq: raise NotImplementedError("TODO: RX channel-interleaved mode only " "supported for noiseless 8-bit complex.") BLOCK_N = 16*1024*1024 demux = blocks.vector_to_streams(2, len(uhd_sinks)) self.connect(blocks.file_source(2*len(uhd_sinks)*BLOCK_N, filenames[0], False), blocks.vector_to_stream(2*len(uhd_sinks), BLOCK_N), demux) for ix, sink in enumerate(uhd_sinks): self.connect((demux, ix), blocks.vector_to_stream(1, 2), blocks.interleaved_char_to_complex(), # [-128.0, +127.0] blocks.multiply_const_cc(1.0/1024), # [-0.125, 0.125) # blocks.vector_to_stream(8, 16*1024), sink) else: for i, filename in enumerate(filenames): src = blocks.file_source(gr.sizeof_char*1, filename, False) if dual: channel = i % 2 sink = uhd_sinks[i/2] else: channel = 0 sink = uhd_sinks[i] if iq: node = blocks.multiply_const_cc(1.0/1024) if onebit: self.connect(src, blocks.unpack_k_bits_bb(8), blocks.char_to_short(), # [0, 1] -> [0, 256] blocks.add_const_ss(-128), # [-128, +128], blocks.interleaved_short_to_complex(), # [ -128.0, +128.0] node) # [-0.125, +0.125] else: self.connect(src, # [-128..127] blocks.interleaved_char_to_complex(), # [-128.0, +127.0] node) # [-0.125, +0.125) else: node = blocks.float_to_complex(1) if onebit: self.connect(src, blocks.unpack_k_bits_bb(8), # [0, 1] -> [-0.125, +0.125] blocks.char_to_float(vlen=1, scale=4), blocks.add_const_vff((-0.125, )), node) else: self.connect(src, # [-128..127] -> [-0.125, +0.125) blocks.char_to_float(vlen=1, scale=1024), node) if noise: combiner = blocks.add_vcc(1) self.connect((node, 0), (combiner, 0), (sink, channel)) self.connect(analog.fastnoise_source_c(analog.GR_GAUSSIAN, noise, -222, 8192), (combiner, 1)) else: self.connect((node, 0), (sink, channel)) print "Setting clocks..." if sync_pps: time.sleep(1.1) # Ensure there's been an edge. TODO: necessary? last_pps_time = uhd_sinks[0].get_time_last_pps() while last_pps_time == uhd_sinks[0].get_time_last_pps(): time.sleep(0.1) print "Got edge" [sink.set_time_next_pps(uhd.time_spec(round(time.time())+1)) for sink in uhd_sinks] time.sleep(1.0) # Wait for edge to set the clocks else: # No external PPS/10 MHz. Just set each clock and accept some skew. t = time.time() [sink.set_time_now(uhd.time_spec(time.time())) for sink in uhd_sinks] if len(uhd_sinks) > 1 or dual: print "Uncabled; loosely synced only. Initial skew ~ %.1f ms" % ( (time.time()-t) * 1000) t_start = uhd.time_spec(time.time() + 1.5) [sink.set_start_time(t_start) for sink in uhd_sinks] print "ready" # setup message handler self.async_msgq = gr.msg_queue(0) self.async_src = uhd.amsg_source("", self.async_msgq) self.async_rcv = gru.msgq_runner(self.async_msgq, self.async_callback)
def __init__(self, modulator, demodulator, options, ll_logging, dev_log, start_tb_time, time_cal_timeout, start_controller_time): gr.top_block.__init__(self) # Get the modulation's bits_per_symbol args = modulator.extract_kwargs_from_options(options) symbol_rate = options.modulation_bitrate / modulator(**args).bits_per_symbol() # all subsequent code expects list of ints, so convert from # comma separated string sink_addresses = options.sink_mac_addresses options.sink_mac_addresses = [int(x) for x in sink_addresses.split(',')] # Direct asynchronous notifications to callback function if True:#self.options.show_async_msg: self.async_msgq = gr.msg_queue(0) self.async_src = uhd.amsg_source("", self.async_msgq) self.async_rcv = gru.msgq_runner(self.async_msgq, self.async_callback) self.dev_log = dev_log # how much time should be spent calibrating time sync? self.cal_time = time_cal_timeout self.rx_channelizer = channelizer.rx_channelizer(options, dev_log) self.tx_channelizer = channelizer.tx_channelizer(options, dev_log) self.rx_channelizer.set_beacon_channel(options.gpsbug_cal_channel) upsampled_symbol_rate = symbol_rate*options.digital_freq_hop_num_channels upsample_factor_usrp = options.digital_freq_hop_num_channels #setting up USRP RX self.source = uhd_receiver(options.usrp_args, upsampled_symbol_rate, options.modulation_samples_per_symbol, options.rf_rx_freq, options.rf_rx_gain, options.usrp_spec, "RX2", options.verbose) #setting up USRP TX self.sink = uhd_transmitter(options.usrp_args, upsampled_symbol_rate, options.modulation_samples_per_symbol, options.rf_tx_freq, options.rf_tx_gain, options.usrp_spec, "TX/RX", options.verbose) if self.source._sps != options.modulation_samples_per_symbol: self.dev_log.warning("The USRP does not support the requested sample rate of %f. Using %f instead", options.modulation_samples_per_symbol*upsampled_symbol_rate, self.source._sps*upsampled_symbol_rate) options.modulation_samples_per_symbol = self.source._sps self.digital_scaling = gr.multiply_const_vcc((options.digital_scale_factor,)) # moved down here (after reassignment of self.source._sps so we can use # the actual sample rate the UHD is using self.fs = options.modulation_samples_per_symbol*upsampled_symbol_rate/upsample_factor_usrp self.pmt_rpc = digital_ll.pmt_rpc(obj=self,result_msg=False) self.start_tb_time = start_tb_time self.start_controller_time = start_controller_time # this helps control dc tone problem (Use to be burst_gate now eob_shifter) # TODO: Only programmed for GMSK. Other modulations will need additional work. upsample_factor = 8*options.modulation_samples_per_symbol*options.digital_freq_hop_num_channels self.eob = digital_ll.eob_shifter(upsample_factor) num_d_chans = options.digital_freq_hop_num_channels if options.tx_access_code == '0': tx_access_code = None elif options.tx_access_code == '1': tx_access_code = '0000010000110001010011110100011100100101101110110011010101111110' elif options.tx_access_code == '2': tx_access_code = '1110001100101100010110110001110101100000110001011101000100001110' else: tx_access_code = options.tx_access_code print 'tx access code: %s' % tx_access_code self.packet_framer = digital_ll.packet_framer( fs=self.fs, samples_per_symbol=options.modulation_samples_per_symbol, bits_per_symbol=1, access_code=tx_access_code, number_digital_channels=num_d_chans ) if options.node_role == "tdma_base": self.tdma_mac_sm = tdma_base_sm(options, self.sink, self.source, self.packet_framer.num_bytes_to_num_samples) else: self.tdma_mac_sm = tdma_mobile_sm(options, self.sink, self.source, self.packet_framer.num_bytes_to_num_samples) base_rl_agent_protocol_manager.configure_action_space(options, self.fs) num_mobiles = len(options.sink_mac_addresses) pfs = PatternFrameSchedule() num_actions = pfs.num_actions num_stochastic_states = num_mobiles + 1 num_action_states = num_actions num_states = num_stochastic_states*num_action_states if self.tdma_mac_sm.is_base(): epoch_len = options.agent_epoch_duration discount_factor = options.discount_factor learning_rate = options.learning_rate greedy_epsilon = options.greedy_epsilon use_dynamic_alpha = bool(options.agent_use_adaptive_alpha) use_dynamic_epsilon = bool(options.agent_use_adaptive_greedy_epsilon) use_change_detection = bool(options.agent_use_reward_change_detection) reward_history_len = (options.agent_reward_oldbuffer_size, options.agent_reward_guardbuffer_size, options.agent_reward_newbuffer_size ) change_delay = options.slot_assignment_leadtime mobile_ids = options.sink_mac_addresses if options.agent_type == "q_learner": agent = Q_Learner(num_states, num_actions, learning_rate, discount_factor, greedy_epsilon, q_mask=None, q_seed=None, dynamic_alpha=use_dynamic_alpha, dynamic_epsilon=use_dynamic_epsilon, reward_history_len=reward_history_len, use_change_detection=use_change_detection, min_visit_count=options.agent_epsilon_adaptation_threshold) elif options.agent_type == "sarsa": agent = Sarsa_Learner(num_states, num_actions, learning_rate, discount_factor, greedy_epsilon, q_mask=None, q_seed=None, dynamic_alpha=use_dynamic_alpha, dynamic_epsilon=use_dynamic_epsilon,) agent_wrapper = RL_Agent_Wrapper(agent, epoch_len, num_stochastic_states, num_action_states, change_delay, mobile_ids, tdma_types_to_ints, reward_lookup_states=options.agent_reward_states, reward_lookup_vals=options.agent_reward_vals, num_channels=options.digital_freq_hop_num_channels, do_episodic_learning=False, lock_buffer_len=options.agent_lock_buffer_len, lock_policy=options.agent_lock_policy) manage_slots = base_rl_agent_protocol_manager(tdma_types_to_ints, options=options, tdma_mac=self.tdma_mac_sm, initial_time_ref=start_controller_time, agent_wrapper=agent_wrapper) else: manage_slots = mobile_rl_agent_protocol_manager(tdma_types_to_ints, options=options, tdma_mac = self.tdma_mac_sm,) self.dev_log.info("starting at time %s", start_tb_time) self.tdma_controller = tdma_controller(options=options, mac_sm=self.tdma_mac_sm, manage_slots=manage_slots, fs=self.fs, mux_name="scheduled_mux", rx_channelizer_name="rx_channelizer", fhss_flag=1, start_time=start_controller_time, ) if options.traffic_generation == "infinite": self.traffic = Infinite_Backlog_PDU_Streamer( options, self.tdma_controller.app_queue_size ) self.msg_connect(self.traffic, "out_pkt_port", self.tdma_controller,'from_app') elif options.traffic_generation == "tunnel": self.traffic = Tunnel_Handler_PDU_Streamer(options) self.msg_connect(self.traffic, "out_pkt_port", self.tdma_controller,'from_app') self.msg_connect(self.tdma_controller,'to_app', self.traffic, "in_pkt_port") else: self.traffic = None self.tdma_logger = tdma_logger(ll_logging, upsample_factor_usrp) # set up receive path packet_rx_callback = self.tdma_controller.incoming_packet_callback self.rx_path = receive_path_gmsk(demodulator, packet_rx_callback, options, log_index=-2, use_new_pkt=True) self.gmsk_mod = digital_ll.gmsk_mod( samples_per_symbol=options.modulation_samples_per_symbol, bt=options.bt, verbose=False, log=False, ) # declare time tag shifters is_receive = True self.rx_time_tag_shifter = time_tag_shifter(is_receive, gr.sizeof_gr_complex) self.tx_time_tag_shifter = time_tag_shifter(not is_receive, gr.sizeof_gr_complex) # handle base node specific setup if self.tdma_mac_sm.is_base(): t0 = time.time() t0_int = int(t0)-10 t0_frac = t0-t0_int beacon_sched = (1,1,0,(t0_int, t0_frac),(t0_int, t0_frac)) self.scheduled_mux = digital_ll.scheduled_mux(gr.sizeof_gr_complex,1, self.fs, [beacon_sched]) self.connect(self.source, self.rx_time_tag_shifter, self.rx_channelizer,self.scheduled_mux,self.rx_path) # handle mobile node specific setup else: t0 = time.time() t0_int = int(t0)-10 t0_frac = t0-t0_int beacon_sched = (options.beacon_sense_block_size, options.beacon_sense_block_size, 0,(t0_int, t0_frac),(t0_int, t0_frac)) self.scheduled_mux = digital_ll.scheduled_mux(gr.sizeof_gr_complex,2,self.fs) self.rx_channelizer.switch_channels(options.gpsbug_cal_channel) # Set up receive path for beacon # set up beacon consumer self.beacon_consumer = beacon_consumer(options, overwrite_metadata=True) beacon_rx_callback = self.beacon_consumer.beacon_callback self.beacon_rx_path = receive_path_gmsk(demodulator, beacon_rx_callback, options,log_index=-1,use_new_pkt=True) self.connect(self.source, self.rx_time_tag_shifter,self.rx_channelizer,self.scheduled_mux,self.beacon_consumer) self.connect(self.scheduled_mux,self.beacon_rx_path) self.connect((self.scheduled_mux,1),self.rx_path) self.msg_connect(self.beacon_consumer, "sched_out", self.tdma_controller, "sched_in") # add in time tag shifter block message connections self.msg_connect(self.beacon_consumer, 'time_cal_out', self.rx_time_tag_shifter, 'time_tag_shift') self.msg_connect(self.beacon_consumer, 'time_cal_out', self.tx_time_tag_shifter, 'time_tag_shift') self.msg_connect(self.beacon_consumer, 'time_cal_out', self.tdma_mac_sm.cq_manager, 'time_tag_shift') self.connect(self.rx_channelizer,self.tdma_controller) self.connect(self.packet_framer, self.gmsk_mod, self.digital_scaling, self.tx_channelizer, self.tx_time_tag_shifter, self.eob, self.sink) #self.connect(self.gmsk_mod, self.tdma_logger) self.connect(self.eob, self.tdma_logger) self.msg_connect(self.tdma_controller, "command_out", self.pmt_rpc, "in") self.msg_connect(self.tdma_controller, "outgoing_pkt", self.packet_framer, "in") # store off params for logging self.get_usrp_params(options)
def __init__(self, modulator, demodulator, options, ll_logging, dev_log, start_tb_time, time_cal_timeout, start_controller_time): gr.top_block.__init__(self) # Get the modulation's bits_per_symbol args = modulator.extract_kwargs_from_options(options) symbol_rate = options.modulation_bitrate / modulator( **args).bits_per_symbol() # all subsequent code expects list of ints, so convert from # comma separated string sink_addresses = options.sink_mac_addresses options.sink_mac_addresses = [ int(x) for x in sink_addresses.split(',') ] # Direct asynchronous notifications to callback function if True: #self.options.show_async_msg: self.async_msgq = gr.msg_queue(0) self.async_src = uhd.amsg_source("", self.async_msgq) self.async_rcv = gru.msgq_runner(self.async_msgq, self.async_callback) self.dev_log = dev_log # how much time should be spent calibrating time sync? self.cal_time = time_cal_timeout #setting up USRP RX self.source = uhd_receiver(options.usrp_args, symbol_rate, options.modulation_samples_per_symbol, options.rf_rx_freq, options.rf_rx_gain, options.usrp_spec, "RX2", options.verbose) #setting up USRP TX self.sink = uhd_transmitter(options.usrp_args, symbol_rate, options.modulation_samples_per_symbol, options.rf_tx_freq, options.rf_tx_gain, options.usrp_spec, "TX/RX", options.verbose) if self.source._sps != options.modulation_samples_per_symbol: self.dev_log.warning( "The USRP does not support the requested sample rate of %f. Using %f instead", options.modulation_samples_per_symbol * symbol_rate, self.source._sps * symbol_rate) options.modulation_samples_per_symbol = self.source._sps self.digital_scaling = gr.multiply_const_vcc( (options.digital_scale_factor, )) # moved down here (after reassignment of self.source._sps so we can use # the actual sample rate the UHD is using self.fs = options.modulation_samples_per_symbol * symbol_rate self.pmt_rpc = digital_ll.pmt_rpc(obj=self, result_msg=False) self.start_tb_time = start_tb_time self.start_controller_time = start_controller_time upsample_factor = 8 * options.modulation_samples_per_symbol self.eob = digital_ll.eob_shifter(upsample_factor) options.digital_freq_hop_num_channels = 1 if options.tx_access_code == '0': tx_access_code = None elif options.tx_access_code == '1': tx_access_code = '0000010000110001010011110100011100100101101110110011010101111110' elif options.tx_access_code == '2': tx_access_code = '1110001100101100010110110001110101100000110001011101000100001110' else: tx_access_code = options.tx_access_code print 'tx access code: %s' % tx_access_code self.packet_framer = digital_ll.packet_framer( fs=self.fs, samples_per_symbol=options.modulation_samples_per_symbol, bits_per_symbol=1, access_code=tx_access_code, number_digital_channels=1) if options.node_role == "tdma_base": self.tdma_mac_sm = tdma_base_sm( options, self.sink, self.source, self.packet_framer.num_bytes_to_num_samples) self.frame_sched = parse_frame_file(options.frame_file, start_controller_time, self.fs) for k, slot in enumerate(self.frame_sched["slots"]): self.frame_sched["slots"][k] = slot._replace() # replace the rf_freq field with the value of tx_freq from the ini or # command line for the slots transmitted by the base if (slot.type == "downlink") or (slot.type == "beacon"): self.frame_sched["slots"][k] = slot._replace( rf_freq=options.rf_tx_freq, tx_gain=options.rf_tx_gain, bw=self.fs) # replace the rf_freq field with the value of rx_freq from the ini or # command line for the slots received by the base elif slot.type == "uplink": self.frame_sched["slots"][k] = slot._replace( rf_freq=options.rf_rx_freq, tx_gain=options.rf_tx_gain, bw=self.fs) # for simple case, force all slot baseband frequencies to 0 for k, slot in enumerate(self.frame_sched["slots"]): self.frame_sched["slots"][k] = slot._replace(bb_freq=0) else: self.tdma_mac_sm = tdma_mobile_sm( options, self.sink, self.source, self.packet_framer.num_bytes_to_num_samples) self.frame_sched = None if self.tdma_mac_sm.is_base(): manage_slots = base_slot_manager_static( types_to_ints=tdma_types_to_ints, options=options, tdma_mac=self.tdma_mac_sm, initial_schedule=self.frame_sched) else: manage_slots = mobile_slot_manager_static( types_to_ints=tdma_types_to_ints, options=options, tdma_mac=self.tdma_mac_sm, ) self.dev_log.info("starting at time %s", start_tb_time) self.tdma_controller = tdma_controller( options=options, mac_sm=self.tdma_mac_sm, manage_slots=manage_slots, fs=self.fs, mux_name="scheduled_mux", rx_channelizer_name="rx_channelizer", fhss_flag=0, # No hopping start_time=start_controller_time, ) if options.traffic_generation == "infinite": self.traffic = Infinite_Backlog_PDU_Streamer( options, self.tdma_controller.app_queue_size) self.msg_connect(self.traffic, "out_pkt_port", self.tdma_controller, 'from_app') elif options.traffic_generation == "tunnel": self.traffic = Tunnel_Handler_PDU_Streamer(options) self.msg_connect(self.traffic, "out_pkt_port", self.tdma_controller, 'from_app') self.msg_connect(self.tdma_controller, 'to_app', self.traffic, "in_pkt_port") else: self.traffic = None self.tdma_logger = tdma_logger(ll_logging, 1) # set up receive path packet_rx_callback = self.tdma_controller.incoming_packet_callback self.rx_path = receive_path_gmsk(demodulator, packet_rx_callback, options, log_index=-2, use_new_pkt=True) self.gmsk_mod = digital_ll.gmsk_mod( samples_per_symbol=options.modulation_samples_per_symbol, bt=options.bt, verbose=False, log=False, ) # declare time tag shifters is_receive = True self.rx_time_tag_shifter = time_tag_shifter(is_receive, gr.sizeof_gr_complex) self.tx_time_tag_shifter = time_tag_shifter(not is_receive, gr.sizeof_gr_complex) # handle base node specific setup if self.tdma_mac_sm.is_base(): t0 = time.time() t0_int = int(t0) - 10 t0_frac = t0 - t0_int beacon_sched = (1, 1, 0, (t0_int, t0_frac), (t0_int, t0_frac)) self.scheduled_mux = digital_ll.scheduled_mux( gr.sizeof_gr_complex, 1, self.fs, [beacon_sched]) self.connect(self.source, self.rx_time_tag_shifter, self.scheduled_mux, self.rx_path) # handle mobile node specific setup else: t0 = time.time() t0_int = int(t0) - 10 t0_frac = t0 - t0_int beacon_sched = (options.beacon_sense_block_size, options.beacon_sense_block_size, 0, (t0_int, t0_frac), (t0_int, t0_frac)) self.scheduled_mux = digital_ll.scheduled_mux( gr.sizeof_gr_complex, 2, self.fs) # Set up receive path for beacon # set up beacon consumer self.beacon_consumer = beacon_consumer(options, overwrite_metadata=True) beacon_rx_callback = self.beacon_consumer.beacon_callback self.beacon_rx_path = receive_path_gmsk(demodulator, beacon_rx_callback, options, log_index=-1, use_new_pkt=True) self.connect(self.source, self.rx_time_tag_shifter, self.scheduled_mux, self.beacon_consumer) self.connect(self.scheduled_mux, self.beacon_rx_path) self.connect((self.scheduled_mux, 1), self.rx_path) self.msg_connect(self.beacon_consumer, "sched_out", self.tdma_controller, "sched_in") # add in time tag shifter block message connections self.msg_connect(self.beacon_consumer, 'time_cal_out', self.rx_time_tag_shifter, 'time_tag_shift') self.msg_connect(self.beacon_consumer, 'time_cal_out', self.tx_time_tag_shifter, 'time_tag_shift') self.msg_connect(self.beacon_consumer, 'time_cal_out', self.tdma_mac_sm.cq_manager, 'time_tag_shift') self.connect(self.rx_time_tag_shifter, self.tdma_controller) self.connect(self.packet_framer, self.gmsk_mod, self.digital_scaling, self.tx_time_tag_shifter, self.eob, self.sink) #self.connect(self.gmsk_mod, self.tdma_logger) self.connect(self.eob, self.tdma_logger) self.msg_connect(self.tdma_controller, "command_out", self.pmt_rpc, "in") self.msg_connect(self.tdma_controller, "outgoing_pkt", self.packet_framer, "in") # store off params for logging self.get_usrp_params(options)
def __init__(self, options, filename): gr.top_block.__init__(self) scalar = "scalar=" + str(options.scalar) # Create a UHD device source if options.output_shorts: self._u = uhd.usrp_source(device_addr=options.args, stream_args=uhd.stream_args( 'sc16', options.wire_format, args=scalar)) self._sink = blocks.file_sink(gr.sizeof_short * 2, filename) else: self._u = uhd.usrp_source(device_addr=options.args, stream_args=uhd.stream_args( 'fc32', options.wire_format, args=scalar)) self._sink = blocks.file_sink(gr.sizeof_gr_complex, filename) # 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) # Set receiver sample rate self._u.set_samp_rate(options.samp_rate) # Set receive daughterboard gain if options.gain is None: g = self._u.get_gain_range() options.gain = float(g.start() + g.stop()) / 2 print "Using mid-point gain of", options.gain, "(", g.start( ), "-", g.stop(), ")" self._u.set_gain(options.gain) # Set frequency (tune request takes lo_offset) if (options.lo_offset is not None): treq = uhd.tune_request(options.freq, options.lo_offset) else: treq = uhd.tune_request(options.freq) tr = self._u.set_center_freq(treq) if tr == None: sys.stderr.write('Failed to set center frequency\n') raise SystemExit, 1 # Create head block if needed and wire it up if options.nsamples is None: self.connect(self._u, self._sink) else: if options.output_shorts: self._head = blocks.head(gr.sizeof_short * 2, int(options.nsamples)) else: self._head = blocks.head(gr.sizeof_gr_complex, int(options.nsamples)) self.connect(self._u, self._head, self._sink) input_rate = self._u.get_samp_rate() if options.verbose: print "Args: ", options.args print "Rx gain:", options.gain print "Rx baseband frequency:", n2s(tr.actual_rf_freq) print "Rx DDC frequency:", n2s(tr.actual_dsp_freq) print "Rx Sample Rate:", n2s(input_rate) if options.nsamples is None: print "Receiving samples until Ctrl-C" else: print "Receving", n2s(options.nsamples), "samples" if options.output_shorts: print "Writing 16-bit complex shorts" else: print "Writing 32-bit complex floats" print "Output filename:", filename # Direct asynchronous notifications to callback function if options.show_async_msg: self.async_msgq = gr.msg_queue(0) self.async_src = uhd.amsg_source("", self.async_msgq) self.async_rcv = gru.msgq_runner(self.async_msgq, self.async_callback)
def setup_usrp(self, ctor, args, cpu_format='fc32'): """ Instantiate a USRP object; takes care of all kinds of corner cases and settings. Pop it and some args onto the class that calls this. """ self.channels = args.channels self.cpu_format = cpu_format # Create a UHD device object: self.usrp = ctor( device_addr=args.args, stream_args=uhd.stream_args( cpu_format, args.otw_format, args=args.stream_args, channels=self.channels, ) ) # Set the subdevice spec: if args.spec: for mb_idx in xrange(self.usrp.get_num_mboards()): self.usrp.set_subdev_spec(args.spec, mb_idx) # Sampling rate: self.usrp.set_samp_rate(args.samp_rate) self.samp_rate = self.usrp.get_samp_rate() self.vprint("Using sampling rate: {rate}".format(rate=self.samp_rate)) # Set the antenna: self.antenna = self.normalize_antenna_sel(args) if self.antenna is not None: for i, chan in enumerate(self.channels): if not self.antenna[i] in self.usrp.get_antennas(chan): self.vprint("[ERROR] {} is not a valid antenna name for this USRP device!".format(ant)) exit(1) self.usrp.set_antenna(self.antenna[i], chan) self.vprint("[{prefix}] Channel {chan}: Using antenna {ant}.".format( prefix=self.prefix, chan=chan, ant=self.usrp.get_antenna(chan) )) self.antenna = self.usrp.get_antenna(self.channels[0]) # Set receive daughterboard gain: self.set_gain(args.gain) self.gain_range = self.usrp.get_gain_range(self.channels[0]) # Set frequency (tune request takes lo_offset): if hasattr(args, 'lo_offset') and args.lo_offset is not None: treq = uhd.tune_request(args.freq, args.lo_offset) else: treq = uhd.tune_request(args.freq) self.has_lo_sensor = 'lo_locked' in self.usrp.get_sensor_names() # Make sure tuning is synched: if len(self.channels) > 1: if args.sync == 'pps': self.usrp.set_time_unknown_pps(uhd.time_spec()) cmd_time = self.usrp.get_time_now() + uhd.time_spec(COMMAND_DELAY) for mb_idx in xrange(self.usrp.get_num_mboards()): self.usrp.set_command_time(cmd_time, mb_idx) for chan in self.channels: self.tr = self.usrp.set_center_freq(treq, chan) if self.tr == None: sys.stderr.write('[{prefix}] [ERROR] Failed to set center frequency on channel {chan}\n'.format( prefix=self.prefix, chan=chan )) exit(1) if len(self.channels) > 1: for mb_idx in xrange(self.usrp.get_num_mboards()): self.usrp.clear_command_time(mb_idx) self.vprint("Syncing channels...".format(prefix=self.prefix)) time.sleep(COMMAND_DELAY) self.freq = self.usrp.get_center_freq(self.channels[0]) if args.show_async_msg: self.async_msgq = gr.msg_queue(0) self.async_src = uhd.amsg_source("", self.async_msgq) self.async_rcv = gru.msgq_runner(self.async_msgq, self.async_callback)
def setup_usrp(self, ctor, args, cpu_format='fc32'): """ Instantiate a USRP object; takes care of all kinds of corner cases and settings. Pop it and some args onto the class that calls this. """ self.channels = args.channels self.cpu_format = cpu_format # Create a UHD device object: self.usrp = ctor(device_addr=args.args, stream_args=uhd.stream_args( cpu_format, args.otw_format, args=args.stream_args, channels=self.channels, )) # Set the subdevice spec: if args.spec: for mb_idx in xrange(self.usrp.get_num_mboards()): self.usrp.set_subdev_spec(args.spec, mb_idx) # Set the clock and/or time source: if args.clock_source is not None: for mb_idx in xrange(self.usrp.get_num_mboards()): self.usrp.set_clock_source(args.clock_source, mb_idx) if args.time_source is not None: for mb_idx in xrange(self.usrp.get_num_mboards()): self.usrp.set_time_source(args.time_source, mb_idx) # Sampling rate: self.usrp.set_samp_rate(args.samp_rate) self.samp_rate = self.usrp.get_samp_rate() self.vprint("Using sampling rate: {rate}".format(rate=self.samp_rate)) # Set the antenna: self.antenna = self.normalize_antenna_sel(args) if self.antenna is not None: for i, chan in enumerate(self.channels): if not self.antenna[i] in self.usrp.get_antennas(chan): self.vprint( "[ERROR] {} is not a valid antenna name for this USRP device!" .format(self.antenna[i])) exit(1) self.usrp.set_antenna(self.antenna[i], chan) self.vprint( "[{prefix}] Channel {chan}: Using antenna {ant}.".format( prefix=self.prefix, chan=chan, ant=self.usrp.get_antenna(chan))) self.antenna = self.usrp.get_antenna(self.channels[0]) # Set receive daughterboard gain: self.set_gain(args.gain) self.gain_range = self.usrp.get_gain_range(self.channels[0]) # Set frequency (tune request takes lo_offset): if hasattr(args, 'lo_offset') and args.lo_offset is not None: treq = uhd.tune_request(args.freq, args.lo_offset) else: treq = uhd.tune_request(args.freq) self.has_lo_sensor = 'lo_locked' in self.usrp.get_sensor_names() # Make sure tuning is synched: command_time_set = False if len(self.channels) > 1: if args.sync == 'pps': self.usrp.set_time_unknown_pps(uhd.time_spec()) cmd_time = self.usrp.get_time_now() + uhd.time_spec(COMMAND_DELAY) try: for mb_idx in xrange(self.usrp.get_num_mboards()): self.usrp.set_command_time(cmd_time, mb_idx) command_time_set = True except RuntimeError: sys.stderr.write( '[{prefix}] [WARNING] Failed to set command times.\n'. format(prefix=self.prefix)) for chan in self.channels: self.tr = self.usrp.set_center_freq(treq, chan) if self.tr == None: sys.stderr.write( '[{prefix}] [ERROR] Failed to set center frequency on channel {chan}\n' .format(prefix=self.prefix, chan=chan)) exit(1) if command_time_set: for mb_idx in xrange(self.usrp.get_num_mboards()): self.usrp.clear_command_time(mb_idx) self.vprint("Syncing channels...".format(prefix=self.prefix)) time.sleep(COMMAND_DELAY) self.freq = self.usrp.get_center_freq(self.channels[0]) if args.show_async_msg: self.async_msgq = gr.msg_queue(0) self.async_src = uhd.amsg_source("", self.async_msgq) self.async_rcv = gru.msgq_runner(self.async_msgq, self.async_callback)
def setup_usrp(self, ctor, args, cpu_format='fc32'): """ Instantiate a USRP object; takes care of all kinds of corner cases and settings. Pop it and some args onto the class that calls this. """ self.channels = args.channels self.cpu_format = cpu_format # Create a UHD device object: self.usrp = ctor( device_addr=args.args, stream_args=uhd.stream_args( cpu_format, args.otw_format, args=args.stream_args, channels=self.channels, ) ) # Set the subdevice spec: self.spec = self.normalize_sel("mboards", "subdev", self.usrp.get_num_mboards(), args.spec) if self.spec: for mb_idx in range(self.usrp.get_num_mboards()): self.usrp.set_subdev_spec(self.spec[mb_idx], mb_idx) # Set the clock and/or time source: if args.clock_source is not None: self.clock_source = self.normalize_sel("mboards", "clock-source", self.usrp.get_num_mboards(), args.clock_source) for mb_idx in range(self.usrp.get_num_mboards()): self.usrp.set_clock_source(self.clock_source[mb_idx], mb_idx) if args.time_source is not None: self.time_source = self.normalize_sel("mboards", "time-source", self.usrp.get_num_mboards(), args.time_source) for mb_idx in range(self.usrp.get_num_mboards()): self.usrp.set_time_source(self.time_source[mb_idx], mb_idx) # Sampling rate: self.usrp.set_samp_rate(args.samp_rate) self.samp_rate = self.usrp.get_samp_rate() self.vprint("Using sampling rate: {rate}".format(rate=self.samp_rate)) # Set the antenna: self.antenna = self.normalize_sel("channels", "antenna", len(args.channels), args.antenna) if self.antenna is not None: for i, chan in enumerate(self.channels): if not self.antenna[i] in self.usrp.get_antennas(i): print("[ERROR] {} is not a valid antenna name for this USRP device!".format(self.antenna[i])) exit(1) self.usrp.set_antenna(self.antenna[i], i) self.vprint("[{prefix}] Channel {chan}: Using antenna {ant}.".format( prefix=self.prefix, chan=chan, ant=self.usrp.get_antenna(i) )) self.antenna = self.usrp.get_antenna(0) # Set receive daughterboard gain: self.set_gain(args.gain) self.gain_range = self.usrp.get_gain_range(0) # Set frequency (tune request takes lo_offset): if hasattr(args, 'lo_offset') and args.lo_offset is not None: treq = uhd.tune_request(args.freq, args.lo_offset) else: treq = uhd.tune_request(args.freq) self.has_lo_sensor = 'lo_locked' in self.usrp.get_sensor_names() # Set LO export and LO source operation if (args.lo_export is not None) and (args.lo_source is not None): self.lo_source = self.normalize_sel("channels", "lo-source", len(self.channels), args.lo_source) self.lo_export = self.normalize_sel("channels", "lo-export", len(self.channels), args.lo_export) self.lo_source_channel = None for chan, lo_source, lo_export in zip(self.channels, self.lo_source, self.lo_export): if (lo_source == "None") or (lo_export == "None"): continue if lo_export == "True": #If channel is LO source set frequency and store response self.usrp.set_lo_export_enabled(True, uhd.ALL_LOS, chan) if lo_source == "internal": self.lo_source_channel = chan tune_resp = self.usrp.set_center_freq(treq,chan) self.usrp.set_lo_source(lo_source, uhd.ALL_LOS,chan) # Use lo source tune response to tune dsp_freq on remaining channels if self.lo_source_channel is not None: if getattr(args, 'lo_offset', None) is not None: treq = uhd.tune_request(target_freq=args.freq, rf_freq=args.freq+args.lo_offset, rf_freq_policy=uhd.tune_request.POLICY_MANUAL, dsp_freq=tune_resp.actual_dsp_freq, dsp_freq_policy=uhd.tune_request.POLICY_MANUAL) else: treq = uhd.tune_request(target_freq=args.freq, rf_freq=args.freg, rf_freq_policy=uhd.tune_request.POLICY_MANUAL, dsp_freq=tune_resp.actual_dsp_freq, dsp_freq_policy=uhd.tune_request.POLICY_MANUAL) for chan in args.channels: if chan == self.lo_source_channel: continue self.usrp.set_center_freq(treq,chan) # Make sure tuning is synched: command_time_set = False if len(self.channels) > 1: if args.sync == 'pps': self.usrp.set_time_unknown_pps(uhd.time_spec()) cmd_time = self.usrp.get_time_now() + uhd.time_spec(COMMAND_DELAY) try: for mb_idx in range(self.usrp.get_num_mboards()): self.usrp.set_command_time(cmd_time, mb_idx) command_time_set = True except RuntimeError: sys.stderr.write('[{prefix}] [WARNING] Failed to set command times.\n'.format(prefix=self.prefix)) for i, chan in enumerate(self.channels): self.tr = self.usrp.set_center_freq(treq, i) if self.tr == None: sys.stderr.write('[{prefix}] [ERROR] Failed to set center frequency on channel {chan}\n'.format( prefix=self.prefix, chan=chan )) exit(1) if command_time_set: for mb_idx in range(self.usrp.get_num_mboards()): self.usrp.clear_command_time(mb_idx) self.vprint("Syncing channels...".format(prefix=self.prefix)) time.sleep(COMMAND_DELAY) self.freq = self.usrp.get_center_freq(0) if args.show_async_msg: self.async_msgq = gr.msg_queue(0) self.async_src = uhd.amsg_source("", self.async_msgq) self.async_rcv = gru.msgq_runner(self.async_msgq, self.async_callback)