Difference between revisions of "Guided Tutorial GNU Radio in Python"

From GNU Radio
Jump to: navigation, search
(remove link)
 
(41 intermediate revisions by 7 users not shown)
Line 1: Line 1:
<. [[Guided_Tutorial_GRC|Previous: Working with GRC]]
+
[[Category:Guided Tutorials]]
>. [[Guided_Tutorial_GNU_Radio_in_C++|Next: Programming GNU Radio in C++]]
 
  
 
+
== <b>NOTE:</b> This tutorial has been deprecated in GR 3.8. ==
= Tutorial: Working with GNU Radio in Python =
 
  
 
== Objectives ==
 
== Objectives ==
Line 16: Line 14:
 
== Prerequisites ==
 
== Prerequisites ==
  
* Working Installation of GNU Radio 3.7.4 or later
+
* Working Installation of GNU Radio 3.7
 
* [[Guided_Tutorial_GRC|GRC Tutorial]] (Recommended)
 
* [[Guided_Tutorial_GRC|GRC Tutorial]] (Recommended)
 
* Familiar with Python
 
* Familiar with Python
 
  
 
-----
 
-----
Line 25: Line 22:
 
== 3.1. Intro to Using GNU Radio with Python ==
 
== 3.1. Intro to Using GNU Radio with Python ==
  
