GNU Radio Companion (GRC) generates Python code that is something like this (not exact text). (Make sure you chose the "No GUI" option in GRC.)
class my_block(gr.top_block):
# ...
def main():
tb = my_block()
tb.run()
if __name__ == '__main__':
main()
You can just import
this as a module in your Python program (the if __name__
check will skip running the code that wouldn't be appropriate). Once you've done that, the way you use it is to just create the top block and call tb.start()
. This will start the flow graph without also waiting for it to finish, which is exactly what you want when you have a separate main loop like a web server.
import my_block
tb = my_block.my_block()
tb.start()
When you're shutting down, do this to stop the GNU Radio threads:
tb.stop()
tb.wait()
Then you can also use the generated methods (a getter and setter per GRC "Variable") to change parameters while the flow graph is running. For example, if you have a "Variable" block in GRC with ID freq
, then you can use freq
in other blocks' parameters, and GRC will generate a getter and setter method like this:
def get_freq(self):
return self.freq
def set_freq(self, freq):
self.freq = freq
self.freq_xlating_fir_filter_xxx_0.set_center_freq(self.freq)
And so from your controlling application, you call these methods, like tb.set_freq(123e6)
to change the frequency to 123 MHz, for example.
There's a lot more that can be said about how to go beyond what GRC generates for you (which would best be asked as separate questions), but this is how you get started with integrating a GNU Radio flow graph into a larger program.
I would recommend expecting to eventually stop using GRC's code generation and write your own Python code. This is because GRC has quite a few limitations in what you can do with it — for example, if you want to decide at runtime which type of signal source block to create, you can't do that in GRC but it's easy when you write your own Python. You can always use GRC to generate examples to copy from, when you're unsure how to configure a block.