Example #1
0
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')
    # NOTE: This sets the log level to what was requested for the logger on the
    # command line, but this may not be the correct approach if multiple handlers
    # are intended to be used. The logger level shown here indicates all the log
    # messages that are captured and the handler levels indicate messages each
    # handler will output. A better approach may be resetting this to logging.DEBUG
    # to catch everything and making sure the handlers have the correct levels set.
    # This would be useful for a future GUI logging window that can filter messages
    # independently of the console output. In this case, this should be DEBUG.
    log.setLevel(LOG_LEVELS[args.log])

    # 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())
Example #2
0
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()

    try:
        Gtk.window_set_default_icon(Gtk.IconTheme().load_icon(
            'gnuradio-grc', 256, 0))
    except:
        pass

    # 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())
Example #3
0
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.INFO)

    # 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 __init__(self):
        """
        Make a platform for gnuradio.
        """
        #ensure hier dir
        if not os.path.exists(HIER_BLOCKS_LIB_DIR):
            os.mkdir(HIER_BLOCKS_LIB_DIR)
        # Convert block paths to absolute paths:
        # - Create a mapping from the absolute path to what was passed in
        # - Keep each unique absolute path and maintain order
        block_paths = OrderedDict(
            map(lambda x: (os.path.abspath(x), x), BLOCKS_DIRS))
        #init
        _Platform.__init__(
            self,
            name='GNU Radio Companion',
            version=gr.version(),
            key='grc',
            license=__doc__.strip(),
            website=
            'http://gnuradio.org/redmine/wiki/gnuradio/GNURadioCompanion',
            block_paths=block_paths,
            block_dtd=BLOCK_DTD,
            default_flow_graph=DEFAULT_FLOW_GRAPH,
            generator=Generator,
            colors=COLORS,
        )

        _GUIPlatform.__init__(self, prefs_file=PREFS_FILE)
Example #5
0
def grc_to_py(grcfile, outdir):
    platform = Platform(prefs_file=gr.prefs(),
                        version=gr.version(),
                        version_parts=(gr.major_version(), gr.api_version(),
                                       gr.minor_version()))
    data = platform.parse_flow_graph(grcfile)

    # Clean out the QT GUI, etc.
    blocks = data['flow_graph']['block']
    for b in blocks:
        if b['key'] == 'options':
            for opt in b['param']:
                if opt['key'] == 'generate_options' and opt[
                        'value'] != 'no_gui':
                    opt['value'] = 'no_gui'
                elif opt['key'] == 'run_options' and opt['value'] != 'run':
                    opt['value'] = 'run'
                elif opt['key'] == 'run' and opt['value'] != 'False':
                    opt['value'] = 'False'

    fg = platform.get_new_flow_graph()
    fg.import_data(data)
    fg.grc_file_path = os.path.abspath(grcfile)
    fg.validate()

    if not fg.is_valid():
        raise StandardError("\n\n".join(["Validation failed:"] +
                                        fg.get_error_messages()))

    if outdir[-1] != '/':
        outdir += '/'
    gen = platform.Generator(fg, outdir)
    gen.write()
Example #6
0
    def __init__(self):
        """
        Make a platform for gnuradio.
        """
        #ensure hier dir
        if not os.path.exists(HIER_BLOCKS_LIB_DIR): os.mkdir(HIER_BLOCKS_LIB_DIR)
        #init
        _Platform.__init__(
            self,
            name='GNU Radio Companion',
            version=(gr.version(), gr.major_version(), gr.api_version(), gr.minor_version()),
            key='grc',
            license=__doc__.strip(),
            website='http://gnuradio.org/',
            block_paths=BLOCKS_DIRS,
            block_dtd=BLOCK_DTD,
            default_flow_graph=DEFAULT_FLOW_GRAPH,
            generator=Generator,
            colors=COLORS,
        )

        _GUIPlatform.__init__(
            self,
            prefs_file=PREFS_FILE
        )
Example #7
0
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)
Example #8
0
    def __init__(self):
        """
		Make a platform for gnuradio.
		"""
        #ensure hier dir
        if not os.path.exists(HIER_BLOCKS_LIB_DIR):
            os.mkdir(HIER_BLOCKS_LIB_DIR)
        #convert block paths to absolute paths
        block_paths = set(map(os.path.abspath, BLOCKS_DIRS))
        #init
        _Platform.__init__(
            self,
            name='GNU Radio Companion',
            version=gr.version(),
            key='grc',
            license=__doc__.strip(),
            website=
            'http://gnuradio.org/redmine/wiki/gnuradio/GNURadioCompanion',
            block_paths=block_paths,
            block_dtd=BLOCK_DTD,
            default_flow_graph=DEFAULT_FLOW_GRAPH,
            generator=Generator,
            colors=COLORS,
        )
        _GUIPlatform.__init__(self)