This tutorial goes through three parts. The first is how to modify, create, or simply understand the Python generated files GRC produces for us. The second is how to create our own custom out-of-tree (OOT) modules from the ground up. Lastly we go through an actual project to get more practice and build intuition on how we can use GNU Radio in our own project. As with the last tutorial, all the content - pictures, source code, and grc files - is included in the [https://github.com/gnuradio/gr-tutorial gr-tutorial repository] which we should have a local copy if we followed the directions from the [http://gnuradio.org/redmine/projects/gnuradio/wiki/NewTutorials2#Part-I-Setting-up-the-Tutorials GRC Tutorial]
+
This tutorial goes through three parts. The first is how to modify, create, or simply understand the Python generated files GRC produces for us. The second is how to create our own custom out-of-tree (OOT) modules from the ground up. Lastly we go through an actual project to get more practice and build intuition on how we can use GNU Radio in our own project. As with the last tutorial, all the content - pictures, source code, and grc files - is included in the [https://github.com/gnuradio/gr-tutorial gr-tutorial repository] which we should have a local copy if we followed the directions from the [[Guided_Tutorial_GRC|GRC Tutorial]]
  
 
Again we should have a directory with the solutions and a directory with our work as below:
 
Again we should have a directory with the solutions and a directory with our work as below:
Line 34: Line 31:
 
/home/user/gnuradio/tutorials/work
 
/home/user/gnuradio/tutorials/work
 
</syntaxhighlight>
 
</syntaxhighlight>
 +
 
As a rule, if we hover over the GRC flowgraph images, we will be able to see the corresponding filename. Same applies for other images. Full code files are collapsed with the filename in the collapsed handle.
 
As a rule, if we hover over the GRC flowgraph images, we will be able to see the corresponding filename. Same applies for other images. Full code files are collapsed with the filename in the collapsed handle.
  
Line 46: Line 44:
  
 
<syntaxhighlight lang="python" line="line">
 
<syntaxhighlight lang="python" line="line">
#!/usr/bin/env Python
+
#!/usr/bin/env python3
##################################################
+
# -*- coding: utf-8 -*-
# Gnuradio Python Flow Graph
+
 
# Title: Tutorial Three
+
#
# Generated: Wed Mar 12 15:35:18 2014
+
# SPDX-License-Identifier: GPL-3.0
##################################################
+
#
 +
# GNU Radio Python Flow Graph
 +
# Title: tutorial_three_1
 +
# GNU Radio version: 3.8.0.0
 +
 
 +
from distutils.version import StrictVersion
 +
 
 +
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()")
  
 
from gnuradio import analog
 
from gnuradio import analog
 
from gnuradio import audio
 
from gnuradio import audio
from gnuradio import eng_notation
 
 
from gnuradio import gr
 
from gnuradio import gr
from gnuradio.eng_option import eng_option
 
 
from gnuradio.filter import firdes
 
from gnuradio.filter import firdes
from optparse import OptionParser
+
import sys
 +
import signal
 +
from PyQt5 import Qt
 +
from argparse import ArgumentParser
 +
from gnuradio.eng_arg import eng_float, intx
 +
from gnuradio import eng_notation
 +
from gnuradio import qtgui
  
class tutorial_three(gr.top_block):
+
class tutorial_three_1(gr.top_block, Qt.QWidget):
  
 
     def __init__(self):
 
     def __init__(self):
         gr.top_block.__init__(self, &quot;Tutorial Three&quot;)
+
         gr.top_block.__init__(self, "tutorial_three_1")
 +
        Qt.QWidget.__init__(self)
 +
        self.setWindowTitle("tutorial_three_1")
 +
        qtgui.util.check_set_qss()
 +
        try:
 +
            self.setWindowIcon(Qt.QIcon.fromTheme('gnuradio-grc'))
 +
        except:
 +
            pass
 +
        self.top_scroll_layout = Qt.QVBoxLayout()
 +
        self.setLayout(self.top_scroll_layout)
 +
        self.top_scroll = Qt.QScrollArea()
 +
        self.top_scroll.setFrameStyle(Qt.QFrame.NoFrame)
 +
        self.top_scroll_layout.addWidget(self.top_scroll)
 +
        self.top_scroll.setWidgetResizable(True)
 +
        self.top_widget = Qt.QWidget()
 +
        self.top_scroll.setWidget(self.top_widget)
 +
        self.top_layout = Qt.QVBoxLayout(self.top_widget)
 +
        self.top_grid_layout = Qt.QGridLayout()
 +
        self.top_layout.addLayout(self.top_grid_layout)
 +
 
 +
        self.settings = Qt.QSettings("GNU Radio", "tutorial_three_1")
 +
 
 +
        try:
 +
            if StrictVersion(Qt.qVersion()) < StrictVersion("5.0.0"):
 +
                self.restoreGeometry(self.settings.value("geometry").toByteArray())
 +
            else:
 +
                self.restoreGeometry(self.settings.value("geometry"))
 +
        except:
 +
            pass
  
 
         ##################################################
 
         ##################################################
Line 74: Line 119:
 
         # Blocks
 
         # Blocks
 
         ##################################################
 
         ##################################################
         self.audio_sink_0 = audio.sink(samp_rate, &quot;&quot;, True)
+
         self.audio_sink_0 = audio.sink(samp_rate, '', True)
         self.analog_sig_source_x_1 = analog.sig_source_f(samp_rate, analog.GR_SIN_WAVE, 350, .1, 0)
+
         self.analog_sig_source_x_1 = analog.sig_source_f(samp_rate, analog.GR_COS_WAVE, 350, 0.1, 0, 0)
         self.analog_sig_source_x_0 = analog.sig_source_f(samp_rate, analog.GR_SIN_WAVE, 440, .1, 0)
+
         self.analog_sig_source_x_0 = analog.sig_source_f(samp_rate, analog.GR_COS_WAVE, 440, 0.1, 0, 0)
 +
 
 +
 
  
 
         ##################################################
 
         ##################################################
 
         # Connections
 
         # Connections
 
         ##################################################
 
         ##################################################
 +
        self.connect((self.analog_sig_source_x_0, 0), (self.audio_sink_0, 0))
 
         self.connect((self.analog_sig_source_x_1, 0), (self.audio_sink_0, 1))
 
         self.connect((self.analog_sig_source_x_1, 0), (self.audio_sink_0, 1))
        self.connect((self.analog_sig_source_x_0, 0), (self.audio_sink_0, 0))
 
  
 
+
    def closeEvent(self, event):
# QT sink close method reimplementation
+
        self.settings = Qt.QSettings("GNU Radio", "tutorial_three_1")
 +
        self.settings.setValue("geometry", self.saveGeometry())
 +
        event.accept()
  
 
     def get_samp_rate(self):
 
     def get_samp_rate(self):
Line 94: Line 143:
 
         self.analog_sig_source_x_0.set_sampling_freq(self.samp_rate)
 
         self.analog_sig_source_x_0.set_sampling_freq(self.samp_rate)
 
         self.analog_sig_source_x_1.set_sampling_freq(self.samp_rate)
 
         self.analog_sig_source_x_1.set_sampling_freq(self.samp_rate)
 +
 +
 +
 +
def main(top_block_cls=tutorial_three_1, 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 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_()
 +
  
 
if __name__ == '__main__':
 
if __name__ == '__main__':
     parser = OptionParser(option_class=eng_option, usage=&quot;%prog: [options]&quot;)
+
     main()
    (options, args) = parser.parse_args()
+
 
    tb = tutorial_three()
 
    tb.start()
 
    raw_input('Press Enter to quit: ')
 
    tb.stop()
 
    tb.wait()
 
 
</syntaxhighlight>
 
</syntaxhighlight>
  
The first thing for us to realize is that the GRC can generate Python files that we can then modify to do things we wouldn't be able to do in GNU Radio Companion such as perform [http://gnuradio.org/redmine/projects/gnuradio/wiki/Simulations simulations]. The libraries available in Python open up a whole new realm of possibilities! For now, we will explore the structure of the GRC Python files so we are comfortable creating more interesting applications.
+
The first thing for us to realize is that the GRC can generate Python files that we can then modify to do things we wouldn't be able to do in GNU Radio Companion such as perform [[TutorialsSimulations|simulations]]. The libraries available in Python open up a whole new realm of possibilities! For now, we will explore the structure of the GRC Python files so we are comfortable creating more interesting applications.
  
 
=== 3.1.2. Hello World Dissected ===
 
=== 3.1.2. Hello World Dissected ===
Line 112: Line 186:
  
 
<syntaxhighlight lang="python" line="line">
 
<syntaxhighlight lang="python" line="line">
#!/usr/bin/env Python
+
#!/usr/bin/env Python3
 
from gnuradio import gr
 
from gnuradio import gr
 
from gnuradio import audio
 
from gnuradio import audio
Line 126: Line 200:
 
         src0 = analog.sig_source_f(sample_rate, analog.GR_SIN_WAVE, 350, ampl)
 
         src0 = analog.sig_source_f(sample_rate, analog.GR_SIN_WAVE, 350, ampl)
 
         src1 = analog.sig_source_f(sample_rate, analog.GR_SIN_WAVE, 440, ampl)
 
         src1 = analog.sig_source_f(sample_rate, analog.GR_SIN_WAVE, 440, ampl)
         dst = audio.sink(sample_rate, &quot;&quot;)
+
         dst = audio.sink(sample_rate, "")
 
         self.connect(src0, (dst, 0))
 
         self.connect(src0, (dst, 0))
 
         self.connect(src1, (dst, 1))
 
         self.connect(src1, (dst, 1))
Line 135: Line 209:
 
     except [[KeyboardInterrupt]]:
 
     except [[KeyboardInterrupt]]:
 
         pass
 
         pass
<\syntaxhighlight>
+
 
 +
</syntaxhighlight>
  
 
Let us examine this line by line:
 
Let us examine this line by line:
  
 
<syntaxhighlight lang="python">
 
<syntaxhighlight lang="python">
#!/usr/bin/env python
+
#!/usr/bin/env python3
<\syntaxhighlight>
+
</syntaxhighlight>
 
Tells the shell that this file is a Python file and to use the Python interpreter to run this file. Should always be included at the top to run from the terminal.
 
Tells the shell that this file is a Python file and to use the Python interpreter to run this file. Should always be included at the top to run from the terminal.
  
Line 148: Line 223:
 
from gnuradio import audio
 
from gnuradio import audio
 
from gnuradio import analog
 
from gnuradio import analog
<\syntaxhighlight>
+
</syntaxhighlight>
  
 
Tells Python the modules to include. We must always have '''gr''' to run GNU Radio applications. The audio sink is included in the audio module and the signal_source_f is included in the analog module which is why we include them. [http://legacy.python.org/dev/peps/pep-0008/ PEP8] tells us we should import every module on its own line.
 
Tells Python the modules to include. We must always have '''gr''' to run GNU Radio applications. The audio sink is included in the audio module and the signal_source_f is included in the analog module which is why we include them. [http://legacy.python.org/dev/peps/pep-0008/ PEP8] tells us we should import every module on its own line.
Line 154: Line 229:
 
<syntaxhighlight lang="python">
 
<syntaxhighlight lang="python">
 
class my_top_block(gr.top_block):
 
class my_top_block(gr.top_block):
<\syntaxhighlight>
+
</syntaxhighlight>
Define a class called &quot;my_top_block&quot; which is derived from another class, '''gr.top_block'''. This class is basically a container for the flow graph. By deriving from gr.top_block, we get all the hooks and functions we need to add blocks and interconnect them.
+
Define a class called "my_top_block" which is derived from another class, '''gr.top_block'''. This class is basically a container for the flow graph. By deriving from gr.top_block, we get all the hooks and functions we need to add blocks and interconnect them.
  
 
<syntaxhighlight lang="python">
 
<syntaxhighlight lang="python">
 
def __init__(self):
 
def __init__(self):
<\syntaxhighlight>
+
</syntaxhighlight>
Only one member function is defined for this class: the function &quot;''init''()&quot;, which is the constructor of this class.
+
Only one member function is defined for this class: the function "''init''()", which is the constructor of this class.
  
 
<syntaxhighlight lang="python">
 
<syntaxhighlight lang="python">
 
gr.top_block.__init__(self)
 
gr.top_block.__init__(self)
<\syntaxhighlight>
+
</syntaxhighlight>
 
The parent constructor is called (in Python, this needs to be done explicitly. Most things in Python need to be done explicitly; in fact, this is one main Python principle).
 
The parent constructor is called (in Python, this needs to be done explicitly. Most things in Python need to be done explicitly; in fact, this is one main Python principle).
  
Line 170: Line 245:
 
sample_rate = 32000
 
sample_rate = 32000
 
ampl = 0.1
 
ampl = 0.1
<\syntaxhighlight>
+
</syntaxhighlight>
 
Variable declarations for sampling rate and amplitude that we will later use.
 
Variable declarations for sampling rate and amplitude that we will later use.
  
Line 178: Line 253:
 
src0 = analog.sig_source_f(sample_rate, analog.GR_SIN_WAVE, 350, ampl)
 
src0 = analog.sig_source_f(sample_rate, analog.GR_SIN_WAVE, 350, ampl)
 
src1 = analog.sig_source_f(sample_rate, analog.GR_SIN_WAVE, 440, ampl)
 
src1 = analog.sig_source_f(sample_rate, analog.GR_SIN_WAVE, 440, ampl)
<\syntaxhighlight>
+
</syntaxhighlight>
 
Here we are using functions from GNU Radio so let's have a look at the documentation for '''analog.sig_source_f''' which is available in [http://gnuradio.org/doc/doxygen/classgr_1_1analog_1_1sig__source__f.html the GNU Radio manual]. We can find it easily by using the search function as below:
 
Here we are using functions from GNU Radio so let's have a look at the documentation for '''analog.sig_source_f''' which is available in [http://gnuradio.org/doc/doxygen/classgr_1_1analog_1_1sig__source__f.html the GNU Radio manual]. We can find it easily by using the search function as below:
  
Line 188: Line 263:
 
https://raw.githubusercontent.com/gnuradio/gr-tutorial/master/examples/tutorial3/images/hello_source.png
 
https://raw.githubusercontent.com/gnuradio/gr-tutorial/master/examples/tutorial3/images/hello_source.png
  
We can see that our function '''analog.sig_source_f''' takes in 5 parameters but in our code we are only using 4. There is no error because the last input '''offset''' is set to &quot;0&quot; by default as shown in the documentation. The first input is the '''sampling_freq''' which we defined as '''sample_rate''' in our code. The second input is asking for a '''gr::analog::gr_waveform_t''' waveform so let's click that [http://gnuradio.org/doc/doxygen/group__waveform__generators__blk.html#gac97c0f42ffb63f1265decceaaeab9177 link] to find out more.
+
We can see that our function '''analog.sig_source_f''' takes in 5 parameters but in our code we are only using 4. There is no error because the last input '''offset''' is set to "0" by default as shown in the documentation. The first input is the '''sampling_freq''' which we defined as '''sample_rate''' in our code. The second input is asking for a '''gr::analog::gr_waveform_t''' waveform so let's click that [http://gnuradio.org/doc/doxygen/group__waveform__generators__blk.html#gac97c0f42ffb63f1265decceaaeab9177 link] to find out more.
  
[[File:https://raw.githubusercontent.com/gnuradio/gr-tutorial/master/examples/tutorial3/images/hello_waveform.png|200px|hello_waveform.png]]
 
 
https://raw.githubusercontent.com/gnuradio/gr-tutorial/master/examples/tutorial3/images/hello_waveform.png
 
https://raw.githubusercontent.com/gnuradio/gr-tutorial/master/examples/tutorial3/images/hello_waveform.png
  
We can see that there are a couple of options to choose from. In this case we chose '''analog.GR_SIN_WAVE'''. The third input is '''wave_freq''' which we input &quot;350&quot; or &quot;440&quot;. The fourth input is '''ampl''' which we defined as '''ampl'''.
+
We can see that there are a couple of options to choose from. In this case we chose '''analog.GR_SIN_WAVE'''. The third input is '''wave_freq''' which we input "350" or "440". The fourth input is '''ampl''' which we defined as '''ampl'''.
  
 
<syntaxhighlight lang="python">
 
<syntaxhighlight lang="python">
dst = audio.sink(sample_rate, &quot;&quot;)
+
dst = audio.sink(sample_rate, "")
<\syntaxhighlight>
+
</syntaxhighlight>
 
Because documentation is so important, let's look at another example. Again, we can look at the documentation for '''audio.sink''' which is available on the GNU Radio Manual through the search function:
 
Because documentation is so important, let's look at another example. Again, we can look at the documentation for '''audio.sink''' which is available on the GNU Radio Manual through the search function:
  
Line 206: Line 280:
 
https://raw.githubusercontent.com/gnuradio/gr-tutorial/master/examples/tutorial3/images/hello_sink_detail.png
 
https://raw.githubusercontent.com/gnuradio/gr-tutorial/master/examples/tutorial3/images/hello_sink_detail.png
  
This time we have 3 inputs with the last being optional. In our code, for the first input '''sampling_rate''' we used are '''sample_rate''' variable. In the second input, we have a choice for what device to use for audio output. If we leave it alone as &quot;&quot; then it'll choose the default on our machine.
+
This time we have 3 inputs with the last being optional. In our code, for the first input '''sampling_rate''' we used are '''sample_rate''' variable. In the second input, we have a choice for what device to use for audio output. If we leave it alone as "" then it'll choose the default on our machine.
  
 
=== 3.1.4. Connecting the Block Together ===
 
=== 3.1.4. Connecting the Block Together ===
Line 213: Line 287:
 
self.connect(src0, (dst, 0))
 
self.connect(src0, (dst, 0))
 
self.connect(src1, (dst, 1))
 
self.connect(src1, (dst, 1))
<\syntaxhighlight>
+
</syntaxhighlight>
 
The general syntax for connecting blocks is self.connect(block1, block2, block3, ...) which would connect the output of block1 with the input of block2, the output of block2 with the input of block3 and so on. We can connect as many blocks as we wish with one connect() call. However this only work when there is a one-to-one correspondence. If we go back to our initial flowgraph, there are 2 inputs to the '''Audio Sink''' block. The way to connect them is by using the syntax above. The first line connects the only output of src0 (350 Hz waveform) to the first input of dst (Audio Sink). The second line connects the only output of src1 (440 Hz waveform) to the second input of dst (Audio Sink). The code so far is equivalent to the flowgraph we have created in the beginning; the rest of the lines simply start the flowgraph and provide a keyboard interrupt.
 
The general syntax for connecting blocks is self.connect(block1, block2, block3, ...) which would connect the output of block1 with the input of block2, the output of block2 with the input of block3 and so on. We can connect as many blocks as we wish with one connect() call. However this only work when there is a one-to-one correspondence. If we go back to our initial flowgraph, there are 2 inputs to the '''Audio Sink''' block. The way to connect them is by using the syntax above. The first line connects the only output of src0 (350 Hz waveform) to the first input of dst (Audio Sink). The second line connects the only output of src1 (440 Hz waveform) to the second input of dst (Audio Sink). The code so far is equivalent to the flowgraph we have created in the beginning; the rest of the lines simply start the flowgraph and provide a keyboard interrupt.
  
Line 222: Line 296:
 
     except KeyboardInterrupt:
 
     except KeyboardInterrupt:
 
         pass
 
         pass
<\syntaxhighlight>
+
</syntaxhighlight>
  
 
Luckily we are past the early years of GNU Radio when there was no GRC to make the Python files for us. Nowadays we can simply click things together in GRC instead of having to write code in Python to build flowgraphs. Still, a good understanding of what is going on every time we run GRC is good to know as it gives us more control of what we want the program to do.
 
Luckily we are past the early years of GNU Radio when there was no GRC to make the Python files for us. Nowadays we can simply click things together in GRC instead of having to write code in Python to build flowgraphs. Still, a good understanding of what is going on every time we run GRC is good to know as it gives us more control of what we want the program to do.
Line 234: Line 308:
 
https://raw.githubusercontent.com/gnuradio/gr-tutorial/master/examples/tutorial3/images/if_else.png
 
https://raw.githubusercontent.com/gnuradio/gr-tutorial/master/examples/tutorial3/images/if_else.png
  
<span style="color:blue">- '''Frequency''' to &quot;freq&quot;, '''Amplitude''' to &quot;ampl&quot;</span><br />
+
<span style="color:blue">- '''Frequency''' to "freq", '''Amplitude''' to "ampl"</span><br />
<span style="color:red">- '''ID''' to &quot;probe&quot;</span><br />
+
<span style="color:red">- '''ID''' to "probe"</span><br />
 
- Everything else is visible
 
- Everything else is visible
  
Line 244: Line 318:
 
Now we can open up the GRC generated python file if_else.py which is copied below:
 
Now we can open up the GRC generated python file if_else.py which is copied below:
  
{{collapse(if_else.py)
+
<syntaxhighlight lang="python" line="line">
 +
#!/usr/bin/env python3
 +
# -*- coding: utf-8 -*-
  
<syntaxhighlight lang="python" line="line">
+
#
#!/usr/bin/env python
+
# SPDX-License-Identifier: GPL-3.0
##################################################
+
#
# Gnuradio Python Flow Graph
+
# GNU Radio Python Flow Graph
# Title: Top Block
+
# Title: if_else
# Generated: Wed Jul  2 01:39:19 2014
+
# GNU Radio version: 3.8.0.0
##################################################
+
 
 +
from distutils.version import StrictVersion
 +
 
 +
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()")
  
from PyQt4 import Qt
+
from PyQt5 import Qt
from gnuradio import analog
 
from gnuradio import blocks
 
 
from gnuradio import eng_notation
 
from gnuradio import eng_notation
from gnuradio import gr
 
 
from gnuradio import qtgui
 
from gnuradio import qtgui
from gnuradio.eng_option import eng_option
 
 
from gnuradio.filter import firdes
 
from gnuradio.filter import firdes
from optparse import OptionParser
 
 
import sip
 
import sip
 +
from gnuradio import analog
 +
from gnuradio import blocks
 +
from gnuradio import gr
 
import sys
 
import sys
 +
import signal
 +
from argparse import ArgumentParser
 +
from gnuradio.eng_arg import eng_float, intx
 +
import time
 
import threading
 
import threading
import time
+
from gnuradio import qtgui
  
class top_block(gr.top_block, Qt.QWidget):
+
class if_else(gr.top_block, Qt.QWidget):
  
 
     def __init__(self):
 
     def __init__(self):
         gr.top_block.__init__(self, &quot;Top Block&quot;)
+
         gr.top_block.__init__(self, "if_else")
 
         Qt.QWidget.__init__(self)
 
         Qt.QWidget.__init__(self)
         self.setWindowTitle(&quot;Top Block&quot;)
+
         self.setWindowTitle("if_else")
 +
        qtgui.util.check_set_qss()
 
         try:
 
         try:
            self.setWindowIcon(Qt.QIcon.fromTheme('gnuradio-grc'))
+
            self.setWindowIcon(Qt.QIcon.fromTheme('gnuradio-grc'))
 
         except:
 
         except:
            pass
+
            pass
 
         self.top_scroll_layout = Qt.QVBoxLayout()
 
         self.top_scroll_layout = Qt.QVBoxLayout()
 
         self.setLayout(self.top_scroll_layout)
 
         self.setLayout(self.top_scroll_layout)
Line 290: Line 380:
 
         self.top_layout.addLayout(self.top_grid_layout)
 
         self.top_layout.addLayout(self.top_grid_layout)
  
         self.settings = Qt.QSettings(&quot;GNU Radio&quot;, &quot;top_block&quot;)
+
         self.settings = Qt.QSettings("GNU Radio", "if_else")
        self.restoreGeometry(self.settings.value(&quot;geometry&quot;).toByteArray())
 
  
 +
        try:
 +
            if StrictVersion(Qt.qVersion()) < StrictVersion("5.0.0"):
 +
                self.restoreGeometry(self.settings.value("geometry").toByteArray())
 +
            else:
 +
                self.restoreGeometry(self.settings.value("geometry"))
 +
        except:
 +
            pass
  
 
         ##################################################
 
         ##################################################
Line 307: Line 403:
 
         self.probe = blocks.probe_signal_f()
 
         self.probe = blocks.probe_signal_f()
 
         self._freq_tool_bar = Qt.QToolBar(self)
 
         self._freq_tool_bar = Qt.QToolBar(self)
         self._freq_tool_bar.addWidget(Qt.QLabel(&quot;freq&quot;+&quot;: &quot;))
+
         self._freq_tool_bar.addWidget(Qt.QLabel('freq' + ": "))
 
         self._freq_line_edit = Qt.QLineEdit(str(self.freq))
 
         self._freq_line_edit = Qt.QLineEdit(str(self.freq))
 
         self._freq_tool_bar.addWidget(self._freq_line_edit)
 
         self._freq_tool_bar.addWidget(self._freq_line_edit)
 
         self._freq_line_edit.returnPressed.connect(
 
         self._freq_line_edit.returnPressed.connect(
             lambda: self.set_freq(int(self._freq_line_edit.text().toAscii())))
+
             lambda: self.set_freq(int(str(self._freq_line_edit.text()))))
         self.top_layout.addWidget(self._freq_tool_bar)
+
         self.top_grid_layout.addWidget(self._freq_tool_bar)
 
         self._ampl_tool_bar = Qt.QToolBar(self)
 
         self._ampl_tool_bar = Qt.QToolBar(self)
         self._ampl_tool_bar.addWidget(Qt.QLabel(&quot;ampl&quot;+&quot;: &quot;))
+
         self._ampl_tool_bar.addWidget(Qt.QLabel('ampl' + ": "))
 
         self._ampl_line_edit = Qt.QLineEdit(str(self.ampl))
 
         self._ampl_line_edit = Qt.QLineEdit(str(self.ampl))
 
         self._ampl_tool_bar.addWidget(self._ampl_line_edit)
 
         self._ampl_tool_bar.addWidget(self._ampl_line_edit)
 
         self._ampl_line_edit.returnPressed.connect(
 
         self._ampl_line_edit.returnPressed.connect(
             lambda: self.set_ampl(int(self._ampl_line_edit.text().toAscii())))
+
             lambda: self.set_ampl(int(str(self._ampl_line_edit.text()))))
         self.top_layout.addWidget(self._ampl_tool_bar)
+
         self.top_grid_layout.addWidget(self._ampl_tool_bar)
 
         def _variable_function_probe_0_probe():
 
         def _variable_function_probe_0_probe():
 
             while True:
 
             while True:
                 val = self.probe.level()
+
 
 +
                 val = self.probe.get_number()
 
                 try:
 
                 try:
 
                     self.set_variable_function_probe_0(val)
 
                     self.set_variable_function_probe_0(val)
Line 331: Line 428:
 
         _variable_function_probe_0_thread.daemon = True
 
         _variable_function_probe_0_thread.daemon = True
 
         _variable_function_probe_0_thread.start()
 
         _variable_function_probe_0_thread.start()
 +
 
         self.qtgui_time_sink_x_0 = qtgui.time_sink_f(
 
         self.qtgui_time_sink_x_0 = qtgui.time_sink_f(
 
             1024, #size
 
             1024, #size
 
             samp_rate, #samp_rate
 
             samp_rate, #samp_rate
             &quot;QT GUI Plot&quot;, #name
+
             "", #name
 
             1 #number of inputs
 
             1 #number of inputs
 
         )
 
         )
 
         self.qtgui_time_sink_x_0.set_update_time(0.10)
 
         self.qtgui_time_sink_x_0.set_update_time(0.10)
 
         self.qtgui_time_sink_x_0.set_y_axis(-1, 1)
 
         self.qtgui_time_sink_x_0.set_y_axis(-1, 1)
         self.qtgui_time_sink_x_0.enable_tags(-1, True)
+
 
         self.qtgui_time_sink_x_0.set_trigger_mode(qtgui.TRIG_MODE_FREE, qtgui.TRIG_SLOPE_POS, 0.0, 0, 0, &quot;&quot;)
+
        self.qtgui_time_sink_x_0.set_y_label('Amplitude', "")
 +
 
 +
         self.qtgui_time_sink_x_0.enable_tags(True)
 +
         self.qtgui_time_sink_x_0.set_trigger_mode(qtgui.TRIG_MODE_FREE, qtgui.TRIG_SLOPE_POS, 0.0, 0, 0, "")
 
         self.qtgui_time_sink_x_0.enable_autoscale(False)
 
         self.qtgui_time_sink_x_0.enable_autoscale(False)
 +
        self.qtgui_time_sink_x_0.enable_grid(False)
 +
        self.qtgui_time_sink_x_0.enable_axis_labels(True)
 +
        self.qtgui_time_sink_x_0.enable_control_panel(False)
 +
        self.qtgui_time_sink_x_0.enable_stem_plot(False)
  
         labels = [&quot;&quot;, &quot;&quot;, &quot;&quot;, &quot;&quot;, &quot;&quot;,
+
 
                  &quot;&quot;, &quot;&quot;, &quot;&quot;, &quot;&quot;, &quot;&quot;]
+
         labels = ['Signal 1', 'Signal 2', 'Signal 3', 'Signal 4', 'Signal 5',
 +
            'Signal 6', 'Signal 7', 'Signal 8', 'Signal 9', 'Signal 10']
 
         widths = [1, 1, 1, 1, 1,
 
         widths = [1, 1, 1, 1, 1,
                  1, 1, 1, 1, 1]
+
            1, 1, 1, 1, 1]
         colors = [&quot;blue&quot;, &quot;red&quot;, &quot;green&quot;, &quot;black&quot;, &quot;cyan&quot;,
+
         colors = ['blue', 'red', 'green', 'black', 'cyan',
                  &quot;magenta&quot;, &quot;yellow&quot;, &quot;dark red&quot;, &quot;dark green&quot;, &quot;blue&quot;]
+
            'magenta', 'yellow', 'dark red', 'dark green', 'dark blue']
 +
        alphas = [1.0, 1.0, 1.0, 1.0, 1.0,
 +
            1.0, 1.0, 1.0, 1.0, 1.0]
 
         styles = [1, 1, 1, 1, 1,
 
         styles = [1, 1, 1, 1, 1,
                  1, 1, 1, 1, 1]
+
            1, 1, 1, 1, 1]
 
         markers = [-1, -1, -1, -1, -1,
 
         markers = [-1, -1, -1, -1, -1,
                  -1, -1, -1, -1, -1]
+
            -1, -1, -1, -1, -1]
        alphas = [1.0, 1.0, 1.0, 1.0, 1.0,
+
 
                  1.0, 1.0, 1.0, 1.0, 1.0]
 
  
         for i in xrange(1):
+
         for i in range(1):
 
             if len(labels[i]) == 0:
 
             if len(labels[i]) == 0:
                 self.qtgui_time_sink_x_0.set_line_label(i, &quot;Data {0}&quot;.format(i))
+
                 self.qtgui_time_sink_x_0.set_line_label(i, "Data {0}".format(i))
 
             else:
 
             else:
 
                 self.qtgui_time_sink_x_0.set_line_label(i, labels[i])
 
                 self.qtgui_time_sink_x_0.set_line_label(i, labels[i])
Line 368: Line 475:
  
 
         self._qtgui_time_sink_x_0_win = sip.wrapinstance(self.qtgui_time_sink_x_0.pyqwidget(), Qt.QWidget)
 
         self._qtgui_time_sink_x_0_win = sip.wrapinstance(self.qtgui_time_sink_x_0.pyqwidget(), Qt.QWidget)
         self.top_layout.addWidget(self._qtgui_time_sink_x_0_win)
+
         self.top_grid_layout.addWidget(self._qtgui_time_sink_x_0_win)
 
         self.blocks_throttle_0 = blocks.throttle(gr.sizeof_float*1, samp_rate,True)
 
         self.blocks_throttle_0 = blocks.throttle(gr.sizeof_float*1, samp_rate,True)
         self.analog_sig_source_x_1 = analog.sig_source_f(samp_rate, analog.GR_SIN_WAVE, freq, ampl, 0)
+
         self.analog_sig_source_x_0_0 = analog.sig_source_f(samp_rate, analog.GR_COS_WAVE, freq, ampl, 0, 0)
         self.analog_sig_source_x_0 = analog.sig_source_f(samp_rate, analog.GR_SQR_WAVE, 0.1, 1, 0)
+
         self.analog_sig_source_x_0 = analog.sig_source_f(samp_rate, analog.GR_SQR_WAVE, 0.1, 1, 0, 0)
 +
 
 +
 
  
 
         ##################################################
 
         ##################################################
Line 377: Line 486:
 
         ##################################################
 
         ##################################################
 
         self.connect((self.analog_sig_source_x_0, 0), (self.blocks_throttle_0, 0))
 
         self.connect((self.analog_sig_source_x_0, 0), (self.blocks_throttle_0, 0))
 +
        self.connect((self.analog_sig_source_x_0_0, 0), (self.qtgui_time_sink_x_0, 0))
 
         self.connect((self.blocks_throttle_0, 0), (self.probe, 0))
 
         self.connect((self.blocks_throttle_0, 0), (self.probe, 0))
        self.connect((self.analog_sig_source_x_1, 0), (self.qtgui_time_sink_x_0, 0))
 
  
 
# QT sink close method reimplementation
 
 
     def closeEvent(self, event):
 
     def closeEvent(self, event):
         self.settings = Qt.QSettings(&quot;GNU Radio&quot;, &quot;top_block&quot;)
+
         self.settings = Qt.QSettings("GNU Radio", "if_else")
         self.settings.setValue(&quot;geometry&quot;, self.saveGeometry())
+
         self.settings.setValue("geometry", self.saveGeometry())
 
         event.accept()
 
         event.accept()
  
Line 398: Line 505:
 
     def set_samp_rate(self, samp_rate):
 
     def set_samp_rate(self, samp_rate):
 
         self.samp_rate = samp_rate
 
         self.samp_rate = samp_rate
 +
        self.analog_sig_source_x_0.set_sampling_freq(self.samp_rate)
 +
        self.analog_sig_source_x_0_0.set_sampling_freq(self.samp_rate)
 
         self.blocks_throttle_0.set_sample_rate(self.samp_rate)
 
         self.blocks_throttle_0.set_sample_rate(self.samp_rate)
        self.analog_sig_source_x_0.set_sampling_freq(self.samp_rate)
 
 
         self.qtgui_time_sink_x_0.set_samp_rate(self.samp_rate)
 
         self.qtgui_time_sink_x_0.set_samp_rate(self.samp_rate)
        self.analog_sig_source_x_1.set_sampling_freq(self.samp_rate)
 
  
 
     def get_freq(self):
 
     def get_freq(self):
Line 408: Line 515:
 
     def set_freq(self, freq):
 
     def set_freq(self, freq):
 
         self.freq = freq
 
         self.freq = freq
         Qt.QMetaObject.invokeMethod(self._freq_line_edit, &quot;setText&quot;, Qt.Q_ARG(&quot;QString&quot;, str(self.freq)))
+
         Qt.QMetaObject.invokeMethod(self._freq_line_edit, "setText", Qt.Q_ARG("QString", str(self.freq)))
         self.analog_sig_source_x_1.set_frequency(self.freq)
+
         self.analog_sig_source_x_0_0.set_frequency(self.freq)
  
 
     def get_ampl(self):
 
     def get_ampl(self):
Line 416: Line 523:
 
     def set_ampl(self, ampl):
 
     def set_ampl(self, ampl):
 
         self.ampl = ampl
 
         self.ampl = ampl
         Qt.QMetaObject.invokeMethod(self._ampl_line_edit, &quot;setText&quot;, Qt.Q_ARG(&quot;QString&quot;, str(self.ampl)))
+
         Qt.QMetaObject.invokeMethod(self._ampl_line_edit, "setText", Qt.Q_ARG("QString", str(self.ampl)))
         self.analog_sig_source_x_1.set_amplitude(self.ampl)
+
         self.analog_sig_source_x_0_0.set_amplitude(self.ampl)
  
if __name__ == '__main__':
+
 
    import ctypes
+
 
    import sys
+
def main(top_block_cls=if_else, options=None):
     if sys.platform.startswith('linux'):
+
 
        try:
+
     if StrictVersion("4.5.0") <= StrictVersion(Qt.qVersion()) < StrictVersion("5.0.0"):
            x11 = ctypes.cdll.LoadLibrary('libX11.so')
+
        style = gr.prefs().get_string('qtgui', 'style', 'raster')
            x11.XInitThreads()
+
        Qt.QApplication.setGraphicsSystem(style)
        except:
 
            print &quot;Warning: failed to XInitThreads()&quot;
 
    parser = OptionParser(option_class=eng_option, usage=&quot;%prog: [options]&quot;)
 
    (options, args) = parser.parse_args()
 
    Qt.QApplication.setGraphicsSystem(gr.prefs().get_string('qtgui','style','raster'))
 
 
     qapp = Qt.QApplication(sys.argv)
 
     qapp = Qt.QApplication(sys.argv)
     tb = top_block()
+
 
 +
     tb = top_block_cls()
 
     tb.start()
 
     tb.start()
 
     tb.show()
 
     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():
 
     def quitting():
 
         tb.stop()
 
         tb.stop()
 
         tb.wait()
 
         tb.wait()
     qapp.connect(qapp, Qt.SIGNAL(&quot;aboutToQuit()&quot;), quitting)
+
     qapp.aboutToQuit.connect(quitting)
 
     qapp.exec_()
 
     qapp.exec_()
     tb = None #to clean up Qt widgets
+
 
<\syntaxhighlight>
+
 
}}
+
if __name__ == '__main__':
 +
     main()
 +
 
 +
</syntaxhighlight>
  
 
We are only concerned about a couple of parts namely the part where the probe is being read:
 
We are only concerned about a couple of parts namely the part where the probe is being read:
  
 
<syntaxhighlight lang="python">
 
<syntaxhighlight lang="python">
      def _variable_function_probe_0_probe():
+
        def _variable_function_probe_0_probe():
 
             while True:
 
             while True:
 +
 
                 val = self.probe.level()
 
                 val = self.probe.level()
 
                 try:
 
                 try:
Line 455: Line 573:
 
                     pass
 
                     pass
 
                 time.sleep(1.0 / (10))
 
                 time.sleep(1.0 / (10))
<\syntaxhighlight>
+
</syntaxhighlight>
 
We can see that the variable '''val''' is obtaining the value of the probe block. We can write our if-else statement here based on the value of '''val''' to change the amplitude and frequency of our sine wave. But how do we change the frequency and amplitude? We can use the part where the '''QT GUI Entry''' updates the flowgraph. For the variable freq:
 
We can see that the variable '''val''' is obtaining the value of the probe block. We can write our if-else statement here based on the value of '''val''' to change the amplitude and frequency of our sine wave. But how do we change the frequency and amplitude? We can use the part where the '''QT GUI Entry''' updates the flowgraph. For the variable freq:
  
 
<syntaxhighlight lang="python">
 
<syntaxhighlight lang="python">
  def set_freq(self, freq):
+
    def set_freq(self, freq):
 
         self.freq = freq
 
         self.freq = freq
         Qt.QMetaObject.invokeMethod(self._freq_line_edit, &quot;setText&quot;, Qt.Q_ARG(&quot;QString&quot;, str(self.freq)))
+
         Qt.QMetaObject.invokeMethod(self._freq_line_edit, "setText", Qt.Q_ARG("QString", str(self.freq)))
         self.analog_sig_source_x_1.set_frequency(self.freq)
+
         self.analog_sig_source_x_0_0.set_frequency(self.freq)
<\syntaxhighlight>
+
</syntaxhighlight>
  
 
and for the variable ampl:
 
and for the variable ampl:
  
 
<syntaxhighlight lang="python">
 
<syntaxhighlight lang="python">
  def set_ampl(self, ampl):
+
    def set_ampl(self, ampl):
 
         self.ampl = ampl
 
         self.ampl = ampl
         Qt.QMetaObject.invokeMethod(self._ampl_line_edit, &quot;setText&quot;, Qt.Q_ARG(&quot;QString&quot;, str(self.ampl)))
+
         Qt.QMetaObject.invokeMethod(self._ampl_line_edit, "setText", Qt.Q_ARG("QString", str(self.ampl)))
         self.analog_sig_source_x_1.set_amplitude(self.ampl)
+
         self.analog_sig_source_x_0_0.set_amplitude(self.ampl)
<\syntaxhighlight>
+
</syntaxhighlight>
 
We can see that the functions set_ampl and set_freq can be used for just that - setting the amplitude and the frequency. Thus we can go back and modify our probe function with the if-else statement to give power to our friend.
 
We can see that the functions set_ampl and set_freq can be used for just that - setting the amplitude and the frequency. Thus we can go back and modify our probe function with the if-else statement to give power to our friend.
  
  
 
<syntaxhighlight lang="python">
 
<syntaxhighlight lang="python">
      def _variable_function_probe_0_probe():
+
        def _variable_funct ion_probe_0_probe():
 
             while True:
 
             while True:
 +
 
                 val = self.probe.level()
 
                 val = self.probe.level()
 
                 print val
 
                 print val
Line 492: Line 611:
 
                     pass
 
                     pass
 
                 time.sleep(1.0 / (10))
 
                 time.sleep(1.0 / (10))
<\syntaxhighlight>
+
</syntaxhighlight>
 +
 
 +
Now there is one more thing we need to take care of. GRC has compiled the python file in the order of creation of the elements, which was okay as long as there were no crossreferences. With the introduced adaptation (calling set_ampl and set_freq inside the _variable_function_probe_0_probe()) we need to fix the order of declarations. As set_ampl and set_freq both modify parameters of analog_sig_source_x_0_0 but analog_sig_source_x_0_0 is not instantiated before line  150, we have to move the declaration of the _variable_function_probe_0_probe() and everything related below that.
 +
 
 +
<syntaxhighlight lang="python">
 +
        self._qtgui_time_sink_x_0_win = sip.wrapinstance(self.qtgui_time_sink_x_0.pyqwidget(), Qt.QWidget)
 +
        self.top_grid_layout.addWidget(self._qtgui_time_sink_x_0_win)
 +
        self.blocks_throttle_0 = blocks.throttle(gr.sizeof_float*1, samp_rate,True)
 +
        self.analog_sig_source_x_1 = analog.sig_source_f(samp_rate, analog.GR_SIN_WAVE, freq, ampl, 0)
 +
        self.analog_sig_source_x_0 = analog.sig_source_f(samp_rate, analog.GR_SQR_WAVE, 0.1, 1, 0)
 +
</syntaxhighlight>
  
 
Full code copied below:
 
Full code copied below:
Line 498: Line 627:
  
 
<syntaxhighlight lang="python">
 
<syntaxhighlight lang="python">
#!/usr/bin/env python
+
#!/usr/bin/env python3
##################################################
+
# -*- coding: utf-8 -*-
# Gnuradio Python Flow Graph
 
# Title: Top Block
 
# Generated: Wed Jul  2 01:39:19 2014
 
##################################################
 
  
from PyQt4 import Qt
+
#
from gnuradio import analog
+
# SPDX-License-Identifier: GPL-3.0
from gnuradio import blocks
+
#
 +
# GNU Radio Python Flow Graph
 +
# Title: if_else
 +
# GNU Radio version: 3.8.0.0
 +
 
 +
from distutils.version import StrictVersion
 +
 
 +
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()")
 +
 
 +
from PyQt5 import Qt
 
from gnuradio import eng_notation
 
from gnuradio import eng_notation
from gnuradio import gr
 
 
from gnuradio import qtgui
 
from gnuradio import qtgui
from gnuradio.eng_option import eng_option
 
 
from gnuradio.filter import firdes
 
from gnuradio.filter import firdes
from optparse import OptionParser
 
 
import sip
 
import sip
 +
from gnuradio import analog
 +
from gnuradio import blocks
 +
from gnuradio import gr
 
import sys
 
import sys
 +
import signal
 +
from argparse import ArgumentParser
 +
from gnuradio.eng_arg import eng_float, intx
 +
import time
 
import threading
 
import threading
import time
+
from gnuradio import qtgui
  
class top_block(gr.top_block, Qt.QWidget):
+
class if_else(gr.top_block, Qt.QWidget):
  
 
     def __init__(self):
 
     def __init__(self):
         gr.top_block.__init__(self, &quot;Top Block&quot;)
+
         gr.top_block.__init__(self, "if_else")
 
         Qt.QWidget.__init__(self)
 
         Qt.QWidget.__init__(self)
         self.setWindowTitle(&quot;Top Block&quot;)
+
         self.setWindowTitle("if_else")
 +
        qtgui.util.check_set_qss()
 
         try:
 
         try:
            self.setWindowIcon(Qt.QIcon.fromTheme('gnuradio-grc'))
+
            self.setWindowIcon(Qt.QIcon.fromTheme('gnuradio-grc'))
 
         except:
 
         except:
            pass
+
            pass
 
         self.top_scroll_layout = Qt.QVBoxLayout()
 
         self.top_scroll_layout = Qt.QVBoxLayout()
 
         self.setLayout(self.top_scroll_layout)
 
         self.setLayout(self.top_scroll_layout)
Line 541: Line 688:
 
         self.top_layout.addLayout(self.top_grid_layout)
 
         self.top_layout.addLayout(self.top_grid_layout)
  
         self.settings = Qt.QSettings(&quot;GNU Radio&quot;, &quot;top_block&quot;)
+
         self.settings = Qt.QSettings("GNU Radio", "if_else")
        self.restoreGeometry(self.settings.value(&quot;geometry&quot;).toByteArray())
 
  
 +
        try:
 +
            if StrictVersion(Qt.qVersion()) < StrictVersion("5.0.0"):
 +
                self.restoreGeometry(self.settings.value("geometry").toByteArray())
 +
            else:
 +
                self.restoreGeometry(self.settings.value("geometry"))
 +
        except:
 +
            pass
  
 
         ##################################################
 
         ##################################################
Line 558: Line 711:
 
         self.probe = blocks.probe_signal_f()
 
         self.probe = blocks.probe_signal_f()
 
         self._freq_tool_bar = Qt.QToolBar(self)
 
         self._freq_tool_bar = Qt.QToolBar(self)
         self._freq_tool_bar.addWidget(Qt.QLabel(&quot;freq&quot;+&quot;: &quot;))
+
         self._freq_tool_bar.addWidget(Qt.QLabel('freq' + ": "))
 
         self._freq_line_edit = Qt.QLineEdit(str(self.freq))
 
         self._freq_line_edit = Qt.QLineEdit(str(self.freq))
 
         self._freq_tool_bar.addWidget(self._freq_line_edit)
 
         self._freq_tool_bar.addWidget(self._freq_line_edit)
 
         self._freq_line_edit.returnPressed.connect(
 
         self._freq_line_edit.returnPressed.connect(
             lambda: self.set_freq(int(self._freq_line_edit.text().toAscii())))
+
             lambda: self.set_freq(int(str(self._freq_line_edit.text()))))
         self.top_layout.addWidget(self._freq_tool_bar)
+
         self.top_grid_layout.addWidget(self._freq_tool_bar)
 
         self._ampl_tool_bar = Qt.QToolBar(self)
 
         self._ampl_tool_bar = Qt.QToolBar(self)
         self._ampl_tool_bar.addWidget(Qt.QLabel(&quot;ampl&quot;+&quot;: &quot;))
+
         self._ampl_tool_bar.addWidget(Qt.QLabel('ampl' + ": "))
 
         self._ampl_line_edit = Qt.QLineEdit(str(self.ampl))
 
         self._ampl_line_edit = Qt.QLineEdit(str(self.ampl))
 
         self._ampl_tool_bar.addWidget(self._ampl_line_edit)
 
         self._ampl_tool_bar.addWidget(self._ampl_line_edit)
 
         self._ampl_line_edit.returnPressed.connect(
 
         self._ampl_line_edit.returnPressed.connect(
             lambda: self.set_ampl(int(self._ampl_line_edit.text().toAscii())))
+
             lambda: self.set_ampl(int(str(self._ampl_line_edit.text()))))
         self.top_layout.addWidget(self._ampl_tool_bar)
+
         self.top_grid_layout.addWidget(self._ampl_tool_bar)
        def _variable_function_probe_0_probe():
+
 
            while True:
 
                val = self.probe.level()
 
                if val == 1:
 
                    self.set_ampl(1)
 
                    self.set_freq(1000)
 
                else:
 
                    self.set_ampl(.3)
 
                    self.set_freq(100)
 
                try:
 
                    self.set_variable_function_probe_0(val)
 
                except AttributeError:
 
                    pass
 
                time.sleep(1.0 / (10))
 
        _variable_function_probe_0_thread = threading.Thread(target=_variable_function_probe_0_probe)
 
        _variable_function_probe_0_thread.daemon = True
 
        _variable_function_probe_0_thread.start()
 
 
         self.qtgui_time_sink_x_0 = qtgui.time_sink_f(
 
         self.qtgui_time_sink_x_0 = qtgui.time_sink_f(
 
             1024, #size
 
             1024, #size
 
             samp_rate, #samp_rate
 
             samp_rate, #samp_rate
             &quot;QT GUI Plot&quot;, #name
+
             "", #name
 
             1 #number of inputs
 
             1 #number of inputs
 
         )
 
         )
 
         self.qtgui_time_sink_x_0.set_update_time(0.10)
 
         self.qtgui_time_sink_x_0.set_update_time(0.10)
 
         self.qtgui_time_sink_x_0.set_y_axis(-1, 1)
 
         self.qtgui_time_sink_x_0.set_y_axis(-1, 1)
         self.qtgui_time_sink_x_0.enable_tags(-1, True)
+
 
         self.qtgui_time_sink_x_0.set_trigger_mode(qtgui.TRIG_MODE_FREE, qtgui.TRIG_SLOPE_POS, 0.0, 0, 0, &quot;&quot;)
+
        self.qtgui_time_sink_x_0.set_y_label('Amplitude', "")
 +
 
 +
         self.qtgui_time_sink_x_0.enable_tags(True)
 +
         self.qtgui_time_sink_x_0.set_trigger_mode(qtgui.TRIG_MODE_FREE, qtgui.TRIG_SLOPE_POS, 0.0, 0, 0, "")
 
         self.qtgui_time_sink_x_0.enable_autoscale(False)
 
         self.qtgui_time_sink_x_0.enable_autoscale(False)
 +
        self.qtgui_time_sink_x_0.enable_grid(False)
 +
        self.qtgui_time_sink_x_0.enable_axis_labels(True)
 +
        self.qtgui_time_sink_x_0.enable_control_panel(False)
 +
        self.qtgui_time_sink_x_0.enable_stem_plot(False)
  
         labels = [&quot;&quot;, &quot;&quot;, &quot;&quot;, &quot;&quot;, &quot;&quot;,
+
 
                  &quot;&quot;, &quot;&quot;, &quot;&quot;, &quot;&quot;, &quot;&quot;]
+
         labels = ['Signal 1', 'Signal 2', 'Signal 3', 'Signal 4', 'Signal 5',
 +
            'Signal 6', 'Signal 7', 'Signal 8', 'Signal 9', 'Signal 10']
 
         widths = [1, 1, 1, 1, 1,
 
         widths = [1, 1, 1, 1, 1,
                  1, 1, 1, 1, 1]
+
            1, 1, 1, 1, 1]
         colors = [&quot;blue&quot;, &quot;red&quot;, &quot;green&quot;, &quot;black&quot;, &quot;cyan&quot;,
+
         colors = ['blue', 'red', 'green', 'black', 'cyan',
                  &quot;magenta&quot;, &quot;yellow&quot;, &quot;dark red&quot;, &quot;dark green&quot;, &quot;blue&quot;]
+
            'magenta', 'yellow', 'dark red', 'dark green', 'dark blue']
 +
        alphas = [1.0, 1.0, 1.0, 1.0, 1.0,
 +
            1.0, 1.0, 1.0, 1.0, 1.0]
 
         styles = [1, 1, 1, 1, 1,
 
         styles = [1, 1, 1, 1, 1,
                  1, 1, 1, 1, 1]
+
            1, 1, 1, 1, 1]
 
         markers = [-1, -1, -1, -1, -1,
 
         markers = [-1, -1, -1, -1, -1,
                  -1, -1, -1, -1, -1]
+
            -1, -1, -1, -1, -1]
        alphas = [1.0, 1.0, 1.0, 1.0, 1.0,
+
 
                  1.0, 1.0, 1.0, 1.0, 1.0]
 
  
         for i in xrange(1):
+
         for i in range(1):
 
             if len(labels[i]) == 0:
 
             if len(labels[i]) == 0:
                 self.qtgui_time_sink_x_0.set_line_label(i, &quot;Data {0}&quot;.format(i))
+
                 self.qtgui_time_sink_x_0.set_line_label(i, "Data {0}".format(i))
 
             else:
 
             else:
 
                 self.qtgui_time_sink_x_0.set_line_label(i, labels[i])
 
                 self.qtgui_time_sink_x_0.set_line_label(i, labels[i])
Line 625: Line 771:
  
 
         self._qtgui_time_sink_x_0_win = sip.wrapinstance(self.qtgui_time_sink_x_0.pyqwidget(), Qt.QWidget)
 
         self._qtgui_time_sink_x_0_win = sip.wrapinstance(self.qtgui_time_sink_x_0.pyqwidget(), Qt.QWidget)
         self.top_layout.addWidget(self._qtgui_time_sink_x_0_win)
+
         self.top_grid_layout.addWidget(self._qtgui_time_sink_x_0_win)
 
         self.blocks_throttle_0 = blocks.throttle(gr.sizeof_float*1, samp_rate,True)
 
         self.blocks_throttle_0 = blocks.throttle(gr.sizeof_float*1, samp_rate,True)
         self.analog_sig_source_x_1 = analog.sig_source_f(samp_rate, analog.GR_SIN_WAVE, freq, ampl, 0)
+
         self.analog_sig_source_x_0_0 = analog.sig_source_f(samp_rate, analog.GR_COS_WAVE, freq, ampl, 0, 0)
         self.analog_sig_source_x_0 = analog.sig_source_f(samp_rate, analog.GR_SQR_WAVE, 0.1, 1, 0)
+
         self.analog_sig_source_x_0 = analog.sig_source_f(samp_rate, analog.GR_SQR_WAVE, 0.1, 1, 0, 0)
 +
 
 +
        def _variable_function_probe_0_probe():
 +
            while True:
 +
 
 +
                val = self.probe.level()
 +
                print (val)
 +
                if val == 1:
 +
                    self.set_ampl(1)
 +
                    self.set_freq(1000)
 +
                else:
 +
                    self.set_ampl(.3)
 +
                    self.set_freq(100)
 +
                try:
 +
                    self.set_variable_function_probe_0(val)
 +
                except AttributeError:
 +
                    pass
 +
                time.sleep(1.0 / (10))
 +
        _variable_function_probe_0_thread = threading.Thread(target=_variable_function_probe_0_probe)
 +
        _variable_function_probe_0_thread.daemon = True
 +
        _variable_function_probe_0_thread.start()
  
 
         ##################################################
 
         ##################################################
Line 634: Line 800:
 
         ##################################################
 
         ##################################################
 
         self.connect((self.analog_sig_source_x_0, 0), (self.blocks_throttle_0, 0))
 
         self.connect((self.analog_sig_source_x_0, 0), (self.blocks_throttle_0, 0))
 +
        self.connect((self.analog_sig_source_x_0_0, 0), (self.qtgui_time_sink_x_0, 0))
 
         self.connect((self.blocks_throttle_0, 0), (self.probe, 0))
 
         self.connect((self.blocks_throttle_0, 0), (self.probe, 0))
        self.connect((self.analog_sig_source_x_1, 0), (self.qtgui_time_sink_x_0, 0))
 
  
 
# QT sink close method reimplementation
 
 
     def closeEvent(self, event):
 
     def closeEvent(self, event):
         self.settings = Qt.QSettings(&quot;GNU Radio&quot;, &quot;top_block&quot;)
+
         self.settings = Qt.QSettings("GNU Radio", "if_else")
         self.settings.setValue(&quot;geometry&quot;, self.saveGeometry())
+
         self.settings.setValue("geometry", self.saveGeometry())
 
         event.accept()
 
         event.accept()
  
Line 655: Line 819:
 
     def set_samp_rate(self, samp_rate):
 
     def set_samp_rate(self, samp_rate):
 
         self.samp_rate = samp_rate
 
         self.samp_rate = samp_rate
 +
        self.analog_sig_source_x_0.set_sampling_freq(self.samp_rate)
 +
        self.analog_sig_source_x_0_0.set_sampling_freq(self.samp_rate)
 
         self.blocks_throttle_0.set_sample_rate(self.samp_rate)
 
         self.blocks_throttle_0.set_sample_rate(self.samp_rate)
        self.analog_sig_source_x_0.set_sampling_freq(self.samp_rate)
 
 
         self.qtgui_time_sink_x_0.set_samp_rate(self.samp_rate)
 
         self.qtgui_time_sink_x_0.set_samp_rate(self.samp_rate)
        self.analog_sig_source_x_1.set_sampling_freq(self.samp_rate)
 
  
 
     def get_freq(self):
 
     def get_freq(self):
Line 665: Line 829:
 
     def set_freq(self, freq):
 
     def set_freq(self, freq):
 
         self.freq = freq
 
         self.freq = freq
         Qt.QMetaObject.invokeMethod(self._freq_line_edit, &quot;setText&quot;, Qt.Q_ARG(&quot;QString&quot;, str(self.freq)))
+
         Qt.QMetaObject.invokeMethod(self._freq_line_edit, "setText", Qt.Q_ARG("QString", str(self.freq)))
         self.analog_sig_source_x_1.set_frequency(self.freq)
+
         self.analog_sig_source_x_0_0.set_frequency(self.freq)
  
 
     def get_ampl(self):
 
     def get_ampl(self):
Line 673: Line 837:
 
     def set_ampl(self, ampl):
 
     def set_ampl(self, ampl):
 
         self.ampl = ampl
 
         self.ampl = ampl
         Qt.QMetaObject.invokeMethod(self._ampl_line_edit, &quot;setText&quot;, Qt.Q_ARG(&quot;QString&quot;, str(self.ampl)))
+
         Qt.QMetaObject.invokeMethod(self._ampl_line_edit, "setText", Qt.Q_ARG("QString", str(self.ampl)))
         self.analog_sig_source_x_1.set_amplitude(self.ampl)
+
         self.analog_sig_source_x_0_0.set_amplitude(self.ampl)
 +
 
 +
 
 +
 
 +
def main(top_block_cls=if_else, options=None):
  
if __name__ == '__main__':
+
     if StrictVersion("4.5.0") <= StrictVersion(Qt.qVersion()) < StrictVersion("5.0.0"):
    import ctypes
+
        style = gr.prefs().get_string('qtgui', 'style', 'raster')
    import sys
+
        Qt.QApplication.setGraphicsSystem(style)
     if sys.platform.startswith('linux'):
 
        try:
 
            x11 = ctypes.cdll.LoadLibrary('libX11.so')
 
            x11.XInitThreads()
 
        except:
 
            print &quot;Warning: failed to XInitThreads()&quot;
 
    parser = OptionParser(option_class=eng_option, usage=&quot;%prog: [options]&quot;)
 
    (options, args) = parser.parse_args()
 
    Qt.QApplication.setGraphicsSystem(gr.prefs().get_string('qtgui','style','raster'))
 
 
     qapp = Qt.QApplication(sys.argv)
 
     qapp = Qt.QApplication(sys.argv)
     tb = top_block()
+
 
 +
     tb = top_block_cls()
 
     tb.start()
 
     tb.start()
 
     tb.show()
 
     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():
 
     def quitting():
 
         tb.stop()
 
         tb.stop()
 
         tb.wait()
 
         tb.wait()
     qapp.connect(qapp, Qt.SIGNAL(&quot;aboutToQuit()&quot;), quitting)
+
     qapp.aboutToQuit.connect(quitting)
 
     qapp.exec_()
 
     qapp.exec_()
     tb = None #to clean up Qt widgets
+
 
<\syntaxhighlight>
+
 
 +
if __name__ == '__main__':
 +
     main()
 +
 
 +
</syntaxhighlight>
  
 
We can then simply run our flowgraph from outside of GRC using
 
We can then simply run our flowgraph from outside of GRC using
  
 
<pre>
 
<pre>
$ python if_else_mod.py
+
$ python3 if_else_mod.py
 
</pre>
 
</pre>
 
We should be able to see the numbers 0 and 1 on the terminal and the sine wave changing amplitude and frequency as the numbers change.
 
We should be able to see the numbers 0 and 1 on the terminal and the sine wave changing amplitude and frequency as the numbers change.
 
This tutorial is merely an introduction on using python in GNU Radio, for a more advanced tutorial see [http://gnuradio.org/redmine/projects/gnuradio/wiki/TutorialsWritePythonApplications TutorialsWritePythonApplications]
 
  
 
== 3.2. Where Do Blocks Come From? ==
 
== 3.2. Where Do Blocks Come From? ==
Line 717: Line 890:
 
Before we begin, we need to figure out what the commands for gr_modtool are so let's ask for help.
 
Before we begin, we need to figure out what the commands for gr_modtool are so let's ask for help.
  
<pre>$ gr_modtool help
+
<pre>$ gr_modtool --help
Usage:
+
Usage: gr_modtool [OPTIONS] COMMAND [ARGS]...
gr_modtool [options] -- Run  with the given options.
+
 
gr_modtool help -- Show a list of commands.
+
  A tool for editing GNU Radio out-of-tree modules.
gr_modtool help -- Shows the help for a given command.
+
 
 +
Options:
 +
  --help  Show this message and exit.
 +
 
 +
Commands:
 +
  add      Adds a block to the out-of-tree module.
 +
  disable  Disable selected block in module.
 +
  info      Return information about a given module
 +
  makeyaml Generate YAML files for GRC block bindings.
 +
  newmod    Create new empty module, use add to add blocks.
 +
  rename    Rename a block inside a module.
 +
  rm        Remove a block from a module.
 +
  update    Update the grc bindings for a block
  
List of possible commands:
+
  Manipulate with GNU Radio modules source code tree. Call it without
 +
  options to run specified command interactively
  
Name      Aliases          Description
 
=====================================================================
 
disable  dis              Disable block (comments out CMake entries for files)
 
info      getinfo,inf      Return information about a given module
 
remove    rm,del          Remove block (delete files and remove Makefile entries)
 
makexml  mx              Make XML file for GRC block bindings
 
add      insert          Add block to the out-of-tree module.
 
newmod    nm,create        Create a new out-of-tree module
 
 
</pre>
 
</pre>
 
We immediately see there are many commands available. In this tutorial we will only cover '''newmod''' and '''add'''; however, the thorough explanation should enable smooth usage of the other gr_modtool commands without guidance.
 
We immediately see there are many commands available. In this tutorial we will only cover '''newmod''' and '''add'''; however, the thorough explanation should enable smooth usage of the other gr_modtool commands without guidance.
Line 739: Line 917:
  
 
<pre>
 
<pre>
$ gr_modtool help newmod
+
$ gr_modtool newmod --help
Usage: gr_modtool nm [options].
+
Usage: gr_modtool newmod [OPTIONS] MODULE-NAME
Call gr_modtool without any options to run it interactively.
+
 
 +
  Create a new out-of-tree module
 +
 
 +
  The argument MODULE-NAME is the name of the module to be added.
  
 
Options:
 
Options:
   General options:
+
   --srcdir TEXT            Source directory for the module template.
    -h, --help          Displays this help message.
+
  -d, --directory TEXT      Base directory of the module. Defaults to the cwd.
    -d DIRECTORY, --directory=DIRECTORY
+
  --skip-lib               Don't do anything in the lib/ subdirectory.
                        Base directory of the module. Defaults to the cwd.
+
  --skip-swig               Don't do anything in the swig/ subdirectory.
    -n MODULE_NAME, --module-name=MODULE_NAME
+
  --skip-python            Don't do anything in the python/ subdirectory.
                        Use this to override the current module's name (is
+
  --skip-grc               Don't do anything in the grc/ subdirectory.
                        normally autodetected).
+
  --scm-mode [yes|no|auto]  Use source control management [ yes | no | auto ]).
    -N BLOCK_NAME, --block-name=BLOCK_NAME
+
  -y, --yes                 Answer all questions with 'yes'. This can
                        Name of the block, where applicable.
+
                            overwrite and delete your files, so be careful.
    --skip-lib         Don't do anything in the lib/ subdirectory.
+
  --help                    Show this message and exit.
    --skip-swig         Don't do anything in the swig/ subdirectory.
 
    --skip-Python      Don't do anything in the Python/ subdirectory.
 
    --skip-grc         Don't do anything in the grc/ subdirectory.
 
    --scm-mode=SCM_MODE
 
                        Use source control management (yes, no or auto).
 
    -y, --yes           Answer all questions with 'yes'. This can overwrite
 
                        and delete your files, so be careful.
 
  
  New out-of-tree module options:
 
    --srcdir=SRCDIR    Source directory for the module template
 
 
</pre>
 
</pre>
Now that we have read over the list of commands for newmod, we can deduce that the one we want to pick is -n which is the default so we can simply type the MODULE_NAME after newmod. It is actually advised to avoid using &quot;-n&quot; as for other commands it can override the auto-detected name. For now, let's ignore the other options.
+
Now that we have read over the list of commands for newmod, we can deduce that the one we want to pick is -n which is the default so we can simply type the MODULE_NAME after newmod. It is actually advised to avoid using "-n" as for other commands it can override the auto-detected name. For now, let's ignore the other options.
  
 
=== 3.2.2. Setting up a new block ===
 
=== 3.2.2. Setting up a new block ===
Line 806: Line 978:
 
                         Language (cpp or Python)
 
                         Language (cpp or Python)
 
</pre>
 
</pre>
We can see the '''-l LANG''' and the '''-t BLOCK_TYPE''' are relevant for our example. Thus when creating our new block, we know the command. When prompted for a name simply enter &quot;multiply_py_ff&quot;, when prompted for an argument list enter &quot;multiple&quot;, and when prompted for Python QA (Quality Assurance) code type &quot;y&quot;, or just hit enter (the capital letter is the default value).
+
We can see the '''-l LANG''' and the '''-t BLOCK_TYPE''' are relevant for our example. Thus when creating our new block, we know the command. When prompted for a name simply enter "multiply_py_ff", when prompted for an argument list enter "multiple", and when prompted for Python QA (Quality Assurance) code type "y", or just hit enter (the capital letter is the default value).
  
 
<pre>gr-tutorial$ gr_modtool add -t sync -l python
 
<pre>gr-tutorial$ gr_modtool add -t sync -l python
Line 818: Line 990:
 
Adding file 'Python/qa_multiply_py_ff.py'...
 
Adding file 'Python/qa_multiply_py_ff.py'...
 
Editing Python/CMakeLists.txt...
 
Editing Python/CMakeLists.txt...
Adding file 'grc/tutorial_multiply_py_ff.xml'...
+
Adding file 'grc/tutorial_multiply_py_ff.yml'...
 
Editing grc/CMakeLists.txt...
 
Editing grc/CMakeLists.txt...
 
</pre>
 
</pre>
Line 836: Line 1,008:
  
 
class multiply_py_ff(gr.sync_block):
 
class multiply_py_ff(gr.sync_block):
     &quot;&quot;&quot;
+
     """
 
     docstring for block multiply_py_ff
 
     docstring for block multiply_py_ff
     &quot;&quot;&quot;
+
     """
 
     def __init__(self, multiple):
 
     def __init__(self, multiple):
 
         gr.sync_block.__init__(self,
 
         gr.sync_block.__init__(self,
             name=&quot;multiply_py_ff&quot;,
+
             name="multiply_py_ff",
             in_sig=[&lt;+numpy.float+&gt;],
+
             in_sig=[<+numpy.float+>],
             out_sig=[&lt;+numpy.float+&gt;])
+
             out_sig=[<+numpy.float+>])
 
         self.multiple = multiple
 
         self.multiple = multiple
  
Line 850: Line 1,022:
 
         in0 = input_items[0]
 
         in0 = input_items[0]
 
         out = output_items[0]
 
         out = output_items[0]
         # &lt;+signal processing here+&gt;
+
         # <+signal processing here+>
 
         out[:] = in0
 
         out[:] = in0
 
         return len(output_items[0])
 
         return len(output_items[0])
<syntaxhighlight>
+
</syntaxhighlight>
Let's take this one line by line as our first Python examples. We are already familiar with the imports so we will skip those lines. We are familiar with the constructor (init) of Python so can immediately see that if we want to use our variable &quot;multiple&quot;, we need to add another line. Let us not forget to preserve those spaces as some code editors like to add tabs to new lines. How do we use the variable multiple?
+
Let's take this one line by line as our first Python examples. We are already familiar with the imports so we will skip those lines. We are familiar with the constructor (init) of Python so can immediately see that if we want to use our variable "multiple", we need to add another line. Let us not forget to preserve those spaces as some code editors like to add tabs to new lines. How do we use the variable multiple?
  
{{collapse(View How to use variable multiple...)
+
How to use variable multiple...
  
 
<syntaxhighlight lang="python">
 
<syntaxhighlight lang="python">
Line 862: Line 1,034:
 
         self.multiple = multiple
 
         self.multiple = multiple
 
         gr.sync_block.__init__(self,
 
         gr.sync_block.__init__(self,
<syntaxhighlight>
+
</syntaxhighlight>
}}
 
  
We notice that there are &quot;&lt;''...''&gt;&quot; scattered in many places. These placeholders are from gr_modtool and tell us where we need to alter things
+
 
 +
We notice that there are "&lt;''...''&gt;" scattered in many places. These placeholders are from gr_modtool and tell us where we need to alter things
  
 
<syntaxhighlight lang="python">
 
<syntaxhighlight lang="python">
in_sig=[&lt;+numpy.float+&gt;]
+
in_sig=[<+numpy.float+>]
out_sig=[&lt;+numpy.float+&gt;]
+
out_sig=[<+numpy.float+>]
<\syntaxhighlight>
+
</syntaxhighlight>
The '''gr.sync_block.''init''''' takes in 4 inputs: self, name, and the size/type of the input and output vectors. First, we want to make the item size a single precision float or numpy.float32 by removing the &quot;&lt;''&quot; and the &quot;''&gt;&quot;. If we wanted vectors, we could define those as in_sig=[(numpy.float32,4),numpy.float32]. This means there are two input ports, one for vectors of 4 floats and the other for scalars. It is worth noting that if in_sig contains nothing then it becomes a source block, and if out_sig contains nothing it becomes a sink block (provided we change return <code>len(output_items[0])</code> to return <code>len(input_items[0])</code> since output_items is empty). Our changes to the first placeholders should appear as follows:
+
The '''gr.sync_block.''init''''' takes in 4 inputs: self, name, and the size/type of the input and output vectors. First, we want to make the item size a single precision float or numpy.float32 by removing the "&lt;''" and the "''&gt;". If we wanted vectors, we could define those as in_sig=[(numpy.float32,4),numpy.float32]. This means there are two input ports, one for vectors of 4 floats and the other for scalars. It is worth noting that if in_sig contains nothing then it becomes a source block, and if out_sig contains nothing it becomes a sink block (provided we change return <code>len(output_items[0])</code> to return <code>len(input_items[0])</code> since output_items is empty). Our changes to the first placeholders should appear as follows:
  
 
<syntaxhighlight lang="python">
 
<syntaxhighlight lang="python">
 
in_sig=[numpy.float32]
 
in_sig=[numpy.float32]
 
out_sig=[numpy.float32]
 
out_sig=[numpy.float32]
<\syntaxhighlight>
+
</syntaxhighlight>
 
The other piece of code that has the placeholders is in the work function but let us first get a better understanding of the work function:
 
The other piece of code that has the placeholders is in the work function but let us first get a better understanding of the work function:
  
 
<syntaxhighlight lang="python">
 
<syntaxhighlight lang="python">
 
def work(self, input_items, output_items)
 
def work(self, input_items, output_items)
<\syntaxhighlight>
+
</syntaxhighlight>
 
The work function is where the actual processing happens, where we want our code to be. Because this is a sync block, the number of input items always equals the number of output items because synchronous block ensures a fixed output to input rate. There are also decimation and interpolation blocks where the number of output items are a user specified multiple of the number of input items. We will further discuss when to use what block type in the third section of this tutorial. For now we look at the placeholder:
 
The work function is where the actual processing happens, where we want our code to be. Because this is a sync block, the number of input items always equals the number of output items because synchronous block ensures a fixed output to input rate. There are also decimation and interpolation blocks where the number of output items are a user specified multiple of the number of input items. We will further discuss when to use what block type in the third section of this tutorial. For now we look at the placeholder:
  
Line 887: Line 1,059:
 
in0 = input_items[0]
 
in0 = input_items[0]
 
out = output_items[0]
 
out = output_items[0]
# &lt;+signal processing here+&gt;
+
# <+signal processing here+>
 
out[:] = in0
 
out[:] = in0
 
return len(output_items[0])
 
return len(output_items[0])
<syntaxhighlight>
+
</syntaxhighlight>
The &quot;in0&quot; and &quot;out&quot; simply store the input and output in a variable to make the block easier to write. The signal processing can be anything including if statements, loops, function calls but for this example we only need to modify the out[:] = in0 line so that our input signal is multiplied by our variable multiple. What do we need to add to make the in0 multiply by our multiple?
+
The "in0" and "out" simply store the input and output in a variable to make the block easier to write. The signal processing can be anything including if statements, loops, function calls but for this example we only need to modify the out[:] = in0 line so that our input signal is multiplied by our variable multiple. What do we need to add to make the in0 multiply by our multiple?
  
{{collapse(How to Multiple...)
+
How to Multiple...
  
 
<syntaxhighlight lang="python">
 
<syntaxhighlight lang="python">
 
out[:] = in0*self.multiple
 
out[:] = in0*self.multiple
<\syntaxhighlight>
+
</syntaxhighlight>
}}
 
  
 
That's it! Our block should now be able to multiply but to be sure we have these things called Quality Assurance tests!
 
That's it! Our block should now be able to multiply but to be sure we have these things called Quality Assurance tests!
Line 926: Line 1,097:
  
 
if __name__ == '__main__':
 
if __name__ == '__main__':
     gr_unittest.run(qa_multiply_py_ff, &quot;qa_multiply_py_ff.xml&quot;)
+
     gr_unittest.run(qa_multiply_py_ff)
<\syntaxhighlight>
+
</syntaxhighlight>
 
gr_unittest adds support for checking approximate equality of tuples of float and complex numbers. The only part we need to worry about is the def test_001_t function. We know we need input data so let us create data. We want it to be in the form of a vector so that we can test multiple values at once. Let us create a vector of floats
 
gr_unittest adds support for checking approximate equality of tuples of float and complex numbers. The only part we need to worry about is the def test_001_t function. We know we need input data so let us create data. We want it to be in the form of a vector so that we can test multiple values at once. Let us create a vector of floats
  
 
<syntaxhighlight lang="python">
 
<syntaxhighlight lang="python">
 
src_data = (0, 1, -2, 5.5, -0.5)
 
src_data = (0, 1, -2, 5.5, -0.5)
<\syntaxhighlight>
+
</syntaxhighlight>
 
We also need output data so we can compare the input of the block to ensure that it is doing what we expect it to do. Let us multiply by 2 for simplicity.
 
We also need output data so we can compare the input of the block to ensure that it is doing what we expect it to do. Let us multiply by 2 for simplicity.
  
 
<syntaxhighlight lang="python">expected_result = (0, 2, -4, 11, -1)
 
<syntaxhighlight lang="python">expected_result = (0, 2, -4, 11, -1)
<syntaxhighlight>
+
</syntaxhighlight>
Now we can create a flowgraph as we have when we first introduced using Python in GNU Radio. We can use the blocks library specifically the [http://gnuradio.org/doc/doxygen/classgr_1_1blocks_1_1vector__source__f.html vector_source_f] function and the [http://gnuradio.org/doc/doxygen/classgr_1_1blocks_1_1vector__sink__f.html vector_sink_f] function which are linked to the doxygen manual which we should be able to read and understand. Let us assign three variables &quot;src&quot;, &quot;mult&quot;, and &quot;snk&quot; to the blocks. The first is shown below:
+
Now we can create a flowgraph as we have when we first introduced using Python in GNU Radio. We can use the blocks library specifically the [http://gnuradio.org/doc/doxygen/classgr_1_1blocks_1_1vector__source__f.html vector_source_f] function and the [http://gnuradio.org/doc/doxygen/classgr_1_1blocks_1_1vector__sink__f.html vector_sink_f] function which are linked to the doxygen manual which we should be able to read and understand. Let us assign three variables "src", "mult", and "snk" to the blocks. The first is shown below:
  
<syntaxhighlight lang="python">src = blocks.vector_source_f(src_data)<\syntaxhighlight>
+
<syntaxhighlight lang="python">src = blocks.vector_source_f(src_data)</syntaxhighlight>
 
The rest are hidden below as an exercise:
 
The rest are hidden below as an exercise:
  
{{collapse(What do we assign snk and mult?)
+
What do we assign snk and mult?
  
 
<syntaxhighlight lang="python">mult = multiply_py_ff(2)
 
<syntaxhighlight lang="python">mult = multiply_py_ff(2)
 
snk = blocks.vector_sink_f()
 
snk = blocks.vector_sink_f()
<syntaxhighlight>
+
</syntaxhighlight>
}}
+
 
  
 
Now we need to connect everything as src <s>&gt; mult</s>&gt; snk. Instead of using self.connect as we did in our other blocks we need to use self.tb.connect because of the setUp function. Below is how we would connect the src block to the mult block.
 
Now we need to connect everything as src <s>&gt; mult</s>&gt; snk. Instead of using self.connect as we did in our other blocks we need to use self.tb.connect because of the setUp function. Below is how we would connect the src block to the mult block.
  
<syntaxhighlight lang="python" line="line">self.tb.connect (src, mult)
+
<syntaxhighlight lang="python">
<syntaxhighlight>
+
self.tb.connect (src, mult)
{{collapse(How would we connect the other blocks together?)
+
</syntaxhighlight>
 +
 
 +
How would we connect the other blocks together?
 +
 
 +
<syntaxhighlight lang="python">
 +
self.tb.connect (mult, snk)
 +
</syntaxhighlight>
  
<syntaxhighlight lang="python" line="line">self.tb.connect (mult, snk)
 
<syntaxhighlight>
 
}}
 
  
 
Then we can run the graph and store the data from the sink as below:
 
Then we can run the graph and store the data from the sink as below:
  
<syntaxhighlight lang="python" line="line">self.tb.run ()
+
<syntaxhighlight lang="python">self.tb.run ()
 
result_data = snk.data ()
 
result_data = snk.data ()
<syntaxhighlight>
+
</syntaxhighlight>
Lastly we can run our comparison function that will tell us whether the numbers match up to 6 decimal places. We are using the assertFloatTuplesAlmostEqual instead of the &quot;regular assert functions&quot;https://docs.python.org/2/library/unittest.html#assert-methods included in python's unittest because there may be situations where we cannot get a=b due to rounding in floating point numbers.
+
Lastly we can run our comparison function that will tell us whether the numbers match up to 6 decimal places. We are using the assertFloatTuplesAlmostEqual instead of the "regular assert functions"https://docs.python.org/2/library/unittest.html#assert-methods included in python's unittest because there may be situations where we cannot get a=b due to rounding in floating point numbers.
  
<syntaxhighlight lang="python" line="line">self.assertFloatTuplesAlmostEqual (expected_result, result_data, 6)
+
<syntaxhighlight lang="python">
<syntaxhighlight>
+
self.assertFloatTuplesAlmostEqual (expected_result, result_data, 6)
 +
</syntaxhighlight>
 
All together the new test_001_t function should appear as below:
 
All together the new test_001_t function should appear as below:
  
<syntaxhighlight lang="python" line="line">src_data = (0, 1, -2, 5.5, -0.5)
+
<syntaxhighlight lang="python">
 +
src_data = (0, 1, -2, 5.5, -0.5)
 
expected_result = (0, 2, -4, 11, -1)
 
expected_result = (0, 2, -4, 11, -1)
 
src = blocks.vector_source_f (src_data)
 
src = blocks.vector_source_f (src_data)
Line 980: Line 1,156:
 
result_data = snk.data ()
 
result_data = snk.data ()
 
self.assertFloatTuplesAlmostEqual (expected_result, result_data, 6)
 
self.assertFloatTuplesAlmostEqual (expected_result, result_data, 6)
<syntaxhighlight>
+
</syntaxhighlight>
 +
 
 
We can then go to the python directory and run:
 
We can then go to the python directory and run:
  
<syntaxhighlight lang="python" line="line">gr-tutorial/python$ python qa_multiply_py_ff.py
+
<pre>
 +
gr-tutorial/python$ python qa_multiply_py_ff.py
 
.
 
.
 
----------------------------------------------------------------------
 
----------------------------------------------------------------------
Line 989: Line 1,167:
  
 
OK
 
OK
<syntaxhighlight>
+
</pre>
 +
 
 
While we are here, we should take a break to change one of the numbers in the src_data to ensure that the block is actually checking the values and to simply see what an error looks like. Python allows for really quick testing of blocks without having to compile anything; simply change something and re-run the QA test.
 
While we are here, we should take a break to change one of the numbers in the src_data to ensure that the block is actually checking the values and to simply see what an error looks like. Python allows for really quick testing of blocks without having to compile anything; simply change something and re-run the QA test.
  
=== 3.2.5. XML Files ===
+
=== 3.2.5. YAML Files ===
  
At this point we should have written a Python block and a QA test for that block. The next thing to do is edit the XML file in the grc folder so that we can get another step closer to using it in GRC. GRC uses the XML files for all the options we see. We actually don't need to write any Python or C++ code to have a block display in GRC but of course if we would connect it, it wouldn't do anything but give errors. We should get out of the python folder and go to the grc folder where all the XML files reside. There is a tool in gr_modtool called makexml but it is only available for C++ blocks. Let us open the tutorial_multiply_py_ff.xml file copied below:
+
At this point we should have written a Python block and a QA test for that block. The next thing to do is edit the YAML file in the grc folder so that we can get another step closer to using it in GRC. GRC uses the YAML files for all the options we see. We actually don't need to write any Python or C++ code to have a block display in GRC but of course if we would connect it, it wouldn't do anything but give errors. We should get out of the python folder and go to the grc folder where all the YAML files reside. There is a tool in gr_modtool called makexml but it is only available for C++ blocks. Let us open the tutorial_multiply_py_ff.xml file copied below:
  
<syntaxhighlight lang="python" line="line">
+
<syntaxhighlight lang="YAML" line="line">
  multiply_py_ff
+
id: tutorial_multiply_py_ff
  tutorial_multiply_py_ff
+
label: multiply_py_ff
  tutorial
+
category: '[tutorial]'
   import tutorial
+
 
   tutorial.multiply_py_ff($multiple)
+
templates:
    
+
   imports: import tutorial
    
+
   make: tutorial.multiply_py_ff(${multiple})
    ...
+
 
    ...
+
#  Make one 'parameters' list entry for every Parameter you want settable from the GUI.
    ...
+
#    Sub-entries of dictionary:
    
+
#    * id (makes the value accessible as \$keyname, e.g. in the make entry)
 +
#    * label
 +
#    * dtype
 +
parameters:
 +
- id: ...
 +
   label: ...
 +
   dtype: ...
 +
- id: ...
 +
  label: ...
 +
   dtype: ...
  
    
+
#  Make one 'inputs' list entry per input. Sub-entries of dictionary:
    
+
#      * label (an identifier for the GUI)
    in
+
#      * domain
   
+
#      * dtype
    
+
#      * vlen
 +
#      * optional (set to 1 for optional inputs)
 +
inputs:
 +
- label: ...
 +
   domain: ...
 +
   dtype: ...
 +
   vlen: ...
  
 
+
#  Make one 'outputs' list entry per output. Sub-entries of dictionary:
 
+
#      * label (an identifier for the GUI)
    out
+
#      * dtype
   
+
#      * vlen
    
+
#      * optional (set to 1 for optional inputs)
<syntaxhighlight>
+
- label: ...
</code>
+
  domain: ...
 +
   dtype: ... #!-- e.g. int, float, complex, byte, short, xxx_vector, ...--
 +
 
 +
file_format: 1
 +
</syntaxhighlight>
  
 
We can change the name that appears and the category it will appear in GRC. The category is where the block will be found in GRC. Examples of categories tag are '''Audio''' and '''Waveform Generators''' used in previous examples. Examples of names tag are the '''QT GUI Time Sink''' or the '''Audio Sink'''. Again, we can go through the file and find the modtool place holders. The first is copied below:
 
We can change the name that appears and the category it will appear in GRC. The category is where the block will be found in GRC. Examples of categories tag are '''Audio''' and '''Waveform Generators''' used in previous examples. Examples of names tag are the '''QT GUI Time Sink''' or the '''Audio Sink'''. Again, we can go through the file and find the modtool place holders. The first is copied below:
  
<syntaxhighlight lang="python" line="line"><\syntaxhighlight>
+
<syntaxhighlight lang="YAML" line="line">
This is referring to the parameter that we used in the very beginning when creating our block: the variable called &quot;multiple&quot;. We can fill it in as below:
+
#  Make one 'parameters' list entry for every Parameter you want settable from the GUI.
 +
#    Sub-entries of dictionary:
 +
#    * id (makes the value accessible as \$keyname, e.g. in the make entry)
 +
#    * label
 +
#    * dtype
 +
</syntaxhighlight>
 +
This is referring to the parameter that we used in the very beginning when creating our block: the variable called "multiple". We can fill it in as below:
  
<syntaxhighlight lang="python" line="line">   
+
<syntaxhighlight lang="YAML" line="line">   
    Multiple
+
parameters:
    multiple
+
- id: multiple
    float
+
  label: Multiple
    
+
   dtype: float
<syntaxhighlight>
+
</syntaxhighlight>
The next placeholder can be found in the sink and source tags:
+
The next placeholder can be found in the inputs and outputs tags:
  
<syntaxhighlight lang="python" line="line">   
+
<syntaxhighlight lang="YAML" line="line">
    in
+
inputs:
   
+
- label: in
    
+
   dtype: float
<syntaxhighlight>
+
 
We can see that it is asking for a type so we can simply erase everything in the tag and replace it with &quot;float&quot; for both the source and the sink blocks. That should do it for this block. The best way to get more experience writing xml files is to look at the source code of previously made blocks such as the existing multiple block. Let's go back to this and use the documentation tag!
+
outputs:
 +
- label: out
 +
   dtype: float #!-- e.g. int, float, complex, byte, short, xxx_vector, ...--
 +
</syntaxhighlight>
 +
We can see that it is asking for a type so we can simply erase everything in the tag and replace it with "float" for both the source and the sink blocks. That should do it for this block. The best way to get more experience writing YAML files is to look at the source code of previously made blocks such as the existing multiple block. Let's go back to this and use the documentation tag!
  
 
=== 3.2.6. Installing Python Blocks ===
 
=== 3.2.6. Installing Python Blocks ===
  
Now that we have edited the XML file; we are ready to install the block into the GRC. First, we need to get out of the /grc directory and create a build directory called &quot;build&quot;. Inside the build directory, we can then run a series of commands:
+
Now that we have edited the XML file; we are ready to install the block into the GRC. First, we need to get out of the /grc directory and create a build directory called "build". Inside the build directory, we can then run a series of commands:
 +
 
 +
cmake ../
 +
make
 +
sudo make install
 +
sudo ldconfig
  
<syntaxhighlight lang="python" line="line">cmake ../
 
make
 
sudo make install
 
sudo ldconfig
 
<syntaxhighlight>
 
<\syntaxhighlight>
 
 
We should then open up the GRC and take a look at the new block.
 
We should then open up the GRC and take a look at the new block.
  
[[File:https://raw.githubusercontent.com/gnuradio/gr-tutorial/master/examples/tutorial3/images/xml_blockname.png|xml_blockname.png]]
 
 
https://raw.githubusercontent.com/gnuradio/gr-tutorial/master/examples/tutorial3/images/xml_blockname.png
 
https://raw.githubusercontent.com/gnuradio/gr-tutorial/master/examples/tutorial3/images/xml_blockname.png
  
Line 1,064: Line 1,270:
 
Now that we can see our block, let us test it to make sure it works. Below is an example of one of the many ways to check whether it is actually multiplying.
 
Now that we can see our block, let us test it to make sure it works. Below is an example of one of the many ways to check whether it is actually multiplying.
  
[[File:https://raw.githubusercontent.com/gnuradio/gr-tutorial/master/examples/tutorial3/images/tutorial_three_2.png|600px|tutorial_three_2.png]]
 
 
https://raw.githubusercontent.com/gnuradio/gr-tutorial/master/examples/tutorial3/images/tutorial_three_2.png
 
https://raw.githubusercontent.com/gnuradio/gr-tutorial/master/examples/tutorial3/images/tutorial_three_2.png
  
 
== 3.3. My QPSK Demodulator for Satellites ==
 
== 3.3. My QPSK Demodulator for Satellites ==
  
Now that we have a better understanding on how to add new blocks to GNU Radio for use in the GRC, we can do another example. This time we will be creating a QPSK demodulator block using the same process as before in the same module. Let's first setup the scenario. There is a &quot;noise source&quot; that outputs data in complex float format but let's pretend it comes from a satellite being aimed at our computer. Our secret agent insider tells us this particular satellite encodes digital data using QPSK modulation. We can decode this using a QPSK demodulator that outputs data into bytes. Our insider tells us the space manual doesn't specify whether it's gray code or not. We want to read the bytes using a time sink. What would our flowgraph look like?
+
Now that we have a better understanding on how to add new blocks to GNU Radio for use in the GRC, we can do another example. This time we will be creating a QPSK demodulator block using the same process as before in the same module. Let's first setup the scenario. There is a "noise source" that outputs data in complex float format but let's pretend it comes from a satellite being aimed at our computer. Our secret agent insider tells us this particular satellite encodes digital data using QPSK modulation. We can decode this using a QPSK demodulator that outputs data into bytes. Our insider tells us the space manual doesn't specify whether it's gray code or not. We want to read the bytes using a time sink. What would our flowgraph look like?
  
{{collapse(Incomplete Flowgraph...)<br />
+
Incomplete Flowgraph...
[[File:https://raw.githubusercontent.com/gnuradio/gr-tutorial/master/examples/tutorial3/images/tutorial_three_3.png|600px|tutorial_three_3.png]]<br />
 
 
https://raw.githubusercontent.com/gnuradio/gr-tutorial/master/examples/tutorial3/images/tutorial_three_3.png
 
https://raw.githubusercontent.com/gnuradio/gr-tutorial/master/examples/tutorial3/images/tutorial_three_3.png
}}
+
 
  
 
Now that we know the input type, output type, and parameters, we can ask the question we skipped with our multiply_py_ff block. What type of block do we want?
 
Now that we know the input type, output type, and parameters, we can ask the question we skipped with our multiply_py_ff block. What type of block do we want?
Line 1,089: Line 1,293:
 
When we insert data into our block, do we need more samples or less samples? Or put another way, should our sample rate change?
 
When we insert data into our block, do we need more samples or less samples? Or put another way, should our sample rate change?
  
{{collapse(What Type of Block Should we Use?)
+
What Type of Block Should we Use?
 +
* Sync Block or Basic Block
  
<syntaxhighlight lang="python" line="line">Sync Block or Basic Block
 
<syntaxhighlight>
 
}}
 
  
 
=== 3.3.2. Adding Another Block to our OOT Module ===
 
=== 3.3.2. Adding Another Block to our OOT Module ===
  
Now we know everything we need to know to create the block in gr_modtool. As a refresher, what would our gr_modtool command be?g
+
Now we know everything we need to know to create the block in gr_modtool. As a refresher, what would our gr_modtool command be?
  
{{collapse(gr_modtool command...)
+
gr_modtool command...
 +
<pre>
 +
gr-tutorial$ gr_modtool add -t sync -l python
 +
 +
name: qpsk_demod_py_cb (c for complex input and b for byte/char/int8 output)<br />
 +
args: gray_code<br />
 +
QA Code: y
 +
</pre>
  
<syntaxhighlight lang="python" line="line">gr-tutorial$ gr_modtool add -t sync -l python
 
<syntaxhighlight>
 
}}
 
 
name: qpsk_demod_py_cb (c for complex input and b for byte/char/int8 output)<br />
 
args: gray_code<br />
 
QA Code: y
 
  
 
Now we have our files setup so we can begin with editing the qpsk_demod_py.py file in the /python folder
 
Now we have our files setup so we can begin with editing the qpsk_demod_py.py file in the /python folder
Line 1,117: Line 1,319:
 
With [http://en.wikipedia.org/wiki/Phase-shift_keying#Quadrature_phase-shift_keying_.28QPSK.29 Gray coding] (adjacent only flips by 1). Note that the mapping we use here is different from the mapping on wikipedia:
 
With [http://en.wikipedia.org/wiki/Phase-shift_keying#Quadrature_phase-shift_keying_.28QPSK.29 Gray coding] (adjacent only flips by 1). Note that the mapping we use here is different from the mapping on wikipedia:
  
<syntaxhighlight lang="python" line="line">(-1+1j) 10 | 00 (1+1j)
+
 
-----------+-----------
+
(-1+1j) 10 | 00 (1+1j)
(-1-1j) 11 | 01 (1-1j)
+
-----------+-----------
<syntaxhighlight>
+
(-1-1j) 11 | 01 (1-1j)
 +
 
 
Without Gray coding:
 
Without Gray coding:
  
<syntaxhighlight lang="python" line="line">(-1+1j) 11 | 00 (1+1j)
+
(-1+1j) 11 | 00 (1+1j)
-----------+-----------
+
-----------+-----------
(-1-1j) 10 | 01 (1-1j)
+
(-1-1j) 10 | 01 (1-1j)
<syntaxhighlight>
+
 
 
We can see that we will need to write an if-else statement to take into account the gray_code variable. We will also need four other if-else statements inside the main if-else so that we can pick the mapping. Our pseudocode will look as follows:
 
We can see that we will need to write an if-else statement to take into account the gray_code variable. We will also need four other if-else statements inside the main if-else so that we can pick the mapping. Our pseudocode will look as follows:
  
<syntaxhighlight lang="python" line="line">if gray_code
+
if gray_code
    if 1+1j
+
    if 1+1j
        binary &quot;00&quot; = 0
+
        binary "00" = 0
    ....
+
    ....
    elif -1-1j
+
    elif -1-1j
        binary &quot;11&quot; = 3
+
        binary "11" = 3
else
+
else
    if 1+1j
+
    if 1+1j
        binary &quot;00&quot; = 0
+
        binary "00" = 0
    ....
+
    ....
    elif -1-1j
+
    elif -1-1j
        binary &quot;10&quot; = 2
+
        binary "10" = 2
<syntaxhighlight>
+
 
 
So we have everything we need to implement. Let's go ahead and fill in our gr_modtoool placeholders. We can begin with def init. There are three changes. How do we use the variable gray_code outside the function (similar to what we did with multiple in the last example)? What are the input and output types in [http://docs.scipy.org/doc/numpy/user/basics.types.html? numpy]
 
So we have everything we need to implement. Let's go ahead and fill in our gr_modtoool placeholders. We can begin with def init. There are three changes. How do we use the variable gray_code outside the function (similar to what we did with multiple in the last example)? What are the input and output types in [http://docs.scipy.org/doc/numpy/user/basics.types.html? numpy]
  
{{collapse(Changes to def ''init''...)
+
Changes to def ''init''...
  
<syntaxhighlight lang="python" line="line">   def __init__(self, gray_code):
+
<syntaxhighlight lang="python">
 +
    def __init__(self, gray_code):
 
         self.gray_code=gray_code
 
         self.gray_code=gray_code
 
         gr.sync_block.__init__(self,
 
         gr.sync_block.__init__(self,
             name=&quot;qpsk_demod_py&quot;,
+
             name="qpsk_demod_py",
 
             in_sig=[numpy.complex64],
 
             in_sig=[numpy.complex64],
 
             out_sig=[numpy.uint8])
 
             out_sig=[numpy.uint8])
<syntaxhighlight>
+
</syntaxhighlight>
</code><br />
 
}}
 
  
Once we have our constructor setup, we can go onto the work function. For simplicity and beauty, let us call the pseudocode we made above a function &quot;get_minimum_distance&quot; that takes samples as input arguments. In our multiply_py_ff example, we took all the samples and multiplied them with with out[:] = in0*self.multiple. The in0 is actually a vector so contains many samples within it. The multiply example required the same operation for each sample so it was okay to simply operate on the entire vector but now we need to have different operations per sample so what do we do?
+
Once we have our constructor setup, we can go onto the work function. For simplicity and beauty, let us call the pseudocode we made above a function "get_minimum_distance" that takes samples as input arguments. In our multiply_py_ff example, we took all the samples and multiplied them with with out[:] = in0*self.multiple. The in0 is actually a vector so contains many samples within it. The multiply example required the same operation for each sample so it was okay to simply operate on the entire vector but now we need to have different operations per sample so what do we do?
  
{{collapse(How can we operate on samples in a vector?)<br />
+
How can we operate on samples in a vector?
loops!
+
* loops!
  
<syntaxhighlight lang="python" line="line">       for i in range(0, len(output_items[0])):
+
<syntaxhighlight lang="python">
 +
        for i in range(0, len(output_items[0])):
 
             sample = in0[i]
 
             sample = in0[i]
 
             out[i] = self.get_minimum_distances(sample)
 
             out[i] = self.get_minimum_distances(sample)
<syntaxhighlight>
+
</syntaxhighlight>
</code><br />
+
 
}}
 
  
 
Now we can move onto the get_minimum_distances(self, sample) function. We already have pseudo code so the next step is translating to Python. Below is a snip of what the code can look like. Again there are multiple ways to do this
 
Now we can move onto the get_minimum_distances(self, sample) function. We already have pseudo code so the next step is translating to Python. Below is a snip of what the code can look like. Again there are multiple ways to do this
  
<syntaxhighlight lang="python" line="line">   def get_minimum_distances(self, sample):
+
<syntaxhighlight lang="python" line="line">
 +
    def get_minimum_distances(self, sample):
 
         if self.gray_code == 1:
 
         if self.gray_code == 1:
             if (sample.imag &gt;= 0 and sample.real &gt;= 0):
+
             if (sample.imag >= 0 and sample.real >= 0):
 
                 return 0 # 1+1j
 
                 return 0 # 1+1j
             elif (sample.imag &gt;= 0 and sample.real &lt; 0):
+
             elif (sample.imag >= 0 and sample.real < 0):
 
                 return 2 # -1+1j
 
                 return 2 # -1+1j
<syntaxhighlight>
+
</syntaxhighlight>
 
Let us try to fill in the other cases for gray code and non-gray code. Below is what the entire file Python file can look like once complete:
 
Let us try to fill in the other cases for gray code and non-gray code. Below is what the entire file Python file can look like once complete:
  
{{collapse(qpsk_demod_py_cb.py)
+
qpsk_demod_py_cb.py
  
<syntaxhighlight lang="python" line="line">import numpy
+
<syntaxhighlight lang="python" line="line">
 +
import numpy
 
from gnuradio import gr
 
from gnuradio import gr
  
 
class qpsk_demod_py(gr.sync_block):
 
class qpsk_demod_py(gr.sync_block):
     &quot;&quot;&quot;
+
     """
 
     docstring for block qpsk_demod_py
 
     docstring for block qpsk_demod_py
     &quot;&quot;&quot;
+
     """
 
     def __init__(self, gray_code):
 
     def __init__(self, gray_code):
 
         self.gray_code=gray_code
 
         self.gray_code=gray_code
 
         gr.sync_block.__init__(self,
 
         gr.sync_block.__init__(self,
             name=&quot;qpsk_demod_py&quot;,
+
             name="qpsk_demod_py",
 
             in_sig=[numpy.complex64],
 
             in_sig=[numpy.complex64],
 
             out_sig=[numpy.uint8])
 
             out_sig=[numpy.uint8])
Line 1,197: Line 1,401:
 
     def get_minimum_distances(self, sample):
 
     def get_minimum_distances(self, sample):
 
         if self.gray_code == 1:
 
         if self.gray_code == 1:
             if (sample.imag &gt;= 0 and sample.real &gt;= 0):
+
             if (sample.imag >= 0 and sample.real >= 0):
 
                 return 0 # 1+1j
 
                 return 0 # 1+1j
             elif (sample.imag &gt;= 0 and sample.real &lt; 0):
+
             elif (sample.imag >= 0 and sample.real < 0):
 
                 return 2 # -1+1j
 
                 return 2 # -1+1j
             elif (sample.imag &lt; 0 and sample.real &lt; 0):
+
             elif (sample.imag < 0 and sample.real < 0):
 
                 return 3 # -1-1j
 
                 return 3 # -1-1j
             elif (sample.imag &lt; 0 and sample.real &gt;= 0):
+
             elif (sample.imag < 0 and sample.real >= 0):
 
                 return 1 # 1-1j
 
                 return 1 # 1-1j
 
         else:
 
         else:
             if (sample.imag &gt;= 0 and sample.real &gt;= 0):
+
             if (sample.imag >= 0 and sample.real >= 0):
 
                 return 0 # 1+1j
 
                 return 0 # 1+1j
             elif (sample.imag &gt;= 0 and sample.real &lt; 0):
+
             elif (sample.imag >= 0 and sample.real < 0):
 
                 return 3 # -1+1j
 
                 return 3 # -1+1j
             elif (sample.imag &lt; 0 and sample.real &lt; 0):
+
             elif (sample.imag < 0 and sample.real < 0):
 
                 return 2 # -1-1j
 
                 return 2 # -1-1j
             elif (sample.imag &lt; 0 and sample.real &gt;= 0):
+
             elif (sample.imag < 0 and sample.real >= 0):
 
                 return 1 # 1-1j
 
                 return 1 # 1-1j
  
Line 1,224: Line 1,428:
  
 
         return len(output_items[0])
 
         return len(output_items[0])
<syntaxhighlight>
+
</syntaxhighlight>
}}
+
 
  
 
Now that we have code, we know what's next!
 
Now that we have code, we know what's next!
Line 1,235: Line 1,439:
 
We can copy the def test_001_t from the qa_multiply_py_ff code which is copied below:
 
We can copy the def test_001_t from the qa_multiply_py_ff code which is copied below:
  
<syntaxhighlight lang="python" line="line">   def test_001_t (self):
+
<syntaxhighlight lang="python" line="line">
 +
    def test_001_t (self):
 
         src_data = (-3, 4, -5.5, 2, 3)
 
         src_data = (-3, 4, -5.5, 2, 3)
 
         expected_result = (-6, 8, -11, 4, 6)
 
         expected_result = (-6, 8, -11, 4, 6)
Line 1,246: Line 1,451:
 
         result_data = dst.data ()
 
         result_data = dst.data ()
 
         self.assertFloatTuplesAlmostEqual (expected_result, result_data, 6)
 
         self.assertFloatTuplesAlmostEqual (expected_result, result_data, 6)
<syntaxhighlight>
+
</syntaxhighlight>
 
This time we are working with a complex input so our src = blocks.vector_source_f must change. If we use the search bar in the manual we can find the other options:
 
This time we are working with a complex input so our src = blocks.vector_source_f must change. If we use the search bar in the manual we can find the other options:
  
Line 1,257: Line 1,462:
 
s - short
 
s - short
  
{{collapse(What do we change our source and sink vectors to?)<br />
+
What do we change our source and sink vectors to?<br />
 
src = blocks.vector_source_c (src_data)<br />
 
src = blocks.vector_source_c (src_data)<br />
 
dst = blocks.vector_sink_b ()<br />
 
dst = blocks.vector_sink_b ()<br />
}}
+
 
  
 
Before we move onto actual test cases, let us decide which mode we are testing for the test_001_t. We can create a new variable and assign it False (translates to 0) to test non-Gray code
 
Before we move onto actual test cases, let us decide which mode we are testing for the test_001_t. We can create a new variable and assign it False (translates to 0) to test non-Gray code
  
<syntaxhighlight lang="python" line="line">gray_code = False
+
<syntaxhighlight lang="python">
<syntaxhighlight>
+
gray_code = False
 +
</syntaxhighlight>
 
Once we know we want to test non gray_code mappings, we can refer to our chart above and start placing in the proper inputs and outputs into the src_data and the expected_results. For instance if we were testing only two cases for non gray_code, we would do:
 
Once we know we want to test non gray_code mappings, we can refer to our chart above and start placing in the proper inputs and outputs into the src_data and the expected_results. For instance if we were testing only two cases for non gray_code, we would do:
  
 
<syntaxhighlight lang="python" line="line">src_data = ((-1-1j), (-1+1j))
 
<syntaxhighlight lang="python" line="line">src_data = ((-1-1j), (-1+1j))
 
expected_result = (2, 3)
 
expected_result = (2, 3)
<syntaxhighlight>
+
</syntaxhighlight>
Last thing to do is call upon our new block in the &quot;qpsk =&quot; line and pass it the gray_code parameter
+
Last thing to do is call upon our new block in the "qpsk =" line and pass it the gray_code parameter
  
{{collapse(qpsk = ?)<br />
+
qpsk = ?
qpsk = qpsk_demod_py_cb (gray_code)<br />
+
* qpsk = qpsk_demod_py_cb (gray_code)
}}
 
  
Now that we are done with the non gray_code test, we can simply create another test &quot;def test_002_t (self):&quot; and copy the contents underneath making sure that for this test we set gray_code = True and change the expected_result so it matches gray_code mapping. The full test is copied below:
+
Now that we are done with the non gray_code test, we can simply create another test "def test_002_t (self):" and copy the contents underneath making sure that for this test we set gray_code = True and change the expected_result so it matches gray_code mapping. The full test is copied below:
  
{{collapse(Full QA QPSK Demod Code...)
+
Full QA QPSK Demod Code...
  
<syntaxhighlight lang="python" line="line">from gnuradio import gr, gr_unittest
+
<syntaxhighlight lang="python" line="line">
 +
from gnuradio import gr, gr_unittest
 
from gnuradio import blocks
 
from gnuradio import blocks
 
import numpy
 
import numpy
Line 1,321: Line 1,527:
  
 
if __name__ == '__main__':
 
if __name__ == '__main__':
     gr_unittest.run(qa_qpsk_demod, &quot;qpsk_demod_py_cb.xml&quot;)
+
     gr_unittest.run(qa_qpsk_demod, "qpsk_demod_py_cb.xml")
<syntaxhighlight>
+
</syntaxhighlight>
}}
+
 
  
 
We can then run the test in Python and all should say something similar to:
 
We can then run the test in Python and all should say something similar to:
  
<syntaxhighlight lang="python" line="line">Ran 2 tests in 0.005s
+
Ran 2 tests in 0.005s
 +
 +
OK
  
OK
 
<syntaxhighlight>
 
 
So once we verify it works as expected, we can then edit our XML file so that it is usable inside GRC.
 
So once we verify it works as expected, we can then edit our XML file so that it is usable inside GRC.
  
Line 1,337: Line 1,543:
 
This XML is very similar to the XML file for the multiply_py_ff block so all we need to do is set the gray_code parameter and pick the correct input (complex) and output (byte) types. A copy of the full XML file is below:
 
This XML is very similar to the XML file for the multiply_py_ff block so all we need to do is set the gray_code parameter and pick the correct input (complex) and output (byte) types. A copy of the full XML file is below:
  
{{collapse(XML File for QPSK Demod)
+
XML File for QPSK Demod
  
 
<syntaxhighlight lang="python" line="line">
 
<syntaxhighlight lang="python" line="line">
 +
<?xml version="1.0"?>
 +
<block>
 +
  <name>qpsk_demod_py</name>
 +
  <key>tutorial_qpsk_demod_py</key>
 +
  <category>tutorial</category>
 +
  <import>import tutorial</import>
 +
  <make>tutorial.qpsk_demod_py($gray_code)</make>
 +
  <!-- Make one 'param' node for every Parameter you want settable from the GUI.
 +
      Sub-nodes:
 +
      * name
 +
      * key (makes the value accessible as $keyname, e.g. in the make node)
 +
      * type -->
 +
  <param>
 +
    <name>Gray Code</name>
 +
    <key>gray_code</key>
 +
    <type>int</type>
 +
  </param>
  
   qpsk_demod_py
+
   <!-- Make one 'sink' node per input. Sub-nodes:
  tutorial_qpsk_demod_py
+
      * name (an identifier for the GUI)
  tutorial
+
      * type
  import tutorial
+
      * vlen
  tutorial.qpsk_demod_py($gray_code)
+
      * optional (set to 1 for optional inputs) -->
    
+
   <sink>
 
+
     <name>in</name>
    Gray Code
+
     <type>complex</type>
     gray_code
+
   </sink>
     int
 
    
 
  
    
+
   <!-- Make one 'source' node per output. Sub-nodes:
    
+
      * name (an identifier for the GUI)
     in
+
      * type
     complex
+
      * vlen
    
+
      * optional (set to 1 for optional inputs) -->
 +
      <!-- e.g. int, float, complex, byte, short, xxx_vector, ...-->
 +
   <source>
 +
     <name>out</name>
 +
     <type>byte</type>
 +
   </source>
 +
</block>
 +
 
 +
</syntaxhighlight>
  
 
 
     
 
 
 
    out
 
    byte
 
 
 
<\syntaxhighlight>
 
}}
 
  
 
We can then install as we did for the multiply block however we need to rerun cmake in order to take into account the new block:
 
We can then install as we did for the multiply block however we need to rerun cmake in order to take into account the new block:
 
+
<pre>
<syntaxhighlight lang="bash" line="line">
+
cd build
cd build
+
cmake ../
cmake ../
+
make
make
+
sudo make install
sudo make install
+
sudo ldconfig
sudo ldconfig
+
</pre>
<\syntaxhighlight>
 
 
Then we can open up our GRC file from the beginning and place our missing block we just made.
 
Then we can open up our GRC file from the beginning and place our missing block we just made.
  
{{collapse(What is the Expected Output?)<br />
+
What is the Expected Output?
[[File:https://raw.githubusercontent.com/gnuradio/gr-tutorial/master/examples/tutorial3/images/tutorial_three_4.png|600px|tutorial_three_4.png]]<br />
 
 
https://raw.githubusercontent.com/gnuradio/gr-tutorial/master/examples/tutorial3/images/tutorial_three_4.png
 
https://raw.githubusercontent.com/gnuradio/gr-tutorial/master/examples/tutorial3/images/tutorial_three_4.png
}}
 
  
 
== 3.4. Conclusion ==
 
== 3.4. Conclusion ==
  
And that is it for now with Python. Let us know your thoughts before going on to the [http://gnuradio.org/redmine/projects/gnuradio/wiki/NewTutorials4 C++ tutorial].
+
And that is it for now with Python. Let us know your thoughts before going on to the [[Guided_Tutorial_GNU_Radio_in_C++|C++ tutorial]].
  
 
=== 3.4.1. Questions We Should Now be Able to Answer ===
 
=== 3.4.1. Questions We Should Now be Able to Answer ===
Line 1,392: Line 1,610:
 
1. How do we set input- and output signatures in Python blocks?<br />
 
1. How do we set input- and output signatures in Python blocks?<br />
 
2. Consider this I/O signature: (FIXME). Which input types and output types does it take?
 
2. Consider this I/O signature: (FIXME). Which input types and output types does it take?
 
=== 3.4.2. Links to Further Information ===
 
 
* [http://gnuradio.org/redmine/projects/gnuradio/wiki/BlocksCodingGuide Blocks Coding Guide]
 
* [http://gnuradio.org/redmine/projects/gnuradio/wiki/OutOfTreeModules Out-of-Tree Modules]
 
* [http://gnuradio.org/redmine/projects/gnuradio/wiki/TutorialsWritePythonApplications Writing Python Applications]
 
  
 
== 3.5. Candidates for Future Sections ==
 
== 3.5. Candidates for Future Sections ==
Line 1,404: Line 1,616:
 
- How to add documentation to blocks<br />
 
- How to add documentation to blocks<br />
 
- Constructor arguments, History, Output Multiple
 
- Constructor arguments, History, Output Multiple
 
 
-----
 
 
&lt;. [[Guided_Tutorial_GRC|Previous: Working with GRC]]
 
&gt;. [[Guided_Tutorial_GNU_Radio_in_C++|Next: Programming GNU Radio in C++]]
 
 
[[Category:Guided Tutorials]]
 

Latest revision as of 13:46, 25 May 2020


NOTE: This tutorial has been deprecated in GR 3.8.[edit]

Objectives[edit]

  • Python Blocks
  • OOT modules make the actual apps / functionality (GR is the API!)
  • How to add OOTs
  • How to add Python blocks with gr_modtool and how to code them
  • QPSK mapping
  • How to add GRC bindings for block

Prerequisites[edit]

  • Working Installation of GNU Radio 3.7
  • GRC Tutorial (Recommended)
  • Familiar with Python

3.1. Intro to Using GNU Radio with Python[edit]

This tutorial goes through three parts. The first is how to modify, create, or simply understand the Python generated files GRC produces for us. The second is how to create our own custom out-of-tree (OOT) modules from the ground up. Lastly we go through an actual project to get more practice and build intuition on how we can use GNU Radio in our own project. As with the last tutorial, all the content - pictures, source code, and grc files - is included in the gr-tutorial repository which we should have a local copy if we followed the directions from the GRC Tutorial

Again we should have a directory with the solutions and a directory with our work as below:


1 /home/user/gnuradio/tutorials/solutions
2 /home/user/gnuradio/tutorials/work

As a rule, if we hover over the GRC flowgraph images, we will be able to see the corresponding filename. Same applies for other images. Full code files are collapsed with the filename in the collapsed handle.

3.1.1. GRC Generated Python Files[edit]

Let us look at a dial-tone example on the GRC:

tutorial_three_1.png

When we click the Generate button, the terminal tells us it produced a .py file so let's open that to examine its code which is reproduced below:


  1 #!/usr/bin/env python3
  2 # -*- coding: utf-8 -*-
  3 
  4 #
  5 # SPDX-License-Identifier: GPL-3.0
  6 #
  7 # GNU Radio Python Flow Graph
  8 # Title: tutorial_three_1
  9 # GNU Radio version: 3.8.0.0
 10 
 11 from distutils.version import StrictVersion
 12 
 13 if __name__ == '__main__':
 14     import ctypes
 15     import sys
 16     if sys.platform.startswith('linux'):
 17         try:
 18             x11 = ctypes.cdll.LoadLibrary('libX11.so')
 19             x11.XInitThreads()
 20         except:
 21             print("Warning: failed to XInitThreads()")
 22 
 23 from gnuradio import analog
 24 from gnuradio import audio
 25 from gnuradio import gr
 26 from gnuradio.filter import firdes
 27 import sys
 28 import signal
 29 from PyQt5 import Qt
 30 from argparse import ArgumentParser
 31 from gnuradio.eng_arg import eng_float, intx
 32 from gnuradio import eng_notation
 33 from gnuradio import qtgui
 34 
 35 class tutorial_three_1(gr.top_block, Qt.QWidget):
 36 
 37     def __init__(self):
 38         gr.top_block.__init__(self, "tutorial_three_1")
 39         Qt.QWidget.__init__(self)
 40         self.setWindowTitle("tutorial_three_1")
 41         qtgui.util.check_set_qss()
 42         try:
 43             self.setWindowIcon(Qt.QIcon.fromTheme('gnuradio-grc'))
 44         except:
 45             pass
 46         self.top_scroll_layout = Qt.QVBoxLayout()
 47         self.setLayout(self.top_scroll_layout)
 48         self.top_scroll = Qt.QScrollArea()
 49         self.top_scroll.setFrameStyle(Qt.QFrame.NoFrame)
 50         self.top_scroll_layout.addWidget(self.top_scroll)
 51         self.top_scroll.setWidgetResizable(True)
 52         self.top_widget = Qt.QWidget()
 53         self.top_scroll.setWidget(self.top_widget)
 54         self.top_layout = Qt.QVBoxLayout(self.top_widget)
 55         self.top_grid_layout = Qt.QGridLayout()
 56         self.top_layout.addLayout(self.top_grid_layout)
 57 
 58         self.settings = Qt.QSettings("GNU Radio", "tutorial_three_1")
 59 
 60         try:
 61             if StrictVersion(Qt.qVersion()) < StrictVersion("5.0.0"):
 62                 self.restoreGeometry(self.settings.value("geometry").toByteArray())
 63             else:
 64                 self.restoreGeometry(self.settings.value("geometry"))
 65         except:
 66             pass
 67 
 68         ##################################################
 69         # Variables
 70         ##################################################
 71         self.samp_rate = samp_rate = 32000
 72 
 73         ##################################################
 74         # Blocks
 75         ##################################################
 76         self.audio_sink_0 = audio.sink(samp_rate, '', True)
 77         self.analog_sig_source_x_1 = analog.sig_source_f(samp_rate, analog.GR_COS_WAVE, 350, 0.1, 0, 0)
 78         self.analog_sig_source_x_0 = analog.sig_source_f(samp_rate, analog.GR_COS_WAVE, 440, 0.1, 0, 0)
 79 
 80 
 81 
 82         ##################################################
 83         # Connections
 84         ##################################################
 85         self.connect((self.analog_sig_source_x_0, 0), (self.audio_sink_0, 0))
 86         self.connect((self.analog_sig_source_x_1, 0), (self.audio_sink_0, 1))
 87 
 88     def closeEvent(self, event):
 89         self.settings = Qt.QSettings("GNU Radio", "tutorial_three_1")
 90         self.settings.setValue("geometry", self.saveGeometry())
 91         event.accept()
 92 
 93     def get_samp_rate(self):
 94         return self.samp_rate
 95 
 96     def set_samp_rate(self, samp_rate):
 97         self.samp_rate = samp_rate
 98         self.analog_sig_source_x_0.set_sampling_freq(self.samp_rate)
 99         self.analog_sig_source_x_1.set_sampling_freq(self.samp_rate)
100 
101 
102 
103 def main(top_block_cls=tutorial_three_1, options=None):
104 
105     if StrictVersion("4.5.0") <= StrictVersion(Qt.qVersion()) < StrictVersion("5.0.0"):
106         style = gr.prefs().get_string('qtgui', 'style', 'raster')
107         Qt.QApplication.setGraphicsSystem(style)
108     qapp = Qt.QApplication(sys.argv)
109 
110     tb = top_block_cls()
111     tb.start()
112     tb.show()
113 
114     def sig_handler(sig=None, frame=None):
115         Qt.QApplication.quit()
116 
117     signal.signal(signal.SIGINT, sig_handler)
118     signal.signal(signal.SIGTERM, sig_handler)
119 
120     timer = Qt.QTimer()
121     timer.start(500)
122     timer.timeout.connect(lambda: None)
123 
124     def quitting():
125         tb.stop()
126         tb.wait()
127     qapp.aboutToQuit.connect(quitting)
128     qapp.exec_()
129 
130 
131 if __name__ == '__main__':
132     main()

The first thing for us to realize is that the GRC can generate Python files that we can then modify to do things we wouldn't be able to do in GNU Radio Companion such as perform simulations. The libraries available in Python open up a whole new realm of possibilities! For now, we will explore the structure of the GRC Python files so we are comfortable creating more interesting applications.

3.1.2. Hello World Dissected[edit]

While examining the code, we need to get familiar with documentation. GNU Radio uses Doxygen (the software) for the GNU Radio Manual. The easiest way to go through the documentation is to go through the functions that we use so let us simplify our code by only including the bare bones needed to run the dial-tone example.

 1 #!/usr/bin/env Python3
 2 from gnuradio import gr
 3 from gnuradio import audio
 4 from gnuradio import analog
 5 
 6 class my_top_block(gr.top_block):
 7     def __init__(self):
 8         gr.top_block.__init__(self)
 9 
10         sample_rate = 32000
11         ampl = 0.1
12 
13         src0 = analog.sig_source_f(sample_rate, analog.GR_SIN_WAVE, 350, ampl)
14         src1 = analog.sig_source_f(sample_rate, analog.GR_SIN_WAVE, 440, ampl)
15         dst = audio.sink(sample_rate, "")
16         self.connect(src0, (dst, 0))
17         self.connect(src1, (dst, 1))
18 
19 if __name__ == '__main__':
20     try:
21         my_top_block().run()
22     except [[KeyboardInterrupt]]:
23         pass

Let us examine this line by line:

#!/usr/bin/env python3

Tells the shell that this file is a Python file and to use the Python interpreter to run this file. Should always be included at the top to run from the terminal.

from gnuradio import gr
from gnuradio import audio
from gnuradio import analog

Tells Python the modules to include. We must always have gr to run GNU Radio applications. The audio sink is included in the audio module and the signal_source_f is included in the analog module which is why we include them. PEP8 tells us we should import every module on its own line.

class my_top_block(gr.top_block):

Define a class called "my_top_block" which is derived from another class, gr.top_block. This class is basically a container for the flow graph. By deriving from gr.top_block, we get all the hooks and functions we need to add blocks and interconnect them.

def __init__(self):

Only one member function is defined for this class: the function "init()", which is the constructor of this class.

gr.top_block.__init__(self)

The parent constructor is called (in Python, this needs to be done explicitly. Most things in Python need to be done explicitly; in fact, this is one main Python principle).

sample_rate = 32000
ampl = 0.1

Variable declarations for sampling rate and amplitude that we will later use.

3.1.3. A Look at Documentation[edit]

src0 = analog.sig_source_f(sample_rate, analog.GR_SIN_WAVE, 350, ampl)
src1 = analog.sig_source_f(sample_rate, analog.GR_SIN_WAVE, 440, ampl)

Here we are using functions from GNU Radio so let's have a look at the documentation for analog.sig_source_f which is available in the GNU Radio manual. We can find it easily by using the search function as below:


hello_search.png

We can then scroll down to Member Function Documentation to see how the function is used and the parameters it accepts as below:

hello_source.png

We can see that our function analog.sig_source_f takes in 5 parameters but in our code we are only using 4. There is no error because the last input offset is set to "0" by default as shown in the documentation. The first input is the sampling_freq which we defined as sample_rate in our code. The second input is asking for a gr::analog::gr_waveform_t waveform so let's click that link to find out more.

hello_waveform.png

We can see that there are a couple of options to choose from. In this case we chose analog.GR_SIN_WAVE. The third input is wave_freq which we input "350" or "440". The fourth input is ampl which we defined as ampl.

dst = audio.sink(sample_rate, "")

Because documentation is so important, let's look at another example. Again, we can look at the documentation for audio.sink which is available on the GNU Radio Manual through the search function:

hello_sink.png

We can then as before scroll down to the Member Function Documentation to see the parameters it accepts:

hello_sink_detail.png

This time we have 3 inputs with the last being optional. In our code, for the first input sampling_rate we used are sample_rate variable. In the second input, we have a choice for what device to use for audio output. If we leave it alone as "" then it'll choose the default on our machine.

3.1.4. Connecting the Block Together[edit]

self.connect(src0, (dst, 0))
self.connect(src1, (dst, 1))

The general syntax for connecting blocks is self.connect(block1, block2, block3, ...) which would connect the output of block1 with the input of block2, the output of block2 with the input of block3 and so on. We can connect as many blocks as we wish with one connect() call. However this only work when there is a one-to-one correspondence. If we go back to our initial flowgraph, there are 2 inputs to the Audio Sink block. The way to connect them is by using the syntax above. The first line connects the only output of src0 (350 Hz waveform) to the first input of dst (Audio Sink). The second line connects the only output of src1 (440 Hz waveform) to the second input of dst (Audio Sink). The code so far is equivalent to the flowgraph we have created in the beginning; the rest of the lines simply start the flowgraph and provide a keyboard interrupt.

if __name__ == '__main__':
    try:
        my_top_block().run()
    except KeyboardInterrupt:
        pass

Luckily we are past the early years of GNU Radio when there was no GRC to make the Python files for us. Nowadays we can simply click things together in GRC instead of having to write code in Python to build flowgraphs. Still, a good understanding of what is going on every time we run GRC is good to know as it gives us more control of what we want the program to do.

3.1.5. Modifying the GRC Generated Python File[edit]

For instance, what if we wanted to change variables such as frequency and amplitude when a certain event occurs. How do we implement if statements, state machines, etc in GNU Radio? One way is to create our own blocks which we will delve into at length later. Another is to modify our GRC generated python file.

Our friend heard we were into RF so being cheap he has asked us to power his house using RF. He wants us to give him high power during the day so he can watch TV and play video games while at night give him low power so he power his alarm clock to wake up for work in the morning. We first need to setup the clock which keeps track of the day and gives us 1 for day or 0 for night. Once we get the time we can send him power through a sine wave using our massive terawatt amplifier and massive dish in our backyard. We did the calculations and we want to pulse at 1kHz, 1 amplitude during the day and 100Hz, 0.3 amplitude at night. Here's what we came up with in GRC:

if_else.png

- Frequency to "freq", Amplitude to "ampl"
- ID to "probe"
- Everything else is visible

The top section keeps track of time and will switch from 0 to 1 while the bottom section sends the pulse. The problem we encounter however is that there is no if-statement block. Sure we can tie the probe to the frequency as we did in tutorial2 for the singing sine wave but that only allows changing by a factor. What if we wanted to change multiple things and not by a linear factor? Let's start by running the flowgraph to make sure we get the output as below:

if_else_output.png

Now we can open up the GRC generated python file if_else.py which is copied below:

  1 #!/usr/bin/env python3
  2 # -*- coding: utf-8 -*-
  3 
  4 #
  5 # SPDX-License-Identifier: GPL-3.0
  6 #
  7 # GNU Radio Python Flow Graph
  8 # Title: if_else
  9 # GNU Radio version: 3.8.0.0
 10 
 11 from distutils.version import StrictVersion
 12 
 13 if __name__ == '__main__':
 14     import ctypes
 15     import sys
 16     if sys.platform.startswith('linux'):
 17         try:
 18             x11 = ctypes.cdll.LoadLibrary('libX11.so')
 19             x11.XInitThreads()
 20         except:
 21             print("Warning: failed to XInitThreads()")
 22 
 23 from PyQt5 import Qt
 24 from gnuradio import eng_notation
 25 from gnuradio import qtgui
 26 from gnuradio.filter import firdes
 27 import sip
 28 from gnuradio import analog
 29 from gnuradio import blocks
 30 from gnuradio import gr
 31 import sys
 32 import signal
 33 from argparse import ArgumentParser
 34 from gnuradio.eng_arg import eng_float, intx
 35 import time
 36 import threading
 37 from gnuradio import qtgui
 38 
 39 class if_else(gr.top_block, Qt.QWidget):
 40 
 41     def __init__(self):
 42         gr.top_block.__init__(self, "if_else")
 43         Qt.QWidget.__init__(self)
 44         self.setWindowTitle("if_else")
 45         qtgui.util.check_set_qss()
 46         try:
 47             self.setWindowIcon(Qt.QIcon.fromTheme('gnuradio-grc'))
 48         except:
 49             pass
 50         self.top_scroll_layout = Qt.QVBoxLayout()
 51         self.setLayout(self.top_scroll_layout)
 52         self.top_scroll = Qt.QScrollArea()
 53         self.top_scroll.setFrameStyle(Qt.QFrame.NoFrame)
 54         self.top_scroll_layout.addWidget(self.top_scroll)
 55         self.top_scroll.setWidgetResizable(True)
 56         self.top_widget = Qt.QWidget()
 57         self.top_scroll.setWidget(self.top_widget)
 58         self.top_layout = Qt.QVBoxLayout(self.top_widget)
 59         self.top_grid_layout = Qt.QGridLayout()
 60         self.top_layout.addLayout(self.top_grid_layout)
 61 
 62         self.settings = Qt.QSettings("GNU Radio", "if_else")
 63 
 64         try:
 65             if StrictVersion(Qt.qVersion()) < StrictVersion("5.0.0"):
 66                 self.restoreGeometry(self.settings.value("geometry").toByteArray())
 67             else:
 68                 self.restoreGeometry(self.settings.value("geometry"))
 69         except:
 70             pass
 71 
 72         ##################################################
 73         # Variables
 74         ##################################################
 75         self.variable_function_probe_0 = variable_function_probe_0 = 0
 76         self.samp_rate = samp_rate = 32000
 77         self.freq = freq = 1000
 78         self.ampl = ampl = 1
 79 
 80         ##################################################
 81         # Blocks
 82         ##################################################
 83         self.probe = blocks.probe_signal_f()
 84         self._freq_tool_bar = Qt.QToolBar(self)
 85         self._freq_tool_bar.addWidget(Qt.QLabel('freq' + ": "))
 86         self._freq_line_edit = Qt.QLineEdit(str(self.freq))
 87         self._freq_tool_bar.addWidget(self._freq_line_edit)
 88         self._freq_line_edit.returnPressed.connect(
 89             lambda: self.set_freq(int(str(self._freq_line_edit.text()))))
 90         self.top_grid_layout.addWidget(self._freq_tool_bar)
 91         self._ampl_tool_bar = Qt.QToolBar(self)
 92         self._ampl_tool_bar.addWidget(Qt.QLabel('ampl' + ": "))
 93         self._ampl_line_edit = Qt.QLineEdit(str(self.ampl))
 94         self._ampl_tool_bar.addWidget(self._ampl_line_edit)
 95         self._ampl_line_edit.returnPressed.connect(
 96             lambda: self.set_ampl(int(str(self._ampl_line_edit.text()))))
 97         self.top_grid_layout.addWidget(self._ampl_tool_bar)
 98         def _variable_function_probe_0_probe():
 99             while True:
100 
101                 val = self.probe.get_number()
102                 try:
103                     self.set_variable_function_probe_0(val)
104                 except AttributeError:
105                     pass
106                 time.sleep(1.0 / (10))
107         _variable_function_probe_0_thread = threading.Thread(target=_variable_function_probe_0_probe)
108         _variable_function_probe_0_thread.daemon = True
109         _variable_function_probe_0_thread.start()
110 
111         self.qtgui_time_sink_x_0 = qtgui.time_sink_f(
112             1024, #size
113             samp_rate, #samp_rate
114             "", #name
115             1 #number of inputs
116         )
117         self.qtgui_time_sink_x_0.set_update_time(0.10)
118         self.qtgui_time_sink_x_0.set_y_axis(-1, 1)
119 
120         self.qtgui_time_sink_x_0.set_y_label('Amplitude', "")
121 
122         self.qtgui_time_sink_x_0.enable_tags(True)
123         self.qtgui_time_sink_x_0.set_trigger_mode(qtgui.TRIG_MODE_FREE, qtgui.TRIG_SLOPE_POS, 0.0, 0, 0, "")
124         self.qtgui_time_sink_x_0.enable_autoscale(False)
125         self.qtgui_time_sink_x_0.enable_grid(False)
126         self.qtgui_time_sink_x_0.enable_axis_labels(True)
127         self.qtgui_time_sink_x_0.enable_control_panel(False)
128         self.qtgui_time_sink_x_0.enable_stem_plot(False)
129 
130 
131         labels = ['Signal 1', 'Signal 2', 'Signal 3', 'Signal 4', 'Signal 5',
132             'Signal 6', 'Signal 7', 'Signal 8', 'Signal 9', 'Signal 10']
133         widths = [1, 1, 1, 1, 1,
134             1, 1, 1, 1, 1]
135         colors = ['blue', 'red', 'green', 'black', 'cyan',
136             'magenta', 'yellow', 'dark red', 'dark green', 'dark blue']
137         alphas = [1.0, 1.0, 1.0, 1.0, 1.0,
138             1.0, 1.0, 1.0, 1.0, 1.0]
139         styles = [1, 1, 1, 1, 1,
140             1, 1, 1, 1, 1]
141         markers = [-1, -1, -1, -1, -1,
142             -1, -1, -1, -1, -1]
143 
144 
145         for i in range(1):
146             if len(labels[i]) == 0:
147                 self.qtgui_time_sink_x_0.set_line_label(i, "Data {0}".format(i))
148             else:
149                 self.qtgui_time_sink_x_0.set_line_label(i, labels[i])
150             self.qtgui_time_sink_x_0.set_line_width(i, widths[i])
151             self.qtgui_time_sink_x_0.set_line_color(i, colors[i])
152             self.qtgui_time_sink_x_0.set_line_style(i, styles[i])
153             self.qtgui_time_sink_x_0.set_line_marker(i, markers[i])
154             self.qtgui_time_sink_x_0.set_line_alpha(i, alphas[i])
155 
156         self._qtgui_time_sink_x_0_win = sip.wrapinstance(self.qtgui_time_sink_x_0.pyqwidget(), Qt.QWidget)
157         self.top_grid_layout.addWidget(self._qtgui_time_sink_x_0_win)
158         self.blocks_throttle_0 = blocks.throttle(gr.sizeof_float*1, samp_rate,True)
159         self.analog_sig_source_x_0_0 = analog.sig_source_f(samp_rate, analog.GR_COS_WAVE, freq, ampl, 0, 0)
160         self.analog_sig_source_x_0 = analog.sig_source_f(samp_rate, analog.GR_SQR_WAVE, 0.1, 1, 0, 0)
161 
162 
163 
164         ##################################################
165         # Connections
166         ##################################################
167         self.connect((self.analog_sig_source_x_0, 0), (self.blocks_throttle_0, 0))
168         self.connect((self.analog_sig_source_x_0_0, 0), (self.qtgui_time_sink_x_0, 0))
169         self.connect((self.blocks_throttle_0, 0), (self.probe, 0))
170 
171     def closeEvent(self, event):
172         self.settings = Qt.QSettings("GNU Radio", "if_else")
173         self.settings.setValue("geometry", self.saveGeometry())
174         event.accept()
175 
176     def get_variable_function_probe_0(self):
177         return self.variable_function_probe_0
178 
179     def set_variable_function_probe_0(self, variable_function_probe_0):
180         self.variable_function_probe_0 = variable_function_probe_0
181 
182     def get_samp_rate(self):
183         return self.samp_rate
184 
185     def set_samp_rate(self, samp_rate):
186         self.samp_rate = samp_rate
187         self.analog_sig_source_x_0.set_sampling_freq(self.samp_rate)
188         self.analog_sig_source_x_0_0.set_sampling_freq(self.samp_rate)
189         self.blocks_throttle_0.set_sample_rate(self.samp_rate)
190         self.qtgui_time_sink_x_0.set_samp_rate(self.samp_rate)
191 
192     def get_freq(self):
193         return self.freq
194 
195     def set_freq(self, freq):
196         self.freq = freq
197         Qt.QMetaObject.invokeMethod(self._freq_line_edit, "setText", Qt.Q_ARG("QString", str(self.freq)))
198         self.analog_sig_source_x_0_0.set_frequency(self.freq)
199 
200     def get_ampl(self):
201         return self.ampl
202 
203     def set_ampl(self, ampl):
204         self.ampl = ampl
205         Qt.QMetaObject.invokeMethod(self._ampl_line_edit, "setText", Qt.Q_ARG("QString", str(self.ampl)))
206         self.analog_sig_source_x_0_0.set_amplitude(self.ampl)
207 
208 
209 
210 def main(top_block_cls=if_else, options=None):
211 
212     if StrictVersion("4.5.0") <= StrictVersion(Qt.qVersion()) < StrictVersion("5.0.0"):
213         style = gr.prefs().get_string('qtgui', 'style', 'raster')
214         Qt.QApplication.setGraphicsSystem(style)
215     qapp = Qt.QApplication(sys.argv)
216 
217     tb = top_block_cls()
218     tb.start()
219     tb.show()
220 
221     def sig_handler(sig=None, frame=None):
222         Qt.QApplication.quit()
223 
224     signal.signal(signal.SIGINT, sig_handler)
225     signal.signal(signal.SIGTERM, sig_handler)
226 
227     timer = Qt.QTimer()
228     timer.start(500)
229     timer.timeout.connect(lambda: None)
230 
231     def quitting():
232         tb.stop()
233         tb.wait()
234     qapp.aboutToQuit.connect(quitting)
235     qapp.exec_()
236 
237 
238 if __name__ == '__main__':
239     main()

We are only concerned about a couple of parts namely the part where the probe is being read:

        def _variable_function_probe_0_probe():
            while True:

                val = self.probe.level()
                try:
                    self.set_variable_function_probe_0(val)
                except AttributeError:
                    pass
                time.sleep(1.0 / (10))

We can see that the variable val is obtaining the value of the probe block. We can write our if-else statement here based on the value of val to change the amplitude and frequency of our sine wave. But how do we change the frequency and amplitude? We can use the part where the QT GUI Entry updates the flowgraph. For the variable freq:

    def set_freq(self, freq):
        self.freq = freq
        Qt.QMetaObject.invokeMethod(self._freq_line_edit, "setText", Qt.Q_ARG("QString", str(self.freq)))
        self.analog_sig_source_x_0_0.set_frequency(self.freq)

and for the variable ampl:

    def set_ampl(self, ampl):
        self.ampl = ampl
        Qt.QMetaObject.invokeMethod(self._ampl_line_edit, "setText", Qt.Q_ARG("QString", str(self.ampl)))
        self.analog_sig_source_x_0_0.set_amplitude(self.ampl)

We can see that the functions set_ampl and set_freq can be used for just that - setting the amplitude and the frequency. Thus we can go back and modify our probe function with the if-else statement to give power to our friend.


        def _variable_funct ion_probe_0_probe():
            while True:

                val = self.probe.level()
                print val
                if val == 1:
                    self.set_ampl(1)
                    self.set_freq(1000)
                else:
                    self.set_ampl(.3)
                    self.set_freq(100)
                try:
                    self.set_variable_function_probe_0(val)
                except AttributeError:
                    pass
                time.sleep(1.0 / (10))

Now there is one more thing we need to take care of. GRC has compiled the python file in the order of creation of the elements, which was okay as long as there were no crossreferences. With the introduced adaptation (calling set_ampl and set_freq inside the _variable_function_probe_0_probe()) we need to fix the order of declarations. As set_ampl and set_freq both modify parameters of analog_sig_source_x_0_0 but analog_sig_source_x_0_0 is not instantiated before line 150, we have to move the declaration of the _variable_function_probe_0_probe() and everything related below that.

        self._qtgui_time_sink_x_0_win = sip.wrapinstance(self.qtgui_time_sink_x_0.pyqwidget(), Qt.QWidget)
        self.top_grid_layout.addWidget(self._qtgui_time_sink_x_0_win)
        self.blocks_throttle_0 = blocks.throttle(gr.sizeof_float*1, samp_rate,True)
        self.analog_sig_source_x_1 = analog.sig_source_f(samp_rate, analog.GR_SIN_WAVE, freq, ampl, 0)
        self.analog_sig_source_x_0 = analog.sig_source_f(samp_rate, analog.GR_SQR_WAVE, 0.1, 1, 0)

Full code copied below:


#!/usr/bin/env python3
# -*- coding: utf-8 -*-

#
# SPDX-License-Identifier: GPL-3.0
#
# GNU Radio Python Flow Graph
# Title: if_else
# GNU Radio version: 3.8.0.0

from distutils.version import StrictVersion

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

from PyQt5 import Qt
from gnuradio import eng_notation
from gnuradio import qtgui
from gnuradio.filter import firdes
import sip
from gnuradio import analog
from gnuradio import blocks
from gnuradio import gr
import sys
import signal
from argparse import ArgumentParser
from gnuradio.eng_arg import eng_float, intx
import time
import threading
from gnuradio import qtgui

class if_else(gr.top_block, Qt.QWidget):

    def __init__(self):
        gr.top_block.__init__(self, "if_else")
        Qt.QWidget.__init__(self)
        self.setWindowTitle("if_else")
        qtgui.util.check_set_qss()
        try:
            self.setWindowIcon(Qt.QIcon.fromTheme('gnuradio-grc'))
        except:
            pass
        self.top_scroll_layout = Qt.QVBoxLayout()
        self.setLayout(self.top_scroll_layout)
        self.top_scroll = Qt.QScrollArea()
        self.top_scroll.setFrameStyle(Qt.QFrame.NoFrame)
        self.top_scroll_layout.addWidget(self.top_scroll)
        self.top_scroll.setWidgetResizable(True)
        self.top_widget = Qt.QWidget()
        self.top_scroll.setWidget(self.top_widget)
        self.top_layout = Qt.QVBoxLayout(self.top_widget)
        self.top_grid_layout = Qt.QGridLayout()
        self.top_layout.addLayout(self.top_grid_layout)

        self.settings = Qt.QSettings("GNU Radio", "if_else")

        try:
            if StrictVersion(Qt.qVersion()) < StrictVersion("5.0.0"):
                self.restoreGeometry(self.settings.value("geometry").toByteArray())
            else:
                self.restoreGeometry(self.settings.value("geometry"))
        except:
            pass

        ##################################################
        # Variables
        ##################################################
        self.variable_function_probe_0 = variable_function_probe_0 = 0
        self.samp_rate = samp_rate = 32000
        self.freq = freq = 1000
        self.ampl = ampl = 1

        ##################################################
        # Blocks
        ##################################################
        self.probe = blocks.probe_signal_f()
        self._freq_tool_bar = Qt.QToolBar(self)
        self._freq_tool_bar.addWidget(Qt.QLabel('freq' + ": "))
        self._freq_line_edit = Qt.QLineEdit(str(self.freq))
        self._freq_tool_bar.addWidget(self._freq_line_edit)
        self._freq_line_edit.returnPressed.connect(
            lambda: self.set_freq(int(str(self._freq_line_edit.text()))))
        self.top_grid_layout.addWidget(self._freq_tool_bar)
        self._ampl_tool_bar = Qt.QToolBar(self)
        self._ampl_tool_bar.addWidget(Qt.QLabel('ampl' + ": "))
        self._ampl_line_edit = Qt.QLineEdit(str(self.ampl))
        self._ampl_tool_bar.addWidget(self._ampl_line_edit)
        self._ampl_line_edit.returnPressed.connect(
            lambda: self.set_ampl(int(str(self._ampl_line_edit.text()))))
        self.top_grid_layout.addWidget(self._ampl_tool_bar)

        self.qtgui_time_sink_x_0 = qtgui.time_sink_f(
            1024, #size
            samp_rate, #samp_rate
            "", #name
            1 #number of inputs
        )
        self.qtgui_time_sink_x_0.set_update_time(0.10)
        self.qtgui_time_sink_x_0.set_y_axis(-1, 1)

        self.qtgui_time_sink_x_0.set_y_label('Amplitude', "")

        self.qtgui_time_sink_x_0.enable_tags(True)
        self.qtgui_time_sink_x_0.set_trigger_mode(qtgui.TRIG_MODE_FREE, qtgui.TRIG_SLOPE_POS, 0.0, 0, 0, "")
        self.qtgui_time_sink_x_0.enable_autoscale(False)
        self.qtgui_time_sink_x_0.enable_grid(False)
        self.qtgui_time_sink_x_0.enable_axis_labels(True)
        self.qtgui_time_sink_x_0.enable_control_panel(False)
        self.qtgui_time_sink_x_0.enable_stem_plot(False)


        labels = ['Signal 1', 'Signal 2', 'Signal 3', 'Signal 4', 'Signal 5',
            'Signal 6', 'Signal 7', 'Signal 8', 'Signal 9', 'Signal 10']
        widths = [1, 1, 1, 1, 1,
            1, 1, 1, 1, 1]
        colors = ['blue', 'red', 'green', 'black', 'cyan',
            'magenta', 'yellow', 'dark red', 'dark green', 'dark blue']
        alphas = [1.0, 1.0, 1.0, 1.0, 1.0,
            1.0, 1.0, 1.0, 1.0, 1.0]
        styles = [1, 1, 1, 1, 1,
            1, 1, 1, 1, 1]
        markers = [-1, -1, -1, -1, -1,
            -1, -1, -1, -1, -1]


        for i in range(1):
            if len(labels[i]) == 0:
                self.qtgui_time_sink_x_0.set_line_label(i, "Data {0}".format(i))
            else:
                self.qtgui_time_sink_x_0.set_line_label(i, labels[i])
            self.qtgui_time_sink_x_0.set_line_width(i, widths[i])
            self.qtgui_time_sink_x_0.set_line_color(i, colors[i])
            self.qtgui_time_sink_x_0.set_line_style(i, styles[i])
            self.qtgui_time_sink_x_0.set_line_marker(i, markers[i])
            self.qtgui_time_sink_x_0.set_line_alpha(i, alphas[i])

        self._qtgui_time_sink_x_0_win = sip.wrapinstance(self.qtgui_time_sink_x_0.pyqwidget(), Qt.QWidget)
        self.top_grid_layout.addWidget(self._qtgui_time_sink_x_0_win)
        self.blocks_throttle_0 = blocks.throttle(gr.sizeof_float*1, samp_rate,True)
        self.analog_sig_source_x_0_0 = analog.sig_source_f(samp_rate, analog.GR_COS_WAVE, freq, ampl, 0, 0)
        self.analog_sig_source_x_0 = analog.sig_source_f(samp_rate, analog.GR_SQR_WAVE, 0.1, 1, 0, 0)

        def _variable_function_probe_0_probe():
            while True:

                val = self.probe.level()
                print (val)
                if val == 1:
                    self.set_ampl(1)
                    self.set_freq(1000)
                else:
                    self.set_ampl(.3)
                    self.set_freq(100)
                try:
                    self.set_variable_function_probe_0(val)
                except AttributeError:
                    pass
                time.sleep(1.0 / (10))
        _variable_function_probe_0_thread = threading.Thread(target=_variable_function_probe_0_probe)
        _variable_function_probe_0_thread.daemon = True
        _variable_function_probe_0_thread.start()

        ##################################################
        # Connections
        ##################################################
        self.connect((self.analog_sig_source_x_0, 0), (self.blocks_throttle_0, 0))
        self.connect((self.analog_sig_source_x_0_0, 0), (self.qtgui_time_sink_x_0, 0))
        self.connect((self.blocks_throttle_0, 0), (self.probe, 0))

    def closeEvent(self, event):
        self.settings = Qt.QSettings("GNU Radio", "if_else")
        self.settings.setValue("geometry", self.saveGeometry())
        event.accept()

    def get_variable_function_probe_0(self):
        return self.variable_function_probe_0

    def set_variable_function_probe_0(self, variable_function_probe_0):
        self.variable_function_probe_0 = variable_function_probe_0

    def get_samp_rate(self):
        return self.samp_rate

    def set_samp_rate(self, samp_rate):
        self.samp_rate = samp_rate
        self.analog_sig_source_x_0.set_sampling_freq(self.samp_rate)
        self.analog_sig_source_x_0_0.set_sampling_freq(self.samp_rate)
        self.blocks_throttle_0.set_sample_rate(self.samp_rate)
        self.qtgui_time_sink_x_0.set_samp_rate(self.samp_rate)

    def get_freq(self):
        return self.freq

    def set_freq(self, freq):
        self.freq = freq
        Qt.QMetaObject.invokeMethod(self._freq_line_edit, "setText", Qt.Q_ARG("QString", str(self.freq)))
        self.analog_sig_source_x_0_0.set_frequency(self.freq)

    def get_ampl(self):
        return self.ampl

    def set_ampl(self, ampl):
        self.ampl = ampl
        Qt.QMetaObject.invokeMethod(self._ampl_line_edit, "setText", Qt.Q_ARG("QString", str(self.ampl)))
        self.analog_sig_source_x_0_0.set_amplitude(self.ampl)



def main(top_block_cls=if_else, 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 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_()


if __name__ == '__main__':
    main()

We can then simply run our flowgraph from outside of GRC using

$ python3 if_else_mod.py

We should be able to see the numbers 0 and 1 on the terminal and the sine wave changing amplitude and frequency as the numbers change.

3.2. Where Do Blocks Come From?[edit]

Now that we have covered some of the ways we can modify our GRC generated Python files, we can see how to make our own blocks to add functionality to suit our specific project needs. Let us start off simple to get a feel for the waters. We will be making a block that is able to multiply a signal by the number we specify. The first thing we need to realize is that GNU Radio comes with gr_modtool, a utility that makes creating OOT Modules easy. Let us open up a terminal and begin in a project folder for the tutorial three.

3.2.1. Using gr_modtool[edit]

Before we begin, we need to figure out what the commands for gr_modtool are so let's ask for help.

$ gr_modtool --help
Usage: gr_modtool [OPTIONS] COMMAND [ARGS]...

  A tool for editing GNU Radio out-of-tree modules.

Options:
  --help  Show this message and exit.

Commands:
  add       Adds a block to the out-of-tree module.
  disable   Disable selected block in module.
  info      Return information about a given module
  makeyaml  Generate YAML files for GRC block bindings.
  newmod    Create new empty module, use add to add blocks.
  rename    Rename a block inside a module.
  rm        Remove a block from a module.
  update    Update the grc bindings for a block

  Manipulate with GNU Radio modules source code tree. Call it without
  options to run specified command interactively

We immediately see there are many commands available. In this tutorial we will only cover newmod and add; however, the thorough explanation should enable smooth usage of the other gr_modtool commands without guidance.

First, we notice that in addition to getting help seeing the commands we can use, we can also request more information on individual commands. Let us start with newmod as that is the command to create a new out-of-tree module.

$ gr_modtool newmod --help
Usage: gr_modtool newmod [OPTIONS] MODULE-NAME

  Create a new out-of-tree module

  The argument MODULE-NAME is the name of the module to be added.

Options:
  --srcdir TEXT             Source directory for the module template.
  -d, --directory TEXT      Base directory of the module. Defaults to the cwd.
  --skip-lib                Don't do anything in the lib/ subdirectory.
  --skip-swig               Don't do anything in the swig/ subdirectory.
  --skip-python             Don't do anything in the python/ subdirectory.
  --skip-grc                Don't do anything in the grc/ subdirectory.
  --scm-mode [yes|no|auto]  Use source control management [ yes | no | auto ]).
  -y, --yes                 Answer all questions with 'yes'. This can
                            overwrite and delete your files, so be careful.
  --help                    Show this message and exit.

Now that we have read over the list of commands for newmod, we can deduce that the one we want to pick is -n which is the default so we can simply type the MODULE_NAME after newmod. It is actually advised to avoid using "-n" as for other commands it can override the auto-detected name. For now, let's ignore the other options.

3.2.2. Setting up a new block[edit]

$ gr_modtool newmod tutorial
Creating out-of-tree module in ./gr-tutorial... Done.
Use 'gr_modtool add' to add a new block to this currently empty module.

We should now see a new folder, gr-tutorial, in our current directory. Let's examine the folder to figure out what gr_modtool has done for us.

gr-tutorial$ ls
apps  cmake  CMakeLists.txt  docs  examples  grc  include  lib  Python  swig

Since we are dealing with Python in this tutorial we only need to concern ourselves with the Python folder and the grc folder. Before we can dive into code, we need to create a block from a template. There are actually four different types of Python blocks, however it's a little too soon to discuss that. We will dive into the synchronous 1:1 input to output block to make explaining things easier (this is a block that outputs as many items as it gets as input, but don't worry about this right now).

Now we know the language we want to write our block in (Python) and the type of block (synchronous block) we can now add a block to our module. Again, we should run the gr_modtool help command until we are familiar with the different commands. We see that the add command is what we are looking for. Now we need to run help on the add command in order to see what we need to enter given the information we have so far.

gr-tutorial$ gr_modtool help add
... (General Options from Last Help)
Add module options:
    -t BLOCK_TYPE, --block-type=BLOCK_TYPE
                        One of sink, source, sync, decimator, interpolator,
                        general, tagged_stream, hier, noblock.
    --license-file=LICENSE_FILE
                        File containing the license header for every source
                        code file.
    --argument-list=ARGUMENT_LIST
                        The argument list for the constructor and make
                        functions.
    --add-Python-qa     If given, Python QA code is automatically added if
                        possible.
    --add-cpp-qa        If given, C++ QA code is automatically added if
                        possible.
    --skip-cmakefiles   If given, only source files are written, but
                        CMakeLists.txt files are left unchanged.
    -l LANG, --lang=LANG
                        Language (cpp or Python)

We can see the -l LANG and the -t BLOCK_TYPE are relevant for our example. Thus when creating our new block, we know the command. When prompted for a name simply enter "multiply_py_ff", when prompted for an argument list enter "multiple", and when prompted for Python QA (Quality Assurance) code type "y", or just hit enter (the capital letter is the default value).

gr-tutorial$ gr_modtool add -t sync -l python
GNU Radio module name identified: tutorial
Language: Python
Enter name of block/code (without module name prefix): multiply_py_ff
Block/code identifier: multiply_py_ff
Enter valid argument list, including default arguments: multiple
Add Python QA code? [Y/n] y
Adding file 'Python/multiply_py_ff.py'...
Adding file 'Python/qa_multiply_py_ff.py'...
Editing Python/CMakeLists.txt...
Adding file 'grc/tutorial_multiply_py_ff.yml'...
Editing grc/CMakeLists.txt...

We notice 5 changes: Two changes to CMakeLists.txt files, one new file qa_multiply_py_ff.py which is used to test our code, one new file multiply_py_ff.py which is the functional part, and one new file tutorial_multiply_py_ff.xml, which is used to link the block to the GRC. Again all this happens in the Python and grc subfolders.

3.2.2.1. What's with the _ff?[edit]

For blocks with strict types, we use suffixes to declare the input and output types. This block operates on floats, so we give it the suffix _ff: Float in, float out. Other suffixes are _cc (complex in, complex out), or simply _f (a sink or source with no in- or outputs that uses floats). For a more detailed description, see the FAQ or the BlocksCodingGuide.

3.2.3. Modifying the Python Block File[edit]

Let's begin with the multiply_py_ff.py file found in the Python folder. Opening it without any changes gives the following:

import numpy
from gnuradio import gr

class multiply_py_ff(gr.sync_block):
    """
    docstring for block multiply_py_ff
    """
    def __init__(self, multiple):
        gr.sync_block.__init__(self,
            name="multiply_py_ff",
            in_sig=[<+numpy.float+>],
            out_sig=[<+numpy.float+>])
        self.multiple = multiple


    def work(self, input_items, output_items):
        in0 = input_items[0]
        out = output_items[0]
        # <+signal processing here+>
        out[:] = in0
        return len(output_items[0])

Let's take this one line by line as our first Python examples. We are already familiar with the imports so we will skip those lines. We are familiar with the constructor (init) of Python so can immediately see that if we want to use our variable "multiple", we need to add another line. Let us not forget to preserve those spaces as some code editors like to add tabs to new lines. How do we use the variable multiple?

How to use variable multiple...

def __init__(self, multiple):
        self.multiple = multiple
        gr.sync_block.__init__(self,


We notice that there are "<...>" scattered in many places. These placeholders are from gr_modtool and tell us where we need to alter things

in_sig=[<+numpy.float+>]
out_sig=[<+numpy.float+>]

The gr.sync_block.init takes in 4 inputs: self, name, and the size/type of the input and output vectors. First, we want to make the item size a single precision float or numpy.float32 by removing the "<" and the ">". If we wanted vectors, we could define those as in_sig=[(numpy.float32,4),numpy.float32]. This means there are two input ports, one for vectors of 4 floats and the other for scalars. It is worth noting that if in_sig contains nothing then it becomes a source block, and if out_sig contains nothing it becomes a sink block (provided we change return len(output_items[0]) to return len(input_items[0]) since output_items is empty). Our changes to the first placeholders should appear as follows:

in_sig=[numpy.float32]
out_sig=[numpy.float32]

The other piece of code that has the placeholders is in the work function but let us first get a better understanding of the work function:

def work(self, input_items, output_items)

The work function is where the actual processing happens, where we want our code to be. Because this is a sync block, the number of input items always equals the number of output items because synchronous block ensures a fixed output to input rate. There are also decimation and interpolation blocks where the number of output items are a user specified multiple of the number of input items. We will further discuss when to use what block type in the third section of this tutorial. For now we look at the placeholder:

in0 = input_items[0]
out = output_items[0]
# <+signal processing here+>
out[:] = in0
return len(output_items[0])

The "in0" and "out" simply store the input and output in a variable to make the block easier to write. The signal processing can be anything including if statements, loops, function calls but for this example we only need to modify the out[:] = in0 line so that our input signal is multiplied by our variable multiple. What do we need to add to make the in0 multiply by our multiple?

How to Multiple...

out[:] = in0*self.multiple

That's it! Our block should now be able to multiply but to be sure we have these things called Quality Assurance tests!

3.2.4. QA Tests[edit]

Now we need to test it to make sure it will run correctly when we install it unto GNU Radio. This is a very important step and we should never forget to include tests with our code! Let us open up qa_multiply_py_ff.py which is copied below:

from gnuradio import gr, gr_unittest
from gnuradio import blocks
from multiply_py_ff import multiply_py_ff

class qa_multiply_py_ff (gr_unittest.TestCase):

    def setUp (self):
        self.tb = gr.top_block ()

    def tearDown (self):
        self.tb = None

    def test_001_t (self):
        # set up fg
        self.tb.run ()
        # check data


if __name__ == '__main__':
    gr_unittest.run(qa_multiply_py_ff)

gr_unittest adds support for checking approximate equality of tuples of float and complex numbers. The only part we need to worry about is the def test_001_t function. We know we need input data so let us create data. We want it to be in the form of a vector so that we can test multiple values at once. Let us create a vector of floats

src_data = (0, 1, -2, 5.5, -0.5)

We also need output data so we can compare the input of the block to ensure that it is doing what we expect it to do. Let us multiply by 2 for simplicity.

expected_result = (0, 2, -4, 11, -1)

Now we can create a flowgraph as we have when we first introduced using Python in GNU Radio. We can use the blocks library specifically the vector_source_f function and the vector_sink_f function which are linked to the doxygen manual which we should be able to read and understand. Let us assign three variables "src", "mult", and "snk" to the blocks. The first is shown below:

src = blocks.vector_source_f(src_data)

The rest are hidden below as an exercise:

What do we assign snk and mult?

mult = multiply_py_ff(2)
snk = blocks.vector_sink_f()


Now we need to connect everything as src > mult> snk. Instead of using self.connect as we did in our other blocks we need to use self.tb.connect because of the setUp function. Below is how we would connect the src block to the mult block.

self.tb.connect (src, mult)

How would we connect the other blocks together?

self.tb.connect (mult, snk)


Then we can run the graph and store the data from the sink as below:

self.tb.run ()
result_data = snk.data ()

Lastly we can run our comparison function that will tell us whether the numbers match up to 6 decimal places. We are using the assertFloatTuplesAlmostEqual instead of the "regular assert functions"https://docs.python.org/2/library/unittest.html#assert-methods included in python's unittest because there may be situations where we cannot get a=b due to rounding in floating point numbers.

self.assertFloatTuplesAlmostEqual (expected_result, result_data, 6)

All together the new test_001_t function should appear as below:

src_data = (0, 1, -2, 5.5, -0.5)
expected_result = (0, 2, -4, 11, -1)
src = blocks.vector_source_f (src_data)
mult = multiply_py_ff (2)
snk = blocks.vector_sink_f ()
self.tb.connect (src, mult)
self.tb.connect (mult, snk)
self.tb.run ()
result_data = snk.data ()
self.assertFloatTuplesAlmostEqual (expected_result, result_data, 6)

We can then go to the python directory and run:

gr-tutorial/python$ python qa_multiply_py_ff.py
.
----------------------------------------------------------------------
Ran 1 test in 0.004s

OK

While we are here, we should take a break to change one of the numbers in the src_data to ensure that the block is actually checking the values and to simply see what an error looks like. Python allows for really quick testing of blocks without having to compile anything; simply change something and re-run the QA test.

3.2.5. YAML Files[edit]

At this point we should have written a Python block and a QA test for that block. The next thing to do is edit the YAML file in the grc folder so that we can get another step closer to using it in GRC. GRC uses the YAML files for all the options we see. We actually don't need to write any Python or C++ code to have a block display in GRC but of course if we would connect it, it wouldn't do anything but give errors. We should get out of the python folder and go to the grc folder where all the YAML files reside. There is a tool in gr_modtool called makexml but it is only available for C++ blocks. Let us open the tutorial_multiply_py_ff.xml file copied below:

 1 id: tutorial_multiply_py_ff
 2 label: multiply_py_ff
 3 category: '[tutorial]'
 4 
 5 templates:
 6   imports: import tutorial
 7   make: tutorial.multiply_py_ff(${multiple})
 8 
 9 #  Make one 'parameters' list entry for every Parameter you want settable from the GUI.
10 #     Sub-entries of dictionary:
11 #     * id (makes the value accessible as \$keyname, e.g. in the make entry)
12 #     * label
13 #     * dtype 
14 parameters:
15 - id: ...
16   label: ...
17   dtype: ...
18 - id: ...
19   label: ...
20   dtype: ...
21 
22 #  Make one 'inputs' list entry per input. Sub-entries of dictionary:
23 #      * label (an identifier for the GUI)
24 #      * domain
25 #      * dtype
26 #      * vlen
27 #      * optional (set to 1 for optional inputs) 
28 inputs:
29 - label: ...
30   domain: ...
31   dtype: ...
32   vlen: ...
33 
34 #  Make one 'outputs' list entry per output. Sub-entries of dictionary:
35 #      * label (an identifier for the GUI)
36 #      * dtype
37 #      * vlen
38 #      * optional (set to 1 for optional inputs) 
39 - label: ...
40   domain: ...
41   dtype: ... #!-- e.g. int, float, complex, byte, short, xxx_vector, ...--
42 
43 file_format: 1

We can change the name that appears and the category it will appear in GRC. The category is where the block will be found in GRC. Examples of categories tag are Audio and Waveform Generators used in previous examples. Examples of names tag are the QT GUI Time Sink or the Audio Sink. Again, we can go through the file and find the modtool place holders. The first is copied below:

1 #  Make one 'parameters' list entry for every Parameter you want settable from the GUI.
2 #     Sub-entries of dictionary:
3 #     * id (makes the value accessible as \$keyname, e.g. in the make entry)
4 #     * label
5 #     * dtype

This is referring to the parameter that we used in the very beginning when creating our block: the variable called "multiple". We can fill it in as below:

1    
2 parameters:
3 - id: multiple
4   label: Multiple
5   dtype: float

The next placeholder can be found in the inputs and outputs tags:

1   
2 inputs:
3 - label: in
4   dtype: float
5 
6 outputs: 
7 - label: out
8   dtype: float #!-- e.g. int, float, complex, byte, short, xxx_vector, ...--

We can see that it is asking for a type so we can simply erase everything in the tag and replace it with "float" for both the source and the sink blocks. That should do it for this block. The best way to get more experience writing YAML files is to look at the source code of previously made blocks such as the existing multiple block. Let's go back to this and use the documentation tag!

3.2.6. Installing Python Blocks[edit]

Now that we have edited the XML file; we are ready to install the block into the GRC. First, we need to get out of the /grc directory and create a build directory called "build". Inside the build directory, we can then run a series of commands:

cmake ../
make
sudo make install
sudo ldconfig

We should then open up the GRC and take a look at the new block.

xml_blockname.png

We can see the category and the block name. When we drag it into the GRC workspace, we can see the multiple variable we set in the param tag of the XML file.

xml_param.png

Now that we can see our block, let us test it to make sure it works. Below is an example of one of the many ways to check whether it is actually multiplying.

tutorial_three_2.png

3.3. My QPSK Demodulator for Satellites[edit]

Now that we have a better understanding on how to add new blocks to GNU Radio for use in the GRC, we can do another example. This time we will be creating a QPSK demodulator block using the same process as before in the same module. Let's first setup the scenario. There is a "noise source" that outputs data in complex float format but let's pretend it comes from a satellite being aimed at our computer. Our secret agent insider tells us this particular satellite encodes digital data using QPSK modulation. We can decode this using a QPSK demodulator that outputs data into bytes. Our insider tells us the space manual doesn't specify whether it's gray code or not. We want to read the bytes using a time sink. What would our flowgraph look like?

Incomplete Flowgraph... tutorial_three_3.png


Now that we know the input type, output type, and parameters, we can ask the question we skipped with our multiply_py_ff block. What type of block do we want?

3.3.1. Choosing a Block Type[edit]

The GNU Radio scheduler optimizes for throughput (as opposed to latency). To do this it needs to know the number of samples each block is inputting and outputting thus came the creation of decimation and interpolation blocks where we specify the multiple factor. This is directly related to the sampling rate discussion we had in tutorial 2 where these special types of blocks are able to change the sampling rate to something else in order to comply with a specific piece of hardware such as our soundcard or a specific modulation/demodulation.

  • Synchronous (1:1) - Number of items at input port equals the number of items at output port. An example is the multiply_py_ff block.
  • Decimation (N:1) - Number of input items is a fixed multiple of the number of output items. Examples include filters such as decimating high pass and low pass filters (e.g., for sampling rate conversion).
  • Interpolation (1:M) - Number of output items is a fixed multiple of the number of input items. An example is the Interpolating FIR Filter.
  • General/Basic (N:M) - Provides no relation between the number of input items and the number of output items. An example is the rational resampler block which can be either a sync, decimator, or interpolator.

When we insert data into our block, do we need more samples or less samples? Or put another way, should our sample rate change?

What Type of Block Should we Use?

  • Sync Block or Basic Block


3.3.2. Adding Another Block to our OOT Module[edit]

Now we know everything we need to know to create the block in gr_modtool. As a refresher, what would our gr_modtool command be?

gr_modtool command...

 gr-tutorial$ gr_modtool add -t sync -l python
 
 name: qpsk_demod_py_cb (c for complex input and b for byte/char/int8 output)<br />
 args: gray_code<br />
 QA Code: y


Now we have our files setup so we can begin with editing the qpsk_demod_py.py file in the /python folder

3.3.3. The QPSK Demodulator[edit]

The code here is a little more than we have done before so let's take it in steps. First what do we expect our block to do? We can start with a constellation plot which shows the four different quadrants and their mappings to bit 0 and bit 1

With Gray coding (adjacent only flips by 1). Note that the mapping we use here is different from the mapping on wikipedia:


(-1+1j) 10 | 00 (1+1j)
-----------+-----------
(-1-1j) 11 | 01 (1-1j)

Without Gray coding:

(-1+1j) 11 | 00 (1+1j)
-----------+-----------
(-1-1j) 10 | 01 (1-1j)

We can see that we will need to write an if-else statement to take into account the gray_code variable. We will also need four other if-else statements inside the main if-else so that we can pick the mapping. Our pseudocode will look as follows:

if gray_code
    if 1+1j
        binary "00" = 0
    ....
    elif -1-1j
        binary "11" = 3
else
    if 1+1j
        binary "00" = 0
    ....
    elif -1-1j
        binary "10" = 2

So we have everything we need to implement. Let's go ahead and fill in our gr_modtoool placeholders. We can begin with def init. There are three changes. How do we use the variable gray_code outside the function (similar to what we did with multiple in the last example)? What are the input and output types in numpy

Changes to def init...

    def __init__(self, gray_code):
        self.gray_code=gray_code
        gr.sync_block.__init__(self,
            name="qpsk_demod_py",
            in_sig=[numpy.complex64],
            out_sig=[numpy.uint8])

Once we have our constructor setup, we can go onto the work function. For simplicity and beauty, let us call the pseudocode we made above a function "get_minimum_distance" that takes samples as input arguments. In our multiply_py_ff example, we took all the samples and multiplied them with with out[:] = in0*self.multiple. The in0 is actually a vector so contains many samples within it. The multiply example required the same operation for each sample so it was okay to simply operate on the entire vector but now we need to have different operations per sample so what do we do?

How can we operate on samples in a vector?

  • loops!
        for i in range(0, len(output_items[0])):
            sample = in0[i]
            out[i] = self.get_minimum_distances(sample)


Now we can move onto the get_minimum_distances(self, sample) function. We already have pseudo code so the next step is translating to Python. Below is a snip of what the code can look like. Again there are multiple ways to do this

1     def get_minimum_distances(self, sample):
2         if self.gray_code == 1:
3             if (sample.imag >= 0 and sample.real >= 0):
4                 return 0 # 1+1j
5             elif (sample.imag >= 0 and sample.real < 0):
6                 return 2 # -1+1j

Let us try to fill in the other cases for gray code and non-gray code. Below is what the entire file Python file can look like once complete:

qpsk_demod_py_cb.py

 1 import numpy
 2 from gnuradio import gr
 3 
 4 class qpsk_demod_py(gr.sync_block):
 5     """
 6     docstring for block qpsk_demod_py
 7     """
 8     def __init__(self, gray_code):
 9         self.gray_code=gray_code
10         gr.sync_block.__init__(self,
11             name="qpsk_demod_py",
12             in_sig=[numpy.complex64],
13             out_sig=[numpy.uint8])
14 
15     def get_minimum_distances(self, sample):
16         if self.gray_code == 1:
17             if (sample.imag >= 0 and sample.real >= 0):
18                 return 0 # 1+1j
19             elif (sample.imag >= 0 and sample.real < 0):
20                 return 2 # -1+1j
21             elif (sample.imag < 0 and sample.real < 0):
22                 return 3 # -1-1j
23             elif (sample.imag < 0 and sample.real >= 0):
24                 return 1 # 1-1j
25         else:
26             if (sample.imag >= 0 and sample.real >= 0):
27                 return 0 # 1+1j
28             elif (sample.imag >= 0 and sample.real < 0):
29                 return 3 # -1+1j
30             elif (sample.imag < 0 and sample.real < 0):
31                 return 2 # -1-1j
32             elif (sample.imag < 0 and sample.real >= 0):
33                 return 1 # 1-1j
34 
35     def work(self, input_items, output_items):
36         in0 = input_items[0]
37         out = output_items[0]
38 
39         for i in range(0, len(in0)):
40             sample = in0[i]
41             out[i] = self.get_minimum_distances(sample)
42 
43         return len(output_items[0])


Now that we have code, we know what's next!

3.3.4. Multiple QA Tests[edit]

We can test our qpsk_demod_py for when it is in gray_code mode and when it's not in gray_code mode. To do that we need to setup multiple tests in our single QA file. QA tests generally follow the same setup from before. We select some inputs as tests and we check them against what we expect the outputs to be. The only difference from the multiply qa test is that this qa test requires more cases. There are four quadrants we need to map and two modes so in total there are eight test cases. We can open up our qa_qpsk_demod_py_ff.py file to change things.

We can copy the def test_001_t from the qa_multiply_py_ff code which is copied below:

 1     def test_001_t (self):
 2         src_data = (-3, 4, -5.5, 2, 3)
 3         expected_result = (-6, 8, -11, 4, 6)
 4         src = blocks.vector_source_f (src_data)
 5         mult = multiply_py_ff (2)
 6         dst = blocks.vector_sink_f ()
 7         self.tb.connect (src, mult)
 8         self.tb.connect (mult, dst)
 9         self.tb.run ()
10         result_data = dst.data ()
11         self.assertFloatTuplesAlmostEqual (expected_result, result_data, 6)

This time we are working with a complex input so our src = blocks.vector_source_f must change. If we use the search bar in the manual we can find the other options:

PIC of SEARCH

b - bytes/unsigned char/int8
c - complex
f - float
i - int
s - short

What do we change our source and sink vectors to?
src = blocks.vector_source_c (src_data)
dst = blocks.vector_sink_b ()


Before we move onto actual test cases, let us decide which mode we are testing for the test_001_t. We can create a new variable and assign it False (translates to 0) to test non-Gray code

gray_code = False

Once we know we want to test non gray_code mappings, we can refer to our chart above and start placing in the proper inputs and outputs into the src_data and the expected_results. For instance if we were testing only two cases for non gray_code, we would do:

1 src_data = ((-1-1j), (-1+1j))
2 expected_result = (2, 3)

Last thing to do is call upon our new block in the "qpsk =" line and pass it the gray_code parameter

qpsk = ?

  • qpsk = qpsk_demod_py_cb (gray_code)

Now that we are done with the non gray_code test, we can simply create another test "def test_002_t (self):" and copy the contents underneath making sure that for this test we set gray_code = True and change the expected_result so it matches gray_code mapping. The full test is copied below:

Full QA QPSK Demod Code...

 1 from gnuradio import gr, gr_unittest
 2 from gnuradio import blocks
 3 import numpy
 4 from qpsk_demod_py_cb import qpsk_demod_py
 5 
 6 class qa_qpsk_demod (gr_unittest.TestCase):
 7 
 8     def setUp (self):
 9         self.tb = gr.top_block ()
10 
11     def tearDown (self):
12         self.tb = None
13 
14     def test_001_t (self):
15         gray_code = False
16         src_data = ((-1-1j), (-1+1j), (1+1j), (1-1j))
17         expected_result = (2, 3, 0, 1)
18         src = blocks.vector_source_c (src_data)
19         qpsk = qpsk_demod_py (gray_code)
20         dst = blocks.vector_sink_b ()
21         self.tb.connect (src, qpsk)
22         self.tb.connect (qpsk, dst)
23         self.tb.run ()
24         result_data = dst.data ()
25         self.assertFloatTuplesAlmostEqual (expected_result, result_data, 6)
26 
27     def test_002_t (self):
28         gray_code = True
29         src_data = ((-1-1j), (-1+1j), (1+1j), (1-1j))
30         expected_result = (3, 2, 0, 1)
31         src = blocks.vector_source_c (src_data)
32         qpsk = qpsk_demod_py (gray_code)
33         dst = blocks.vector_sink_b ()
34         self.tb.connect (src, qpsk)
35         self.tb.connect (qpsk, dst)
36         self.tb.run ()
37         result_data = dst.data ()
38         self.assertFloatTuplesAlmostEqual (expected_result, result_data, 6)
39 
40 if __name__ == '__main__':
41     gr_unittest.run(qa_qpsk_demod, "qpsk_demod_py_cb.xml")


We can then run the test in Python and all should say something similar to:

Ran 2 tests in 0.005s

OK

So once we verify it works as expected, we can then edit our XML file so that it is usable inside GRC.

3.3.5. XML Mods, Installation, and Running[edit]

This XML is very similar to the XML file for the multiply_py_ff block so all we need to do is set the gray_code parameter and pick the correct input (complex) and output (byte) types. A copy of the full XML file is below:

XML File for QPSK Demod

 1 <?xml version="1.0"?>
 2 <block>
 3   <name>qpsk_demod_py</name>
 4   <key>tutorial_qpsk_demod_py</key>
 5   <category>tutorial</category>
 6   <import>import tutorial</import>
 7   <make>tutorial.qpsk_demod_py($gray_code)</make>
 8   <!-- Make one 'param' node for every Parameter you want settable from the GUI.
 9        Sub-nodes:
10        * name
11        * key (makes the value accessible as $keyname, e.g. in the make node)
12        * type -->
13   <param>
14     <name>Gray Code</name>
15     <key>gray_code</key>
16     <type>int</type>
17   </param>
18 
19   <!-- Make one 'sink' node per input. Sub-nodes:
20        * name (an identifier for the GUI)
21        * type
22        * vlen
23        * optional (set to 1 for optional inputs) -->
24   <sink>
25     <name>in</name>
26     <type>complex</type>
27   </sink>
28 
29   <!-- Make one 'source' node per output. Sub-nodes:
30        * name (an identifier for the GUI)
31        * type
32        * vlen
33        * optional (set to 1 for optional inputs) -->
34        <!-- e.g. int, float, complex, byte, short, xxx_vector, ...-->
35   <source>
36     <name>out</name>
37     <type>byte</type>
38   </source>
39 </block>


We can then install as we did for the multiply block however we need to rerun cmake in order to take into account the new block:

 cd build
 cmake ../
 make
 sudo make install
 sudo ldconfig

Then we can open up our GRC file from the beginning and place our missing block we just made.

What is the Expected Output? tutorial_three_4.png

3.4. Conclusion[edit]

And that is it for now with Python. Let us know your thoughts before going on to the C++ tutorial.

3.4.1. Questions We Should Now be Able to Answer[edit]

1. How do we set input- and output signatures in Python blocks?
2. Consider this I/O signature: (FIXME). Which input types and output types does it take?

3.5. Candidates for Future Sections[edit]

Possible topics we may want to add depending on feedback and questions on the mailing list
- How to add documentation to blocks
- Constructor arguments, History, Output Multiple