def _set_source(self): options = self.options fusb_block_size = gr.prefs().get_long('fusb', 'block_size', 4096) fusb_nblocks = gr.prefs().get_long('fusb', 'nblocks', 16) self.usrp = usrp.source_c(decim_rate=options.decim, fusb_block_size=fusb_block_size, fusb_nblocks=fusb_nblocks) if options.rx_subdev_spec is None: options.rx_subdev_spec = usrp.pick_rx_subdevice(self.usrp) self.usrp.set_mux(usrp.determine_rx_mux_value(self.usrp, options.rx_subdev_spec)) # determine the daughterboard subdevice self.subdev = usrp.selected_subdev(self.usrp, options.rx_subdev_spec) print "Using Rx d'board %s" % (self.subdev.side_and_name(),) input_rate = self.usrp.adc_freq() / self.usrp.decim_rate() print "USB sample rate %s" % (eng_notation.num_to_str(input_rate)) # set initial values if options.gain is None: # if no gain was specified, use the mid-point in dB g = self.subdev.gain_range() options.gain = float(g[0]+g[1])/2 r = self.usrp.tune(0, self.subdev, options.freq) self.subdev.set_gain(options.gain) return self.usrp
def _parse_fusb_options(options): # Honor the specified values from command-line if present if options.fusb_block_size != 0 or options.fusb_nblocks != 0: return (options.fusb_block_size, options.fusb_nblocks) # Choose some defaults. We try to be more aggressive if real-time # scheduling is enabled. if _enable_realtime(): return (gr.prefs().get_long('fusb', 'rt_block_size', 1024), \ gr.prefs().get_long('fusb', 'rt_nblocks', 16)) else: return (gr.prefs().get_long('fusb', 'block_size', 4096), \ gr.prefs().get_long('fusb', 'nblocks', 16))
def setup(self): (options, self.args) = self.parser.parse_args() self._info['modname'] = options.module_name if self._info['modname'] is None: if len(self.args) >= 2: self._info['modname'] = self.args[1] else: self._info['modname'] = raw_input('Name of the new module: ') if not re.match('[a-zA-Z0-9_]+', self._info['modname']): print 'Invalid module name.' exit(2) self._dir = options.directory if self._dir == '.': self._dir = './gr-%s' % self._info['modname'] try: os.stat(self._dir) except OSError: pass # This is what should happen else: print 'The given directory exists.' exit(2) if options.srcdir is None: options.srcdir = '/usr/local/share/gnuradio/modtool/gr-newmod' self._srcdir = gr.prefs().get_string('modtool', 'newmod_path', options.srcdir) if not os.path.isdir(self._srcdir): print 'Error: Could not find gr-newmod source dir.' exit(2)
def __init__(self, fmt, item_size, channels, is_complex, sample_rate, flip_complex=True, baseband_freq=None, decimation=1, scale=1.0, overlap=None, slide_size=None, fft_size=None, jump_step=None, x_slip=None, mode='pipe', buffered=True, kill_on_del=True, memory=None, peak_hold=False, **kwds): gr.hier_block2.__init__(self, "baudline_sink", gr.io_signature(1, 1, item_size), gr.io_signature(0, 0, 0)) baudline_path = gr.prefs().get_string('baudline', 'path', 'baudline') #tf = tempfile.NamedTemporaryFile(delete=False) #tf.write(gp) #tf.close() #print tf.name self.mode = mode self.kill_on_del = kill_on_del if mode == 'fifo': fifo_name = 'baudline_fifo' self.tmpdir = tempfile.mkdtemp() self.filename = os.path.join(self.tmpdir, fifo_name) print self.filename try: os.mkfifo(self.filename) except OSError, e: print "Failed to create FIFO: %s" % e raise
def main(args=None): args = args or argument_parser().parse_args() platform = Platform( name='GNU Radio Companion Compiler', prefs=gr.prefs(), version=gr.version(), version_parts=(gr.major_version(), gr.api_version(), gr.minor_version()) ) platform.build_library() out_dir = args.output if not args.user_lib_dir else platform.config.hier_block_lib_dir if os.path.exists(out_dir): pass # all is well elif args.save_to_lib: os.mkdir(out_dir) # create missing hier_block lib directory else: exit('Error: Invalid output directory') Messages.send_init(platform) flow_graph = file_path = None for grc_file in args.grc_files: os.path.exists(grc_file) or exit('Error: missing ' + grc_file) Messages.send('\n') flow_graph, file_path = platform.load_and_generate_flow_graph( os.path.abspath(grc_file), os.path.abspath(out_dir)) if not file_path: exit('Compilation error') if file_path and args.run: run_command_args = flow_graph.get_run_command(file_path, split=True) subprocess.call(run_command_args)
def __init__(self, address="127.0.0.1", port=8888, verbose = True): gr.hier_block2.__init__(self, "ais_decoder", gr.io_signature(1, 1, gr.sizeof_short*1), gr.io_signature(0, 0, 0)) decoder_path = gr.prefs().get_string('ais_decoder', 'path', 'ais_decoder') mode='fifo' buffered=True kill_on_del=True memory=None self.mode = mode self.kill_on_del = kill_on_del if mode == 'fifo': fifo_name = 'ais_fifo' self.tmpdir = tempfile.mkdtemp() self.filename = os.path.join(self.tmpdir, fifo_name) print self.filename try: os.mkfifo(self.filename) except OSError, e: print "Failed to create FIFO: %s" % e raise
def setup_parser(self): """ Init the option parser. If derived classes need to add options, override this and call the parent function. """ parser = OptionParser(add_help_option=False) parser.usage = '%prog ' + self.name + ' [options] <PATTERN> \n' + \ ' Call "%prog ' + self.name + '" without any options to run it interactively.' ogroup = OptionGroup(parser, "General options") ogroup.add_option("-h", "--help", action="help", help="Displays this help message.") ogroup.add_option("-d", "--directory", type="string", default=".", help="Base directory of the module. Defaults to the cwd.") ogroup.add_option("-n", "--module-name", type="string", default=None, help="Use this to override the current module's name (is normally autodetected).") ogroup.add_option("-N", "--block-name", type="string", default=None, help="Name of the block, where applicable.") ogroup.add_option("--skip-lib", action="store_true", default=False, help="Don't do anything in the lib/ subdirectory.") ogroup.add_option("--skip-swig", action="store_true", default=False, help="Don't do anything in the swig/ subdirectory.") ogroup.add_option("--skip-python", action="store_true", default=False, help="Don't do anything in the python/ subdirectory.") ogroup.add_option("--skip-grc", action="store_true", default=False, help="Don't do anything in the grc/ subdirectory.") ogroup.add_option("--scm-mode", type="choice", choices=('yes', 'no', 'auto'), default=gr.prefs().get_string('modtool', 'scm_mode', 'no'), help="Use source control management (yes, no or auto).") ogroup.add_option("-y", "--yes", action="store_true", default=False, help="Answer all questions with 'yes'. This can overwrite and delete your files, so be careful.") parser.add_option_group(ogroup) return parser
def setup(self, args, positional): # Don't call ModTool.setup(), that assumes an existing module. self._info['modname'] = args.module_name if self._info['modname'] is None: if len(positional) >= 2: self._info['modname'] = positional[1] else: self._info['modname'] = input('Name of the new module: ') if not re.match('[a-zA-Z0-9_]+$', self._info['modname']): raise ModToolException('Invalid module name.') self._dir = args.directory if self._dir == '.': self._dir = './rfnoc-%s' % self._info['modname'] try: os.stat(self._dir) except OSError: pass # This is what should happen else: raise ModToolException('The given directory exists.') if args.srcdir is None: post_path = os.path.join('share', 'gr-ettus', 'rfnoc_modtool', 'rfnoc-newmod') if os.environ.get('PYBOMBS_PREFIX'): args.srcdir = os.path.join(os.environ.get('PYBOMBS_PREFIX'), post_path) else: args.srcdir = os.path.join('/usr', 'local', post_path) self._srcdir = gr.prefs().get_string('rfnocmodtool', 'newmod_path', args.srcdir) if not os.path.isdir(self._srcdir): raise ModToolException("Could not find rfnoc-newmod source dir. \n" "Please run: \n\n\t $ rfnocmodtool newmod [NAME] --srcdir" " {path/to/rfnoc-newmod/}\n\n" "Specifying the path where the newmod template is located.") self.args = args self._setup_scm(mode='new')
def setup(self, options): # Don't call ModTool.setup(), that assumes an existing module. self._info['modname'] = options.module_name if self._info['modname'] is None: if options.module_name: self._info['modname'] = options.module_name else: self._info['modname'] = input('Name of the new module: ') if not re.match('[a-zA-Z0-9_]+$', self._info['modname']): raise ModToolException('Invalid module name.') self._dir = options.directory if self._dir == '.': self._dir = './gr-%s' % self._info['modname'] try: os.stat(self._dir) except OSError: pass # This is what should happen else: raise ModToolException('The given directory exists.') if options.srcdir is None: options.srcdir = '/usr/local/share/gnuradio/modtool/gr-newmod' self._srcdir = gr.prefs().get_string('modtool', 'newmod_path', options.srcdir) if not os.path.isdir(self._srcdir): raise ModToolException('Could not find gr-newmod source dir.') self.options = options self._setup_scm(mode='new')
def __init__(self, blockname=None, module_name=None, **kwargs): # List subdirs where stuff happens self._subdirs = ['lib', 'include', 'python', 'swig', 'grc'] self.has_subdirs = {} self.skip_subdirs = {} self.info = {} self._file = {} for subdir in self._subdirs: self.has_subdirs[subdir] = False self.skip_subdirs[subdir] = False self.info['blockname'] = blockname self.info['modname'] = module_name self.cli = kwargs.get('cli', False) self.dir = kwargs.get('directory', '.') self.skip_subdirs['lib'] = kwargs.get('skip_lib', False) self.skip_subdirs['python'] = kwargs.get('skip_python', False) self.skip_subdirs['swig'] = kwargs.get('skip_swig', False) self.skip_subdirs['grc'] = kwargs.get('skip_grc', False) self._scm = kwargs.get('scm_mode', gr.prefs().get_string('modtool', 'scm_mode', 'no')) if not self.cli: logging.basicConfig(level=logging.ERROR, format='%(message)s') self.info['yes'] = True else: self.info['yes'] = kwargs.get('yes', False) from ..cli import setup_cli_logger setup_cli_logger(logger) if not type(self).__name__ in ['ModToolInfo', 'ModToolNewModule']: if self.cli: self._validate()
def check_set_qss(): app = QtGui.qApp qssfile = gr.prefs().get_string("qtgui","qss","") if(len(qssfile)>0): try: app.setStyleSheet(open(qssfile).read()) except: print "WARNING: bad QSS file, %s"%(qssfile)
def setup_usrp(self): options = self.options #set resonable defaults if no user prefs set if options.realtime: if options.fusb_block_size == 0: options.fusb_block_size = gr.prefs().get_long('fusb', 'rt_block_size', 1024) if options.fusb_nblocks == 0: options.fusb_nblocks = gr.prefs().get_long('fusb', 'rt_nblocks', 16) else: if options.fusb_block_size == 0: options.fusb_block_size = gr.prefs().get_long('fusb', 'block_size', 4096) if options.fusb_nblocks == 0: options.fusb_nblocks = gr.prefs().get_long('fusb', 'nblocks', 16) print >> sys.stderr, "fusb_block_size =", options.fusb_block_size print >> sys.stderr, "fusb_nblocks =", options.fusb_nblocks #self.ursp = usrp.source_c(decim_rate=options.decim,fusb_block_size=options.fusb_block_size,fusb_nblocks=options.fusb_nblocks) self.ursp.set_fpga_master_clock_freq(options.clock_frequency) if options.rx_subdev_spec is None: options.rx_subdev_spec = pick_subdevice(self.ursp) #self.ursp.set_mux(usrp.determine_rx_mux_value(self.ursp, options.rx_subdev_spec)) # determine the daughterboard subdevice #self.subdev = usrp.selected_subdev(self.ursp, options.rx_subdev_spec) input_rate = self.ursp.adc_freq() / self.ursp.decim_rate() if options.antenna is not None: print >> sys.stderr, "USRP antenna %s" % (options.antenna,) self.subdev.select_rx_antenna(options.antenna) # set initial values if options.gain is None: # if no gain was specified, use the mid-point in dB g = self.subdev.gain_range() options.gain = float(g[0]+g[1])/2 self.set_gain(options.gain) self.source = self.ursp
def __init__(self, host=None, port=None): from gnuradio.ctrlport.GNURadio import ttypes self.BaseTypes = ttypes.BaseTypes self.KnobBase = ttypes.KnobBase # If not set by the user, get the port number from the thrift # config file, if one is set. Defaults to 9090 otherwise. if port is None: p = gr.prefs() thrift_config_file = p.get_string("ControlPort", "config", ""); if(len(thrift_config_file) > 0): p.add_config_file(thrift_config_file) port = p.get_long("thrift", "port", 9090) else: port = 9090 else: port = int(port) super(RPCConnectionThrift, self).__init__(method='thrift', port=port, host=host) self.newConnection(host, port) self.unpack_dict = { self.BaseTypes.BOOL: lambda k,b: self.Knob(k, b.value.a_bool, self.BaseTypes.BOOL), self.BaseTypes.BYTE: lambda k,b: self.Knob(k, b.value.a_byte, self.BaseTypes.BYTE), self.BaseTypes.SHORT: lambda k,b: self.Knob(k, b.value.a_short, self.BaseTypes.SHORT), self.BaseTypes.INT: lambda k,b: self.Knob(k, b.value.a_int, self.BaseTypes.INT), self.BaseTypes.LONG: lambda k,b: self.Knob(k, b.value.a_long, self.BaseTypes.LONG), self.BaseTypes.DOUBLE: lambda k,b: self.Knob(k, b.value.a_double, self.BaseTypes.DOUBLE), self.BaseTypes.STRING: lambda k,b: self.Knob(k, b.value.a_string, self.BaseTypes.STRING), self.BaseTypes.COMPLEX: lambda k,b: self.Knob(k, b.value.a_complex, self.BaseTypes.COMPLEX), self.BaseTypes.F32VECTOR: lambda k,b: self.Knob(k, b.value.a_f32vector, self.BaseTypes.F32VECTOR), self.BaseTypes.F64VECTOR: lambda k,b: self.Knob(k, b.value.a_f64vector, self.BaseTypes.F64VECTOR), self.BaseTypes.S64VECTOR: lambda k,b: self.Knob(k, b.value.a_s64vector, self.BaseTypes.S64VECTOR), self.BaseTypes.S32VECTOR: lambda k,b: self.Knob(k, b.value.a_s32vector, self.BaseTypes.S32VECTOR), self.BaseTypes.S16VECTOR: lambda k,b: self.Knob(k, b.value.a_s16vector, self.BaseTypes.S16VECTOR), self.BaseTypes.S8VECTOR: lambda k,b: self.Knob(k, b.value.a_s8vector, self.BaseTypes.S8VECTOR), self.BaseTypes.C32VECTOR: lambda k,b: self.Knob(k, b.value.a_c32vector, self.BaseTypes.C32VECTOR), } self.pack_dict = { self.BaseTypes.BOOL: lambda k: ttypes.Knob(type=k.ktype, value=ttypes.KnobBase(a_bool = k.value)), self.BaseTypes.BYTE: lambda k: ttypes.Knob(type=k.ktype, value=ttypes.KnobBase(a_byte = k.value)), self.BaseTypes.SHORT: lambda k: ttypes.Knob(type=k.ktype, value=ttypes.KnobBase(a_short = k.value)), self.BaseTypes.INT: lambda k: ttypes.Knob(type=k.ktype, value=ttypes.KnobBase(a_int = k.value)), self.BaseTypes.LONG: lambda k: ttypes.Knob(type=k.ktype, value=ttypes.KnobBase(a_long = k.value)), self.BaseTypes.DOUBLE: lambda k: ttypes.Knob(type=k.ktype, value=ttypes.KnobBase(a_double = k.value)), self.BaseTypes.STRING: lambda k: ttypes.Knob(type=k.ktype, value=ttypes.KnobBase(a_string = k.value)), self.BaseTypes.COMPLEX: lambda k: ttypes.Knob(type=k.ktype, value=ttypes.KnobBase(a_complex = k.value)), self.BaseTypes.F32VECTOR: lambda k: ttypes.Knob(type=k.ktype, value=ttypes.KnobBase(a_f32vector = k.value)), self.BaseTypes.F64VECTOR: lambda k: ttypes.Knob(type=k.ktype, value=ttypes.KnobBase(a_f64vector = k.value)), self.BaseTypes.S64VECTOR: lambda k: ttypes.Knob(type=k.ktype, value=ttypes.KnobBase(a_s64vector = k.value)), self.BaseTypes.S32VECTOR: lambda k: ttypes.Knob(type=k.ktype, value=ttypes.KnobBase(a_s32vector = k.value)), self.BaseTypes.S16VECTOR: lambda k: ttypes.Knob(type=k.ktype, value=ttypes.KnobBase(a_s16vector = k.value)), self.BaseTypes.S8VECTOR: lambda k: ttypes.Knob(type=k.ktype, value=ttypes.KnobBase(a_s8vector = k.value)), self.BaseTypes.C32VECTOR: lambda k: ttypes.Knob(type=k.ktype, value=ttypes.KnobBase(a_c32vector = k.value)), }
def __init__(self,tool="gr-ctrlport-monitor"): print "ControlPort Monitor running." self.started = False self.tool = tool atexit.register(self.shutdown) try: # setup export prefs gr.prefs().singleton().set_bool("ControlPort","on",True); if(tool == "gr-ctrlport-monitor"): gr.prefs().singleton().set_bool("ControlPort","edges_list",True); gr.prefs().singleton().set_bool("PerfCounters","on",True); gr.prefs().singleton().set_bool("PerfCounters","export",True); except: print "no support for gr.prefs setting"
def main(top_block_cls=top_block, options=None): if StrictVersion("4.5.0") <= StrictVersion(Qt.qVersion()) < StrictVersion("5.0.0"): style = gr.prefs().get_string('qtgui', 'style', 'raster') Qt.QApplication.setGraphicsSystem(style) qapp = Qt.QApplication(sys.argv) tb = top_block_cls() tb.start() tb.show() def quitting(): tb.stop() tb.wait() qapp.aboutToQuit.connect(quitting) qapp.exec_()
def main(top_block_cls=top_block, options=None): from distutils.version import StrictVersion if StrictVersion(Qt.qVersion()) >= StrictVersion("4.5.0"): style = gr.prefs().get_string('qtgui', 'style', 'raster') Qt.QApplication.setGraphicsSystem(style) qapp = Qt.QApplication(sys.argv) tb = top_block_cls() tb.start() tb.show() def quitting(): tb.stop() tb.wait() qapp.connect(qapp, Qt.SIGNAL("aboutToQuit()"), quitting) qapp.exec_()
def main(): from gnuradio import gr parser = argparse.ArgumentParser( description=VERSION_AND_DISCLAIMER_TEMPLATE % gr.version()) parser.add_argument('flow_graphs', nargs='*') parser.add_argument('--log', choices=['debug', 'info', 'warning', 'error', 'critical'], default='warning') args = parser.parse_args() # Enable logging # Note: All other modules need to use the 'grc.<module>' convention log = logging.getLogger('grc') log.setLevel(logging.DEBUG) # Console formatting console = logging.StreamHandler() console.setLevel(LOG_LEVELS[args.log]) #msg_format = '[%(asctime)s - %(levelname)8s] --- %(message)s (%(filename)s:%(lineno)s)' msg_format = '[%(levelname)s] %(message)s (%(filename)s:%(lineno)s)' date_format = '%I:%M' formatter = logging.Formatter(msg_format, datefmt=date_format) #formatter = utils.log.ConsoleFormatter() console.setFormatter(formatter) log.addHandler(console) py_version = sys.version.split()[0] log.debug("Starting GNU Radio Companion ({})".format(py_version)) # Delay importing until the logging is setup from .gui.Platform import Platform from .gui.Application import Application log.debug("Loading platform") platform = Platform( version=gr.version(), version_parts=(gr.major_version(), gr.api_version(), gr.minor_version()), prefs=gr.prefs(), install_prefix=gr.prefix() ) platform.build_library() log.debug("Loading application") app = Application(args.flow_graphs, platform) log.debug("Running") sys.exit(app.run())
def main(top_block_cls=RX_2017, options=None): if gr.enable_realtime_scheduling() != gr.RT_OK: print "Error: failed to enable real-time scheduling." from distutils.version import StrictVersion if StrictVersion(Qt.qVersion()) >= StrictVersion("4.5.0"): style = gr.prefs().get_string('qtgui', 'style', 'raster') Qt.QApplication.setGraphicsSystem(style) qapp = Qt.QApplication(sys.argv) tb = top_block_cls() tb.start() tb.show() def quitting(): tb.stop() tb.wait() qapp.connect(qapp, Qt.SIGNAL("aboutToQuit()"), quitting) qapp.exec_()
def main(top_block_cls=upsat_transceiver_qt, options=None): if options is None: options, _ = argument_parser().parse_args() from distutils.version import StrictVersion if StrictVersion(Qt.qVersion()) >= StrictVersion("4.5.0"): style = gr.prefs().get_string('qtgui', 'style', 'raster') Qt.QApplication.setGraphicsSystem(style) qapp = Qt.QApplication(sys.argv) tb = top_block_cls(bind_addr=options.bind_addr, dest_addr=options.dest_addr, lo_offset=options.lo_offset, recv_port=options.recv_port, rx_sdr_device=options.rx_sdr_device, send_port=options.send_port, tx_sdr_device=options.tx_sdr_device, wod_port=options.wod_port) tb.start() tb.show() def quitting(): tb.stop() tb.wait() qapp.connect(qapp, Qt.SIGNAL("aboutToQuit()"), quitting) qapp.exec_()
def main(): parser = optparse.OptionParser( usage='usage: %prog [options] [saved flow graphs]', version=VERSION_AND_DISCLAIMER_TEMPLATE % gr.version()) options, args = parser.parse_args() try: gtk.window_set_default_icon(gtk.IconTheme().load_icon('gnuradio-grc', 256, 0)) except: pass platform = Platform( prefs_file=gr.prefs(), version=gr.version(), version_parts=(gr.major_version(), gr.api_version(), gr.minor_version()), install_prefix=gr.prefix() ) ActionHandler(args, platform) gtk.main()
def __init__ (): p = gr.prefs() # get preferences (config file) object verbose = p.get_bool('audio', 'verbose', False) module = p.get_string('audio', 'audio_module', 'auto') if module == 'auto': # search our list for the first one that we can import for m in known_modules: if try_import(m): if verbose: sys.stderr.write('audio: using %s\n' % (m,)) return raise ImportError, 'Unable to locate an audio module.' else: # use the one the user specified if try_import(module): if verbose: sys.stderr.write('audio: using %s\n' % (module,)) else: msg = 'Failed to import user-specified audio module %s' % (module,) if verbose: sys.stderr.write('audio: %s\n' % (msg,)) raise ImportError, msg
def main(top_block_cls=top_block, options=None): if options is None: options, _ = argument_parser().parse_args() from distutils.version import StrictVersion if StrictVersion(Qt.qVersion()) >= StrictVersion("4.5.0"): style = gr.prefs().get_string('qtgui', 'style', 'raster') Qt.QApplication.setGraphicsSystem(style) qapp = Qt.QApplication(sys.argv) tb = top_block_cls(large_sig_len=options.large_sig_len, signal_mult=options.signal_mult, freq=options.freq) tb.start() tb.show() def quitting(): tb.stop() tb.wait() qapp.connect(qapp, Qt.SIGNAL("aboutToQuit()"), quitting) qapp.exec_()
def main(top_block_cls=bladeRF_loopback, options=None): if options is None: options, _ = argument_parser().parse_args() from distutils.version import StrictVersion if StrictVersion(Qt.qVersion()) >= StrictVersion("4.5.0"): style = gr.prefs().get_string('qtgui', 'style', 'raster') Qt.QApplication.setGraphicsSystem(style) qapp = Qt.QApplication(sys.argv) tb = top_block_cls(instance=options.instance, loopback=options.loopback, rx_bandwidth=options.rx_bandwidth, rx_frequency=options.rx_frequency, rx_lna_gain=options.rx_lna_gain, rx_num_buffers=options.rx_num_buffers, rx_num_xfers=options.rx_num_xfers, rx_sample_rate=options.rx_sample_rate, rx_vga_gain=options.rx_vga_gain, serial=options.serial, tx_bandwidth=options.tx_bandwidth, tx_frequency=options.tx_frequency, tx_num_buffers=options.tx_num_buffers, tx_num_xfers=options.tx_num_xfers, tx_sample_rate=options.tx_sample_rate, tx_vga1=options.tx_vga1, tx_vga2=options.tx_vga2, verbosity=options.verbosity) tb.start() tb.show() def quitting(): tb.stop() tb.wait() qapp.connect(qapp, Qt.SIGNAL("aboutToQuit()"), quitting) qapp.exec_()
def main(top_block_cls=inets_transceiver_test_client, options=None): from distutils.version import StrictVersion if StrictVersion(Qt.qVersion()) >= StrictVersion("4.5.0"): style = gr.prefs().get_string('qtgui', 'style', 'raster') Qt.QApplication.setGraphicsSystem(style) qapp = Qt.QApplication(sys.argv) tb = top_block_cls() tb.start() rssi_probe = rssi_test(tb) rssi_thread = threading.Thread(target=rssi_probe.run_test) rssi_thread.start() tb.show() def quitting(): tb.stop() tb.wait() qapp.connect(qapp, Qt.SIGNAL("aboutToQuit()"), quitting) qapp.exec_()
def main(top_block_cls=top_block, options=None): if options is None: options, _ = argument_parser().parse_args() if gr.enable_realtime_scheduling() != gr.RT_OK: print "Error: failed to enable real-time scheduling." from distutils.version import StrictVersion if StrictVersion(Qt.qVersion()) >= StrictVersion("4.5.0"): style = gr.prefs().get_string('qtgui', 'style', 'raster') Qt.QApplication.setGraphicsSystem(style) qapp = Qt.QApplication(sys.argv) tb = top_block_cls(MCS=options.MCS, N_CCE=options.N_CCE, N_dl_prb=options.N_dl_prb, RB_start_UE_1=options.RB_start_UE_1, RB_start_UE_2=options.RB_start_UE_2, aggregation1=options.aggregation1, aggregation2=options.aggregation2, allocation_len_UE_1=options.allocation_len_UE_1, allocation_len_UE_2=options.allocation_len_UE_2, cfi_val=options.cfi_val, n_pdcch=options.n_pdcch) tb.start() tb.show() def quitting(): tb.stop() tb.wait() qapp.connect(qapp, Qt.SIGNAL("aboutToQuit()"), quitting) qapp.exec_()
def get_parser(): """Init the option parser.""" parser = ArgumentParser( description='Manipulate with GNU Radio modules source code tree. ' + \ 'Call it withou options to run specified command interactively', formatter_class=RawDescriptionHelpFormatter) parser.add_argument("-d", "--directory", default=".", help="Base directory of the module. Defaults to the cwd.") parser.add_argument("--skip-lib", action="store_true", help="Don't do anything in the lib/ subdirectory.") parser.add_argument("--skip-swig", action="store_true", help="Don't do anything in the swig/ subdirectory.") parser.add_argument("--skip-python", action="store_true", help="Don't do anything in the python/ subdirectory.") parser.add_argument("--skip-grc", action="store_true", help="Don't do anything in the grc/ subdirectory.") parser.add_argument("--scm-mode", choices=('yes', 'no', 'auto'), default=gr.prefs().get_string('modtool', 'scm_mode', 'no'), help="Use source control management [ yes | no | auto ]).") parser.add_argument("-y", "--yes", action="store_true", help="Answer all questions with 'yes'. This can overwrite and delete your files, so be careful.") return parser
def common_params(func): """ Common parameters for various modules""" @click.option('-d', '--directory', default='.', help="Base directory of the module. Defaults to the cwd.") @click.option('--skip-lib', is_flag=True, help="Don't do anything in the lib/ subdirectory.") @click.option('--skip-swig', is_flag=True, help="Don't do anything in the swig/ subdirectory.") @click.option('--skip-python', is_flag=True, help="Don't do anything in the python/ subdirectory.") @click.option('--skip-grc', is_flag=True, help="Don't do anything in the grc/ subdirectory.") @click.option('--scm-mode', type=click.Choice(['yes', 'no', 'auto']), default=gr.prefs().get_string('modtool', 'scm_mode', 'no'), help="Use source control management [ yes | no | auto ]).") @click.option('-y', '--yes', is_flag=True, help="Answer all questions with 'yes'. " + "This can overwrite and delete your files, so be careful.") @functools.wraps(func) def wrapper(*args, **kwargs): """ Decorator that wraps common options """ return func(*args, **kwargs) return wrapper
def cli(**kwargs): """ \b Create a new out-of-tree module The argument MODULE-NAME is the name of the module to be added. """ kwargs['cli'] = True self = ModToolNewModule(**kwargs) get_modname(self) self.dir = os.path.join(self.dir, 'gr-{}'.format(self.info['modname'])) try: os.stat(self.dir) except OSError: pass # This is what should happen else: raise ModToolException('The given directory exists.') if self.srcdir is None: self.srcdir = '/usr/local/share/gnuradio/modtool/templates/gr-newmod' self.srcdir = gr.prefs().get_string('modtool', 'newmod_path', self.srcdir) if not os.path.isdir(self.srcdir): raise ModToolException('Could not find gr-newmod source dir.') run(self)
import plotter import common import wx import numpy import math import pubsub from constants import * from gnuradio import gr #for gr.prefs import forms ################################################## # Constants ################################################## SLIDER_STEPS = 100 AVG_ALPHA_MIN_EXP, AVG_ALPHA_MAX_EXP = -3, 0 DEFAULT_FRAME_RATE = gr.prefs().get_long('wxgui', 'waterfall_rate', 30) DEFAULT_COLOR_MODE = gr.prefs().get_string('wxgui', 'waterfall_color', 'rgb1') DEFAULT_WIN_SIZE = (600, 300) DIV_LEVELS = (1, 2, 5, 10, 20) MIN_DYNAMIC_RANGE, MAX_DYNAMIC_RANGE = 10, 200 DYNAMIC_RANGE_STEP = 10. COLOR_MODES = ( ('RGB1', 'rgb1'), ('RGB2', 'rgb2'), ('RGB3', 'rgb3'), ('Gray', 'gray'), ) ################################################## # Waterfall window control panel
def main(): mods = modulation_utils.type_1_mods() demods = modulation_utils.type_1_demods() parser = OptionParser (option_class=eng_option, conflict_handler="resolve") expert_grp = parser.add_option_group("Expert") expert_grp.add_option("", "--rx-freq", type="eng_float", default=None, help="set Rx frequency to FREQ [default=%default]", metavar="FREQ") expert_grp.add_option("", "--tx-freq", type="eng_float", default=None, help="set transmit frequency to FREQ [default=%default]", metavar="FREQ") parser.add_option("-m", "--modulation", type="choice", choices=mods.keys(), default='gmsk', help="Select modulation from: %s [default=%%default]" % (', '.join(mods.keys()),)) parser.add_option("-b","--bssid", default="00:00:00:00:00:00", help="set bssid for network in the form xx:xx:xx:xx:xx:xx") #ZLM copy form chenlong parser.add_option("-v","--verbose", action="store_true", default=False) expert_grp.add_option("-c", "--carrier-threshold", type="eng_float", default=30, help="set carrier detect threshold (dB) [default=%default]") parser.add_option("","--tun", action="store_true", default=False, help="use tun device instead of tap to pass packets.") #ZLM copy form chenlong expert_grp.add_option("","--tun-device-filename", default="/dev/net/tun", help="path to tun device file [default=%default]") usrp_transmit_path.add_options(parser, expert_grp) usrp_receive_path.add_options(parser, expert_grp) for mod in mods.values(): mod.add_options(expert_grp) for demod in demods.values(): demod.add_options(expert_grp) (options, args) = parser.parse_args () if len(args) != 0: parser.print_help(sys.stderr) sys.exit(1) bssid = validate_mac_addr(options.bssid) if bssid == 0: print "Invalid BSSID ", options.bssid parser.print_help() sys.exit(1) mod_kwargs = { 'bt' : options.bt, } pkttype = 'eth' tuntype = 'tap' mcache = None if options.tun: pkttype = 'ip' tuntype = 'tun' # open the TUN/TAP interface (tun_fd, tun_ifname) = open_tun_interface(tuntype, options.tun_device_filename) tun_mac = get_mac_for_interface(tun_ifname) mac_addr = validate_mac_addr(tun_mac) if mac_addr == 0: print "Invalid MAC address ", tun_mac, " for interface ", tun_ifname print "exiting." sys.exit(1) if options.verbose: print "Using MAC address ", tun_mac, " for interface ", tun_ifname # Attempt to enable realtime scheduling r = gr.enable_realtime_scheduling() if r == gr.RT_OK: realtime = True else: realtime = False print "Note: failed to enable realtime scheduling" # If the user hasn't set the fusb_* parameters on the command line, # pick some values that will reduce latency. if options.fusb_block_size == 0 and options.fusb_nblocks == 0: if realtime: # be more aggressive options.fusb_block_size = gr.prefs().get_long('fusb', 'rt_block_size', 1024) options.fusb_nblocks = gr.prefs().get_long('fusb', 'rt_nblocks', 16) else: options.fusb_block_size = gr.prefs().get_long('fusb', 'block_size', 4096) options.fusb_nblocks = gr.prefs().get_long('fusb', 'nblocks', 16) #print "fusb_block_size =", options.fusb_block_size #print "fusb_nblocks =", options.fusb_nblocks numchan = 3 # instantiate the MACi DC = [2.810e9,] for i in range(numchan): DC += [DC[i] + 0.002 * 10**9] #gen channel QCH = makeQCH.makeQCH(numchan)[1] #gen QCH number # QCH = [1,1,1,1,1,1,1,1,1] mac = cs_mac(tun_fd, mac_addr, pkttype, bssid, mcache, DC, QCH, verbose=True) # build the graph (PHY) fg = my_graph(mods[options.modulation],demods[options.modulation], mac.phy_rx_callback, options) mac.set_flow_graph(fg) # give the MAC a handle for the PHY if fg.txpath.bitrate() != fg.rxpath.bitrate(): print "WARNING: Transmit bitrate = %sb/sec, Receive bitrate = %sb/sec" % ( eng_notation.num_to_str(fg.txpath.bitrate()), eng_notation.num_to_str(fg.rxpath.bitrate())) print "modulation: %s" % (options.modulation,) print "freq: %s" % (eng_notation.num_to_str(options.tx_freq)) print "bitrate: %sb/sec" % (eng_notation.num_to_str(fg.txpath.bitrate()),) print "samples/symbol: %3d" % (fg.txpath.samples_per_symbol(),) #print "interp: %3d" % (tb.txpath.interp(),) #print "decim: %3d" % (tb.rxpath.decim(),) fg.rxpath.set_carrier_threshold(options.carrier_threshold) print "Carrier sense threshold:", options.carrier_threshold, "dB" print print "Allocated virtual ethernet interface: %s" % (tun_ifname,) print "You must now use ifconfig to set its IP address. E.g.," print print " $ sudo ifconfig %s 192.168.200.1" % (tun_ifname,) print print "Be sure to use a different address in the same subnet for each machine." print fg.start() # Start executing the flow graph (runs in separate threads) f1 = open('reservation_time.txt','w') f2 = open('reservation_slot.txt','w') f3 = open('Qlearn.txt','w') f4 = open('channel.txt','w') # mac.main_loop(f1,f2,f3) mac.main_loop(f1,f2,f3,f4) # don't expect this to return... f1.close() f2.close() f3.close() fg.stop() # but if it does, tell flow graph to stop. fg.wait() # wait for it to finish
# Boston, MA 02110-1301, USA. # from gnuradio import gr, gru, eng_notation from gnuradio import analog from gnuradio import blocks from gnuradio import wxgui from gnuradio.wxgui import stdgui2 import wx import gnuradio.wxgui.plot as plot import numpy import struct default_scopesink_size = (640, 240) default_v_scale = 1000 default_frame_decim = gr.prefs().get_long('wxgui', 'frame_decim', 1) class scope_sink_f(gr.hier_block2): def __init__(self, parent, title='', sample_rate=1, size=default_scopesink_size, frame_decim=default_frame_decim, v_scale=default_v_scale, t_scale=None, num_inputs=1, **kwargs): gr.hier_block2.__init__(
def main(top_block_cls=Ether_Gnu_Radio_Companion, options=None): if gr.enable_realtime_scheduling() != gr.RT_OK: print("Error: failed to enable real-time scheduling.") if StrictVersion("4.5.0") <= StrictVersion( Qt.qVersion()) < StrictVersion("5.0.0"): style = gr.prefs().get_string('qtgui', 'style', 'raster') Qt.QApplication.setGraphicsSystem(style) qapp = Qt.QApplication(sys.argv) tb = self = top_block_cls() #tb.eventFilter = eventFilter # Import des bookmarks -------------------------- class CSV(csv.DictReader): def __init__(self, path): csvfile = self.inFile = open(path, "r", encoding="utf-8") delimiter = ";" # csv.Sniffer().sniff(csvfile.readline(), delimiters=";,\t").delimiter start = csvfile.read().find("# Frequency") + 2 csvfile.seek(start) #print("dected delimiter : ",repr(delimiter)) csv.DictReader.__init__(self, csvfile, delimiter=delimiter) def close(self): self.inFile.close() inCsv = CSV("bookmarks.csv") dictsList = [] #labels = [""] #options = [0] frequences_labels = [] for row in inCsv: rowDict = dict() for key, value in row.items(): if value: key = key.strip() value = value.strip() if key in ('Frequency', 'Bandwidth'): value = int(value) rowDict[key] = value #print(rowDict['Tags']) if rowDict['Tags'] == 'ether' and rowDict['Modulation'].startswith( 'WFM'): frequences_labels.append( (rowDict['Frequency'], rowDict["Name"] + " - " + str(rowDict['Frequency'] / 1e6) + " MHz")) options, labels = zip(*sorted(frequences_labels)) self._radio_frequency_center_menu_labels = labels self._radio_frequency_center_menu_options = options for _label in self._radio_frequency_center_menu_labels: self._radio_frequency_center_menu_combo_box.addItem(_label) # Scann Automatique des frequences --------------- #time_between_frequencies = 10 #time_stop_on_frequency = 10 update_frequency = 10 # v1 (avec thread, marche mal )------------------- if False: #self._radio_frequency_center_menu_combo_box.setCurrentIndex(1) step_float = 2000 / (self.time_between_frequencies * update_frequency) def _radio_frequency_delta_probe(): value = 0 while True: if self.get_radio_scann(): if int( value ) != self._radio_frequency__delta_MHz_win.d_widget.value(): value = self._radio_frequency__delta_MHz_win.d_widget.value( ) if (value <= 1000) and ((value + step_float) >= 1000): print(value) time.sleep(self.time_stop_on_frequency) value += step_float value += step_float if value >= 2000: self._radio_frequency_center_menu_combo_box.setCurrentIndex( self._radio_frequency_center_menu_combo_box. currentIndex() + 1) value = 0 self._radio_frequency__delta_MHz_win.d_widget.setValue( int(value)) time.sleep(1.0 / update_frequency) _radio_frequency_delta_thread = threading.Thread( target=_radio_frequency_delta_probe) _radio_frequency_delta_thread.daemon = True _radio_frequency_delta_thread.start() # v2 (avec QTimer)------------------- if True: self.between_frequencies_position = 0 def _radio_scann_tick(): if self.get_radio_scann(): self.timer.setInterval(int(1000 / update_frequency)) current_index = self._radio_frequency_center_menu_combo_box.currentIndex( ) next_index = current_index + 1 if next_index >= self._radio_frequency_center_menu_combo_box.count( ): next_index = 0 self._radio_frequency_center_menu_combo_box.setCurrentIndex( next_index) self.between_frequencies_position = 0 self.epy_block_0_1_0.set_mode(STATIC) radio_frequency = self._radio_frequency_center_menu_options[ next_index] self.set_radio_frequency_center(radio_frequency) self.timer.setInterval( int(self.time_stop_on_frequency * 1000)) else: radio_frequency_1 = self._radio_frequency_center_menu_options[ current_index] radio_frequency_2 = self._radio_frequency_center_menu_options[ next_index] radio_frequency = radio_frequency_1 + ( radio_frequency_2 - radio_frequency_1) * self.between_frequencies_position self.set_radio_frequency_center(radio_frequency) self.between_frequencies_position += 1 / ( self.time_between_frequencies * update_frequency) if self.between_frequencies_position >= 1: self._radio_frequency_center_menu_combo_box.setCurrentIndex( next_index) self.between_frequencies_position = 0 self.epy_block_0_1_0.set_mode(STATIC) self.timer.setInterval( int(self.time_stop_on_frequency * 1000)) else: self.epy_block_0_1_0.set_mode(SCANNING) self.timer = Qt.QTimer(parent=qapp) self.timer.setInterval(int(1000 / update_frequency)) self.timer.timeout.connect(_radio_scann_tick) self.epy_block_0_1_0.set_mode(SCANNING) self.timer.start() tb.start() tb.show() tb.showFullScreen() def sig_handler(sig=None, frame=None): Qt.QApplication.quit() signal.signal(signal.SIGINT, sig_handler) signal.signal(signal.SIGTERM, sig_handler) timer = Qt.QTimer() timer.start(500) timer.timeout.connect(lambda: None) def quitting(): tb.stop() tb.wait() qapp.aboutToQuit.connect(quitting) qapp.exec_()
from gnuradio import gr, gru, fft import gnuradio.filter as grfilter from gnuradio import blocks from gnuradio import analog from gnuradio.wxgui import stdgui2 from gnuradio.filter import window import wx import plot import numpy import math DIV_LEVELS = (1, 2, 5, 10, 20) default_fftsink_size = (640, 240) default_fft_rate = gr.prefs().get_long('wxgui', 'fft_rate', 15) class fft_sink_base(object): def __init__(self, input_is_real=False, baseband_freq=0, y_per_div=10, y_divs=8, ref_level=50, sample_rate=1, fft_size=512, fft_rate=default_fft_rate, average=False, avg_alpha=None, title='',
def main(top_block_cls=ofdm_multichannel_receiver, options=None): global n_rcvd, n_right, printout n_rcvd = 0 n_right = 0 printout = False def rx_callback(ok, payload): global n_rcvd, n_right n_rcvd += 1 (pktno, ) = struct.unpack('!H', payload[0:2]) if ok: n_right += 1 if printout: print "ok: %r \t pktno: %d \t n_rcvd: %d \t n_right: %d" % ( ok, pktno, n_rcvd, n_right) if 0: printlst = list() for x in payload[2:]: t = hex(ord(x)).replace('0x', '') if (len(t) == 1): t = '0' + t printlst.append(t) printable = ''.join(printlst) if printout: print printable print "\n" ################################################ # SETUP options # {'from_file': None, 'verbose': False, 'antenna': None, 'discontinuous': False, # 'args': 'addr=192.168.20.2', 'tx_freq': 900000000.0, 'fft_length': 512, # 'modulation': 'bpsk', 'bandwidth': 500000.0, 'snr': 30.0, 'log': False, # 'clock_source': None, 'lo_offset': 0, 'occupied_tones': 200, # 'cp_length': 128, 'freq': None, 'rx_freq': 900000000.0, 'spec': None, 'rx_gain': None} # options['from_file'] = None # options.verbose = False # options.antenna = None # options.discontinuous = False # options.args = 'addr=192.168.20.2' # options.tx_freq = 900000000 # options.fft_length = 512 # options.modulation = 'bpsk' # options.bandwidth = 500000 # options.snr = 30 # options.log = False # options.clock_source = None # options.lo_offset = 0 # options.occupied_tones = 200 # options.cp_length = 128 # options.freq = None # options.rx_freq = 900000000 # options.spec = None # options.rx_gain = None parser = OptionParser(option_class=eng_option, conflict_handler="resolve") expert_grp = parser.add_option_group("Expert") parser.add_option("", "--discontinuous", action="store_true", default=False, help="enable discontinuous") parser.add_option("", "--from-file", default=None, help="input file of samples to demod") receive_path.add_options(parser, expert_grp) uhd_receiver.add_options(parser) digital.ofdm_demod.add_options(parser, expert_grp) (options, args) = parser.parse_args() if options.from_file is None: if options.rx_freq is None: options.rx_freq = 900000000 ################################################ if gr.enable_realtime_scheduling() != gr.RT_OK: print "Error: failed to enable real-time scheduling." from distutils.version import StrictVersion if StrictVersion(Qt.qVersion()) >= StrictVersion("4.5.0"): style = gr.prefs().get_string('qtgui', 'style', 'raster') Qt.QApplication.setGraphicsSystem(style) qapp = Qt.QApplication(sys.argv) tb = top_block_cls(rx_callback, options) tb.start() tb.show() def quitting(): tb.stop() tb.wait() qapp.connect(qapp, Qt.SIGNAL("aboutToQuit()"), quitting) qapp.exec_()
import common import wx import numpy import math import pubsub from constants import * from gnuradio import gr #for gr.prefs import forms ################################################## # Constants ################################################## SLIDER_STEPS = 200 ALPHA_MIN_EXP, ALPHA_MAX_EXP = -6, -0.301 GAIN_MU_MIN_EXP, GAIN_MU_MAX_EXP = -6, -0.301 DEFAULT_FRAME_RATE = gr.prefs().get_long('wxgui', 'const_rate', 5) DEFAULT_WIN_SIZE = (500, 400) DEFAULT_CONST_SIZE = gr.prefs().get_long('wxgui', 'const_size', 2048) CONST_PLOT_COLOR_SPEC = (0, 0, 1) MARKER_TYPES = ( ('Dot Small', 1.0), ('Dot Medium', 2.0), ('Dot Large', 3.0), ('Line Link', None), ) DEFAULT_MARKER_TYPE = 2.0 ################################################## # Constellation window control panel ##################################################
def __init__(self, host=None, port=None): from gnuradio.ctrlport.GNURadio import ttypes self.BaseTypes = ttypes.BaseTypes self.KnobBase = ttypes.KnobBase # If not set by the user, get the port number from the thrift # config file, if one is set. Defaults to 9090 otherwise. if port is None: p = gr.prefs() thrift_config_file = p.get_string("ControlPort", "config", "") if (len(thrift_config_file) > 0): p.add_config_file(thrift_config_file) port = p.get_long("thrift", "port", 9090) else: port = 9090 else: port = int(port) super(RPCConnectionThrift, self).__init__(method='thrift', port=port, host=host) self.newConnection(host, port) self.unpack_dict = { self.BaseTypes.BOOL: lambda k, b: self.Knob(k, b.value.a_bool, self.BaseTypes.BOOL), self.BaseTypes.BYTE: lambda k, b: self.Knob(k, b.value.a_byte, self.BaseTypes.BYTE), self.BaseTypes.SHORT: lambda k, b: self.Knob(k, b.value.a_short, self.BaseTypes.SHORT), self.BaseTypes.INT: lambda k, b: self.Knob(k, b.value.a_int, self.BaseTypes.INT), self.BaseTypes.LONG: lambda k, b: self.Knob(k, b.value.a_long, self.BaseTypes.LONG), self.BaseTypes.DOUBLE: lambda k, b: self.Knob(k, b.value.a_double, self.BaseTypes.DOUBLE), self.BaseTypes.STRING: lambda k, b: self.Knob(k, b.value.a_string, self.BaseTypes.STRING), self.BaseTypes.COMPLEX: lambda k, b: self.Knob(k, b.value.a_complex, self.BaseTypes.COMPLEX ), self.BaseTypes.F32VECTOR: lambda k, b: self.Knob(k, b.value.a_f32vector, self.BaseTypes. F32VECTOR), self.BaseTypes.F64VECTOR: lambda k, b: self.Knob(k, b.value.a_f64vector, self.BaseTypes. F64VECTOR), self.BaseTypes.S64VECTOR: lambda k, b: self.Knob(k, b.value.a_s64vector, self.BaseTypes. S64VECTOR), self.BaseTypes.S32VECTOR: lambda k, b: self.Knob(k, b.value.a_s32vector, self.BaseTypes. S32VECTOR), self.BaseTypes.S16VECTOR: lambda k, b: self.Knob(k, b.value.a_s16vector, self.BaseTypes. S16VECTOR), self.BaseTypes.S8VECTOR: lambda k, b: self.Knob(k, b.value.a_s8vector, self.BaseTypes. S8VECTOR), self.BaseTypes.C32VECTOR: lambda k, b: self.Knob(k, b.value.a_c32vector, self.BaseTypes. C32VECTOR), } self.pack_dict = { self.BaseTypes.BOOL: lambda k: ttypes.Knob(type=k.ktype, value=ttypes.KnobBase(a_bool=k.value)), self.BaseTypes.BYTE: lambda k: ttypes.Knob(type=k.ktype, value=ttypes.KnobBase(a_byte=k.value)), self.BaseTypes.SHORT: lambda k: ttypes.Knob(type=k.ktype, value=ttypes.KnobBase(a_short=k.value)), self.BaseTypes.INT: lambda k: ttypes.Knob(type=k.ktype, value=ttypes.KnobBase(a_int=k.value)), self.BaseTypes.LONG: lambda k: ttypes.Knob(type=k.ktype, value=ttypes.KnobBase(a_long=k.value)), self.BaseTypes.DOUBLE: lambda k: ttypes.Knob(type=k.ktype, value=ttypes.KnobBase(a_double=k.value)), self.BaseTypes.STRING: lambda k: ttypes.Knob(type=k.ktype, value=ttypes.KnobBase(a_string=k.value)), self.BaseTypes.COMPLEX: lambda k: ttypes.Knob(type=k.ktype, value=ttypes.KnobBase(a_complex=k.value)), self.BaseTypes.F32VECTOR: lambda k: ttypes.Knob(type=k.ktype, value=ttypes.KnobBase(a_f32vector=k.value)), self.BaseTypes.F64VECTOR: lambda k: ttypes.Knob(type=k.ktype, value=ttypes.KnobBase(a_f64vector=k.value)), self.BaseTypes.S64VECTOR: lambda k: ttypes.Knob(type=k.ktype, value=ttypes.KnobBase(a_s64vector=k.value)), self.BaseTypes.S32VECTOR: lambda k: ttypes.Knob(type=k.ktype, value=ttypes.KnobBase(a_s32vector=k.value)), self.BaseTypes.S16VECTOR: lambda k: ttypes.Knob(type=k.ktype, value=ttypes.KnobBase(a_s16vector=k.value)), self.BaseTypes.S8VECTOR: lambda k: ttypes.Knob(type=k.ktype, value=ttypes.KnobBase(a_s8vector=k.value)), self.BaseTypes.C32VECTOR: lambda k: ttypes.Knob(type=k.ktype, value=ttypes.KnobBase(a_c32vector=k.value)), }
def main(top_block_cls=transceiver_OQPSK_Slave): if gr.enable_realtime_scheduling() != gr.RT_OK: print "Error: failed to enable real-time scheduling." from distutils.version import StrictVersion if StrictVersion(Qt.qVersion()) >= StrictVersion("4.5.0"): style = gr.prefs().get_string('qtgui', 'style', 'raster') Qt.QApplication.setGraphicsSystem(style) qapp = Qt.QApplication(sys.argv) global tb, usrp_addr, gotSync, frequencies, i, Lines #, tunName global word, port, p_listenSlave, subp_listenSlave, tun parser = OptionParser(option_class=eng_option, usage="%prog: [options]") parser.add_option("-u", "--usrp-addr", default="addr = 192.168.10.2", help="IP address of the USRP without \"addr=\"") parser.add_option("-f", "--init-freq", type="eng_float", default=174, help="initial frequency in MHz [default=%default]") parser.add_option( "-o", "--otw", default="sc16", help="select over the wire data format (sc16 or sc8) [default=%default]" ) parser.add_option( "-l", "--no-self-loop", action="store_false", default=True, help= "enable mechanism of avoiding self-routed packets [default=%default]") parser.add_option( "", "--source", type="choice", choices=['socket', 'tuntap', 'strobe'], default='tuntap', help="'tuntap' interface, 'socket' or 'strobe' [default=%default]") parser.add_option( "-y", "--bytes", type="eng_float", default=256, help= "Number of bytes to read/write from/to filedescriptors (for debug purpose) [default=%default]" ) parser.add_option( "-t", "--tunnel", action="store_true", default=False, help= "enable tunnel mode or send random data generated locally at slave node [default=%default]" ) parser.add_option( "-i", "--interval", type="eng_float", default=0.2, help= "interval in seconds between two packets being sent [default=%default]" ) parser.add_option( "-S", "--scan-interv", type="eng_float", default=2, help= "interval in sec between every scan for frequency to sync with the master node [default=%default]" ) parser.add_option( "-w", "--dwell", type="eng_float", default=2, help= "dwell time in each center frequency in the sync phase [default=%default]" ) parser.add_option( "-p", "--period-check", type="eng_float", default=1, help="interval in sec for period check of beacon [default=%default]") parser.add_option( "", "--slot", type="eng_float", default=60, help= "duration in sec of the slave given slot to communicate data [default=%default]" ) ## Debugging and Verbose options parser.add_option("", "--debug-MAC", action="store_true", default=False, help="Debugging the MAC Layer [default=%default]") parser.add_option("-W", "--wireshark", action="store_true", default=False, help="Enable Wireshark capture[default=%default]") parser.add_option("-v", "--verbose", action="store_true", default=False, help="verbose mode [default=%default]") parser.add_option("", "--no-usrp", action="store_true", default=False, help="Using file sink and source instead of USRPs") (options, args) = parser.parse_args() usrp_addr = "addr=" + options.usrp_addr word = "FFFFFFFF" port = "52004" i = 1 initialFreq = 1e6 * float(options.init_freq) CE_channels_indices = (36, 37, 38, 39, 40, 41, 42, 43, 44) TVWS_CE_channels = { x: TVWS_channelmap.Channels[x] for x in CE_channels_indices } #frequencies = [x * 1e6 for x in (TVWS_channelmap.Channels).values()] frequencies = [x * 1e6 for x in TVWS_CE_channels.values()] open('utils/listenSlave', 'w').close() tb = top_block_cls(options.usrp_addr, options.no_usrp, initialFreq, options.otw, options.source, options.no_self_loop, options.debug_MAC, options.wireshark) if not options.no_usrp: from gnuradio import uhd, digital print "\n Initial frequency: ", initialFreq / 1e6, "MHz" tb.set_samp_rate(4e6) tb.set_freq(initialFreq) subp_listenSlave = subprocess.Popen( "ncat -u -l -p 3333 > utils/listenSlave", shell=True) ### Frequency Sweep procedure ## threading.Timer(2, sync, [ options.no_usrp, options.tunnel, options.scan_interv, options.dwell, options.slot, options.period_check, options.interval ]).start() if (options.tunnel): parent_conn, child_conn = Pipe() tun = tunnel(tb.ieee802_15_4_mac_0, port, options.slot, child_conn.fileno(), options.interval, options.verbose) try: subprocess.call("""sudo tunctl -d tap1 -f /dev/net/tun sudo tunctl -t tap1 -u $USER -f /dev/net/tun sudo ip addr add 10.0.1.8/24 dev tap1 sudo ip link set tap1 up""", shell=True) except OSError as e: print >> sys.stderr, "Execution failed:", e tb.start() tb.show() def quitting(): tb.stop() tb.wait() qapp.connect(qapp, Qt.SIGNAL("aboutToQuit()"), quitting) qapp.exec_()
# # Originally created by Frank of radiorausch (http://sites.google.com/site/radiorausch/USRPFastAutocorrelation.html) # Upgraded for blks2 compatibility by Balint Seeber (http://wiki.spench.net/wiki/Fast_Auto-correlation) from gnuradio import gr, gru, window from gnuradio.wxgui import stdgui2, common import wx import gnuradio.wxgui.plot as plot #import Numeric import numpy import threading import math default_facsink_size = (640, 240) default_fac_rate = gr.prefs().get_long('wxgui', 'fac_rate', 10) # was 15, 3 class fac_sink_base(gr.hier_block2, common.wxgui_hb): def __init__(self, input_is_real=False, baseband_freq=0, y_per_div=10, ref_level=50, sample_rate=1, fac_size=512, fac_rate=default_fac_rate, average=False, avg_alpha=None, title='', peak_hold=False):
# GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # ################################################## # conditional disconnections of wx flow graph ################################################## import wx from gnuradio import gr from gnuradio import blocks RUN_ALWAYS = gr.prefs().get_bool('wxgui', 'run_always', False) class wxgui_hb(object): """ The wxgui hier block helper/wrapper class: A hier block should inherit from this class to make use of the wxgui connect method. To use, call wxgui_connect in place of regular connect; self.win must be defined. The implementation will conditionally enable the copy block after the source (self). This condition depends on weather or not the window is visible with the parent notebooks. This condition will be re-checked on every ui update event. """ def wxgui_connect(self, *points): """ Use wxgui connect when the first point is the self source of the hb. The win property of this object should be set to the wx window.
def __init__(self, fmt, item_size, channels, is_complex, sample_rate, aggregate_channel_count=1, flip_complex=False, baseband_freq=None, decimation=1, scale=1.0, overlap=None, slide_size=None, fft_size=None, jump_step=None, x_slip=None, mode='pipe', buffered=True, kill_on_del=True, memory=None, peak_hold=False, **kwds): gr.hier_block2.__init__(self, "baudline_sink", gr.io_signature(1, 1, item_size), gr.io_signature(0, 0, 0)) baudline_path = gr.prefs().get_string('baudline', 'path', 'baudline') #tf = tempfile.NamedTemporaryFile(delete=False) #tf.write(gp) #tf.close() #print tf.name self.mode = mode self.kill_on_del = kill_on_del if mode == 'fifo': fifo_name = 'baudline_fifo' self.tmpdir = tempfile.mkdtemp() self.filename = os.path.join(self.tmpdir, fifo_name) print(self.filename) try: os.mkfifo(self.filename) except OSError as e: print("Failed to create FIFO: %s" % e) raise baudline_exec = [ baudline_path, "-stdin", "-record", "-spacebar", "recordpause", "-samplerate", str(int(sample_rate)), "-channels", str(channels * aggregate_channel_count), "-format", fmt, #"-backingstore", # # #"-threads", #"-pipeline", #"-memory", # MB #"-verticalsync" #"-realtime", #"-psd" #"-reversetimeaxis", #"-overclock", #"-debug", #"-debugtimer", str(1000) #"-debugfragments", #"-debugcadence", #"-debugjitter", #"-debugrate", #"-debugmeasure ] if is_complex: baudline_exec += ["-quadrature"] if flip_complex: baudline_exec += ["-flipcomplex"] if baseband_freq is not None and baseband_freq > 0: baudline_exec += ["-basefrequency", str(baseband_freq)] if decimation > 1: baudline_exec += ["-decimateby", str(decimation)] if scale != 1.0: baudline_exec += ["-scaleby", str(scale)] if overlap is not None and overlap > 0: baudline_exec += ["-overlap", str(overlap)] #"-slidesize" if slide_size is not None and slide_size > 0: baudline_exec += ["-slidesize", str(slide_size)] if fft_size is not None and fft_size > 0: baudline_exec += ["-fftsize", str(fft_size)] if jump_step is not None and jump_step > 0: baudline_exec += ["-jumpstep", str(jump_step)] if x_slip is not None and x_slip > 0: baudline_exec += ["-xslip", str(x_slip)] if memory is not None and memory > 0: baudline_exec += ["-memory", str(memory)] if peak_hold: baudline_exec += ["-peakhold"] for k in kwds.keys(): arg = str(k).strip() if arg[0] != '-': arg = "-" + arg baudline_exec += [arg] val = kwds[k] if val is not None: val = str(val).strip() if val.find(' ') > -1 and len(val) > 1: if val[0] != '\"': val = "\"" + val if val[-1] != '\"': val += "\"" baudline_exec += [val] if mode == 'fifo': baudline_exec += ["<", self.filename] #baudline_exec = ["cat", self.filename, "|"] + baudline_exec baudline_exec = [" ".join(baudline_exec)] self.p = None #res = 0 try: #res = subprocess.call(gp_exec) print(baudline_exec) if mode == 'pipe': self.p = subprocess.Popen( baudline_exec, stdin=subprocess.PIPE ) # , stdout=subprocess.PIPE, stderr=subprocess.PIPE, bufsize=16384 or -1 elif mode == 'fifo': self.p = subprocess.Popen(baudline_exec, shell=True) #self.p.communicate(input=) #self.p.stdin.write() #self.p.wait() #except KeyboardInterrupt: # print "Caught CTRL+C" except Exception as e: print(e) raise #if self.p is not None and not self.p.returncode == 0: # print "Failed to run subprocess (result: %d)" % (self.p.returncode) #if res != 0: # print "Failed to run subprocess (result: %d)" % (res) if mode == 'pipe': print("==> Using FD:", self.p.stdin.fileno()) self.file_sink = blocks.file_descriptor_sink( item_size, self.p.stdin.fileno()) # os.dup elif mode == 'fifo': self.file_sink = blocks.file_sink(item_size, self.filename) # os.dup self.file_sink.set_unbuffered( not buffered) # Flowgraph won't die if baudline exits self.connect(self, self.file_sink)
from gnuradio import gr, gru, fft import gnuradio.filter as grfilter from gnuradio import blocks from gnuradio import analog from gnuradio.wxgui import stdgui2 from gnuradio.filter import window import wx import plot import numpy import math DIV_LEVELS = (1, 2, 5, 10, 20) default_fftsink_size = (640,240) default_fft_rate = gr.prefs().get_long('wxgui', 'fft_rate', 15) class fft_sink_base(object): def __init__(self, input_is_real=False, baseband_freq=0, y_per_div=10, y_divs=8, ref_level=50, sample_rate=1, fft_size=512, fft_rate=default_fft_rate, average=False, avg_alpha=None, title='', peak_hold=False, use_persistence=False, persist_alpha=0.2): # initialize common attributes self.baseband_freq = baseband_freq self.y_per_div=y_per_div self.y_divs = y_divs self.ref_level = ref_level self.sample_rate = sample_rate
def main(top_block_cls=top_block, options=None): from distutils.version import StrictVersion if StrictVersion(Qt.qVersion()) >= StrictVersion("4.5.0"): style = gr.prefs().get_string('qtgui', 'style', 'raster') Qt.QApplication.setGraphicsSystem(style) qapp = Qt.QApplication(sys.argv) ######## ACTUALLY WHERE STUFF HAPPENS ####### tb = top_block_cls() tb.start() tb.show() print('Receiving ...') global darksky global darksky_exists def snapshot( int_time): #straight snapshot over a certain integration time. tb.set_integration_time(int_time) # print 'Integration time set to '+str(int_time)+ ' seconds.' print 'Snapshot ' + str(int_time) + ' sec' vec = tb.get_variable_function_probe() #old vector pointa = vec[0] pointb = vec[-1] tb.toggle_copy(True) #start copying while vec[0] == pointa and vec[-1] == pointb: pytime.sleep(1) vec = tb.get_variable_function_probe() tb.toggle_copy(False) #stop copying return np.array(vec) def dark_sky_calib(int_time): #for use when pointing at the dark sky global darksky darksky = snapshot(int_time) global darksky_exists darksky_exists = True return def observe(int_time): #dark sky calbrated snapshot vec = snapshot(int_time) wait(int_time) global darksky_exists if darksky_exists: calib = vec - darksky return calib else: print('Warning: No dark sky calibration has been performed.') return vec def wait(sec): pytime.sleep(sec) return def graphing(int_time, iter=float('inf')): plt.ion() plt.figure() vec = tb.get_variable_function_probe() #vector n = len(vec) x = np.linspace(flo, fhi, n) i = 0 while (i < iter): plt.pause(int_time) y = observe(int_time) plt.clf() plt.xlabel('Frequency (MHz)') plt.ylabel('Scaled power') plt.axvline(x=1420.406, color='black', ls='--') plt.ticklabel_format(useOffset=False) plt.plot(x, y) plt.draw() i += 1 return () def track(N): client.track(N) #runs in background #usr/bin/python from galcoord import gal_to_altaz import matplotlib as mpl mpl.use('Agg') import matplotlib.pyplot as plt from galcoord import get_time from math import sin gain = 60 tb.set_sdr_gain(gain) freq = tb.get_sdr_frequency() / 1000000 #MHz freq_offset = tb.get_output_vector_bandwidth() / 2000000. #MHz flo = freq - freq_offset fhi = freq + freq_offset num_chan = tb.get_num_channels() freq_range = np.linspace(flo, fhi, num_chan) #convert frequency f to radial velocity at galactic coordinate l #account for movement of the sun relative to galactic center def freq_to_vel(f, l): c = 2.998e5 #km/s v_rec = (freq - f) * c / freq v_sun = 220 #km/s correction = v_sun * np.sin(np.deg2rad(l)) return v_rec + correction ############ Editable variables ########### savefolder = 'gal_scans/run26/' savetitle = 'vectors.txt' int_time = 30 l_start = 0 l_stop = 360 l_step = 2.5 ######################################### # BEGIN COMMANDS # ######################################### large_step = 1 #signals that the dish just moved a bunch and we need to wait longer for it to settle #print 'Moving to initial galactic longitude l=' + str(l) #point at galactic center and give time to settle l = l_start # pos=gal_to_altaz(l,0) # # while pos[1] <= 0: # # pos=gal_to_altaz(l,0) # # if pos[1] > 0: break # # if l > l_stop: break # point(pos[0],pos[1]) # wait(10) #do the survey file = open(savefolder + savetitle, 'w') file.write('Integration time ' + str(int_time) + ' seconds. Center frequency ' + str(freq) + ' MHz. \n \n') file.write('Azimuth Elevation RA DEC Time Center Data_vector \n \n') while l <= l_stop: #take data at a position pos = gal_to_altaz(l, 0) if pos[1] > 0: print 'Moving to galactic longitude l=' + str(l) point(pos[0], pos[1]) if large_step: wait(10) else: wait(2) large_step = 0 print "Observing at galactic coordinates (" + str(l) + ', 0).' time = get_time() data = observe(int_time) #write to file file.write(str(l) + ' ') file.write(str(0) + ' ') file.write(str(time) + ' ') file.write(str(data) + '\n \n') #frequency binned figure plt.figure() plt.title('l=' + str(l) + ' ' + str(time)) plt.xlabel('Frequency (MHz)') plt.ylabel('Power at Feed (W/Hz)') plt.axvline(x=freq, color='black', ls='--') plt.ticklabel_format(useOffset=False) plt.plot(freq_range, data) plt.savefig(savefolder + 'lat' + str(l) + '_freq.pdf') wait(1) plt.close() #velocity binned figure vel_range = np.array([freq_to_vel(f, l) for f in freq_range]) center_vel = freq_to_vel(freq, l) plt.figure() plt.title('l=' + str(l) + ' ' + str(time)) plt.xlabel('Velocity (km/s)') plt.ylabel('Power at Feed (W)') plt.axvline(x=0, color='black', ls='--') plt.ticklabel_format(useOffset=False) plt.plot(vel_range, data) plt.savefig(savefolder + 'lat' + str(l) + '_vel.pdf') wait(1) plt.close() print 'Data logged.' print ' ' else: large_step = 1 l += l_step if l >= l_stop: break #move to next position # pos=gal_to_altaz(l,0) # point(pos[0],pos[1]) # wait(2) file.close() #!/usr/bin/python def quitting(): tb.stop() tb.wait() # qapp.connect(qapp, Qt.SIGNAL("aboutToQuit()"), quitting) # qapp.exec_() quitting()
from gnuradio import gr enable_ctrlport = True try: import Ice from gnuradio.ctrlport import GNURadio from gnuradio import ctrlport except: enable_ctrlport = False import gr_profiler # force controlport export configuration on at startup for (cat,opt) in [("ControlPort","on"), ("ControlPort","edges_list"), ("PerfCounters","on"), ("PerfCounters","export")]: gr.prefs().singleton().set_bool(cat,opt,True); def add_argparser(): parser = ArgumentParser(description='Benchmarking tool for GR flowgraphs') parser.add_argument('-F', '--file', type=str, default=None, help='Config file listing tests to run [default=%(default)s]') parser.add_argument('-D', '--directory', type=str, default=None, help='Directory to read the benchmark scripts from [default=%(default)s]') parser.add_argument('-o', '--ofile', type=str, default='output.pkl', help='Output file to write to [default=%(default)s]') parser.add_argument('--iscripts', nargs='*', type=str, default=None, help='Input benchmarking scripts to read [default=%(default)s]') parser.add_argument('--nitems', nargs='*', type=int, help='Number of items to process [default=%(default)s]') parser.add_argument('--iters', nargs='*', type=int,
GNU Radio Companion is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA """ import os import stat from gnuradio import gr _gr_prefs = gr.prefs() #setup paths PATH_SEP = {'/':':', '\\':';'}[os.path.sep] HIER_BLOCKS_LIB_DIR = os.path.join(os.path.expanduser('~'), '.grc_gnuradio') BLOCKS_DIRS = filter( #filter blank strings lambda x: x, PATH_SEP.join([ os.environ.get('GRC_BLOCKS_PATH', ''), _gr_prefs.get_string('grc', 'local_blocks_path', ''), _gr_prefs.get_string('grc', 'global_blocks_path', ''), ]).split(PATH_SEP), ) + [HIER_BLOCKS_LIB_DIR] #user settings XTERM_EXECUTABLE = _gr_prefs.get_string('grc', 'xterm_executable', 'xterm')
def main(top_block_cls=top_block, options=None): from distutils.version import StrictVersion if StrictVersion(Qt.qVersion()) >= StrictVersion("4.5.0"): style = gr.prefs().get_string('qtgui', 'style', 'raster') Qt.QApplication.setGraphicsSystem(style) qapp = Qt.QApplication(sys.argv) ######## ACTUALLY WHERE STUFF HAPPENS ####### tb = top_block_cls() tb.start() tb.show() print('Receiving ...') global darksky global darksky_exists def snapshot(int_time): #straight snapshot over a certain integration time. tb.set_integration_time(int_time) # print 'Integration time set to '+str(int_time)+ ' seconds.' print 'Snapshot '+ str(int_time) + ' sec' vec=tb.get_variable_function_probe() #old vector pointa=vec[0] pointb=vec[-1] tb.toggle_copy(True) #start copying while vec[0]==pointa and vec[-1]==pointb: pytime.sleep(1) vec=tb.get_variable_function_probe() tb.toggle_copy(False) #stop copying return np.array(vec) def dark_sky_calib(int_time): #for use when pointing at the dark sky global darksky darksky=snapshot(int_time) global darksky_exists darksky_exists=True return def observe(int_time): #dark sky calbrated snapshot vec=snapshot(int_time) wait(int_time) global darksky_exists if darksky_exists: calib=vec-darksky return calib else: print('Warning: No dark sky calibration has been performed.') return vec def wait(sec): pytime.sleep(sec) return def graphing(int_time, iter=float('inf')): plt.ion() plt.figure() vec=tb.get_variable_function_probe() #vector n=len(vec) x=np.linspace(flo, fhi, n) i=0 while(i<iter): plt.pause(int_time) y=observe(int_time) plt.clf() plt.xlabel('Frequency (MHz)') plt.ylabel('Scaled power') plt.axvline(x=1420.406, color='black', ls='--') plt.ticklabel_format(useOffset=False) plt.plot(x,y) plt.draw() i+=1 return() def track(N): client.track(N)
def _handle_action(self, action, *args): #print action ################################################## # Initialize/Quit ################################################## if action == Actions.APPLICATION_INITIALIZE: if ParseXML.xml_failures: Messages.send_xml_errors_if_any(ParseXML.xml_failures) Actions.XML_PARSER_ERRORS_DISPLAY.set_sensitive(True) if not self.init_file_paths: self.init_file_paths = filter(os.path.exists, Preferences.files_open()) if not self.init_file_paths: self.init_file_paths = [''] for file_path in self.init_file_paths: if file_path: self.main_window.new_page( file_path) #load pages from file paths if Preferences.file_open() in self.init_file_paths: self.main_window.new_page(Preferences.file_open(), show=True) if not self.get_page(): self.main_window.new_page( ) #ensure that at least a blank page exists self.main_window.btwin.search_entry.hide() # Disable all actions, then re-enable a few for action in Actions.get_all_actions(): action.set_sensitive(False) #set all actions disabled for action in ( Actions.APPLICATION_QUIT, Actions.FLOW_GRAPH_NEW, Actions.FLOW_GRAPH_OPEN, Actions.FLOW_GRAPH_SAVE_AS, Actions.FLOW_GRAPH_CLOSE, Actions.ABOUT_WINDOW_DISPLAY, Actions.FLOW_GRAPH_SCREEN_CAPTURE, Actions.HELP_WINDOW_DISPLAY, Actions.TYPES_WINDOW_DISPLAY, Actions.TOGGLE_BLOCKS_WINDOW, Actions.TOGGLE_REPORTS_WINDOW, Actions.TOGGLE_HIDE_DISABLED_BLOCKS, Actions.TOOLS_RUN_FDESIGN, Actions.TOGGLE_SCROLL_LOCK, Actions.CLEAR_REPORTS, Actions.SAVE_REPORTS, Actions.TOGGLE_AUTO_HIDE_PORT_LABELS, Actions.TOGGLE_SNAP_TO_GRID, Actions.TOGGLE_SHOW_BLOCK_COMMENTS, Actions.TOGGLE_SHOW_CODE_PREVIEW_TAB, Actions.TOGGLE_SHOW_FLOWGRAPH_COMPLEXITY, Actions.FLOW_GRAPH_OPEN_QSS_THEME, ): action.set_sensitive(True) if hasattr(action, 'load_from_preferences'): action.load_from_preferences() elif action == Actions.APPLICATION_QUIT: if self.main_window.close_pages(): gtk.main_quit() exit(0) ################################################## # Selections ################################################## elif action == Actions.ELEMENT_SELECT: pass #do nothing, update routines below elif action == Actions.NOTHING_SELECT: self.get_flow_graph().unselect() ################################################## # Enable/Disable ################################################## elif action == Actions.BLOCK_ENABLE: if self.get_flow_graph().enable_selected(True): self.get_flow_graph().update() self.get_page().get_state_cache().save_new_state( self.get_flow_graph().export_data()) self.get_page().set_saved(False) elif action == Actions.BLOCK_DISABLE: if self.get_flow_graph().enable_selected(False): self.get_flow_graph().update() self.get_page().get_state_cache().save_new_state( self.get_flow_graph().export_data()) self.get_page().set_saved(False) elif action == Actions.BLOCK_BYPASS: if self.get_flow_graph().bypass_selected(): self.get_flow_graph().update() self.get_page().get_state_cache().save_new_state( self.get_flow_graph().export_data()) self.get_page().set_saved(False) ################################################## # Cut/Copy/Paste ################################################## elif action == Actions.BLOCK_CUT: Actions.BLOCK_COPY() Actions.ELEMENT_DELETE() elif action == Actions.BLOCK_COPY: self.clipboard = self.get_flow_graph().copy_to_clipboard() elif action == Actions.BLOCK_PASTE: if self.clipboard: self.get_flow_graph().paste_from_clipboard(self.clipboard) self.get_flow_graph().update() self.get_page().get_state_cache().save_new_state( self.get_flow_graph().export_data()) self.get_page().set_saved(False) ################################################## # Create heir block ################################################## elif action == Actions.BLOCK_CREATE_HIER: # keeping track of coordinates for pasting later coords = self.get_flow_graph().get_selected_blocks( )[0].get_coordinate() x, y = coords x_min = x y_min = y pads = [] params = [] # Save the state of the leaf blocks for block in self.get_flow_graph().get_selected_blocks(): # Check for string variables within the blocks for param in block.get_params(): for variable in self.get_flow_graph().get_variables(): # If a block parameter exists that is a variable, create a parameter for it if param.get_value() == variable.get_id(): params.append(param.get_value()) for flow_param in self.get_flow_graph().get_parameters(): # If a block parameter exists that is a parameter, create a parameter for it if param.get_value() == flow_param.get_id(): params.append(param.get_value()) # keep track of x,y mins for pasting later (x, y) = block.get_coordinate() if x < x_min: x_min = x if y < y_min: y_min = y for connection in block.get_connections(): # Get id of connected blocks source_id = connection.get_source().get_parent().get_id() sink_id = connection.get_sink().get_parent().get_id() # If connected block is not in the list of selected blocks create a pad for it if self.get_flow_graph().get_block( source_id) not in self.get_flow_graph( ).get_selected_blocks(): pads.append({ 'key': connection.get_sink().get_key(), 'coord': connection.get_source().get_coordinate(), 'block_id': block.get_id(), 'direction': 'source' }) if self.get_flow_graph().get_block( sink_id) not in self.get_flow_graph( ).get_selected_blocks(): pads.append({ 'key': connection.get_source().get_key(), 'coord': connection.get_sink().get_coordinate(), 'block_id': block.get_id(), 'direction': 'sink' }) # Copy the selected blocks and paste them into a new page # then move the flowgraph to a reasonable position Actions.BLOCK_COPY() self.main_window.new_page() Actions.BLOCK_PASTE() coords = (x_min, y_min) self.get_flow_graph().move_selected(coords) # Set flow graph to heir block type top_block = self.get_flow_graph().get_block("top_block") top_block.get_param('generate_options').set_value('hb') # this needs to be a unique name top_block.get_param('id').set_value('new_heir') # Remove the default samp_rate variable block that is created remove_me = self.get_flow_graph().get_block("samp_rate") self.get_flow_graph().remove_element(remove_me) # Add the param blocks along the top of the window x_pos = 150 for param in params: param_id = self.get_flow_graph().add_new_block( 'parameter', (x_pos, 10)) param_block = self.get_flow_graph().get_block(param_id) param_block.get_param('id').set_value(param) x_pos = x_pos + 100 for pad in pads: # Add the pad sources and sinks within the new heir block if pad['direction'] == 'sink': # Add new PAD_SINK block to the canvas pad_id = self.get_flow_graph().add_new_block( 'pad_sink', pad['coord']) # setup the references to the sink and source pad_block = self.get_flow_graph().get_block(pad_id) pad_sink = pad_block.get_sinks()[0] source_block = self.get_flow_graph().get_block( pad['block_id']) source = source_block.get_source(pad['key']) # Ensure the port types match while pad_sink.get_type() != source.get_type(): # Special case for some blocks that have non-standard type names, e.g. uhd if pad_sink.get_type( ) == 'complex' and source.get_type() == 'fc32': break pad_block.type_controller_modify(1) # Connect the pad to the proper sinks new_connection = self.get_flow_graph().connect( source, pad_sink) elif pad['direction'] == 'source': pad_id = self.get_flow_graph().add_new_block( 'pad_source', pad['coord']) # setup the references to the sink and source pad_block = self.get_flow_graph().get_block(pad_id) pad_source = pad_block.get_sources()[0] sink_block = self.get_flow_graph().get_block( pad['block_id']) sink = sink_block.get_sink(pad['key']) # Ensure the port types match while sink.get_type() != pad_source.get_type(): # Special case for some blocks that have non-standard type names, e.g. uhd if pad_source.get_type( ) == 'complex' and sink.get_type() == 'fc32': break pad_block.type_controller_modify(1) # Connect the pad to the proper sinks new_connection = self.get_flow_graph().connect( pad_source, sink) # update the new heir block flow graph self.get_flow_graph().update() ################################################## # Move/Rotate/Delete/Create ################################################## elif action == Actions.BLOCK_MOVE: self.get_page().get_state_cache().save_new_state( self.get_flow_graph().export_data()) self.get_page().set_saved(False) elif action == Actions.BLOCK_ROTATE_CCW: if self.get_flow_graph().rotate_selected(90): self.get_flow_graph().update() self.get_page().get_state_cache().save_new_state( self.get_flow_graph().export_data()) self.get_page().set_saved(False) elif action == Actions.BLOCK_ROTATE_CW: if self.get_flow_graph().rotate_selected(-90): self.get_flow_graph().update() self.get_page().get_state_cache().save_new_state( self.get_flow_graph().export_data()) self.get_page().set_saved(False) elif action == Actions.ELEMENT_DELETE: if self.get_flow_graph().remove_selected(): self.get_flow_graph().update() self.get_page().get_state_cache().save_new_state( self.get_flow_graph().export_data()) Actions.NOTHING_SELECT() self.get_page().set_saved(False) elif action == Actions.ELEMENT_CREATE: self.get_flow_graph().update() self.get_page().get_state_cache().save_new_state( self.get_flow_graph().export_data()) Actions.NOTHING_SELECT() self.get_page().set_saved(False) elif action == Actions.BLOCK_INC_TYPE: if self.get_flow_graph().type_controller_modify_selected(1): self.get_flow_graph().update() self.get_page().get_state_cache().save_new_state( self.get_flow_graph().export_data()) self.get_page().set_saved(False) elif action == Actions.BLOCK_DEC_TYPE: if self.get_flow_graph().type_controller_modify_selected(-1): self.get_flow_graph().update() self.get_page().get_state_cache().save_new_state( self.get_flow_graph().export_data()) self.get_page().set_saved(False) elif action == Actions.PORT_CONTROLLER_INC: if self.get_flow_graph().port_controller_modify_selected(1): self.get_flow_graph().update() self.get_page().get_state_cache().save_new_state( self.get_flow_graph().export_data()) self.get_page().set_saved(False) elif action == Actions.PORT_CONTROLLER_DEC: if self.get_flow_graph().port_controller_modify_selected(-1): self.get_flow_graph().update() self.get_page().get_state_cache().save_new_state( self.get_flow_graph().export_data()) self.get_page().set_saved(False) ################################################## # Window stuff ################################################## elif action == Actions.ABOUT_WINDOW_DISPLAY: Dialogs.AboutDialog(self.get_flow_graph().get_parent()) elif action == Actions.HELP_WINDOW_DISPLAY: Dialogs.HelpDialog() elif action == Actions.TYPES_WINDOW_DISPLAY: Dialogs.TypesDialog(self.get_flow_graph().get_parent()) elif action == Actions.ERRORS_WINDOW_DISPLAY: Dialogs.ErrorsDialog(self.get_flow_graph()) elif action == Actions.TOGGLE_REPORTS_WINDOW: if action.get_active(): self.main_window.reports_scrolled_window.show() else: self.main_window.reports_scrolled_window.hide() action.save_to_preferences() elif action == Actions.TOGGLE_BLOCKS_WINDOW: if action.get_active(): self.main_window.btwin.show() else: self.main_window.btwin.hide() action.save_to_preferences() elif action == Actions.TOGGLE_SCROLL_LOCK: active = action.get_active() self.main_window.text_display.scroll_lock = active if active: self.main_window.text_display.scroll_to_end() action.save_to_preferences() elif action == Actions.CLEAR_REPORTS: self.main_window.text_display.clear() elif action == Actions.SAVE_REPORTS: file_path = SaveReportsFileDialog( self.get_page().get_file_path()).run() if file_path is not None: self.main_window.text_display.save(file_path) elif action == Actions.TOGGLE_HIDE_DISABLED_BLOCKS: Actions.NOTHING_SELECT() elif action == Actions.TOGGLE_AUTO_HIDE_PORT_LABELS: action.save_to_preferences() for page in self.main_window.get_pages(): page.get_flow_graph().create_shapes() elif action == Actions.TOGGLE_SNAP_TO_GRID: action.save_to_preferences() elif action == Actions.TOGGLE_SHOW_BLOCK_COMMENTS: action.save_to_preferences() elif action == Actions.TOGGLE_SHOW_CODE_PREVIEW_TAB: action.save_to_preferences() elif action == Actions.TOGGLE_SHOW_FLOWGRAPH_COMPLEXITY: action.save_to_preferences() for page in self.main_window.get_pages(): page.get_flow_graph().update() ################################################## # Param Modifications ################################################## elif action == Actions.BLOCK_PARAM_MODIFY: selected_block = self.get_flow_graph().get_selected_block() if selected_block: dialog = PropsDialog(selected_block) response = gtk.RESPONSE_APPLY while response == gtk.RESPONSE_APPLY: # rerun the dialog if Apply was hit response = dialog.run() if response in (gtk.RESPONSE_APPLY, gtk.RESPONSE_ACCEPT): self.get_flow_graph().update() self.get_page().get_state_cache().save_new_state( self.get_flow_graph().export_data()) self.get_page().set_saved(False) else: # restore the current state n = self.get_page().get_state_cache( ).get_current_state() self.get_flow_graph().import_data(n) self.get_flow_graph().update() if response == gtk.RESPONSE_APPLY: # null action, that updates the main window Actions.ELEMENT_SELECT() dialog.destroy() ################################################## # View Parser Errors ################################################## elif action == Actions.XML_PARSER_ERRORS_DISPLAY: ParserErrorsDialog(ParseXML.xml_failures).run() ################################################## # Undo/Redo ################################################## elif action == Actions.FLOW_GRAPH_UNDO: n = self.get_page().get_state_cache().get_prev_state() if n: self.get_flow_graph().unselect() self.get_flow_graph().import_data(n) self.get_flow_graph().update() self.get_page().set_saved(False) elif action == Actions.FLOW_GRAPH_REDO: n = self.get_page().get_state_cache().get_next_state() if n: self.get_flow_graph().unselect() self.get_flow_graph().import_data(n) self.get_flow_graph().update() self.get_page().set_saved(False) ################################################## # New/Open/Save/Close ################################################## elif action == Actions.FLOW_GRAPH_NEW: self.main_window.new_page() if args: self.get_flow_graph()._options_block.get_param( 'generate_options').set_value(args[0]) self.get_flow_graph().update() elif action == Actions.FLOW_GRAPH_OPEN: file_paths = OpenFlowGraphFileDialog( self.get_page().get_file_path()).run() if file_paths: #open a new page for each file, show only the first for i, file_path in enumerate(file_paths): self.main_window.new_page(file_path, show=(i == 0)) elif action == Actions.FLOW_GRAPH_OPEN_QSS_THEME: file_paths = OpenQSSFileDialog(GR_PREFIX + '/share/gnuradio/themes/').run() if file_paths: try: from gnuradio import gr gr.prefs().set_string("qtgui", "qss", file_paths[0]) gr.prefs().save() except Exception as e: Messages.send("Failed to save QSS preference: " + str(e)) elif action == Actions.FLOW_GRAPH_CLOSE: self.main_window.close_page() elif action == Actions.FLOW_GRAPH_SAVE: #read-only or undefined file path, do save-as if self.get_page().get_read_only( ) or not self.get_page().get_file_path(): Actions.FLOW_GRAPH_SAVE_AS() #otherwise try to save else: try: ParseXML.to_file(self.get_flow_graph().export_data(), self.get_page().get_file_path()) self.get_flow_graph().grc_file_path = self.get_page( ).get_file_path() self.get_page().set_saved(True) except IOError: Messages.send_fail_save(self.get_page().get_file_path()) self.get_page().set_saved(False) elif action == Actions.FLOW_GRAPH_SAVE_AS: file_path = SaveFlowGraphFileDialog( self.get_page().get_file_path()).run() if file_path is not None: self.get_page().set_file_path(file_path) Actions.FLOW_GRAPH_SAVE() elif action == Actions.FLOW_GRAPH_SCREEN_CAPTURE: file_path = SaveImageFileDialog( self.get_page().get_file_path()).run() if file_path is not None: pixbuf = self.get_flow_graph().get_drawing_area().get_pixbuf() pixbuf.save(file_path, IMAGE_FILE_EXTENSION[1:]) ################################################## # Gen/Exec/Stop ################################################## elif action == Actions.FLOW_GRAPH_GEN: if not self.get_page().get_proc(): if not self.get_page().get_saved() or not self.get_page( ).get_file_path(): Actions.FLOW_GRAPH_SAVE( ) #only save if file path missing or not saved if self.get_page().get_saved() and self.get_page( ).get_file_path(): generator = self.get_page().get_generator() try: Messages.send_start_gen(generator.get_file_path()) generator.write() except Exception, e: Messages.send_fail_gen(e) else: self.generator = None
# Date: Feb. 8, 2018 # # For more details, please refer to the Columbia FlexICoN project ######################################################################################################## import gen_data_psk as gen import usrp_txrx_psk as txrx import dig_sic_off_psk as sic from PyQt4 import Qt from gnuradio import gr import sys import time from distutils.version import StrictVersion if StrictVersion(Qt.qVersion()) >= StrictVersion("4.5.0"): style = gr.prefs().get_string('qtgui', 'style', 'raster') Qt.QApplication.setGraphicsSystem(style) qapp = Qt.QApplication(sys.argv) def gen_main(top_block_cls=gen.gen_data_psk, options=None): # from distutils.version import StrictVersion # if StrictVersion(Qt.qVersion()) >= StrictVersion("4.5.0"): # style = gr.prefs().get_string('qtgui', 'style', 'raster') # Qt.QApplication.setGraphicsSystem(style) # qapp = Qt.QApplication(sys.argv) tb = top_block_cls() tb.start() tb.show()
def test_001(self): p = gr.prefs() # Read some options self.assertFalse(p.has_option('doesnt', 'exist'))
# any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr p = gr.prefs() style = p.get_string('wxgui', 'style', 'auto') if style == 'auto' or style == 'gl': try: import wx.glcanvas from OpenGL.GL import * from scopesink_gl import scope_sink_f, scope_sink_c except ImportError: if style == 'gl': raise RuntimeError( "Unable to import OpenGL. Are Python wrappers for OpenGL installed?" ) else: # Fall backto non-gl sinks from scopesink_nongl import scope_sink_f, scope_sink_c
def main(top_block_cls=ROC_enDet, options=None): from distutils.version import StrictVersion if StrictVersion(Qt.qVersion()) >= StrictVersion("4.5.0"): style = gr.prefs().get_string('qtgui', 'style', 'raster') Qt.QApplication.setGraphicsSystem(style) qapp = Qt.QApplication(sys.argv) tb = top_block_cls() tb.start() tb.show() # By default the ROC_energy block is called in the calibration mode which estimates the noise floor sleep(5) # take 5 seconds of samples in the calibration mode # load the estimated noise value estN = scipy.fromfile(open( "C:\Users\usuario\Documents\gnuRadio\Misc\SpectrumSensing\P_absSq.dat" ), dtype=scipy.float32) estN = np.mean(estN[np.abs(estN) >= 1e-15]) yy = scipy.fromfile(open( "C:\Users\usuario\Documents\gnuRadio\Misc\SpectrumSensing\P_var_reim.dat" ), dtype=scipy.float32) yy = np.mean(yy[np.abs(yy) >= 1e-15]) zz = scipy.fromfile(open( "C:\Users\usuario\Documents\gnuRadio\Misc\SpectrumSensing\P_var.dat"), dtype=scipy.float32) zz = np.mean(zz[np.abs(zz) >= 1e-15]) print('Estimated noise floor in dB: ', estN, yy, zz) # Reconfigure flow-graph # tb.lock() tb.stop() tb.wait() tb.disconnect((tb.ROC_energy_block, 0), (tb.blocks_file_sink_3, 0)) tb.disconnect((tb.ROC_energy_block, 1), (tb.blocks_file_sink_4, 0)) tb.disconnect((tb.ROC_energy_block, 2), (tb.blocks_file_sink_5, 0)) # Connect the other sink blocks and restart tb.connect((tb.ROC_energy_block, 0), (tb.blocks_file_sink_0, 0)) tb.connect((tb.ROC_energy_block, 1), (tb.blocks_file_sink_1, 0)) tb.connect((tb.ROC_energy_block, 2), (tb.blocks_file_sink_2, 0)) #tb.unlock() tb.start() tb.set_theta(1.0) # enable signal 'transmission' tb.set_fun('meas') # change to the 'measurement' mode # sleep(0.1) for targPf in np.logspace( -6, 0, 21 ): # data with the first value of threshold is invalidated due to the noise floor #new_thr = (10**(estN/10))*scpsp.gammainccinv(tb.get_N(), targPf) new_thr = tb.get_sigma_n()**2 * scpsp.gammainccinv( tb.get_N(), targPf) #use this for simulation accuracy tb.set_thr(new_thr) # change threshold sleep(1) # run the flowgraph (with current values) for 3 seconds tb.stop() tb.wait() def quitting(): tb.stop() tb.wait() qapp.connect(qapp, Qt.SIGNAL("aboutToQuit()"), quitting) qapp.exec_()
def main(top_block_cls=measureSignalOriginal, options=None): from distutils.version import StrictVersion if StrictVersion(Qt.qVersion()) >= StrictVersion("4.5.0"): style = gr.prefs().get_string('qtgui', 'style', 'raster') Qt.QApplication.setGraphicsSystem(style) qapp = Qt.QApplication(sys.argv) tb = top_block_cls() # ZYG: Move quitting here and add new one for debugging. def quitting(): tb.stop() tb.wait() def logGps(): gpsDo = gpsdo.gpsdo(tb.uhd_usrp_source_0, \ os.path.join(tb.outFilesPath, \ 'measureSignal_'+tb.epochTimeStrForLogFile+'_GPS.log')) gpsDo.log(tb.get_rx_gain()) keepProbingGps = True def probeGps(): logGps() time.sleep(3) if keepProbingGps: probeGps() def quiteFromTimer(): print(tb.uhd_usrp_source_0) logGps() print('Quitting by Timer...') keepProbingGps = False quitting() qapp.quit() if FLAG_TRY_TO_LOCK_GPSDO: print(' ') print('Trying to lock GPSDO to satellite...') print(' ') print(' Available sensors:') print(tb.uhd_usrp_source_0.get_mboard_sensor_names()) print(' ') time.sleep(3) t = Timer(240.0, quiteFromTimer) probeGps() else: t = Timer(3.0, quiteFromTimer) tb.start() tb.show() # ZYG t.start() # ZYG # def quitting(): # tb.stop() # tb.wait() qapp.connect(qapp, Qt.SIGNAL("aboutToQuit()"), quitting) qapp.exec_()
def test_bits_flipped_vs_noise(top_block_cls=eve_re_learn_testbed_graph, options=None): from distutils.version import StrictVersion if StrictVersion(Qt.qVersion()) >= StrictVersion("4.5.0"): style = gr.prefs().get_string('qtgui', 'style', 'raster') Qt.QApplication.setGraphicsSystem(style) qapp = Qt.QApplication(sys.argv) db_list = range(-20, 21) avg_bits_flipped_list = [] for test_db in db_list: tb = top_block_cls(test_db, test_db) tb.start() tb.wait() # grab data from sink alice_sent = tb.blocks_vector_sink_alice.data() bob_rec = tb.blocks_vector_sink_bob.data() # create np array to hold sent and rec data data_sent_n_rec = np.zeros((tb.max_items, 2)) #print(data_sent_n_rec) for index, val in enumerate(alice_sent): data_sent_n_rec[index][0] = val for index, val in enumerate(bob_rec): data_sent_n_rec[index][1] = val #print(data_sent_n_rec) #print("\n\n") bits_flipped_list = [] for row in data_sent_n_rec: alice_sent_bin_list = int_to_binlist(int(row[0]), 8) bob_rec_bin_list = int_to_binlist(int(row[1]), 8) num_bits_flipped = count_bits_flipped(alice_sent_bin_list, bob_rec_bin_list) bits_flipped_list.append(num_bits_flipped) # print(bin(int(row[0]))) # print("%s" % (bin(int(row[0])))) # print("%s\t%d bits flipped" % (bin(int(row[1])),num_bits_flipped)) # print("-----------") avg_bits_flipped = sum(bits_flipped_list) / float( len(bits_flipped_list)) avg_bits_flipped_list.append(avg_bits_flipped) print("%d db, avg bits flipped: %f" % (test_db, avg_bits_flipped)) # def int_to_binlist(num_int, num_bin_digits): # def count_bits_flipped(bin_list1, bin_list2): plt.plot(db_list, avg_bits_flipped_list, 'r-') plt.title("Bits Flipped vs Eve and Channel Noise", fontsize=18) plt.xlabel('Eve and Channel Noise (db)') plt.ylabel('Bits Flipped') plt.grid(True) plt.savefig('./plots/bits-flipped_vs_channel-noise_large_1.png', format='png', dpi=300) #tb.show() def quitting(): tb.stop() tb.wait() qapp.connect(qapp, Qt.SIGNAL("aboutToQuit()"), quitting) qapp.exec_()
def setup_parser(self): """ Init the option parser. If derived classes need to add options, override this and call the parent function. """ parser = ArgumentParser( usage='%(prog)s ' + self.name + ' [options] <PATTERN> \n' + \ ' Call "%(prog)s ' + self.name + '" without any options to run it' + \ ' interactively.', add_help=False ) agroup = parser.add_argument_group("General options") agroup.add_argument("-h", "--help", action="help", help="Displays this help message.") agroup.add_argument( "-d", "--directory", default=".", help="Base directory of the module. Defaults to the cwd.") agroup.add_argument("-n", "--module-name", default=None, help="Use this to override the current module's name" + \ " (is normally autodetected).") agroup.add_argument("-N", "--block-name", default=None, help="Name of the block, where applicable.") agroup.add_argument("--skip-lib", action="store_true", default=False, help="Don't do anything in the lib/ subdirectory.") agroup.add_argument( "--skip-swig", action="store_true", default=False, help="Don't do anything in the swig/ subdirectory.") agroup.add_argument( "--skip-python", action="store_true", default=False, help="Don't do anything in the python/ subdirectory.") agroup.add_argument("--skip-grc", action="store_true", default=False, help="Don't do anything in the grc/ subdirectory.") agroup.add_argument( "--skip-rfnoc", action="store_true", default=False, help="Don't do anything in the rfnoc/ subdirectory.") agroup.add_argument( "--scm-mode", choices=('yes', 'no', 'auto'), default=gr.prefs().get_string('rfnocmodtool', 'scm_mode', 'no'), help="Use source control management (yes, no or auto).") agroup.add_argument("-y", "--yes", action="store_true", default=False, help="Answer all questions with 'yes'. This " + \ "can overwrite and delete your files, so be careful.") return parser
def main(top_block_cls=dvbs_tx_var_v4, options=None): if gr.enable_realtime_scheduling() != gr.RT_OK: print "Error: failed to enable real-time scheduling." global symbol_rate global code_rate global fec_display global dvb parser = argparse.ArgumentParser() srate_help = 'symbol rate (ks/s): 125, 250, 500, 1000, 2000 (default).' parser.add_argument('-sr', '--symbole-rate', dest='srate', default='1000', type=str, help=srate_help) rate_help = 'Viterbi rate. 1/2, 2/3, 3/4, 5/6, 7/8 (default).' parser.add_argument('-vr', '--viterbi-rate', dest='rate', default='7/8', type=str, help=rate_help) args = parser.parse_args() if args.srate == '125': symbol_rate = 125000.0 elif args.srate == '250': symbol_rate = 250000.0 elif args.srate == '500': symbol_rate = 500000.0 elif args.srate == '1000': symbol_rate = 1000000.0 elif args.srate == '2000': symbol_rate = 2000000.0 else: sys.stderr.write('*******************************************' + '\n') sys.stderr.write('Invalid symbol rate: ' + (args.srate) + '\n') sys.stderr.write('*******************************************' + '\n') sys.exit(1) if args.rate == '1/2': code_rate = dtv.C1_2 elif args.rate == '2/3': code_rate = dtv.C2_3 elif args.rate == '3/4': code_rate = dtv.C3_4 elif args.rate == '5/6': code_rate = dtv.C5_6 elif args.rate == '7/8': code_rate = dtv.C7_8 else: sys.stderr.write('*******************************************' + '\n') sys.stderr.write('Invalid Viterbi rate: ' + args.rate + '\n') sys.stderr.write('*******************************************' + '\n') sys.exit(1) fec_display = args.rate from distutils.version import StrictVersion if StrictVersion(Qt.qVersion()) >= StrictVersion("4.5.0"): style = gr.prefs().get_string('qtgui', 'style', 'raster') Qt.QApplication.setGraphicsSystem(style) qapp = Qt.QApplication(sys.argv) tb = top_block_cls() tb.start() tb.show() def quitting(): tb.stop() tb.wait() qapp.connect(qapp, Qt.SIGNAL("aboutToQuit()"), quitting) qapp.exec_()
import common import wx import numpy import math import pubsub from constants import * from gnuradio import gr #for gr.prefs import forms ################################################## # Constants ################################################## SLIDER_STEPS = 100 AVG_ALPHA_MIN_EXP, AVG_ALPHA_MAX_EXP = -3, 0 PERSIST_ALPHA_MIN_EXP, PERSIST_ALPHA_MAX_EXP = -2, 0 DEFAULT_WIN_SIZE = (600, 300) DEFAULT_FRAME_RATE = gr.prefs().get_long('wxgui', 'fft_rate', 30) DB_DIV_MIN, DB_DIV_MAX = 1, 20 FFT_PLOT_COLOR_SPEC = (0.3, 0.3, 1.0) PEAK_VALS_COLOR_SPEC = (0.0, 0.8, 0.0) EMPTY_TRACE = list() TRACES = ('A', 'B') TRACES_COLOR_SPEC = { 'A': (1.0, 0.0, 0.0), 'B': (0.8, 0.0, 0.8), } ################################################## # FFT window control panel ################################################## class control_panel(wx.Panel):
# Imports ################################################## import plotter import common import wx import numpy import time import pubsub from constants import * from gnuradio import gr #for gr.prefs, trigger modes import forms ################################################## # Constants ################################################## DEFAULT_FRAME_RATE = gr.prefs().get_long('wxgui', 'scope_rate', 30) PERSIST_ALPHA_MIN_EXP, PERSIST_ALPHA_MAX_EXP = -2, 0 SLIDER_STEPS = 100 DEFAULT_TRIG_MODE = gr.prefs().get_long('wxgui', 'trig_mode', gr.gr_TRIG_MODE_AUTO) DEFAULT_WIN_SIZE = (600, 300) COUPLING_MODES = ( ('DC', False), ('AC', True), ) TRIGGER_MODES = ( ('Freerun', gr.gr_TRIG_MODE_FREE), ('Auto', gr.gr_TRIG_MODE_AUTO), ('Normal', gr.gr_TRIG_MODE_NORM), ('Stripchart', gr.gr_TRIG_MODE_STRIPCHART), )
help="Set Set number of FFT bins [default=%default]") parser.add_option("-f", "--freq", dest="freq", type="eng_float", default=eng_notation.num_to_str(833e6), help="Set Default Frequency [default=%default]") parser.add_option("-g", "--gain", dest="gain", type="eng_float", default=eng_notation.num_to_str(20), help="Set Set gain in dB (default is midpoint) [default=%default]") parser.add_option("-s", "--samp-rate", dest="samp_rate", type="eng_float", default=eng_notation.num_to_str(13e6), help="Set Sample Rate [default=%default]") parser.add_option("", "--spec", dest="spec", type="string", default="", help="Set Subdev [default=%default]") parser.add_option("", "--stream-args", dest="stream_args", type="string", default="", help="Set Set additional stream args [default=%default]") parser.add_option("", "--update-rate", dest="update_rate", type="eng_float", default=eng_notation.num_to_str(.1), help="Set Set GUI widget update rate [default=%default]") parser.add_option("", "--wire-format", dest="wire_format", type="string", default="", help="Set Wire format [default=%default]") (options, args) = parser.parse_args() if gr.enable_realtime_scheduling() != gr.RT_OK: print "Error: failed to enable realtime scheduling." if(StrictVersion(Qt.qVersion()) >= StrictVersion("4.5.0")): Qt.QApplication.setGraphicsSystem(gr.prefs().get_string('qtgui','style','raster')) qapp = Qt.QApplication(sys.argv) tb = spectrum_analyzer(antenna=options.antenna, args=options.args, fft_size=options.fft_size, freq=options.freq, gain=options.gain, samp_rate=options.samp_rate, spec=options.spec, stream_args=options.stream_args, update_rate=options.update_rate, wire_format=options.wire_format) tb.start() tb.show() def quitting(): tb.stop() tb.wait() qapp.connect(qapp, Qt.SIGNAL("aboutToQuit()"), quitting) qapp.exec_() tb = None #to clean up Qt widgets
def main(): parser = OptionParser(option_class=eng_option, conflict_handler="resolve") expert_grp = parser.add_option_group("Expert") parser.add_option( "-m", "--modulation", type="choice", choices=['bpsk', 'qpsk'], default='bpsk', help="Select modulation from: bpsk, qpsk [default=%%default]") parser.add_option("-v", "--verbose", action="store_true", default=False) expert_grp.add_option( "-c", "--carrier-threshold", type="eng_float", default=30, help="set carrier detect threshold (dB) [default=%default]") expert_grp.add_option("", "--tun-device-filename", default="/dev/net/tun", help="path to tun device file [default=%default]") usrp_graph.add_options(parser, expert_grp) transmit_path.add_options(parser, expert_grp) receive_path.add_options(parser, expert_grp) blks2.ofdm_mod.add_options(parser, expert_grp) blks2.ofdm_demod.add_options(parser, expert_grp) fusb_options.add_options(expert_grp) (options, args) = parser.parse_args() if len(args) != 0: parser.print_help(sys.stderr) sys.exit(1) if options.rx_freq is None or options.tx_freq is None: sys.stderr.write("You must specify -f FREQ or --freq FREQ\n") parser.print_help(sys.stderr) sys.exit(1) # open the TUN/TAP interface (tun_fd, tun_ifname) = open_tun_interface(options.tun_device_filename) # Attempt to enable realtime scheduling r = gr.enable_realtime_scheduling() if r == gr.RT_OK: realtime = True else: realtime = False print "Note: failed to enable realtime scheduling" # If the user hasn't set the fusb_* parameters on the command line, # pick some values that will reduce latency. if options.fusb_block_size == 0 and options.fusb_nblocks == 0: if realtime: # be more aggressive options.fusb_block_size = gr.prefs().get_long( 'fusb', 'rt_block_size', 1024) options.fusb_nblocks = gr.prefs().get_long('fusb', 'rt_nblocks', 16) else: options.fusb_block_size = gr.prefs().get_long( 'fusb', 'block_size', 4096) options.fusb_nblocks = gr.prefs().get_long('fusb', 'nblocks', 16) #print "fusb_block_size =", options.fusb_block_size #print "fusb_nblocks =", options.fusb_nblocks # instantiate the MAC mac = cs_mac(tun_fd, verbose=True) # build the graph (PHY) tb = usrp_graph(mac.phy_rx_callback, options) mac.set_flow_graph(tb) # give the MAC a handle for the PHY #if fg.txpath.bitrate() != fg.rxpath.bitrate(): # print "WARNING: Transmit bitrate = %sb/sec, Receive bitrate = %sb/sec" % ( # eng_notation.num_to_str(fg.txpath.bitrate()), # eng_notation.num_to_str(fg.rxpath.bitrate())) print "modulation: %s" % (options.modulation, ) print "freq: %s" % (eng_notation.num_to_str(options.tx_freq)) #print "bitrate: %sb/sec" % (eng_notation.num_to_str(fg.txpath.bitrate()),) #print "samples/symbol: %3d" % (fg.txpath.samples_per_symbol(),) #print "interp: %3d" % (fg.txpath.interp(),) #print "decim: %3d" % (fg.rxpath.decim(),) tb.rxpath.set_carrier_threshold(options.carrier_threshold) print "Carrier sense threshold:", options.carrier_threshold, "dB" print print "Allocated virtual ethernet interface: %s" % (tun_ifname, ) print "You must now use ifconfig to set its IP address. E.g.," print print " $ sudo ifconfig %s 192.168.200.1" % (tun_ifname, ) print print "Be sure to use a different address in the same subnet for each machine." print tb.start() # Start executing the flow graph (runs in separate threads) mac.main_loop() # don't expect this to return... tb.stop() # but if it does, tell flow graph to stop. tb.wait() # wait for it to finish
def get_audio_rate(self): return self.audio_rate def set_audio_rate(self, audio_rate): self.audio_rate = audio_rate self.qtgui_freq_sink_x_0.set_frequency_range(0, self.audio_rate) if __name__ == '__main__': import ctypes import sys if sys.platform.startswith('linux'): try: x11 = ctypes.cdll.LoadLibrary('libX11.so') x11.XInitThreads() except: print "Warning: failed to XInitThreads()" parser = OptionParser(option_class=eng_option, usage="%prog: [options]") (options, args) = parser.parse_args() if(StrictVersion(Qt.qVersion()) >= StrictVersion("4.5.0")): Qt.QApplication.setGraphicsSystem(gr.prefs().get_string('qtgui','style','raster')) qapp = Qt.QApplication(sys.argv) tb = top_block() tb.start() tb.show() def quitting(): tb.stop() tb.wait() qapp.connect(qapp, Qt.SIGNAL("aboutToQuit()"), quitting) qapp.exec_() tb = None #to clean up Qt widgets
################################################## import common import numpy import wx import pubsub from constants import * from gnuradio import gr #for gr.prefs import forms ################################################## # Constants ################################################## NEG_INF = float('-inf') SLIDER_STEPS = 100 AVG_ALPHA_MIN_EXP, AVG_ALPHA_MAX_EXP = -3, 0 DEFAULT_NUMBER_RATE = gr.prefs().get_long('wxgui', 'number_rate', 5) DEFAULT_WIN_SIZE = (300, 300) DEFAULT_GAUGE_RANGE = 1000 VALUE_REPR_KEY = 'value_repr' VALUE_REAL_KEY = 'value_real' VALUE_IMAG_KEY = 'value_imag' ################################################## # Number window control panel ################################################## class control_panel(wx.Panel): """ A control panel with wx widgits to control the averaging. """ def __init__(self, parent):