Example #9
0
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()

    output_dir = args.output if not args.user_lib_dir else platform.config.hier_block_lib_dir
    try:
        # recursive mkdir: os.makedirs doesn't work with .. paths, resolve with realpath
        os.makedirs(os.path.realpath(output_dir), exist_ok=True)
    except Exception as e:
        exit(str(e))

    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(output_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)
Example #10
0
    def __init__(self):
        """
        Make a platform for gnuradio.
        """
        # ensure hier and conf directories
        if not os.path.exists(HIER_BLOCKS_LIB_DIR):
            os.mkdir(HIER_BLOCKS_LIB_DIR)
        if not os.path.exists(os.path.dirname(PREFS_FILE)):
            os.mkdir(os.path.dirname(PREFS_FILE))

        self.block_docstrings = {}
        self.block_docstrings_loaded_callback = lambda: None  # dummy to be replaced by BlockTreeWindow

        self._docstring_extractor = extract_docs.SubprocessLoader(
            callback_query_result=self._save_docstring_extraction_result,
            callback_finished=lambda: self.block_docstrings_loaded_callback())

        # init
        _Platform.__init__(
            self,
            name='GNU Radio Companion',
            version=(gr.version(), gr.major_version(), gr.api_version(),
                     gr.minor_version()),
            key='grc',
            license=__doc__.strip(),
            website='http://gnuradio.org/',
            block_paths=BLOCKS_DIRS,
            block_dtd=BLOCK_DTD,
            default_flow_graph=DEFAULT_FLOW_GRAPH,
            generator=Generator,
            colors=[(name, color) for name, key, sizeof, color in CORE_TYPES],
        )
        self._move_old_pref_file()
        _GUIPlatform.__init__(self, prefs_file=PREFS_FILE)
        self._auto_hier_block_generate_chain = set()
Example #11
0
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)
Example #12
0
    def __init__(self):
        """
        Make a platform for gnuradio.
        """
        #ensure hier dir
        if not os.path.exists(HIER_BLOCKS_LIB_DIR): os.mkdir(HIER_BLOCKS_LIB_DIR)
        # Convert block paths to absolute paths:
        # - Create a mapping from the absolute path to what was passed in
        # - Keep each unique absolute path and maintain order
        block_paths = OrderedDict(map(lambda x: (os.path.abspath(x), x), BLOCKS_DIRS))
        #init
        _Platform.__init__(
            self,
            name='GNU Radio Companion',
            version=gr.version(),
            key='grc',
            license=__doc__.strip(),
            website='http://gnuradio.org/redmine/wiki/gnuradio/GNURadioCompanion',
            block_paths=block_paths,
            block_dtd=BLOCK_DTD,
            default_flow_graph=DEFAULT_FLOW_GRAPH,
            generator=Generator,
            colors=COLORS,
        )

        _GUIPlatform.__init__(
            self,
            prefs_file=PREFS_FILE
        )
Example #13
0
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())
Example #14
0
    def __init__(self, ppm=0, osr=4, fc=940e6, samp_rate_in=1e6):
        grgsm.hier_block.__init__(
            self,
            "GSM input adaptor",
            gr.io_signature(1, 1, gr.sizeof_gr_complex * 1),
            gr.io_signature(1, 1, gr.sizeof_gr_complex * 1),
        )

        ##################################################
        # Parameters
        ##################################################
        self.ppm = ppm
        self.osr = osr
        self.fc = fc
        self.samp_rate_in = samp_rate_in

        ##################################################
        # Variables
        ##################################################
        self.samp_rate_out = samp_rate_out = 1625000.0 / 6.0 * osr

        ##################################################
        # Blocks
        ##################################################
        if version(gr.version()) >= version('3.7.9'):
            self.message_port_register_hier_in("ppm_in")
        else:
            self.message_port_register_hier_out("ppm_in")

        self.low_pass_filter_0_0 = filter.fir_filter_ccf(
            1,
            firdes.low_pass(1, samp_rate_out, 125e3, 5e3, firdes.WIN_HAMMING,
                            6.76))
        self.gsm_clock_offset_corrector_0 = grgsm.clock_offset_corrector(
            fc=fc,
            ppm=ppm,
            samp_rate_in=samp_rate_in,
        )
        self.fractional_resampler_xx_0 = filter.fractional_resampler_cc(
            0, samp_rate_in / samp_rate_out)

        ##################################################
        # Connections
        ##################################################
        self.connect((self.low_pass_filter_0_0, 0), (self, 0))
        self.connect((self.fractional_resampler_xx_0, 0),
                     (self.low_pass_filter_0_0, 0))
        self.connect((self.gsm_clock_offset_corrector_0, 0),
                     (self.fractional_resampler_xx_0, 0))
        self.connect((self, 0), (self.gsm_clock_offset_corrector_0, 0))

        ##################################################
        # Asynch Message Connections
        ##################################################
        self.msg_connect(self, "ppm_in", self.gsm_clock_offset_corrector_0,
                         "ppm_in")
