简体   繁体   中英

Develop in GNU Radio Companion; call top block's methods in separate Python file

I would like to...

  • Make a flowgraph in GNU Radio Companion
  • Call methods from a separate Python file

For example, let's say I want to scan through center frequencies in this flowgraph:

Osmocom source --> NBFM Receive --> Audio sink

I'm guessing that Message Passing would allow me to set the osmocom's center freq programmatically, but it would be easier (I think...?) to do something like this in Python:

freqs = [100e6, 101e6]
for freq in freqs:
    set_center_freq(freq)

What do you suggest? ( I'm answering my own question, but I'm curious if others have suggested improvements! 🙂 )

You can import the top block from the Python file generated by GRC. That way, when the file is regenerated, you don't lose your changes.

from my_generated_FM_receiver import my_generated_FM_receiver

tb = my_generated_FM_receiver()

There's a little more setup to be done to run the flowgraph. (See here , lines 103-128, starting with def main(top_block_cls... ).

If you want to access the tb variable, you can create a thread and pass tb as an argument, like so (this code is identical to the usual generated code except for the two added lines near the end):



from threading import Thread


def set_up_qt_top_block_and_run_func_in_thread(top_block_cls, func_to_run):

    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 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)

    #######################
    ## this is my addition
    ##
    thread = Thread(target = func_to_run, args = (tb, ), daemon=True)
    thread.start()
    ## end my addition
    #######################
    qapp.exec_()
    

Here's how you could use it:


# This is your GRC-generated Python module
from my_generated_FM_receiver import my_generated_FM_receiver


def runMe(tb):
    freqs = [100e6, 101e6]
    for freq in freqs:
        tb.osmosdr_source_0.set_center_freq(freq)

set_up_qt_top_block_and_run_func_in_thread(my_generated_FM_receiver, runMe)

PS: In GRC 3.9+, the Python Snippit may be better.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM