Windows Installation
Too long, won’t read: Use the RadioConda installer, as linked from our InstallingGR landing page.
Binary Installers
There are a few different unofficial GNU Radio binary installers that are maintained by the community:
1) Radioconda installer. This binary installer tends to be the most up-to-date, but you should check the list of packages to see if it includes what you need. It utilizes the conda
package/environment manager and provides easy access to thousands of Python and other packages that are not strictly related to GNU Radio. This also lets you stay up-to-date without having to re-install. Since this provides the same conda-forge packages available without the installer, the conda install guide might be useful for additional instructions, including how to build additional OOT modules from source.
After installing Radioconda you will get a «GNU Radio Companion» added to your start menu. Run this to start GNU Radio Companion, the graphical GNU Radio design tool.
2) (only outdated versions as of 2023-09) Geof Nieboer’s installer hosted at gcndevelopment.com (recently unreachable in 2022-07, but reachable currently 2022-10-23). This is a binary installer for 64-bit Windows 7/8/10 that includes all dependencies for Windows, a custom python distro, commonly used SDR drivers, and several OOT blocks.
3) (only outdated versions as of 2023-09) Pothos SDR development environment installer. This binary installer includes GNU Radio, Pothos, CubicSDK, and other tools. It has historically been updated about once or twice per year.
Current Windows Status
Installing core GNU Radio and USRP on Windows is becoming more routine. Many OoT modules may still require compiling locally. Please report any success or failures. Patches and enhancements are especially welcome!
Windows Porting Issues
Considerable effort has been put into making the GNU Radio code portable among various operating systems, but there are several reasons why it cannot be «simply» compiled and run under Windows:
- The build and install procedures are based on Linux scripts and tools
- Several third-party libraries are used, each with its own, often system-dependent, installation procedure
- Most GNU Radio applications must interface to hardware (e.g., a sound card or USRP) which require system-dependent drivers and installation procedures
- Because GNU Radio is written as an extension to Python, there are potential problems on Windows if different runtime libraries are used for GNU Radio and Python
The following sections show how these issues can be addressed.
Installation Options
GNU Radio is designed to be flexible. It has a number of modules, capabilities, and options that can be enabled or disabled to suit the needs of the user, and the user can add custom blocks or modules to the system.
To support this flexibility, it comes with a set of files and scripts to be used with GNU software build tools (sh, make, autoconf, automake, etc.). These tools use Linux-like commands and filenames that are not normally available on Windows systems.
Fortunately, we are not the first to face this problem, and several solutions exist. These are presented in order of increasing difficulty:
Building on Windows with Native Tools
Ettus Application note [1] describes how to build from source. Similar is a post at [2] for OOT modules.
Powershell scripts are now available at https://www.github.com/gnieboer/gnuradio_windows_build_scripts that fully automate the build process for GNURadio 3.7.9.2+. A few build dependencies are required (MSVC 2015, Git, Doxygen, CMake, Perl, Wix) but all are free. The script has two options:
- Build all dependencies from source (including python itself)
- Download a prebuilt custom dependency package and then build only GNURadio and a few OOT modules on top.
The binary installers described above are built with these scripts. They ensure that all dependencies are built with the same toolchain against the same runtime libraries, and handle the patches and configuration «tweaks» needed to build them on Windows.
If option 1 is desired, note that to build scipy, the non-free Intel Fortran compiler is required, gfortran cannot build objects that can link with MSVC C objects. If you do not have said compiler, the scripts will download pre-compiled wheels instead.
More information on the build process is available on the GitHub repo readme, and also at http://www.gcndevelopment.com/gnuradio.
GNURadio 3.6 has also been compiled on Windows using native tools as well (see http://voltronics.blogspot.com/2013/01/gnu-radio-windows-build-guide.html and https://lists.gnu.org/archive/html/discuss-gnuradio/2013-08/msg00284.html)
More helpful tips on dependency version information have been reported:
https://lists.gnu.org/archive/html/discuss-gnuradio/2013-12/msg00497.html
MinGW/MSYS
MinGW (http://www.mingw.org/) provides GNU compilers and Window-specific header files for compiling native Windows applications.
MSYS (http://www.mingw.org/msys.shtml) is a companion set of Linux-like commands, shell, and build tools.
MinGW does not include a Linux programming interface; programs should be smaller and faster than with Cygwin (in theory), but will require more Windows-specific code.
MSYS is intended primarily as a build environment, making it more compact than Cygwin.
Because there is no Linux API emulation, GNU Radio built with MinGW should be used with standard Windows versions of Python and the third-party libraries.
MinGW does not provide as much support as Cygwin for installing third-party libraries, but in many cases precompiled binaries are available.
For detailed installation instructions using MinGW and MSYS see Installing GNU Radio with MinGW.
MinGW-w64/MSYS2
MinGW-w64 (https://www.mingw-w64.org/) is an advancement of the original mingw.org project. It was created to support the GCC compiler on Windows systems.
MSYS2 (https://www.msys2.org/) is a software distribution and building platform for Windows. It provides command line terminal, bash, and Linux tools like sed and awk all based on a modified version of Cygwin. To provide easy installation, MSYS2 provides a package management system called Pacman. To install GNU Radio with MSYS2 open up a mintty command line terminal and run either:
pacman -S mingw-w64-x86_64-gnuradio
or:
pacman -S mingw-w64-ucrt-x86_64-gnuradio
For more detailed instructions on using GNU Radio with MinGW-w64 and MSYS2 see Using GNU Radio with MinGW-w64 and MSYS2
Cygwin
Cygwin (http://www.cygwin.com/) is a Linux-like environment for Windows.
It provides the Linux-like shell, file naming, and build tools we need and also makes it easy to install many of the third-party libraries required by GNU Radio. It also provides a Linux programming interface (API); this is not required by GNU Radio, but it lets us use the better-tested Linux versions of some functions.
Because the Linux API uses its own C runtime library, it is best to use Cygwin versions of Python and the third-party libraries when building GNU Radio with Cygwin.
For detailed installation instructions using Cygwin see Installing GNU Radio with Cygwin.
Chocolatey
To quote from the [|https://chocolatey.org/ Chocolatey homepage]: Chocolatey NuGet is a Machine Package Manager, somewhat like apt-get, but built with Windows in mind..
There are packages for gnuradio (and its dependencies) available in a separate repository (currently the best known source is: https://github.com/ariovistus/chocolatey-packages)
To install, open an Administrative command line session and run:
iex ((new-object net.webclient).DownloadString('https://chocolatey.org/install.ps1'))
Now you need to install a source which has the recipes for gnuradio and dependents. The easiest method is to clone the chocolatey-packages from the github repository listed above (https://github.com/ariovistus/chocolatey-packages), then add the local source from within an Administrative command line session:
choco source add -name gnuradio -source C:\<path-to>\chocolatey-packages
Create the numpy package:
cd <path-to>\chocolatey-package\numpy cpack
Create the gnuradio package:
cd <path-to>\chocolatey-package\gnuradio cpack
Now install the gnuradio package:
choco install gnuradio
Follow the command prompts.
WSL | Ubuntu
Enable WSL from windows features.
Install Ubuntu 20.04 (or newer) from Microsoft Store.
Using the Ubuntu terminal, install gnuradio as you would on linux [3]. If you want to develop GNU Radio’s core you will need to build GNU Radio from source.
WSL 1/2 (before WSLg)
Install additional package «libgtk-3-dev»
sudo apt install libgtk-3-dev
WSL 1 and 2 (before WSLg) do not have an X server for displaying graphical applications. Install an X server, either VcXsrv [4] or Xming [5] as WSL does not come with an X server. VcXsrv is recommended as it is open source and self-contained instead of being tied to Cygwin, whereas Xming «asks for donations» to the developer as a dubious «sale» for non-existent support.
Launch VcXsrv, making sure to select «Disable access control» option in the Extra settings so that any application can export to X11.
Edit bashrc to set up the display by adding the following lines at the bottom of the file.
WSL1:
# X11 forwarding for Windows export DISPLAY=:0.0 export LIBGL_ALWAYS_INDIRECT=1
WSL2:
# X11 forwarding for Windows export DISPLAY=$(awk '/nameserver / {print $2; exit}' /etc/resolv.conf 2>/dev/null):0 export LIBGL_ALWAYS_INDIRECT=1
Restart the Ubuntu terminal and run
gnuradio-companion
WSLg
Currently in early testing stages, the WSLg update contains a Wayland graphics server and X interface layer allowing graphical applications to run without extra setup.
From the Ubuntu terminal run
gnuradio-companion
Using an Azure VM
Another way to generate a GNU Radio environment if you’re using Windows, is to create an Azure Virtual Machine running Ubuntu Server 18.04 LTS.
If you already have an existing Azure account you can follow the instructions here[6] to create an Ubuntu VM using the Azure portal. Otherwise, you can sign up for an account here[7]. Azure provides free accounts for students[8] with a limited set of credits.
Once your VM is created you should be able to SSH into it, to install a desktop environment. Full instructions can be found here, but in summary:
Install xfce
sudo apt-get update sudo apt-get -y install xfce4
Install xrdp as a remote desktop server
sudo apt-get -y install xrdp sudo systemctl enable xrdp
Configure xrdp to use xfce
echo xfce4-session >~/.xsession
Restart the xrdp service
sudo service xrdp restart
You will need to create a local password for your Linux VM (on top of your existing SSH key), and open port 3389[9] on the VM.
Finally you can use a remote desktop client, such as Remote Desktop Connection to connect to your VM and follow the instructions for GNU Radio on Ubuntu found here[10].
Current GNU Radio Windows version: 3.10.12.0-0, released on 2025/02/20, compiled on 2025/03/20.
Current packager version (this installer): 1.20
The installer contains the release build. If you need to debug, PDB are also available for downloading as a separate file. Unzip it and add the folder “symbols” to Visual Studio symbol search path.
The installation works out of the box. There is no need to install any extra package or library.
Latest Release
GNURadio_3.10.12.0-0_win64_release
This is the release version of GNU Radio for Windows.
Size: 143 MB
Version: 3.10.12.0
Published: 20 March, 2025
SHA-256 checksum
21AC3C66DEED53D7273C172E45DCA46898B5160390A89D0747C827AACEB2C70A
GNURadio_3.10.12.0-0_win64_symbols
PDB files for debugging.
Size: 74 MB
Version: 3.10.12.0
Published: 20 March, 2025
GNURadio_3.9.4-0_win64_release
This is the release version of GNU Radio for Windows.
Size: 82.36 MB
Version: 3.9.4
Published: 18 November, 2021
SHA-256 checksum
e1e6c67834a1f6a887c6f7432fb1ed4114c49a850dd1bae09cf8c2f122c0ff57
GNURadio_3.9.4-0_win64_symbols
PDB files for debugging.
Size: 103.02MB
Version: 3.9.4
Published: 18 November, 2021
GNURadio_3.8.4-0_win64_release
This is the release version of GNU Radio for Windows.
Size: 57.86 MB
Version: 3.8.4
Published: 22 October, 2021
SHA-256 checksum
9e16795d098e30649915554006c397865ea1b73d947e3cae745f4ff61baafaf0
GNURadio_3.8.4-0_win64_symbols
PDB files for debugging.
Size: 30.10 MB
Version: 3.8.4
Published: 22 October, 2021
DEPENDENCIES
All dependencies are included and it is not needed to download extra packages.
Library | Version |
---|---|
MSVC | 2022 (14.3) |
Python | 3.11.4 |
Boost | 1.78.0 |
FFTW | 3.3.10 |
USB | 1.0.22 |
ZeroMQ | 4.3.5 |
Qt | 5.15.10 |
Qwt | 6.2.1 |
UHD | 4.6.0.0 |
Volk | 3.1.2 |
Atk | 2.38.0 |
Cairo | 1.17.8 |
Cairo-gobject | 1.17.8 |
Ffi | 3.4.4 |
FontConfig | 2.14.2 |
FreeType | 2.13 |
Fribidi | 1.0.13 |
Gdk Pixbuf | 2.42.10 |
Gdk | 3.24.38 |
Gio | 1.76.1 |
Gi Repository | 1.76.1 |
Glib | 2.76.3 |
GModule | 2.76.3 |
GObject | 2.76.3 |
GThread | 2.76.3 |
Gtk+ | 3.24.38 |
PNG | 1.6.39 |
XML | 2.10.4 |
Pango | 1.50.14 |
Pangocairo | 1.50.14 |
Pangoft2 | 1.50.14 |
Pangowin32 | 1.50.14 |
GSL | 2.7.1 |
SDL | 1.2.15 |
Numpy | 1.25.0 |
PygCCXML | 2.2.1 |
Sndfile | 1.2.0 |
SoapySDR | 0.8.1 |
Changelog
This is the changelog of the installer (not the GNU Radio).
Version 1.20:
- Repackage for GNU Radio 3.10.12
Version 1.19:
- Repackage for GNU Radio 3.10.10
- Upgraded libzmq, fmt, Volk and UHD libraries
Version 1.18:
- Repackage for GNU Radio 3.10.6
- Built with Visual Studio 2022
- Upgraded to Python 3.11 and other libraries to most recent version
Version 1.17:
- Repackage for GNU Radio 3.10.3
Version 1.16:
- Repackage for GNU Radio 3.10.1.1
- Repackage for GNU Radio 3.10.0
- Upgraded to Boost 1.74
- Added sdplog library.
- Added libiio library.
- Removed log4cpp library.
Version 1.14:
- Repackage for GNU Radio 3.9.4
Version 1.13:
- Repackage for GNU Radio 3.9.3
Version 1.12:
- Added cmake and pc files to installer when needed.
- Upgrading GSL to 2.5
- Added SoapySDR 0.8
- Repackage for GNU Radio 3.9.2
Version 1.10:
- Moving to Python 3.7.9
- Added PygCCXML
Version 1.9:
- Fixed missing sndfile.dll
- Fixed missing boost_serialization.dll
- Fixed wrong version of lib GSL
Version 1.8:
- Fixed gnuradio-companion.exe
Version 1.7:
- Added MATPLOTLIB.
- Added PIL.
Version 1.6:
- Repackage for GNU Radio 3.9.0.
- Upgraded Volk to 2.4.1.
- Upgraded UHD to 4.0.
- Fix with desktop shortcut.
- Volk is distributed with AVX.
Version 1.5:
- Repackage for GNU Radio 3.8.2.
- Included support for gr-wavelet.
- Included support for gr-video-sdl.
- Upgraded Volk to 2.3.
Version 1.4:
- Repackage for GNU Radio 3.8.1.
Version 1.3:
- Final repackage for GNU Radio 3.8.0.
Version 1.2:
- Fix with menu shortcuts uninstall.
- Fix with environment PATH.
Version 1.11:
- Added GNU Radio icons and license.
- Including Lib YAML for high speed GRC loading.
Version 1.0:
- Initial release.
TLDR: To install GNU Radio on Windows, just install RadioConda and the drivers for your SDR. Create a shortcut, double-click, and you’re running GNU Radio Companion! For hardware support, simply install the drivers for your platform.
The longer version of this post will provide a step-by-step process for using RadioConda to install GNU Radio on your Windows PC as well as building a quick flowgraph to test the installation. I’ll also show you how to enable support for the following hardware:
- HackRF
- PlutoSDR
In addition, I’ll introduce Python virtual environments in general, Conda more specifically, and Radioconda more specifically than that.
What are Virtual Environments?
These are configurations for your computer that include a specific version of Python as well as a number of applications, packages, and dependencies. What’s great is that none of this is installed on your machine itself! You can enter the virtual environment, execute applications, and then exit the virtual environment. Upon exiting, your operating system will return to the state it was in prior to entering the virtual environment.
What is Conda?
Conda is a powerful management tool for virtual environments. You can use it to create any number of Conda environments, and use very simple commands to install hundreds of packages.
What is Mamba?
Mamba is essentially an optimized, higher-performing version of Conda (stuff installs faster).
What is RadioConda?
Finally, we’ve arrived at the tool we’re going to use! RadioConda is based on Conda, but its default configuration includes a ton of SDR-specific packages, such as GNU Radio, RF apps, SDR hardware support, and many key out-of-tree modules. Installing it on your Windows, Linux, or Mac machine will give you an enormous amount of SDR software. And like any other Conda environment, you can enter and exit it at will, leaving your core operating system unaffected.
RadioConda Installation Process for Windows
Navigate to the RadioConda GitHub Page:
Download the Windows installer. If using Edge, you may be temporarily prevented from completing the download. If you click on the downloads button on the upper right, you may see this warning:
Click on the three dots to select “Keep”
And then confirm by selecting “Keep anyway”
Your download should then show as complete
Double-click the installer
Agree to the license
Choose the scope of the installation (“Just Me” is good for most users, unless you want multiple users to have access the software on your machine)
Select a location for the installed files (or just click “Install” to accept the default)
The install will take a few minutes. Click “Next” when it completes
Then click “Finish”
You can now access GNU Radio Companion from your start bar by typing “gnu”
It’s a good idea to click “Pin to taskbar” if you want easy access
Installing HackRF Support
Go back to the RadioConda GitHub Page and find the hardware support section
Clicking the “HackRF (setup)” link leads you down the page to the following:
Clicking the “Install the WinUSB driver with Zadig” link moves you further down the page to this:
Clicking the “Zadig” link takes you to this site, which hosts a general purpose USB driver for windows devices
Scrolling down a bit, you’ll find a download link for the most recent version of the driver. Note that the advertising on this site is… extensive… and that there are may be several other links appearing to be downloads. The “Zadig 2.9” link below is the one you want (although the version may have changed by the time you read this post)
Double-click the installer, and allow it to check for updates online
Then click “Install WCID Driver”
Installing PlutoSDR Support
Go back to the RadioConda GitHub Page and find the hardware support section
Click the “libiio (setup)” link, which leads you down the page to this
Click the link to download, then run the installer, accepting the license agreement
Confirm (or modify) the install location
Then confirm to begin installing
This brings you to an installer wizard, at which you click “Next”
Confirm install from Analog Devices
And Finish
Testing the Installation – HackRF
Bring up GNU Radio by typing GNU into the start bar or clicking the shortcut you’ve made
On the first attempt, I’ve seen a glitch where only a blank window appears. In that case, close the blank window and try again. You should then see the GNU Radio Companion interface.
Create a flowgraph as follows:
- change existing samp_rate variable to “10e6”
- add a Soapy HackRF Source with
- RF Options -> Bandwidth: samp_rate
- RF Options -> Center Freq (Hz): 98e6
- add a QT GUI Frequency Sink with
- General -> Center Frequency (Hz): 98e6
- Connect the source output to the sink input
- Save the flowgraph
Attach your HackRF to the PC via USB. After executing the flowgraph using the Play button in the toolbar, you should a live frequency plot several FM broadcast signals. The specific frequencies you observe will be different depending on the FM broadcasts in your area.
Testing the Installation – PlutoSDR
Bring up GNU Radio by typing GNU into the start bar or clicking the shortcut you’ve made
On the first attempt, I’ve seen a glitch where only a blank window appears. In that case, close the blank window and try again. You should then see the GNU Radio Companion interface.
Create a flowgraph as follows:
- change existing samp_rate variable to “10e6”
- add a Soapy PLUTO Source with
- RF Options -> Bandwidth: samp_rate
- RF Options -> Center Freq (Hz): 98e6
- add a QT GUI Frequency Sink with
- General -> Center Frequency (Hz): 98e6
- Connect the source output to the sink input
- Save the flowgraph
Attach your PlutoSDR to the PC via USB. After executing the flowgraph using the Play button in the toolbar, you should a live frequency plot several FM broadcast signals. The specific frequencies you observe will be different depending on the FM broadcasts in your area.
Время на прочтение10 мин
Количество просмотров52K
Привет, Хабр.
В третьей части было рассказано, как получить доступ к SDR-приемнику посредством языка Python. Сейчас мы познакомимся с программой GNU Radio — системой, позволяющей создать достаточно сложную конфигурацию радиоустройства, не написав ни единой строчки кода.
Для примера рассмотрим задачу параллельного приема нескольких FM-станций на один приемник. В качестве приемника будем использовать все тот же RTL SDR V3.
Продолжение под катом.
Установка
Для начала работы GNU Radio необходимо установить, дистрибутив для Windows можно скачать здесь. Система эта кроссплатформенная, версии есть также под Linux и под OSX (вроде бы GNU Radio успешно запускали и на Raspberry Pi, но 100% гарантии дать не могу).
По сути, GNU Radio это целый фреймворк для цифровой обработки сигналов, в котором программа «собирается» из отдельных модулей. Есть большое количество уже готовых блоков, при желании также можно создавать свои собственные. Сами модули написаны на С++, а для взаимодействия блоков друг с другом используется Python. Желающие могут посмотреть на API более подробно, но на практике это, скорее всего, не пригодится — все действия можно делать визуально в программе GNU Radio Companion.
Система ориентирована на обработку потоков данных, так что каждый блок обычно имеет вход и выход. Далее, соединяя блоки в редакторе, мы получаем готовую систему. Сам интерфейс GNU Radio довольно простой, сложность состоит в понимании того, что делает тот или иной блок. Как говорилось ранее, низкоуровневая работа с SDR имеет высокий порог входа и требует некоторого знания в DSP и математике. Но мы рассмотрим простую задачу, для которой никаких специальных знаний не потребуется. Итак, приступим.
Начало работы
Запускаем GNU Radio Companion, создаем новый проект, тип проекта выбираем WX GUI, добавляем на экран и соединяем два блока, как показано на скриншоте.
Мы видим два типа блоков — Source (источник) и Sink (выход, «слив»). RTL-SDR — это наш приемник, FFT GUI — это виртуальный спектроанализатор.
Переменную Sample Rate устанавливаем в 2048000, это частота дискретизации нашего приемника. Частоту RTL-SDR оставляем по умолчанию равной 100МГц.
Запускаем проект — все работает, мы видим спектр FM-станций. Первая программа для GNU Radio готова!
Если мы посмотрим лог, то увидим такие строки.
Generating: ‘D:\\MyProjects\\GNURadio\\top_block.py’
Executing: C:\Python27\python.exe -u D:\MyProjects\GNURadio\top_block.py
Да, мы можем посмотреть файл top_block.py, который сгенерил нам GNU Radio Companion. Истинные джедаи могут писать непосредственно в Python, но требуемый код, как мы видим, довольно большой. Мы же создали его за 1 минуту.
top_blocks.py
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
##################################################
# GNU Radio Python Flow Graph
# Title: Top Block
# Generated: Wed May 22 22:05:14 2019
##################################################
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 eng_notation
from gnuradio import gr
from gnuradio import wxgui
from gnuradio.eng_option import eng_option
from gnuradio.fft import window
from gnuradio.filter import firdes
from gnuradio.wxgui import fftsink2
from grc_gnuradio import wxgui as grc_wxgui
from optparse import OptionParser
import osmosdr
import time
import wx
class top_block(grc_wxgui.top_block_gui):
def __init__(self):
grc_wxgui.top_block_gui.__init__(self, title="Top Block")
##################################################
# Variables
##################################################
self.samp_rate = samp_rate = 2048000
##################################################
# Blocks
##################################################
self.wxgui_fftsink2_0 = fftsink2.fft_sink_c(
self.GetWin(),
baseband_freq=0,
y_per_div=10,
y_divs=10,
ref_level=0,
ref_scale=2.0,
sample_rate=samp_rate,
fft_size=1024,
fft_rate=15,
average=False,
avg_alpha=None,
title='FFT Plot',
peak_hold=False,
)
self.Add(self.wxgui_fftsink2_0.win)
self.rtlsdr_source_0 = osmosdr.source( args="numchan=" + str(1) + " " + '' )
self.rtlsdr_source_0.set_sample_rate(samp_rate)
self.rtlsdr_source_0.set_center_freq(100e6, 0)
self.rtlsdr_source_0.set_freq_corr(0, 0)
self.rtlsdr_source_0.set_dc_offset_mode(0, 0)
self.rtlsdr_source_0.set_iq_balance_mode(0, 0)
self.rtlsdr_source_0.set_gain_mode(False, 0)
self.rtlsdr_source_0.set_gain(10, 0)
self.rtlsdr_source_0.set_if_gain(20, 0)
self.rtlsdr_source_0.set_bb_gain(20, 0)
self.rtlsdr_source_0.set_antenna('', 0)
self.rtlsdr_source_0.set_bandwidth(0, 0)
##################################################
# Connections
##################################################
self.connect((self.rtlsdr_source_0, 0), (self.wxgui_fftsink2_0, 0))
def get_samp_rate(self):
return self.samp_rate
def set_samp_rate(self, samp_rate):
self.samp_rate = samp_rate
self.wxgui_fftsink2_0.set_sample_rate(self.samp_rate)
self.rtlsdr_source_0.set_sample_rate(self.samp_rate)
def main(top_block_cls=top_block, options=None):
tb = top_block_cls()
tb.Start(True)
tb.Wait()
if __name__ == '__main__':
main()
Впрочем, если убрать громоздкую инициализацию, то мы увидим, что ключевых строк кода не так уж много.
from gnuradio import gr
from gnuradio.wxgui import fftsink2
import osmosdr
class top_block(grc_wxgui.top_block_gui):
def __init__(self):
grc_wxgui.top_block_gui.__init__(self, title="Top Block")
self.samp_rate = samp_rate = 2048000
self.wxgui_fftsink2_0 = fftsink2.fft_sink_c(...)
self.Add(self.wxgui_fftsink2_0.win)
self.rtlsdr_source_0 = osmosdr.source(args="numchan=" + str(1) + " " + '' )
self.connect((self.rtlsdr_source_0, 0), (self.wxgui_fftsink2_0, 0))
def main(top_block_cls=top_block, options=None):
tb = top_block_cls()
tb.Start(True)
tb.Wait()
Так что в принципе, это можно написать вручную. Но мышью оно все-таки быстрее. Хотя возможность поменять код иногда может пригодиться, если захочется добавить какую-то нестандартную логику.
Принимаем FM-радио
Теперь попробуем принять одну из станций. Как было видно из скриншотов, центральная частота приемника 100МГц и ширина полосы пропускания около 2МГц. На спектре мы видим две станции, на 100.1МГц и 100.7МГц соответственно.
Первым шагом необходимо перенести спектр станции в центр, сейчас он отстоит вправо на 100КГц. Для этого вспоминаем школьную формулу умножения косинусов — в результате будет две частоты, сумма и разность — нужная станция сдвинется в центр, что нам и нужно (а лишнее мы потом отфильтруем).
Создаем две переменные для хранения частоты freq_center=100000000 и freq_1=100100000, также добавляем генератор сигналов с частотой freq_center — freq_1.
Т.к. система построена на базе Python, то в полях ввода параметров мы можем использовать выражения, что достаточно удобно.
Схема в итоге должна выглядеть так:
Теперь необходимо добавить сразу несколько блоков — уменьшить тактовую частоту входного сигнала (она равна 2048КГц), отфильтровать сигнал, подать его на FM-декодер, затем еще раз уменьшить тактовую частоту до 48КГц.
Результат показан на картинке:
Считаем внимательно. Мы делим тактовую частоту 2048КГц в 4 раза блоком Rational Resampler (получаем 512КГц), затем после Low Pass фильтра стоит WBFM-декодер с децимацией 10 (получаем 51.2КГц). В принципе, этот сигнал уже можно подать на звуковую карту, но высота тона будет чуть отличаться. Еще раз меняем тактовую частоту в 48/51, в результате будет тактовая частота 48.2КГц, разницей уже можно пренебречь.
Второй важный момент — тип входов. С приемника поступает комплексный IQ-сигнал (входы-выходы синего цвета), с FM-декодера выходит вещественный сигнал — входы и выходы желтого цвета. Если перепутать, ничего не заработает. Подробнее уже было на Хабре, нам достаточно понять общий принцип.
В общем, запускаем, убеждаемся что все работает. Можно запустить программу и слушать радио. Мы пойдем дальше — у нас же все-таки Software Defined радио — добавим одновременный прием второй станции.
Многоканальный прием
Второй приемник добавляется любимым программистским методом — Ctrl+C/Ctrl+V. Добавляем переменную freq_2, копируем блоки и соединяем их точно также.
Результат вполне сюрреалистичный — две FM-станции можно слушать одновременно. Тем же самым методом (Ctrl+V) можно добавить и третью станцию.
Запись
Слушать две станции оригинально, но на практике мало полезно. Сделаем что-то более нужное, например добавим запись звука в отдельные файлы. Это может быть достаточно удобно — с одного физического приемника можно параллельно записывать несколько каналов.
Добавим к каждому выходу компонент File Sink, как показано на скриншоте.
Windows-версия почему-то требует абсолютные пути файлов, иначе запись не работает. Запускаем, убеждаемся что все нормально. Размер сохраняемых файлов довольно большой, т.к. по умолчанию записывается формат float. Запись в формате int оставлю читателям в качестве домашнего задания.
Получившиеся файлы можно открыть в Cool Edit и убедиться, что звук записался нормально.
Разумеется, число записываемых каналов можно увеличить, оно ограничено только полосой пропускания приемника и мощностью компьютера. Кроме File Sink можно использовать и UDP Sink, так что программу можно использовать для трансляции по сети.
Запуск из командной строки
И последнее. Если использовать программу автономно, например для многоканальной записи, то UI в принципе и не нужен. В верхнем левом блоке Options меняем параметр Run Options на No UI. Запускаем программу еще раз, убеждаемся что все работает. Теперь сохраняем сгенерированный файл top_block.py — мы можем просто запускать его из командной строки, например из bat-файла или из консоли.
Если кому интересно, сгенерированный файл сохранен под спойлером.
recorder.py
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
##################################################
# GNU Radio Python Flow Graph
# Title: Top Block
# Generated: Fri May 24 21:47:03 2019
##################################################
from gnuradio import analog
from gnuradio import audio
from gnuradio import blocks
from gnuradio import eng_notation
from gnuradio import filter
from gnuradio import gr
from gnuradio.eng_option import eng_option
from gnuradio.filter import firdes
from optparse import OptionParser
import osmosdr
import time
class top_block(gr.top_block):
def __init__(self):
gr.top_block.__init__(self, "Top Block")
##################################################
# Variables
##################################################
self.samp_rate = samp_rate = 2048000
self.freq_center = freq_center = 100000000
self.freq_2 = freq_2 = 100700000
self.freq_1 = freq_1 = 100100000
##################################################
# Blocks
##################################################
self.rtlsdr_source_0 = osmosdr.source( args="numchan=" + str(1) + " " + '' )
self.rtlsdr_source_0.set_sample_rate(samp_rate)
self.rtlsdr_source_0.set_center_freq(freq_center, 0)
self.rtlsdr_source_0.set_freq_corr(0, 0)
self.rtlsdr_source_0.set_dc_offset_mode(0, 0)
self.rtlsdr_source_0.set_iq_balance_mode(0, 0)
self.rtlsdr_source_0.set_gain_mode(False, 0)
self.rtlsdr_source_0.set_gain(10, 0)
self.rtlsdr_source_0.set_if_gain(20, 0)
self.rtlsdr_source_0.set_bb_gain(20, 0)
self.rtlsdr_source_0.set_antenna('', 0)
self.rtlsdr_source_0.set_bandwidth(0, 0)
self.rational_resampler_xxx_1_0 = filter.rational_resampler_fff(
interpolation=48,
decimation=51,
taps=None,
fractional_bw=None,
)
self.rational_resampler_xxx_1 = filter.rational_resampler_fff(
interpolation=48,
decimation=51,
taps=None,
fractional_bw=None,
)
self.rational_resampler_xxx_0_0 = filter.rational_resampler_ccc(
interpolation=1,
decimation=4,
taps=None,
fractional_bw=None,
)
self.rational_resampler_xxx_0 = filter.rational_resampler_ccc(
interpolation=1,
decimation=4,
taps=None,
fractional_bw=None,
)
self.low_pass_filter_0_0 = filter.fir_filter_ccf(1, firdes.low_pass(
1, samp_rate/4, 100000, 500000, firdes.WIN_HAMMING, 6.76))
self.low_pass_filter_0 = filter.fir_filter_ccf(1, firdes.low_pass(
1, samp_rate/4, 100000, 500000, firdes.WIN_HAMMING, 6.76))
self.blocks_multiply_xx_0_0 = blocks.multiply_vcc(1)
self.blocks_multiply_xx_0 = blocks.multiply_vcc(1)
self.blocks_file_sink_0_0 = blocks.file_sink(gr.sizeof_float*1, 'D:\\Temp\\1\\audio2.snd', False)
self.blocks_file_sink_0_0.set_unbuffered(False)
self.blocks_file_sink_0 = blocks.file_sink(gr.sizeof_float*1, 'D:\\Temp\\1\\audio1.snd', False)
self.blocks_file_sink_0.set_unbuffered(False)
self.audio_sink_0 = audio.sink(48000, '', True)
self.analog_wfm_rcv_0_0 = analog.wfm_rcv(
quad_rate=samp_rate/4,
audio_decimation=10,
)
self.analog_wfm_rcv_0 = analog.wfm_rcv(
quad_rate=samp_rate/4,
audio_decimation=10,
)
self.analog_sig_source_x_0_0 = analog.sig_source_c(samp_rate, analog.GR_COS_WAVE, freq_center - freq_2, 1, 0)
self.analog_sig_source_x_0 = analog.sig_source_c(samp_rate, analog.GR_COS_WAVE, freq_center - freq_1, 1, 0)
##################################################
# Connections
##################################################
self.connect((self.analog_sig_source_x_0, 0), (self.blocks_multiply_xx_0, 1))
self.connect((self.analog_sig_source_x_0_0, 0), (self.blocks_multiply_xx_0_0, 1))
self.connect((self.analog_wfm_rcv_0, 0), (self.rational_resampler_xxx_1, 0))
self.connect((self.analog_wfm_rcv_0_0, 0), (self.rational_resampler_xxx_1_0, 0))
self.connect((self.blocks_multiply_xx_0, 0), (self.rational_resampler_xxx_0, 0))
self.connect((self.blocks_multiply_xx_0_0, 0), (self.rational_resampler_xxx_0_0, 0))
self.connect((self.low_pass_filter_0, 0), (self.analog_wfm_rcv_0, 0))
self.connect((self.low_pass_filter_0_0, 0), (self.analog_wfm_rcv_0_0, 0))
self.connect((self.rational_resampler_xxx_0, 0), (self.low_pass_filter_0, 0))
self.connect((self.rational_resampler_xxx_0_0, 0), (self.low_pass_filter_0_0, 0))
self.connect((self.rational_resampler_xxx_1, 0), (self.audio_sink_0, 0))
self.connect((self.rational_resampler_xxx_1, 0), (self.blocks_file_sink_0, 0))
self.connect((self.rational_resampler_xxx_1_0, 0), (self.audio_sink_0, 1))
self.connect((self.rational_resampler_xxx_1_0, 0), (self.blocks_file_sink_0_0, 0))
self.connect((self.rtlsdr_source_0, 0), (self.blocks_multiply_xx_0, 0))
self.connect((self.rtlsdr_source_0, 0), (self.blocks_multiply_xx_0_0, 0))
def get_samp_rate(self):
return self.samp_rate
def set_samp_rate(self, samp_rate):
self.samp_rate = samp_rate
self.rtlsdr_source_0.set_sample_rate(self.samp_rate)
self.low_pass_filter_0_0.set_taps(firdes.low_pass(1, self.samp_rate/4, 100000, 500000, firdes.WIN_HAMMING, 6.76))
self.low_pass_filter_0.set_taps(firdes.low_pass(1, self.samp_rate/4, 100000, 500000, firdes.WIN_HAMMING, 6.76))
self.analog_sig_source_x_0_0.set_sampling_freq(self.samp_rate)
self.analog_sig_source_x_0.set_sampling_freq(self.samp_rate)
def get_freq_center(self):
return self.freq_center
def set_freq_center(self, freq_center):
self.freq_center = freq_center
self.rtlsdr_source_0.set_center_freq(self.freq_center, 0)
self.analog_sig_source_x_0_0.set_frequency(self.freq_center - self.freq_2)
self.analog_sig_source_x_0.set_frequency(self.freq_center - self.freq_1)
def get_freq_2(self):
return self.freq_2
def set_freq_2(self, freq_2):
self.freq_2 = freq_2
self.analog_sig_source_x_0_0.set_frequency(self.freq_center - self.freq_2)
def get_freq_1(self):
return self.freq_1
def set_freq_1(self, freq_1):
self.freq_1 = freq_1
self.analog_sig_source_x_0.set_frequency(self.freq_center - self.freq_1)
def main(top_block_cls=top_block, options=None):
tb = top_block_cls()
tb.start()
try:
raw_input('Press Enter to quit: ')
except EOFError:
pass
tb.stop()
tb.wait()
if __name__ == '__main__':
main()
Удобно и то, что система является кросс-платформенной, и получившаяся программа может работать на Linux, Windows и OSX.
Заключение
Можно сказать, что GNU Radio достаточно сложная система, не в плане рисования блоков конечно, а в плане понимания того, как все это работает. Но какие-то несложные вещи сделать вполне посильно и интересно. GNU Radio также удобно использовать как «виртуальную лабораторию» для обучения — к любой части схемы можно подключить виртуальный осциллограф или спектроанализатор и посмотреть, как выглядит сигнал.
Если не будет каких-то отдельных пожеланий, тему SDR-приема наверно можно закрыть — все основные моменты уже рассмотрены, да и количество просмотров от первой к третьей части падает почти по экспоненте (хотя еще можно написать про передачу, но оно требует более дорогого «железа» для тестов чем RTL SDR). Надеюсь все же, что некоторое понимание того как это работает, у читателей осталось. Ну и всем удачных экспериментов.
GNURadio Windows Build Scripts v1.7
A series of Powershell scripts to automatically download, build from source, and install GNURadio and -all- it’s dependencies as 64-bit native binaries then package as an .msi using Visual Studio 2015.
For more details on this effort, please see the support website
IF YOU JUST WANT TO USE GNURADIO ON WINDOWS, DON’T USE THESE SCRIPTS… use the binaries that are posted at the above site. The Linux way is to build from source, this is usually not helpful on Windows, so use the installers unless you just want to tinker, in which case enjoy!
The finished MSI includes:
Device Support: UHD, RTL-SDR, hackrf, airspy, airspyhf, BladeRF, osmoSDR, FCD, SoapySDR
GNURadio modules: 3.8.1.0 and 3.7.13.5 with all but gr-comedi modules built and included
OOT modules: gr-iqbal, gr-fosphor, gr-osmosdr, gr-acars, gr-adsb, gr-modtool, gr-air-modes, gr-ais, gr-ax25, gr-burst (incl. bitarray), gr-cdma, gr-display (incl. matplotlib), gr-eventstream, gr-inspector (incl. tensorflow), gr-lte, gr-mapper, gr-nacl, gr-paint (incl. PIL), gr-radar, gr-rds, gr-specest, OpenLTE, gr-gsm
(not all modules available in gr 3.8)
Other Applications: gqrx
There are now two options for that for whatever your reason is, want to build these installers themselves. The newest and recommended option is to use an AWS EC2 instance with a custom AMI that has successfully built these scripts, to avoid configuration issues. I recommend a c5d.2xlarge because you must have the 200GB NVMe drive or larger.
The AMI is: GnuRadio Windows Build — ami-0ac7160e7f16f76ac. AMIs are regional, so you must connect to USA N. Virginia to see it, but you should be able to make a copy as you wish.
Once you log in, there are two shortcuts. The first will initialize the NVMe to your Z: drive. The second will run the scripts.
The second option is to build your own machine:
PREREQUISITES
Windows 10 64-bit (though binaries will run on Win 7)
The following tools must be installed:
- MS Visual Studio 2015
- Git For Windows (not just the version that comes with MSVC)
- CMake 3.13
- Doxygen
- ActiveState Perl
- Wix toolset for VS 2015
Please note that Visual Studio 2017 is not yet supported.
Also, the complete build requires no less than 120 GB of free disk space.
INSTALLATION & BUILD
Run the below from an elevated command prompt (the only command that requires elevation is the Set-ExecutionPolicy. If desired, the rest can be run from a user-privilege account)
git clone http://www.github.com/gnieboer/GNURadio_Windows_Build_Scripts cd GNURadio_Windows_Build_Scripts powershell Set-ExecutionPolicy Unrestricted ./~RUNME_FIRST.ps1
Build logs can be found in the $root/logs directory. The scripts will validate key parts of each step, but are not 100% guaranteed to detect a partial build failure. Use the logs to further diagnose issues.
Once complete, msi files can be found in the [root]/src-stage4-installer/dist subdirectories. The build can be tested after Step 7 by running run_grc.bat in the src-stage3/staged_install/[config]/bin subdirectory to
ISSUES
1- Ensure your anti-virus is off during installation… even Windows Defender. PyQt4 may fail to create manifest files as a result.
2- Right-click your powershell window, go to «Properties» and ensure QuickEdit and Insert Mode are NOT checked. Otherwise when you click on the window, execution may pause without any indication as to why, leading you to believe the build has hung.
3- This has been tested with a B200 UHD, a hackRF, and an RTL-SDR. Other device drivers have not been phyiscally verified to work. If you own one, please let me know if you had success.
4- In the event of issues, I highly recommend Dependency Walker or similar to troubleshoot what libraries are linked to what.
5- If your connection is spotty, you may get partially downloaded packages which cause build failures. To correct, DELETE the suspect package from the /packages directory so it will retry the download.
6- The following devices are NOT currently supported: FCD Pro+, RFSPACE, MiriSDR, SDRPlay, freeSRP
7- CMake 3.13 is the only version currently supported, though versions after 3.5 may be successful; older versions have been reported to have issues detecting the custom python install when at the BuildGNURadio step.
8- Zadig must be manually added to the /bin directory prior to MSI creation
LICENSE
The scripts themselves are released under the GPLv3. The resulting MSI’s are also GPLv3 compatible, see www.gcndevelopment.com/gnuradio for details and access to all modifications to original source code. All patches are released under the same license as the original package it applies to.