Example #15
0
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()
Example #16
0
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__(self, fc=936.6e6, ppm=0, samp_rate_in=1625000.0/6.0*4.0):
        gr.hier_block2.__init__(
            self, "Clock offset corrector",
            gr.io_signature(1, 1, gr.sizeof_gr_complex*1),
            gr.io_signature(1, 1, gr.sizeof_gr_complex*1),
        )
        if version(gr.version()) >= version('3.7.9'):
            self.message_port_register_hier_in("ppm_in")
        else:
            self.message_port_register_hier_out("ppm_in")

        ##################################################
        # Parameters
        ##################################################
        self.fc = fc
        self.ppm = ppm
        self.samp_rate_in = samp_rate_in

        ##################################################
        # Variables
        ##################################################
        self.samp_rate_out = samp_rate_out = samp_rate_in

        ##################################################
        # Blocks
        ##################################################
        self.gsm_controlled_rotator_cc_0 = grgsm.controlled_rotator_cc(0,samp_rate_out)
        self.gsm_controlled_const_source_f_0 = grgsm.controlled_const_source_f(ppm)
        self.fractional_resampler_xx_0 = filter.fractional_resampler_cc(0, samp_rate_in/samp_rate_out)
        self.blocks_multiply_const_vxx_0_0 = blocks.multiply_const_vff((1.0e-6*samp_rate_in/samp_rate_out, ))
        self.blocks_multiply_const_vxx_0 = blocks.multiply_const_vff((fc/samp_rate_out*(2*math.pi)/1e6, ))
        self.blocks_add_const_vxx_0 = blocks.add_const_vff((samp_rate_in/samp_rate_out, ))

        ##################################################
        # Connections
        ##################################################
        self.connect((self, 0), (self.fractional_resampler_xx_0, 0))
        self.connect((self.fractional_resampler_xx_0, 0), (self.gsm_controlled_rotator_cc_0, 0))
        self.connect((self.blocks_add_const_vxx_0, 0), (self.fractional_resampler_xx_0, 1))
        self.connect((self.blocks_multiply_const_vxx_0_0, 0), (self.blocks_add_const_vxx_0, 0))
        self.connect((self.blocks_multiply_const_vxx_0, 0), (self.gsm_controlled_rotator_cc_0, 1))
        self.connect((self.gsm_controlled_rotator_cc_0, 0), (self, 0))
        self.connect((self.gsm_controlled_const_source_f_0, 0), (self.blocks_multiply_const_vxx_0_0, 0))
        self.connect((self.gsm_controlled_const_source_f_0, 0), (self.blocks_multiply_const_vxx_0, 0))

        ##################################################
        # Asynch Message Connections
        ##################################################
        self.msg_connect(self, "ppm_in", self.gsm_controlled_const_source_f_0, "constant_msg")
Example #18
0
    def __init__(self, ppm=0, osr=4, fc=940e6, samp_rate_in=1e6):
        gr.hier_block2.__init__(
            self, "GSM input adaptor",
            gr.io_signature(1, 1, gr.sizeof_gr_complex*1),
            gr.io_signature(1, 1, gr.sizeof_gr_complex*1),
        )

        ##################################################
        # Parameters
        ##################################################
        self.ppm = ppm
        self.osr = osr
        self.fc = fc
        self.samp_rate_in = samp_rate_in

        ##################################################
        # Variables
        ##################################################
        self.samp_rate_out = samp_rate_out = 1625000.0/6.0*osr

        ##################################################
        # Blocks
        ##################################################
        if version(gr.version()) >= version('3.7.9'):
            self.message_port_register_hier_in("ppm_in")
        else:
            self.message_port_register_hier_out("ppm_in")

        self.low_pass_filter_0_0 = filter.fir_filter_ccf(1, firdes.low_pass(
        	1, samp_rate_out, 125e3, 5e3, firdes.WIN_HAMMING, 6.76))
        self.gsm_clock_offset_corrector_0 = grgsm.clock_offset_corrector(
            fc=fc,
            ppm=ppm,
            samp_rate_in=samp_rate_in,
        )
        self.fractional_resampler_xx_0 = filter.fractional_resampler_cc(0, samp_rate_in/samp_rate_out)

        ##################################################
        # Connections
        ##################################################
        self.connect((self.low_pass_filter_0_0, 0), (self, 0))
        self.connect((self.fractional_resampler_xx_0, 0), (self.low_pass_filter_0_0, 0))
        self.connect((self.gsm_clock_offset_corrector_0, 0), (self.fractional_resampler_xx_0, 0))
        self.connect((self, 0), (self.gsm_clock_offset_corrector_0, 0))

        ##################################################
        # Asynch Message Connections
        ##################################################
        self.msg_connect(self, "ppm_in", self.gsm_clock_offset_corrector_0, "ppm_in")
Example #19
0
    def __init__(self):
        """
        Make a platform for gnuradio.
        """
        # ensure hier and conf directories
        if not os.path.exists(HIER_BLOCKS_LIB_DIR):
            os.mkdir(HIER_BLOCKS_LIB_DIR)
        if not os.path.exists(os.path.dirname(PREFS_FILE)):
            os.mkdir(os.path.dirname(PREFS_FILE))

        self.block_docstrings = block_docstrings = dict()
        self.block_docstrings_loaded_callback = lambda: None

        def setter(key, docs):
            block_docstrings[key] = '\n\n'.join(
                '--- {0} ---\n{1}\n'.format(b, d.replace('\n\n', '\n'))
                for b, d in docs.iteritems() if d is not None
            )

        self._docstring_extractor = extract_docs.SubprocessLoader(
            callback_query_result=setter,
            callback_finished=lambda: self.block_docstrings_loaded_callback()
        )

        # init
        _Platform.__init__(
            self,
            name='GNU Radio Companion',
            version=(gr.version(), gr.major_version(), gr.api_version(), gr.minor_version()),
            key='grc',
            license=__doc__.strip(),
            website='http://gnuradio.org/',
            block_paths=BLOCKS_DIRS,
            block_dtd=BLOCK_DTD,
            default_flow_graph=DEFAULT_FLOW_GRAPH,
            generator=Generator,
            colors=COLORS,
        )
        self._move_old_pref_file()
        _GUIPlatform.__init__(
            self,
            prefs_file=PREFS_FILE
        )
        self._auto_hier_block_generate_chain = set()
Example #20
0
    def __init__(self):
        """
        Make a platform for gnuradio.
        """
        # ensure hier and conf directories
        if not os.path.exists(HIER_BLOCKS_LIB_DIR):
            os.mkdir(HIER_BLOCKS_LIB_DIR)
        if not os.path.exists(os.path.dirname(PREFS_FILE)):
            os.mkdir(os.path.dirname(PREFS_FILE))

        self.block_docstrings = block_docstrings = dict()
        self.block_docstrings_loaded_callback = lambda: None

        def setter(key, docs):
            block_docstrings[key] = '\n\n'.join(
                '--- {0} ---\n{1}\n'.format(b, d.replace('\n\n', '\n'))
                for b, d in docs.iteritems() if d is not None)

        self._docstring_extractor = extract_docs.SubprocessLoader(
            callback_query_result=setter,
            callback_finished=lambda: self.block_docstrings_loaded_callback())

        # init
        _Platform.__init__(
            self,
            name='GNU Radio Companion',
            version=(gr.version(), gr.major_version(), gr.api_version(),
                     gr.minor_version()),
            key='grc',
            license=__doc__.strip(),
            website='http://gnuradio.org/',
            block_paths=BLOCKS_DIRS,
            block_dtd=BLOCK_DTD,
            default_flow_graph=DEFAULT_FLOW_GRAPH,
            generator=Generator,
            colors=COLORS,
        )
        self._move_old_pref_file()
        _GUIPlatform.__init__(self, prefs_file=PREFS_FILE)
        self._auto_hier_block_generate_chain = set()
Example #21
0
    def __init__(self):
        """
        Make a platform for gnuradio.
        """
        # ensure hier and conf directories
        if not os.path.exists(HIER_BLOCKS_LIB_DIR):
            os.mkdir(HIER_BLOCKS_LIB_DIR)
        if not os.path.exists(os.path.dirname(PREFS_FILE)):
            os.mkdir(os.path.dirname(PREFS_FILE))

        self.block_docstrings = {}
        self.block_docstrings_loaded_callback = lambda: None  # dummy to be replaced by BlockTreeWindow

        self._docstring_extractor = extract_docs.SubprocessLoader(
            callback_query_result=self._save_docstring_extraction_result,
            callback_finished=lambda: self.block_docstrings_loaded_callback()
        )

        # init
        _Platform.__init__(
            self,
            name='GNU Radio Companion',
            version=(gr.version(), gr.major_version(), gr.api_version(), gr.minor_version()),
            key='grc',
            license=__doc__.strip(),
            website='http://gnuradio.org/',
            block_paths=BLOCKS_DIRS,
            block_dtd=BLOCK_DTD,
            default_flow_graph=DEFAULT_FLOW_GRAPH,
            generator=Generator,
            colors=[(name, color) for name, key, sizeof, color in CORE_TYPES],
        )
        self._move_old_pref_file()
        _GUIPlatform.__init__(
            self,
            prefs_file=PREFS_FILE
        )
        self._auto_hier_block_generate_chain = set()
Example #22
0
 def __init__(self):
     """
     Make a platform for gnuradio.
     """
     #ensure hier dir
     if not os.path.exists(HIER_BLOCKS_LIB_DIR): os.mkdir(HIER_BLOCKS_LIB_DIR)
     #convert block paths to absolute paths
     block_paths = set(map(os.path.abspath, BLOCKS_DIRS))
     #init
     _Platform.__init__(
         self,
         name='GNU Radio Companion',
         version=gr.version(),
         key='grc',
         license=__doc__.strip(),
         website='http://gnuradio.org/redmine/wiki/gnuradio/GNURadioCompanion',
         block_paths=block_paths,
         block_dtd=BLOCK_DTD,
         default_flow_graph=DEFAULT_FLOW_GRAPH,
         generator=Generator,
         colors=COLORS,
     )
     _GUIPlatform.__init__(self)
Example #23
0
    def __init__(self, fc=936.6e6, ppm=0, samp_rate_in=1625000.0 / 6.0 * 4.0):
        gr.hier_block2.__init__(
            self,
            "Clock offset corrector",
            gr.io_signature(1, 1, gr.sizeof_gr_complex * 1),
            gr.io_signature(1, 1, gr.sizeof_gr_complex * 1),
        )
        if version(gr.version()) >= version('3.7.9'):
            self.message_port_register_hier_in("ppm_in")
        else:
            self.message_port_register_hier_out("ppm_in")

        ##################################################
        # Parameters
        ##################################################
        self.fc = fc
        self.ppm = ppm
        self.samp_rate_in = samp_rate_in

        ##################################################
        # Variables
        ##################################################
        self.samp_rate_out = samp_rate_out = samp_rate_in

        ##################################################
        # Blocks
        ##################################################
        self.gsm_controlled_rotator_cc_0 = grgsm.controlled_rotator_cc(
            0, samp_rate_out)
        self.gsm_controlled_const_source_f_0 = grgsm.controlled_const_source_f(
            ppm)
        self.fractional_resampler_xx_0 = filter.fractional_resampler_cc(
            0, samp_rate_in / samp_rate_out)
        self.blocks_multiply_const_vxx_0_0 = blocks.multiply_const_vff(
            (1.0e-6 * samp_rate_in / samp_rate_out, ))
        self.blocks_multiply_const_vxx_0 = blocks.multiply_const_vff(
            (fc / samp_rate_out * (2 * math.pi) / 1e6, ))
        self.blocks_add_const_vxx_0 = blocks.add_const_vff(
            (samp_rate_in / samp_rate_out, ))

        ##################################################
        # Connections
        ##################################################
        self.connect((self, 0), (self.fractional_resampler_xx_0, 0))
        self.connect((self.fractional_resampler_xx_0, 0),
                     (self.gsm_controlled_rotator_cc_0, 0))
        self.connect((self.blocks_add_const_vxx_0, 0),
                     (self.fractional_resampler_xx_0, 1))
        self.connect((self.blocks_multiply_const_vxx_0_0, 0),
                     (self.blocks_add_const_vxx_0, 0))
        self.connect((self.blocks_multiply_const_vxx_0, 0),
                     (self.gsm_controlled_rotator_cc_0, 1))
        self.connect((self.gsm_controlled_rotator_cc_0, 0), (self, 0))
        self.connect((self.gsm_controlled_const_source_f_0, 0),
                     (self.blocks_multiply_const_vxx_0_0, 0))
        self.connect((self.gsm_controlled_const_source_f_0, 0),
                     (self.blocks_multiply_const_vxx_0, 0))

        ##################################################
        # Asynch Message Connections
        ##################################################
        self.msg_connect(self, "ppm_in", self.gsm_controlled_const_source_f_0,
                         "constant_msg")
    import pathlib
    import tempfile
    import threading

    import gi

    gi.require_version("Gtk", "3.0")
    gi.require_version("PangoCairo", "1.0")
    from gi.repository import GLib
    from gnuradio import gr
    from gnuradio.grc.gui.Platform import Platform
    from gnuradio.grc.gui.Application import Actions, Application

    # include the necessary boilerplate from grc's main function to create the app
    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()

    # pick an example that runs a bunch of qt-gui sinks
    example_grc_path = (pathlib.Path(gr.prefix()) / "share" / "gnuradio" /
                        "examples" / "qt-gui" / "qtgui_multi_input.grc")
    app = Application((example_grc_path, ), platform)

    # script what we want to try out with the app
    def script(app):
        # ensure the app is initialized before proceeding
Example #25
0
    def __init__(
        self,
        channel_dir,
        dtype,
        subdir_cadence_secs,
        file_cadence_millisecs,
        sample_rate_numerator,
        sample_rate_denominator,
        start=None,
        ignore_tags=False,
        is_complex=True,
        num_subchannels=1,
        uuid_str=None,
        center_frequencies=None,
        metadata=None,
        is_continuous=True,
        compression_level=0,
        checksum=False,
        marching_periods=True,
        stop_on_skipped=False,
        stop_on_time_tag=False,
        debug=False,
        min_chunksize=None,
    ):
        """Write a channel of data in Digital RF format.

        In addition to storing the input samples in Digital RF format, this
        block also populates the channel's accompanying Digital Metadata
        at the sample indices when the metadata changes or a data skip occurs.
        See the Notes section for details on what metadata is stored.

        Parameters
        ----------
        channel_dir : string
            The directory where this channel is to be written. It will be
            created if it does not exist. The basename (last component) of the
            path is considered the channel's name for reading purposes.

        dtype : np.dtype | object to be cast by np.dtype()
            Object that gives the numpy dtype of the data to be written. This
            value is passed into ``np.dtype`` to get the actual dtype
            (e.g. ``np.dtype('>i4')``). Scalar types, complex types, and
            structured complex types with 'r' and 'i' fields of scalar types
            are valid.

        subdir_cadence_secs : int
            The number of seconds of data to store in one subdirectory. The
            timestamp of any subdirectory will be an integer multiple of this
            value.

        file_cadence_millisecs : int
            The number of milliseconds of data to store in each file. Note that
            an integer number of files must exactly span a subdirectory,
            implying::

                (subdir_cadence_secs*1000 % file_cadence_millisecs) == 0

        sample_rate_numerator : int
            Numerator of sample rate in Hz.

        sample_rate_denominator : int
            Denominator of sample rate in Hz.


        Other Parameters
        ----------------
        start : None | int | float | string, optional
            A value giving the time/index of the channel's first sample. When
            `ignore_tags` is False, 'rx_time' tags will be used to identify
            data gaps and skip the sample index forward appropriately (tags
            that refer to an earlier time will be ignored).
            If None or '' and `ignore_tags` is False, drop data until an
            'rx_time' tag arrives and sets the start time (a ValueError is
            raised if `ignore_tags` is True).
            If an integer, it is interpreted as a sample index given in the
            number of samples since the epoch (time_since_epoch*sample_rate).
            If a float, it is interpreted as a UTC timestamp (seconds since
            epoch).
            If a string, three forms are permitted:
                1) a string which can be evaluated to an integer/float and
                    interpreted as above,
                2) a time in ISO8601 format, e.g. '2016-01-01T16:24:00Z'
                3) 'now' ('nowish'), indicating the current time (rounded up)

        ignore_tags : bool, optional
            If True, do not use 'rx_time' tags to set the sample index and do
            not write other tags as Digital Metadata.

        is_complex : bool, optional
            This parameter is only used when `dtype` is not complex.
            If True (the default), interpret supplied data as interleaved
            complex I/Q samples. If False, each sample has a single value.

        num_subchannels : int, optional
            Number of subchannels to write simultaneously. Default is 1.

        uuid_str : None | string, optional
            UUID string that will act as a unique identifier for the data and
            can be used to tie the data files to metadata. If None, a random
            UUID will be generated.

        center_frequencies : None | array_like of floats, optional
            List of subchannel center frequencies to include in initial
            metadata. If None, ``[0.0]*num_subchannels`` will be used.
            Subsequent center frequency metadata samples can be written using
            'rx_freq' stream tags.

        metadata : dict, optional
            Dictionary of additional metadata to include in initial Digital
            Metadata sample. Subsequent metadata samples can be written
            using 'metadata' stream tags, but all keys intended to be included
            should be set here first even if their values are empty.

        is_continuous : bool, optional
            If True, data will be written in continuous blocks. If False data
            will be written with gapped blocks. Fastest write/read speed is
            achieved with `is_continuous` True, `checksum` False, and
            `compression_level` 0 (all defaults).

        compression_level : int, optional
            0 for no compression (default), 1-9 for varying levels of gzip
            compression (1 == least compression, least CPU; 9 == most
            compression, most CPU).

        checksum : bool, optional
            If True, use HDF5 checksum capability. If False (default), no
            checksum.

        marching_periods : bool, optional
            If True, write a period to stdout for every subdirectory when
            writing.

        stop_on_skipped : bool, optional
            If True, stop writing when a sample would be skipped (such as from
            a dropped packet).

        stop_on_time_tag : bool, optional
            If True, stop writing when any but an initial 'rx_time' tag is received.

        debug : bool, optional
            If True, print debugging information.

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


        Notes
        -----
        By convention, this block sets the following Digital Metadata fields:

            uuid_str : string
                Value provided by the `uuid_str` argument.

            sample_rate_numerator : int
                Value provided by the `sample_rate_numerator` argument.

            sample_rate_denominator : int
                Value provided by the `sample_rate_denominator` argument.

            center_frequencies : list of floats with length `num_subchannels`
                Subchannel center frequencies as specified by
                `center_frequencies` argument and 'rx_freq' stream tags.

        Additional metadata fields can be set using the `metadata` argument and
        stream tags. Nested dictionaries are permitted and are helpful for
        grouping properties. For example, receiver-specific metadata is
        typically specified with a sub-dictionary using the 'receiver' field.


        This block acts on the following stream tags when `ignore_tags` is
        False:

            rx_time : (int secs, float frac) tuple
                Used to set the sample index from the given time since epoch.

            rx_freq : float
                Used to set the 'center_frequencies' value in the channel's
                Digital Metadata as described above.

            metadata : dict
                Used to populate additional (key, value) pairs in the channel's
                Digital Metadata. Any keys passed in 'metadata' tags should be
                included in the `metadata` argument at initialization to ensure
                that they always exist in the Digital Metadata.

        """
        dtype = np.dtype(dtype)
        # create structured dtype for interleaved samples if necessary
        if is_complex and (not np.issubdtype(dtype, np.complexfloating)
                           and not dtype.names):
            realdtype = dtype
            dtype = np.dtype([("r", realdtype), ("i", realdtype)])

        if num_subchannels == 1:
            in_sig = [dtype]
        else:
            in_sig = [(dtype, num_subchannels)]

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

        self._channel_dir = channel_dir
        self._channel_name = os.path.basename(channel_dir)
        self._dtype = dtype
        self._subdir_cadence_secs = subdir_cadence_secs
        self._file_cadence_millisecs = file_cadence_millisecs
        self._sample_rate_numerator = sample_rate_numerator
        self._sample_rate_denominator = sample_rate_denominator
        self._uuid_str = uuid_str
        self._ignore_tags = ignore_tags
        self._is_complex = is_complex
        self._num_subchannels = num_subchannels
        self._is_continuous = is_continuous
        self._compression_level = compression_level
        self._checksum = checksum
        self._marching_periods = marching_periods
        self._stop_on_skipped = stop_on_skipped
        self._stop_on_time_tag = stop_on_time_tag
        self._debug = debug

        self._work_done = False

        self._samples_per_second = np.longdouble(
            np.uint64(sample_rate_numerator)) / np.longdouble(
                np.uint64(sample_rate_denominator))

        if min_chunksize is None:
            self._min_chunksize = max(int(self._samples_per_second // 1000), 1)
        else:
            self._min_chunksize = min_chunksize

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

        # will be None if start is None or ''
        self._start_sample = util.parse_identifier_to_sample(
            start, self._samples_per_second, None)
        if self._start_sample is None:
            if self._ignore_tags:
                raise ValueError("Must specify start if ignore_tags is True.")
            # data without a time tag will be written starting at global index
            # of 0, i.e. the Unix epoch
            # we don't want to guess the start time because the user would
            # know better and it could obscure bugs by setting approximately
            # the correct time (samples in 1970 are immediately obvious)
            self._start_sample = 0
        self._next_rel_sample = 0

        # stream tags to read (in addition to rx_time, handled specially)
        if LooseVersion(gr.version()) >= LooseVersion("3.7.12"):
            self._stream_tag_translators = {
                # disable rx_freq until we figure out what to do with polyphase
                # pmt.intern('rx_freq'): translate_rx_freq,
                pmt.intern("metadata"):
                translate_metadata
            }
        else:
            # USRP source in gnuradio < 3.7.12 has bad rx_freq tags, so avoid
            # trouble by ignoring rx_freq tags for those gnuradio versions
            self._stream_tag_translators = {
                pmt.intern("metadata"): translate_metadata
            }

        # create metadata dictionary that will be updated and written whenever
        # new metadata is received in stream tags
        if metadata is None:
            metadata = {}
        self._metadata = metadata.copy()
        if center_frequencies is None:
            center_frequencies = np.array([0.0] * self._num_subchannels)
        else:
            center_frequencies = np.ascontiguousarray(center_frequencies)
        self._metadata.update(
            # standard metadata by convention
            uuid_str="",
            sample_rate_numerator=self._sample_rate_numerator,
            sample_rate_denominator=self._sample_rate_denominator,
            center_frequencies=center_frequencies,
        )

        # create directories for RF data channel and metadata
        self._metadata_dir = os.path.join(self._channel_dir, "metadata")
        if not os.path.exists(self._metadata_dir):
            os.makedirs(self._metadata_dir)

        # sets self._Writer, self._DMDWriter, and adds to self._metadata
        self._create_writer()

        # dict of metadata samples to be written, add for first sample
        # keys: absolute sample index for metadata
        # values: metadata dictionary to update self._metadata and then write
        self._md_queue = defaultdict(dict)
        self._md_queue[self._start_sample] = {}
# Benchmark runner

if __name__ == '__main__':
    # If a test name was specified, filter the benchmark suite by fuzzy-matching
    # by test name
    if len(sys.argv) > 1:
        MatchedBenchmarkSuite = []

        for benchmark in BenchmarkSuite:
            if benchmark[0].lower().find(sys.argv[1].lower()) >= 0:
                MatchedBenchmarkSuite.append(benchmark)

        BenchmarkSuite = MatchedBenchmarkSuite

    benchmark_results = {
        'version': gr.version(),
        'parameters': {
            'num_trials': BENCH_NUM_TRIALS,
            'trial_duration': BENCH_TRIAL_DURATION
        },
        'benchmarks': []
    }

    for index, benchmark in enumerate(BenchmarkSuite):
        test_name, block_name, test_factory = benchmark

        sys.stderr.write("Running benchmark {}/{} \"{}\"\n".format(index+1, len(BenchmarkSuite), test_name))

        samples_per_second, bytes_per_second = [], []

        # Run each trial
Example #27
0
 def message_port_register_hier_in(self, port_id):
     if version(gr.version()) >= version('3.7.9'):
         super(hier_block, self).message_port_register_hier_in(port_id)
     else:
         super(hier_block, self).message_port_register_hier_out(port_id)
Example #28
0
# Benchmark runner

if __name__ == '__main__':
    # If a test name was specified, filter the benchmark suite by fuzzy-matching
    # by test name
    if len(sys.argv) > 1:
        MatchedBenchmarkSuite = []

        for benchmark in BenchmarkSuite:
            if benchmark[0].lower().find(sys.argv[1].lower()) >= 0:
                MatchedBenchmarkSuite.append(benchmark)

        BenchmarkSuite = MatchedBenchmarkSuite

    benchmark_results = {
        'version': gr.version(),
        'parameters': {
            'num_trials': BENCH_NUM_TRIALS,
            'trial_duration': BENCH_TRIAL_DURATION
        },
        'benchmarks': []
    }

    for index, benchmark in enumerate(BenchmarkSuite):
        test_name, block_name, test_factory = benchmark

        sys.stderr.write("Running benchmark {}/{} \"{}\"\n".format(index+1, len(BenchmarkSuite), test_name))

        samples_per_second, bytes_per_second = [], []

        # Run each trial
Example #29
0
from gnuradio import gr
gr.version()
Example #30
0
 def message_port_register_hier_out(self, port_id):
     if version(gr.version()) >= version('3.7.9'):
         super(hier_block, self).message_port_register_hier_out(port_id)
     else:
         super(hier_block, self).message_port_register_hier_in(port_id)