Browse Source

Merge branch 'drm' of https://github.com/srcejon/sdrangel into drm

chirpmodem-v8.0.0
Jon Beniston 1 month ago
parent
commit
9ea100b720
  1. 1
      CMakeLists.txt
  2. BIN
      doc/img/SELCALDemod_audio_spectrum.png
  3. BIN
      doc/img/SELCALDemod_audio_tones.png
  4. BIN
      doc/img/SELCALDemod_calls.png
  5. BIN
      doc/img/SELCALDemod_plugin.png
  6. 6
      plugins/channelrx/CMakeLists.txt
  7. 77
      plugins/channelrx/demodselcal/CMakeLists.txt
  8. 255
      plugins/channelrx/demodselcal/readme.md
  9. 153
      plugins/channelrx/demodselcal/selcalcarriertracker.cpp
  10. 85
      plugins/channelrx/demodselcal/selcalcarriertracker.h
  11. 919
      plugins/channelrx/demodselcal/selcaldecoder.cpp
  12. 268
      plugins/channelrx/demodselcal/selcaldecoder.h
  13. 727
      plugins/channelrx/demodselcal/selcaldemod.cpp
  14. 181
      plugins/channelrx/demodselcal/selcaldemod.h
  15. 212
      plugins/channelrx/demodselcal/selcaldemodbaseband.cpp
  16. 110
      plugins/channelrx/demodselcal/selcaldemodbaseband.h
  17. 1043
      plugins/channelrx/demodselcal/selcaldemodgui.cpp
  18. 169
      plugins/channelrx/demodselcal/selcaldemodgui.h
  19. 999
      plugins/channelrx/demodselcal/selcaldemodgui.ui
  20. 91
      plugins/channelrx/demodselcal/selcaldemodplugin.cpp
  21. 50
      plugins/channelrx/demodselcal/selcaldemodplugin.h
  22. 397
      plugins/channelrx/demodselcal/selcaldemodsettings.cpp
  23. 99
      plugins/channelrx/demodselcal/selcaldemodsettings.h
  24. 536
      plugins/channelrx/demodselcal/selcaldemodsink.cpp
  25. 128
      plugins/channelrx/demodselcal/selcaldemodsink.h
  26. 52
      plugins/channelrx/demodselcal/selcaldemodwebapiadapter.cpp
  27. 50
      plugins/channelrx/demodselcal/selcaldemodwebapiadapter.h
  28. 22
      plugins/channelrx/demodselcal/selcalmessages.cpp
  29. 97
      plugins/channelrx/demodselcal/selcalmessages.h
  30. 1
      plugins/feature/demodanalyzer/demodanalyzersettings.cpp
  31. 1
      plugins/feature/demodanalyzer/readme.md
  32. 1
      plugins/feature/denoiser/denoisersettings.cpp
  33. 1
      plugins/feature/denoiser/readme.md
  34. 2
      plugins/feature/radiosonde/radiosondegui.h
  35. 2
      sdrbase/CMakeLists.txt
  36. 1
      sdrbase/resources/webapi.qrc
  37. 2
      sdrbase/resources/webapi/doc/swagger/include/ChannelReport.yaml
  38. 2
      sdrbase/resources/webapi/doc/swagger/include/ChannelSettings.yaml
  39. 139
      sdrbase/resources/webapi/doc/swagger/include/SELCALDemod.yaml
  40. 203
      sdrbase/util/selcaldb.cpp
  41. 80
      sdrbase/util/selcaldb.h
  42. 41
      sdrbase/util/sondehub.cpp
  43. 7
      sdrbase/util/sondehub.h
  44. 6
      sdrbase/webapi/webapirequestmapper.cpp
  45. 2
      sdrbase/webapi/webapiutils.cpp
  46. 2
      swagger/sdrangel/api/swagger/include/ChannelReport.yaml
  47. 2
      swagger/sdrangel/api/swagger/include/ChannelSettings.yaml
  48. 140
      swagger/sdrangel/api/swagger/include/SELCALDemod.yaml
  49. 27
      swagger/sdrangel/code/qt5/client/SWGChannelReport.cpp
  50. 5
      swagger/sdrangel/code/qt5/client/SWGChannelReport.h
  51. 27
      swagger/sdrangel/code/qt5/client/SWGChannelSettings.cpp
  52. 5
      swagger/sdrangel/code/qt5/client/SWGChannelSettings.h
  53. 12
      swagger/sdrangel/code/qt5/client/SWGModelFactory.h
  54. 109
      swagger/sdrangel/code/qt5/client/SWGSELCALDemodReport.cpp
  55. 82
      swagger/sdrangel/code/qt5/client/SWGSELCALDemodReport.h
  56. 174
      swagger/sdrangel/code/qt5/client/SWGSELCALDemodSettings.cpp
  57. 132
      swagger/sdrangel/code/qt5/client/SWGSELCALDemodSettings.h

1
CMakeLists.txt

@ -175,6 +175,7 @@ option(ENABLE_CHANNELRX_DEMODNAVTEX "Enable channelrx demodnavtex plugin" ON) @@ -175,6 +175,7 @@ option(ENABLE_CHANNELRX_DEMODNAVTEX "Enable channelrx demodnavtex plugin" ON)
option(ENABLE_CHANNELRX_DEMODRTTY "Enable channelrx demodrtty plugin" ON)
option(ENABLE_CHANNELRX_DEMODPSK31 "Enable channelrx demodpsk31 plugin" ON)
option(ENABLE_CHANNELRX_DEMODILS "Enable channelrx demodils plugin" ON)
option(ENABLE_CHANNELRX_DEMODSELCAL "Enable channelrx demodselcal plugin" ON)
option(ENABLE_CHANNELRX_DEMODDSC "Enable channelrx demoddsc plugin" ON)
option(ENABLE_CHANNELRX_HEATMAP "Enable channelrx heatmap plugin" ON)
option(ENABLE_CHANNELRX_FREQSCANNER "Enable channelrx freqscanner plugin" ON)

BIN
doc/img/SELCALDemod_audio_spectrum.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

BIN
doc/img/SELCALDemod_audio_tones.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

BIN
doc/img/SELCALDemod_calls.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 32 KiB

BIN
doc/img/SELCALDemod_plugin.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 24 KiB

6
plugins/channelrx/CMakeLists.txt

@ -300,3 +300,9 @@ if(NOT SERVER_MODE) @@ -300,3 +300,9 @@ if(NOT SERVER_MODE)
message(STATUS "Not building demodatv (ENABLE_CHANNELRX_DEMODATV=${ENABLE_CHANNELRX_DEMODATV})")
endif()
endif()
if(ENABLE_CHANNELRX_DEMODSELCAL)
add_subdirectory(demodselcal)
else()
message(STATUS "Not building demodselcal (ENABLE_CHANNELRX_DEMODSELCAL=${ENABLE_CHANNELRX_DEMODSELCAL})")
endif()

77
plugins/channelrx/demodselcal/CMakeLists.txt

@ -0,0 +1,77 @@ @@ -0,0 +1,77 @@
project(demodselcal)
set(demodselcal_SOURCES
selcaldemod.cpp
selcaldemodsettings.cpp
selcaldemodbaseband.cpp
selcaldemodsink.cpp
selcalcarriertracker.cpp
selcaldecoder.cpp
selcalmessages.cpp
selcaldemodplugin.cpp
selcaldemodwebapiadapter.cpp
)
set(demodselcal_HEADERS
selcaldemod.h
selcaldemodsettings.h
selcaldemodbaseband.h
selcaldemodsink.h
selcalcarriertracker.h
selcaldecoder.h
selcalmessages.h
selcaldemodplugin.h
selcaldemodwebapiadapter.h
)
include_directories(
${CMAKE_SOURCE_DIR}/swagger/sdrangel/code/qt5/client
)
if(NOT SERVER_MODE)
set(demodselcal_SOURCES
${demodselcal_SOURCES}
selcaldemodgui.cpp
selcaldemodgui.ui
)
set(demodselcal_HEADERS
${demodselcal_HEADERS}
selcaldemodgui.h
)
set(TARGET_NAME ${PLUGINS_PREFIX}demodselcal)
set(TARGET_LIB "Qt::Widgets")
set(TARGET_LIB_GUI "sdrgui")
set(INSTALL_FOLDER ${INSTALL_PLUGINS_DIR})
else()
set(TARGET_NAME ${PLUGINSSRV_PREFIX}demodselcalsrv)
set(TARGET_LIB "")
set(TARGET_LIB_GUI "")
set(INSTALL_FOLDER ${INSTALL_PLUGINSSRV_DIR})
endif()
if(NOT Qt6_FOUND)
add_library(${TARGET_NAME} ${demodselcal_SOURCES})
else()
qt_add_plugin(${TARGET_NAME} CLASS_NAME SELCALDemodPlugin)
target_sources(${TARGET_NAME} PRIVATE ${demodselcal_SOURCES})
endif()
if(NOT BUILD_SHARED_LIBS)
set_property(GLOBAL APPEND PROPERTY STATIC_PLUGINS_PROPERTY ${TARGET_NAME})
endif()
target_link_libraries(${TARGET_NAME} PRIVATE
Qt::Core
${TARGET_LIB}
sdrbase
${TARGET_LIB_GUI}
)
install(TARGETS ${TARGET_NAME} DESTINATION ${INSTALL_FOLDER})
# Install debug symbols
if (WIN32)
install(FILES $<TARGET_PROPERTY:${TARGET_NAME},RUNTIME_OUTPUT_DIRECTORY>/${TARGET_NAME}stripped.pdb CONFIGURATIONS Release DESTINATION ${INSTALL_FOLDER} RENAME ${TARGET_NAME}.pdb )
install(FILES $<TARGET_PDB_FILE:${TARGET_NAME}> CONFIGURATIONS Debug RelWithDebInfo DESTINATION ${INSTALL_FOLDER} )
endif()

255
plugins/channelrx/demodselcal/readme.md

@ -0,0 +1,255 @@ @@ -0,0 +1,255 @@
<h1>SELCAL Demodulator Plugin</h1>
<h2>Introduction</h2>
This plugin decodes aviation SELCAL (selective calling) transmissions from HF USB
and VHF AM signals. It supports the original 12/16-tone system and all 32 tones
listed in the [ASRI SELCAL Users Guide, revision E](https://asri.aero/wp-content/uploads/2021/11/20240910-ASRI-SELCAL-Users-Guide.pdf).
A call consists of two simultaneous tone pairs, displayed as `AC-BD`. The four
tones must be distinct. The order of the pairs is retained; symbols within each
pair are displayed in tone designation order. Aircraft that have been assigned
a code can be displayed using a downloadable database. SELCAL codes do not
uniquely identify aircraft, so several aircraft may be listed for a code.
<h2>Interface</h2>
The top and bottom bars of the channel window are described [here](../../../sdrgui/channel/readme.md).
![SELCAL Demodulator plugin GUI](../../../doc/img/SELCALDemod_plugin.png)
<h3>1: Frequency shift from center frequency of reception</h3>
Use the frequency wheels to set the channel offset in Hz from the device center
frequency. Left click a digit to select it, then use the mouse wheel or keyboard
arrows to adjust it. Shift changes the selected digit by five steps and Control
by two steps. Right click a digit to set the digits to its right to zero.
For USB, tune to the carrier frequency. The channel marker shows the upper
sideband. AM uses a symmetric marker around the carrier.
<h3>2: Channel power</h3>
Displays average received channel power in dB relative to a signal with an
amplitude of 1.0.
<h3>3: Level meter in dB</h3>
- Top bar (green): average power.
- Bottom bar (blue green): instantaneous peak power.
- Bright green vertical marker: peak hold value.
<h3>4: Modulation</h3>
Select **USB** for HF upper-sideband signals or **AM** for VHF amplitude-modulated
signals. Changing modulation selects an initial bandwidth of 3000 Hz for USB or
6000 Hz for AM.
<h3>5: Bandwidth (BW)</h3>
Use the slider to set the bandwidth in 100 Hz steps. For USB, this sets the audio
upper cutoff from 2.0 to 3.6 kHz; the lower cutoff is 100 Hz. For AM, it sets the
full RF bandwidth from 2.0 to 6.0 kHz. The value is displayed beside the slider.
Keep enough bandwidth for both tones in each pair. The highest SELCAL-32 tone is
1557.8 Hz. An AM bandwidth of 6000 Hz covers the complete tone set. The bandwidth
does not change the decoder's sensitivity, as tone levels are measured relative
to the noise in the SELCAL band.
<h3>6: Automatic carrier detection</h3>
Use the carrier button to enable or disable automatic tone offset correction.
It is enabled by default for USB. A stable residual carrier within &plusmn;100 Hz
of the channel tuning supplies the correction automatically. Each tone pair keeps
the offset with which it was acquired. Retuning clears carrier acquisition.
If the carrier is fully suppressed or cannot be detected reliably, the decoder
searches around the manual tone offset. When a carrier fades or is keyed off,
the search is centred on its last measured offset for a further 10 seconds. This button is inactive in AM, which
always tracks the carrier, within &plusmn;1000 Hz, for coherent detection. When
the AM carrier cannot be tracked, envelope detection is used.
<h3>7: Tone offset</h3>
Sets the expected common frequency offset of the received audio tones, from
-100 to +100 Hz. For example, if the tones arrive 20 Hz above their nominal
frequencies, set this to `+20 Hz`.
When automatic carrier detection has a reliable lock, the measured carrier
offset is used instead. Otherwise, the decoder searches for the tones within
&plusmn;6 Hz of this setting, so small USB tuning errors need no correction. The
search is limited to &plusmn;6 Hz because pairs of adjacent tones resemble their
neighbours shifted by about 17.5 Hz: a wider search could decode the wrong code.
For larger errors, tune more accurately, set this offset, or rely on the carrier.
<h3>8: Threshold</h3>
Sets the minimum level of each tone of a pair above the noise, from 6 to 20 dB.
The default is 8 dB. The noise is measured across the SELCAL band, in the
bandwidth of a single tone (about 15 Hz). Lower values detect weaker calls, but
increase the chance of false detections. The tones must also be within 15 dB of
each other, and no third tone or other signal in the SELCAL band may be
comparable with them.
<h3>9: Carrier status</h3>
The status text shows the measured carrier offset and the
tone offset measured by the decoder, for example `Carrier +6.7 Hz, tones +6.7 Hz`.
In AM, it shows whether coherent detection is in use.
<h3>10: Volume</h3>
Use the dial to set the monitoring audio volume from 0.0 (silent) to 10.0 in steps
of 0.1. The default is 1.0, and the value is displayed beside the dial. This does
not change decoder input or detection thresholds.
<h3>11: Squelch threshold (Sq)</h3>
Sets the received RF power threshold for monitoring audio, from -100 to 0 dBFS
in 1 dB steps. The default is -80 dBFS. Audio opens above the threshold, with a
short hold to avoid chatter. The value is displayed beside the dial.
Squelch only controls monitoring audio. SELCAL decoding continues while the
squelch is closed.
<h3>12: Audio mute and audio output selection</h3>
Left click the speaker button to mute or unmute monitoring audio. The button
turns green while the audio squelch is open, including when audio is muted.
Muting audio does not interrupt decoding.
Right click the button to select the audio output device. The current device is
shown in the button's tooltip. See the
[audio management documentation](../../../sdrgui/audio.md) for details.
<h3>13: UDP output</h3>
Check **UDP** to enable or disable forwarding decoded
calls to the UDP address and port. Output is disabled by default. Each received
call produces one UTF-8 JSON datagram, independently of the table filter:
```json
{"code":"AC-BD","utc":"2026-10-02T12:34:56.789Z","frequencyHz":11330000,"rssi":-42.1,"snr":25.0,"toneOffsetHz":6.7}
```
UDP output also works in server mode.
<h3>14: UDP address</h3>
Sets the destination IP address or host name for UDP output. The default is
`127.0.0.1`. A host name is looked up when it is set.
<h3>15: UDP port</h3>
Sets the destination UDP port from 1 to 65535. The default is 9999.
<h3>16: Code filter</h3>
Filters the calls table using a case-insensitive substring match. Hyphens are
ignored, so `acbd` matches `AC-BD`. Leave the field empty to display all calls.
Filtering changes table visibility; logging and UDP output still include every
received call.
<h3>17: Copy calls</h3>
The copy button copies selected rows to the clipboard as tab-separated text,
with the columns shown in the order shown. If no rows are selected, it copies
the code shown in the last-call display.
To copy a single value, right click on its cell in the table and select
**Copy**. For an aircraft image or flag, this copies the registration or
country it represents.
<h3>18: Export calls to CSV</h3>
The export button saves the visible table rows to a selected CSV file. Rows
hidden by the code filter are excluded. The format is the same as the CSV log.
<h3>19: Start/stop logging calls to CSV</h3>
Use the record button to start or stop appending received calls to the selected
CSV log file. Logging is disabled by default. It includes every received call,
independently of the table filter, and also works in server mode.
The CSV columns and an example row are:
```text
UTC,Code,FrequencyHz,RSSI,SNR
2026-10-02T12:34:56.789Z,AC-BD,11330000,-42.1,25
```
<h3>20: CSV log filename</h3>
Click the save button to select the log filename. The current filename is shown
in its tooltip. The default is `selcal_log.csv`.
<h3>21: Download SELCAL database</h3>
Click the download button to download the database of SELCAL codes assigned to
aircraft. It is used to display
the registrations, types and images of aircraft assigned a received code. If the
aircraft database used by the ADS-B demodulator has not been downloaded, you are
asked whether to download it too (45MB): it provides aircraft types and images.
The databases are stored in SDRangel's application data directory.
<h3>22: Read calls from a CSV log</h3>
Click the load button to select an existing CSV log and add its calls to the
table. The file must contain the `UTC`, `Code`, `FrequencyHz`, `RSSI` and `SNR`
columns. Imported calls do not produce logging or UDP output, or increment the
receiver's call count.
<h3>23: Clear calls</h3>
Click the bin button to clear the calls table, including rows hidden by the
filter. This does not erase the log file or reset the receiver's call count.
<h3>Received calls table</h3>
![Received calls table](../../../doc/img/SELCALDemod_calls.png)
The table contains:
- **UTC:** approximate start time of the call, using the reception clock and
sample duration. Recording playback uses reception time rather than the
recording's original timestamp.
- **Code:** the two received tone pairs, such as `AC-BD`.
- **Registration:** registrations of aircraft assigned the code, from the SELCAL
database. Codes are not unique, so several aircraft may be listed. The tooltip
gives the manufacturer, model and operator of each from the aircraft database.
- **Type:** ICAO type designators of the listed aircraft, from the aircraft
database. `?` is shown for an aircraft that is not in the aircraft database.
- **Aircraft:** image of the first listed aircraft that is in the aircraft
database.
- **Country:** flag of the country of registration of that aircraft, or of the
first listed aircraft.
- **Frequency (kHz):** the tuned channel frequency when the call was decoded.
- **RSSI (dB):** average channel power during the two tone bursts, in dB
relative to a signal amplitude of 1.0.
- **SNR (dB):** level of the weaker tone above the noise in the bandwidth of a
tone, as for the threshold. Subtract about 22 dB for that tone's SNR in a
2.5 kHz bandwidth.
Drag column headers to reorder them and resize their edges to change column
widths. Right click on the table header to select which columns are shown.
Column positions, widths and visibility are saved with the channel settings.
There is no automatic history row limit.
<h3>Tone levels table</h3>
![Audio tones](../../../doc/img/SELCALDemod_audio_tones.png)
Open or close this panel using its rollup header. It displays the designation,
nominal frequency and level of each of the 32 SELCAL tones, in dB above the
noise in the bandwidth of a tone, measured at the current tone offset. A tone is
detectable when its level exceeds the threshold.
<h3>Audio spectrum</h3>
![Audio spectrum](../../../doc/img/SELCALDemod_audio_spectrum.png)
Displays the spectrum and waterfall of the audio analysed by the decoder, from
0 to 2 kHz. The 32 tone frequencies, adjusted by the tone offset, are marked at
the top of the spectrum. The tones of a detected pair are marked across the
full height of the spectrum and labelled. The display controls below the
spectrum are described [here](../../../sdrgui/gui/spectrum.md).

153
plugins/channelrx/demodselcal/selcalcarriertracker.cpp

@ -0,0 +1,153 @@ @@ -0,0 +1,153 @@
///////////////////////////////////////////////////////////////////////////////////
// Copyright (C) 2026 Jon Beniston, M7RCE <jon@beniston.com> //
// Some code by AI //
// //
// This program is free software; you can redistribute it and/or modify //
// it under the terms of the GNU General Public License as published by //
// the Free Software Foundation as version 3 of the License, or //
// (at your option) any later version. //
// //
// This program is distributed in the hope that it will be useful, //
// but WITHOUT ANY WARRANTY; without even the implied warranty of //
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //
// GNU General Public License V3 for more details. //
// //
// You should have received a copy of the GNU General Public License //
// along with this program. If not, see <http://www.gnu.org/licenses/>. //
///////////////////////////////////////////////////////////////////////////////////
#include <algorithm>
#include <cmath>
#include "dsp/fftengine.h"
#include "selcalcarriertracker.h"
SELCALCarrierTracker::SELCALCarrierTracker() :
m_fft(FFTEngine::create("")),
m_samples(2 * m_windowSize),
m_window(m_windowSize)
{
m_fft->configure(m_fftSize, false);
for (int i = 0; i < m_windowSize; ++i)
{
m_window[i] = 0.5 - 0.5 * std::cos(2 * M_PI * i / (m_windowSize - 1));
m_windowSum += m_window[i];
}
setRange(m_defaultRange);
}
SELCALCarrierTracker::~SELCALCarrierTracker() = default;
void SELCALCarrierTracker::reset()
{
std::fill(m_samples.begin(), m_samples.end(), Complex{});
m_position = m_count = m_missed = m_stable = 0;
m_candidate = m_offset = 0;
m_locked = false;
}
void SELCALCarrierTracker::setRange(double range)
{
range = std::isfinite(range) ? std::clamp(range, 10.0, 1500.0) : m_defaultRange;
if (range != m_range) {
reset();
}
m_range = range;
}
void SELCALCarrierTracker::feed(const Complex& sample)
{
m_samples[m_position] = m_samples[m_position + m_windowSize] = sample;
m_position = (m_position + 1) % m_windowSize;
if (m_count < m_windowSize) {
++m_count;
}
if (m_count == m_windowSize && m_position % m_hopSize == 0) {
analyse();
}
}
void SELCALCarrierTracker::analyse()
{
// Oldest to newest sample.
const Complex *samples = &m_samples[m_position];
Complex *input = m_fft->in();
for (int i = 0; i < m_windowSize; ++i) {
input[i] = samples[i] * m_window[i];
}
std::fill(input + m_windowSize, input + m_fftSize, Complex{});
m_fft->transform();
const Complex *output = m_fft->out();
double scale = 1.0 / (m_windowSum * m_windowSum);
auto power = [output, scale](int bin) {
return static_cast<double>(std::norm(output[(bin + m_fftSize) % m_fftSize])) * scale;
};
// Search past the capture range, so that a carrier just outside it cannot
// be mistaken for a peak at the edge of the search.
int rangeBins = static_cast<int>(std::ceil(m_range / m_binWidth));
int searchBins = std::min(rangeBins + 26, m_fftSize / 2 - 2);
int noiseBins = std::min(rangeBins + 77, m_fftSize / 2 - 1);
int peak = -searchBins;
for (int bin = -searchBins + 1; bin <= searchBins; ++bin) {
if (power(bin) > power(peak)) {
peak = bin;
}
}
// Excludes the peak's main lobe.
double secondary = 0;
for (int bin = -searchBins; bin <= searchBins; ++bin) {
if (std::abs(bin - peak) > 8) {
secondary = std::max(secondary, power(bin));
}
}
// The median is robust to the carrier and any tones near it. For noise
// each bin is exponentially distributed, so mean = median / ln 2.
m_noise.resize(2 * noiseBins + 1);
for (int bin = -noiseBins; bin <= noiseBins; ++bin) {
m_noise[bin + noiseBins] = power(bin);
}
auto middle = m_noise.begin() + m_noise.size() / 2;
std::nth_element(m_noise.begin(), middle, m_noise.end());
double noise = *middle / M_LN2;
double left = std::log(std::max(power(peak - 1), 1e-30));
double centre = std::log(std::max(power(peak), 1e-30));
double right = std::log(std::max(power(peak + 1), 1e-30));
double curvature = left - 2 * centre + right;
double fraction = curvature < -1e-12 ? 0.5 * (left - right) / curvature : 0;
double frequency = (peak + std::clamp(fraction, -0.5, 0.5)) * m_binWidth;
double carrierPower = power(peak);
bool valid = carrierPower > m_minPower && carrierPower > m_minSnr * noise && secondary < m_maxSecondary * carrierPower &&
std::abs(frequency) <= m_range;
bool measured = false;
if (valid)
{
m_stable = std::abs(frequency - m_candidate) < 1 ? std::min(m_stable + 1, 2) : 1;
m_candidate = frequency;
if (m_stable >= 2)
{
m_offset = m_locked && std::abs(frequency - m_offset) < 2 ? m_offset + 0.25 * (frequency - m_offset) : frequency;
m_locked = true;
measured = true;
}
}
else
{
m_stable = 0;
}
// Retain lock across the inter-pair gap, but expire it during silence or
// loss of the carrier instead of applying a stale correction indefinitely.
if (measured)
{
m_missed = 0;
}
else
{
m_missed = std::min(m_missed + 1, m_expiry);
if (m_missed == m_expiry) {
m_locked = false;
}
}
}

85
plugins/channelrx/demodselcal/selcalcarriertracker.h

@ -0,0 +1,85 @@ @@ -0,0 +1,85 @@
///////////////////////////////////////////////////////////////////////////////////
// Copyright (C) 2026 Jon Beniston, M7RCE <jon@beniston.com> //
// Some code by AI //
// //
// This program is free software; you can redistribute it and/or modify //
// it under the terms of the GNU General Public License as published by //
// the Free Software Foundation as version 3 of the License, or //
// (at your option) any later version. //
// //
// This program is distributed in the hope that it will be useful, //
// but WITHOUT ANY WARRANTY; without even the implied warranty of //
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //
// GNU General Public License V3 for more details. //
// //
// You should have received a copy of the GNU General Public License //
// along with this program. If not, see <http://www.gnu.org/licenses/>. //
///////////////////////////////////////////////////////////////////////////////////
#ifndef INCLUDE_SELCALCARRIERTRACKER_H
#define INCLUDE_SELCALCARRIERTRACKER_H
#include <memory>
#include <vector>
#include "dsp/dsptypes.h"
class FFTEngine;
// Measures the carrier of an 8 kHz channel: a residual USB carrier before the
// audio sideband filter removes it, or an AM carrier for coherent detection.
// The carrier must be the strongest signal within the capture range and stand
// out from the local noise floor.
class SELCALCarrierTracker {
public:
static constexpr int m_sampleRate = 8000;
static constexpr double m_defaultRange = 100.0;
SELCALCarrierTracker();
~SELCALCarrierTracker();
void reset();
// Capture range either side of the channel frequency, in Hz.
void setRange(double range);
void feed(const Complex& sample);
bool locked() const { return m_locked; }
double offset() const { return m_offset; }
// Samples by which the signal should be delayed so that carrier
// acquisition precedes the corresponding audio.
static constexpr int latency();
private:
static constexpr int m_windowSize = 2048; // 256 ms
static constexpr int m_fftSize = 4096;
static constexpr int m_hopSize = 256;
static constexpr int m_expiry = 6; // Analyses without a carrier before lock is lost
static constexpr double m_binWidth = static_cast<double>(m_sampleRate) / m_fftSize;
static constexpr double m_minSnr = 16.0; // Carrier power relative to the mean noise power in a bin (12 dB)
static constexpr double m_maxSecondary = 0.5; // Any other peak in the capture range must be at least 3 dB weaker
static constexpr double m_minPower = 1e-12; // Absolute floor, so that digital silence cannot acquire lock
std::unique_ptr<FFTEngine> m_fft;
std::vector<Complex> m_samples;
std::vector<float> m_window;
std::vector<double> m_noise;
double m_windowSum = 0;
double m_range = m_defaultRange;
int m_position = 0;
int m_count = 0;
int m_missed = 0;
int m_stable = 0;
double m_candidate = 0;
double m_offset = 0;
bool m_locked = false;
void analyse();
};
constexpr int SELCALCarrierTracker::latency()
{
return m_windowSize + 2 * m_hopSize;
}
#endif

919
plugins/channelrx/demodselcal/selcaldecoder.cpp

@ -0,0 +1,919 @@ @@ -0,0 +1,919 @@
///////////////////////////////////////////////////////////////////////////////////
// Copyright (C) 2026 Jon Beniston, M7RCE <jon@beniston.com> //
// Some code by AI //
// //
// This program is free software; you can redistribute it and/or modify //
// it under the terms of the GNU General Public License as published by //
// the Free Software Foundation as version 3 of the License, or //
// (at your option) any later version. //
// //
// This program is distributed in the hope that it will be useful, //
// but WITHOUT ANY WARRANTY; without even the implied warranty of //
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //
// GNU General Public License V3 for more details. //
// //
// You should have received a copy of the GNU General Public License //
// along with this program. If not, see <http://www.gnu.org/licenses/>. //
///////////////////////////////////////////////////////////////////////////////////
#include "selcaldecoder.h"
#include "dsp/fftengine.h"
#include <algorithm>
#include <cmath>
#include <utility>
// Modified Bessel function of the first kind, order 0, for the Kaiser window.
double SELCALDecoder::besselI0(double x)
{
double sum = 1, term = 1;
for (int m = 1; m < 50; ++m)
{
term *= (x / (2 * m)) * (x / (2 * m));
sum += term;
if (term < sum * 1e-12) {
break;
}
}
return sum;
}
// Hz by which the measured offsets of tones of the given frequencies may differ.
double SELCALDecoder::maxOffsetDifference(double frequency1, double frequency2)
{
return m_toneTolerance * (frequency1 + frequency2) + m_offsetMeasurementError;
}
double SELCALDecoder::median(std::vector<double> values)
{
if (values.empty()) {
return 0;
}
auto middle = values.begin() + values.size() / 2;
std::nth_element(values.begin(), middle, values.end());
return *middle;
}
const std::array<SELCALDecoder::Tone, SELCALDecoder::m_toneCount>& SELCALDecoder::tones()
{
// ASRI SELCAL Users Guide, Rev E (10 September 2024), table 2-1.
// Symbol order is deliberately independent of frequency order (SELCAL 32
// inserts frequencies between the original tones).
static const std::array<Tone, m_toneCount> table{
{{'A', 312.6}, {'B', 346.7}, {'C', 384.6}, {'D', 426.6}, {'E', 473.2}, {'F', 524.8}, {'G', 582.1}, {'H', 645.7},
{'J', 716.1}, {'K', 794.3}, {'L', 881.0}, {'M', 977.2}, {'P', 1083.9}, {'Q', 1202.3}, {'R', 1333.5}, {'S', 1479.1},
{'T', 329.2}, {'U', 365.2}, {'V', 405.0}, {'W', 449.3}, {'X', 498.3}, {'Y', 552.7}, {'Z', 613.1}, {'1', 680.0},
{'2', 754.2}, {'3', 836.6}, {'4', 927.9}, {'5', 1029.2}, {'6', 1141.6}, {'7', 1266.2}, {'8', 1404.4}, {'9', 1557.8}}};
return table;
}
SELCALDecoder::SELCALDecoder() :
m_fft(FFTEngine::create(""))
{
m_fft->configure(m_fftSize, false);
// Kaiser windowed halfband lowpass for 8 kHz to 4 kHz decimation: flat to
// 1.7 kHz and more than 65 dB down from 2.3 kHz, where aliases would reach
// the SELCAL band. Even taps other than the centre are zero.
constexpr int centre = m_decimatorTaps / 2;
constexpr double beta = 6.0;
double sum = 0.5;
m_halfbandCentre = 0.5;
for (int j = 0; j < m_halfbandTaps; ++j)
{
int k = 2 * j + 1;
double ratio = static_cast<double>(k) / centre;
double window = besselI0(beta * std::sqrt(std::max(0.0, 1 - ratio * ratio))) / besselI0(beta);
m_halfband[j] = std::sin(M_PI * k / 2) / (M_PI * k) * window;
sum += 2 * m_halfband[j];
}
m_halfbandCentre /= sum;
for (double& coefficient : m_halfband) {
coefficient /= sum;
}
double windowSum = 0;
for (int i = 0; i < m_windowSize; ++i)
{
m_window[i] = 0.5 - 0.5 * std::cos(2 * M_PI * i / (m_windowSize - 1));
windowSum += m_window[i];
}
// A tone of amplitude A measures A^2 at its centre bin.
m_powerScale = 4 / (windowSum * windowSum);
double margin = m_maxFrequencyOffset + m_searchRange + 10;
double lowest = tones()[0].m_frequency, highest = tones()[0].m_frequency;
for (int i = 0; i < m_toneCount; ++i)
{
m_toneBins[i] = tones()[i].m_frequency / m_binWidth;
lowest = std::min(lowest, tones()[i].m_frequency);
highest = std::max(highest, tones()[i].m_frequency);
}
m_bandStart = static_cast<int>(std::floor((lowest - margin) / m_binWidth));
m_bandEnd = static_cast<int>(std::ceil((highest + margin) / m_binWidth)) + 1;
m_hops.resize(m_preRollHops + 1);
for (auto& hop : m_hops) {
hop.m_power.resize(m_bandEnd - m_bandStart);
}
m_scratch.resize(m_bandEnd - m_bandStart);
m_raw.resize(m_bandEnd - m_bandStart);
m_background.resize(m_bandEnd - m_bandStart);
configure(0, m_defaultThreshold);
}
SELCALDecoder::~SELCALDecoder() = default;
void SELCALDecoder::configure(double frequencyOffset, double threshold)
{
threshold = std::isfinite(threshold) ? std::clamp(threshold, 3.0, 30.0) : m_defaultThreshold;
m_threshold = std::pow(10.0, threshold / 10);
setFrequencyOffset(frequencyOffset);
reset();
}
void SELCALDecoder::setFrequencyOffset(double frequencyOffset, double uncertainty)
{
frequencyOffset = std::isfinite(frequencyOffset) ? std::clamp(frequencyOffset, -m_maxFrequencyOffset, m_maxFrequencyOffset) : 0;
uncertainty = std::isfinite(uncertainty) ? std::clamp(uncertainty, 0.0, m_searchRange) : m_searchRange;
m_baseOffset = frequencyOffset / m_binWidth;
m_searchBins = std::max(1, static_cast<int>(std::ceil(uncertainty / m_binWidth)));
}
void SELCALDecoder::reset()
{
m_history.fill(0);
m_historyPosition = 0;
m_samples.fill(0);
m_position = 0;
m_levels.fill(-30);
m_inputCount = 0;
m_analysisCount = 0;
m_hopCount = 0;
m_hopIndex = 0;
m_detected = {{-1, -1}};
m_currentOffset = m_baseOffset;
m_segment = Segment();
m_pending = Burst();
m_held = Burst();
m_holding = false;
m_called = Burst();
m_blankLevel = 0;
m_blankCount = 0;
m_blankRun = 0;
m_blankQuiet = 0;
std::fill(m_background.begin(), m_background.end(), 0.0);
m_backgroundNoise = 0;
m_backgroundCount = 0;
m_learnAfter = 0;
}
const char *SELCALDecoder::stateName(State state)
{
switch (state)
{
case State::FirstPair:
return "First pair";
case State::Gap:
return "Gap";
case State::SecondPair:
return "Second pair";
case State::WaitForSilence:
return "Waiting for silence";
default:
return "Idle";
}
}
SELCALDecoder::State SELCALDecoder::state() const
{
bool waiting = m_pending.m_valid || (m_holding && !brief(m_held));
if (m_segment.m_active) {
return m_segment.m_overlong ? State::WaitForSilence : waiting ? State::SecondPair : State::FirstPair;
}
return waiting ? State::Gap : State::Idle;
}
double SELCALDecoder::frequencyOffset() const
{
double offset = m_segment.m_active ? m_segment.m_offset : m_holding ? m_held.m_offset : m_pending.m_valid ? m_pending.m_offset : m_currentOffset;
return offset * m_binWidth;
}
void SELCALDecoder::feed(double sample)
{
m_history[m_historyPosition] = m_history[m_historyPosition + m_decimatorTaps] = std::isfinite(sample) ? sample : 0;
m_historyPosition = (m_historyPosition + 1) % m_decimatorTaps;
if (++m_inputCount % 2) {
return;
}
// Oldest to newest input.
const double *history = &m_history[m_historyPosition];
constexpr int centre = m_decimatorTaps / 2;
double output = m_halfbandCentre * history[centre];
for (int j = 0; j < m_halfbandTaps; ++j)
{
int k = 2 * j + 1;
output += m_halfband[j] * (history[centre - k] + history[centre + k]);
}
if (m_sampleHandler) {
m_sampleHandler(static_cast<float>(output));
}
blank(output);
m_samples[m_position] = m_samples[m_position + m_windowSize] = output;
m_position = (m_position + 1) % m_windowSize;
if (++m_analysisCount >= m_windowSize && m_analysisCount % m_hopSize == 0) {
analyse();
}
}
int SELCALDecoder::bin(int tone, double offset) const
{
return std::clamp(static_cast<int>(std::lround(m_toneBins[tone] + offset)), m_bandStart, m_bandEnd - 1) - m_bandStart;
}
const SELCALDecoder::Hop& SELCALDecoder::hop(int age) const
{
int size = static_cast<int>(m_hops.size());
return m_hops[(m_hopIndex - age + size) % size];
}
double SELCALDecoder::pairPower(const Hop& hop, const Pair& pair, double offset) const
{
return hop.m_power[bin(pair[0], offset)] + hop.m_power[bin(pair[1], offset)];
}
void SELCALDecoder::analyse()
{
Complex *input = m_fft->in();
const double *samples = &m_samples[m_position];
for (int n = 0; n < m_windowSize; ++n) {
input[n] = Complex(static_cast<Real>(samples[n] * m_window[n]), 0);
}
std::fill(input + m_windowSize, input + m_fftSize, Complex{});
m_fft->transform();
m_hopIndex = (m_hopIndex + 1) % static_cast<int>(m_hops.size());
Hop& current = m_hops[m_hopIndex];
// Window centre in input samples, allowing for the decimator's delay.
current.m_time = 2.0 * static_cast<double>(m_analysisCount) - 431;
const Complex *output = m_fft->out();
for (int b = m_bandStart; b < m_bandEnd; ++b) {
current.m_power[b - m_bandStart] = static_cast<float>(std::norm(output[b]) * m_powerScale);
}
++m_hopCount;
// The median of the band is robust to the tones themselves. For white
// noise each bin is exponentially distributed, so mean = median / ln 2.
std::copy(current.m_power.begin(), current.m_power.end(), m_scratch.begin());
auto middle = m_scratch.begin() + m_scratch.size() / 2;
std::nth_element(m_scratch.begin(), middle, m_scratch.end());
current.m_noise = std::max(static_cast<double>(*middle) / M_LN2, m_noiseFloor);
// Remove steady signals, such as heterodynes, that were present before
// any burst. Otherwise they would be taken as competing tones and prevent
// detection. Tones received on top of them are still measured.
std::copy(current.m_power.begin(), current.m_power.end(), m_raw.begin());
if (m_backgroundCount > 0)
{
for (std::size_t b = 0; b < current.m_power.size(); ++b)
{
if (m_background[b] > m_steadyLevel * m_backgroundNoise)
{
// A strong steady signal's level varies slightly between analyses,
// so a margin is subtracted to prevent residuals being detected.
double power = current.m_power[b] - m_steadyMargin * (m_background[b] - m_backgroundNoise);
current.m_power[b] = static_cast<float>(std::max(power, 1e-3 * current.m_noise));
}
}
}
// Candidate common tone offsets, in bins. While a burst is in progress,
// its own offsets are searched as well as the expected offset, so that a
// spurious burst cannot mask the start of a stronger one elsewhere.
std::array<double, 64> candidates;
std::array<bool, 64> inSegment;
int candidateCount = 0;
auto add = [&](double centre, int range, bool segment) {
for (int c = -range; c <= range && candidateCount < static_cast<int>(candidates.size()); ++c)
{
inSegment[candidateCount] = segment;
candidates[candidateCount++] = centre + c;
}
};
if (m_segment.m_active) {
add(m_segment.m_offset, m_anchorSearch, true);
}
add(m_baseOffset, m_searchBins, false);
const Burst *previous = previousPair();
if (previous) {
add(previous->m_offset, m_anchorSearch, false);
}
bool found = false;
Pair bestPair{{-1, -1}};
double bestOffset = m_segment.m_active ? m_segment.m_offset : previous ? previous->m_offset : m_baseOffset;
double bestSnr = 0;
bool continued = false; // The burst in progress was detected again
double continuedSnr = 0;
double scale = 1.0 / current.m_noise;
Peaks peaks;
findPeaks(current.m_power, peaks);
for (int c = 0; c < candidateCount; ++c)
{
Pair pair;
double snr;
if (!evaluate(current.m_power, peaks, scale, candidates[c], pair, snr)) {
continue;
}
if (inSegment[c] && pair == m_segment.m_pair && snr > continuedSnr)
{
continued = true;
continuedSnr = snr;
}
if (snr > bestSnr)
{
found = true;
bestSnr = snr;
bestOffset = candidates[c];
bestPair = pair;
}
}
if (continued)
{
m_detected = m_segment.m_pair;
m_currentOffset = m_segment.m_offset;
}
else
{
m_detected = bestPair;
m_currentOffset = bestOffset;
}
for (int i = 0; i < m_toneCount; ++i) {
m_levels[i] = 10 * std::log10(std::max(current.m_power[bin(i, m_currentOffset)] * scale, 1e-3));
}
if (m_segment.m_active && m_segment.m_overlong)
{
// Too long for a SELCAL burst, so a steady signal. Its history is no
// longer needed, and it is learnt as background (below) until it no
// longer masks other signals.
if (continued) {
m_segment.m_missed = 0;
} else if (++m_segment.m_missed > m_holdHops) {
closeSegment();
}
}
else if (m_segment.m_active)
{
m_segment.m_power.push_back(pairPower(current, m_segment.m_pair, m_segment.m_offset));
m_segment.m_times.push_back(current.m_time);
m_segment.m_detected.push_back(continued);
if (current.m_time - m_segment.m_times[m_segment.m_first] > (m_maxBurst + 0.125) * m_sampleRate) {
m_segment.m_overlong = true;
}
if (continued)
{
m_segment.m_last = static_cast<int>(m_segment.m_power.size()) - 1;
m_segment.m_missed = 0;
m_segment.m_snr.push_back(continuedSnr);
accumulate(current);
}
else if (++m_segment.m_missed > m_holdHops) {
// Ends the burst. A different pair detected in this hop may start the next one.
closeSegment();
}
}
if (!m_segment.m_active)
{
// The leading edge of a burst can be found up to the pre-roll before it is detected.
double preRoll = m_preRollHops * m_hopSize * 2.0 / m_sampleRate;
if (m_holding && current.m_time - m_held.m_end > (m_maxFadeGap + preRoll) * m_sampleRate) {
releaseHeld();
}
// While a burst is held, it may be the second pair.
if (m_pending.m_valid && !m_holding &&
current.m_time - m_pending.m_end > (m_maxGap + (m_nominalBurst - m_minFadedBurst) + (m_nominalBurst - m_minBurst) + preRoll) * m_sampleRate) {
m_pending.m_valid = false;
}
if (found) {
startSegment(bestPair, bestOffset, bestSnr);
}
}
bool idle = !found && !m_segment.m_active && !m_pending.m_valid && !(m_holding && !brief(m_held));
bool steady = m_segment.m_active && m_segment.m_overlong;
if ((idle || steady) && (m_inputCount >= m_learnAfter)) {
learnBackground(current.m_noise);
}
}
void SELCALDecoder::holdLearning(std::uint64_t samples)
{
m_learnAfter = m_inputCount + samples;
}
void SELCALDecoder::learnBackground(double noise)
{
// Running mean initially, then an exponential average.
m_backgroundCount = std::min(m_backgroundCount + 1, m_backgroundHops);
double alpha = 1.0 / m_backgroundCount;
for (std::size_t b = 0; b < m_raw.size(); ++b) {
m_background[b] += (m_raw[b] - m_background[b]) * alpha;
}
m_backgroundNoise += (noise - m_backgroundNoise) * alpha;
}
std::uint64_t SELCALDecoder::sampleIndex(double time)
{
return static_cast<std::uint64_t>(std::max(0.0, std::round(time)));
}
void SELCALDecoder::findPeaks(const std::vector<float>& power, Peaks& peaks) const
{
// Strongest local maxima of the band, strongest first.
peaks.fill(-1);
for (int b = 1; b + 1 < static_cast<int>(power.size()); ++b)
{
if (power[b] < power[b - 1] || power[b] < power[b + 1] || (peaks[m_peakCount - 1] >= 0 && power[b] <= power[peaks[m_peakCount - 1]])) {
continue;
}
int i = m_peakCount - 1;
while (i > 0 && (peaks[i - 1] < 0 || power[b] > power[peaks[i - 1]]))
{
peaks[i] = peaks[i - 1];
--i;
}
peaks[i] = b;
}
}
bool SELCALDecoder::evaluate(const std::vector<float>& power, const Peaks& peaks, double scale, double offset, Pair& pair, double& snr) const
{
int first = -1, second = -1;
double p1 = -1, p2 = -1, p3 = -1;
for (int i = 0; i < m_toneCount; ++i)
{
double level = power[bin(i, offset)];
if (level > p1)
{
p3 = p2;
second = first;
p2 = p1;
first = i;
p1 = level;
}
else if (level > p2)
{
p3 = p2;
second = i;
p2 = level;
}
else if (level > p3)
{
p3 = level;
}
}
p1 *= scale;
p2 *= scale;
p3 *= scale;
pair = {{std::min(first, second), std::max(first, second)}};
snr = p2;
// The strongest other signal in the band, away from the pair's main lobes.
// Unlike the third tone, this does not depend on the offset: at another
// offset, a three-tone chord could otherwise look like a different pair.
double other = 0;
int firstBin = bin(pair[0], offset), secondBin = bin(pair[1], offset);
for (int peak : peaks)
{
if (peak >= 0 && std::abs(peak - firstBin) > m_mainLobeBins && std::abs(peak - secondBin) > m_mainLobeBins)
{
other = power[peak] * scale;
break;
}
}
// Both tones must stand out from the noise, and not differ too greatly in level.
// A third tone or other signal that is itself significant makes the pair
// ambiguous. The noise maximum across the band is allowed for.
if (!(p2 >= m_threshold && p2 >= p1 * m_minBalance && p3 < std::max(p2 * 0.30, m_threshold) &&
other < std::max(p2 * 0.30, 2 * m_threshold))) {
return false;
}
// Each tone must be a spectral peak. The main lobe is wider than the
// spacing of adjacent tones, so a single signal between two of them could
// otherwise look like a pair.
return peaked(power, pair[0], pair[1], offset) && peaked(power, pair[1], pair[0], offset);
}
int SELCALDecoder::peakRange(int tone, int partner) const
{
// Bins either side of a tone to search for its peak, keeping clear of the
// other tone of the pair.
return std::min(m_anchorSearch + 2, static_cast<int>((std::abs(m_toneBins[partner] - m_toneBins[tone]) - 1) / 2));
}
bool SELCALDecoder::peaked(const std::vector<float>& power, int tone, int partner, double offset) const
{
int range = peakRange(tone, partner);
int centre = bin(tone, offset);
int low = std::max(0, centre - range), high = std::min(static_cast<int>(power.size()) - 1, centre + range);
int peak = low;
for (int b = low; b <= high; ++b) {
if (power[b] > power[peak]) {
peak = b;
}
}
return peak > low && peak < high;
}
void SELCALDecoder::startSegment(const Pair& pair, double offset, double snr)
{
m_segment = Segment();
m_segment.m_active = true;
m_segment.m_pair = pair;
m_segment.m_offset = offset;
m_segment.m_acquired = offset;
// Acquired around the expected offset, or that of the previous pair.
bool expected = std::abs(offset - m_baseOffset) <= m_searchBins + 0.01;
const Burst *previous = previousPair();
m_segment.m_searchCentre = expected || !previous ? m_baseOffset : previous->m_offset;
m_segment.m_searchBins = expected || !previous ? m_searchBins : m_anchorSearch;
m_segment.m_spectrum.assign(m_bandEnd - m_bandStart, 0.0f);
int history = static_cast<int>(std::min<std::uint64_t>(m_preRollHops, m_hopCount - 1));
for (int age = history; age >= 0; --age)
{
const Hop& previous = hop(age);
m_segment.m_power.push_back(pairPower(previous, pair, offset));
m_segment.m_times.push_back(previous.m_time);
m_segment.m_detected.push_back(age == 0);
}
m_segment.m_first = m_segment.m_last = history;
m_segment.m_snr.push_back(snr);
accumulate(hop(0));
}
void SELCALDecoder::accumulate(const Hop& current)
{
double scale = 1.0 / current.m_noise;
for (std::size_t b = 0; b < current.m_power.size(); ++b) {
m_segment.m_spectrum[b] += static_cast<float>(current.m_power[b] * scale);
}
++m_segment.m_spectrumHops;
// The acquisition offset is measured on the burst's leading edge and is
// coarse. Follow the tones' measured offset so they stay centred in the search.
double sum = 0, weight = 0;
for (int k = 0; k < 2; ++k) {
measurePeak(current.m_power, m_segment.m_pair[k], m_segment.m_pair[1 - k], m_segment.m_offset, sum, weight);
}
m_segment.m_offsetSum += sum;
m_segment.m_offsetWeight += weight;
if (m_segment.m_offsetWeight > 0)
{
// Stay within the search, so the tones cannot be followed towards another pair.
double range = m_segment.m_searchBins + 1;
m_segment.m_offset = std::clamp(m_segment.m_offsetSum / m_segment.m_offsetWeight, m_segment.m_searchCentre - range, m_segment.m_searchCentre + range);
}
}
void SELCALDecoder::measurePeak(const std::vector<float>& power, int tone, int partner, double offset, double& sum, double& weight) const
{
// Interpolated spectral peak near the expected tone frequency, keeping
// clear of the other tone of the pair.
int size = static_cast<int>(power.size());
int range = peakRange(tone, partner);
int centre = bin(tone, offset);
int low = std::max(1, centre - range), high = std::min(size - 2, centre + range);
if (low > high) {
return;
}
int peak = low;
for (int b = low; b <= high; ++b) {
if (power[b] > power[peak]) {
peak = b;
}
}
double left = std::log(std::max(static_cast<double>(power[peak - 1]), 1e-30));
double centrePower = std::log(std::max(static_cast<double>(power[peak]), 1e-30));
double right = std::log(std::max(static_cast<double>(power[peak + 1]), 1e-30));
double curvature = left - 2 * centrePower + right;
double fraction = curvature < -1e-12 ? std::clamp(0.5 * (left - right) / curvature, -0.5, 0.5) : 0;
sum += power[peak] * (peak + m_bandStart + fraction - m_toneBins[tone]);
weight += power[peak];
}
bool SELCALDecoder::identify(Pair& pair, double& offset) const
{
// Identify the pair again from the spectrum averaged over the burst. Its
// SNR is much higher than any single analysis, so it reliably distinguishes
// the pair from a similar pair at a different offset.
const Segment& s = m_segment;
pair = s.m_pair;
offset = s.m_offset;
if (s.m_spectrumHops == 0) {
return false;
}
double scale = 1.0 / s.m_spectrumHops;
double best = 0;
Peaks peaks;
findPeaks(s.m_spectrum, peaks);
auto consider = [&](double centre, int range) {
for (int c = -range; c <= range; ++c)
{
Pair candidate;
double snr;
if (evaluate(s.m_spectrum, peaks, scale, centre + c, candidate, snr) && snr > best)
{
best = snr;
pair = candidate;
offset = centre + c;
}
}
};
consider(s.m_searchCentre, s.m_searchBins);
// Both tones of a genuine pair share the offset, to within the tone
// frequency tolerance. When tones are further from the expected offset
// than the search, they can resemble other tones, but rarely with a
// consistent offset.
std::array<double, 2> sums{}, weights{};
for (int k = 0; k < 2; ++k) {
measurePeak(s.m_spectrum, pair[k], pair[1 - k], offset, sums[k], weights[k]);
}
if (weights[0] <= 0 || weights[1] <= 0) {
return false;
}
double first = sums[0] / weights[0], second = sums[1] / weights[1];
offset = std::clamp((sums[0] + sums[1]) / (weights[0] + weights[1]), offset - 1, offset + 1);
double allowed = maxOffsetDifference(tones()[pair[0]].m_frequency, tones()[pair[1]].m_frequency);
return std::abs(first - second) <= allowed / m_binWidth;
}
void SELCALDecoder::closeSegment()
{
Segment& s = m_segment;
s.m_active = false;
// Burst edges are where the pair's amplitude is half its typical value:
// the analysis window is then centred on the edge. This is independent of
// signal level, unlike the first and last hops on which a pair is detected.
std::vector<double> detectedPower;
for (int i = s.m_first; i <= s.m_last; ++i) {
if (s.m_detected[i]) {
detectedPower.push_back(s.m_power[i]);
}
}
double threshold = std::sqrt(median(detectedPower)) / 2;
int count = static_cast<int>(s.m_power.size());
auto amplitude = [&s](int i) {
return std::sqrt(s.m_power[i]);
};
auto crossing = [&](int a, int b) {
double difference = amplitude(b) - amplitude(a);
double fraction = std::abs(difference) > 1e-30 ? (threshold - amplitude(a)) / difference : 0.5;
return s.m_times[a] + (s.m_times[b] - s.m_times[a]) * std::clamp(fraction, 0.0, 1.0);
};
int i = s.m_first;
if (amplitude(i) >= threshold) {
while (i > 0 && amplitude(i - 1) >= threshold) {
--i;
}
}
else
{
while (i < s.m_last && amplitude(i) < threshold) {
++i;
}
}
double start = i > 0 ? crossing(i - 1, i) : s.m_times[0];
int j = s.m_last;
if (amplitude(j) >= threshold) {
while (j + 1 < count && amplitude(j + 1) >= threshold) {
++j;
}
}
else
{
while (j > s.m_first && amplitude(j) < threshold) {
--j;
}
}
double end = j + 1 < count ? crossing(j, j + 1) : s.m_times[j];
Burst burst;
burst.m_consistent = identify(burst.m_pair, burst.m_offset);
burst.m_overlong = s.m_overlong;
burst.m_start = start;
burst.m_end = end;
burst.m_valid = validBurst(burst);
burst.m_snr = 10 * std::log10(std::max(median(s.m_snr), 1e-3));
burst.m_startSample = sampleIndex(start);
segmentClosed(burst);
}
// Impulse blanker. Static crashes spread energy across the whole spectrum of an
// analysis window, masking the tones. Samples much larger than the recent mean
// magnitude are removed. An increase lasting longer than an impulse is a new
// signal, such as the start of a call, so is restored. The beats between two
// tones briefly reduce their level, so short gaps between impulses are part of
// the same increase.
void SELCALDecoder::blank(double& sample)
{
double magnitude = std::abs(sample);
if (m_blankLevel <= 0)
{
m_blankLevel = magnitude;
return;
}
bool impulse = magnitude > m_impulseLevel * m_blankLevel;
if (impulse)
{
m_blankCount = m_impulseHold;
m_blankQuiet = 0;
}
else if ((m_blankRun > 0) && (++m_blankQuiet > m_impulseGap))
{
m_blankRun = 0;
}
if (impulse || (m_blankRun > 0))
{
if (m_blankRun == m_maxImpulse)
{
// Restore the samples removed, which haven't yet left the analysis
// window, and follow the new level.
double sum = 0;
for (int i = 0; i < m_blankRun; ++i)
{
int position = (m_position - m_blankRun + i + m_windowSize) % m_windowSize;
m_samples[position] = m_samples[position + m_windowSize] = m_blanked[i];
sum += std::abs(m_blanked[i]);
}
m_blankLevel = std::max(m_blankLevel, sum / m_blankRun);
m_blankRun = 0;
m_blankCount = 0;
return;
}
m_blanked[m_blankRun++] = sample;
}
else
{
// The mean is held while blanking, so that a new signal continues to be
// blanked until it is recognised, and limited otherwise, so that
// impulses don't raise it much.
m_blankLevel += (std::min(magnitude, m_impulseLevel * m_blankLevel) - m_blankLevel) * m_impulseAveraging;
}
if (m_blankCount > 0)
{
--m_blankCount;
sample = 0;
}
}
bool SELCALDecoder::validBurst(const Burst& burst) const
{
double duration = (burst.m_end - burst.m_start) / m_sampleRate;
return burst.m_consistent && !burst.m_overlong && duration >= m_minFadedBurst && duration <= m_maxBurst;
}
bool SELCALDecoder::brief(const Burst& burst) const
{
return burst.m_end - burst.m_start < m_minBurst / 2 * m_sampleRate;
}
// Whether a burst is part of the same burst as an earlier one, split by a fade.
bool SELCALDecoder::continues(const Burst& burst, const Burst& previous) const
{
return burst.m_pair == previous.m_pair && std::abs(burst.m_offset - previous.m_offset) <= m_anchorSearch + 0.5 &&
burst.m_start - previous.m_end <= m_maxFadeGap * m_sampleRate;
}
// The latest burst that a following pair may complete a call with.
const SELCALDecoder::Burst *SELCALDecoder::previousPair() const
{
if (m_holding && m_held.m_consistent && !brief(m_held)) {
return &m_held;
}
return m_pending.m_valid ? &m_pending : nullptr;
}
void SELCALDecoder::segmentClosed(const Burst& burst)
{
// The rest of a call's second burst, after a fade, was already decoded.
if (m_called.m_valid && continues(burst, m_called))
{
m_called.m_end = std::max(m_called.m_end, burst.m_end);
return;
}
if (m_holding)
{
// A fade split the burst: join the parts.
if (continues(burst, m_held))
{
// The longer part's measurements are the more reliable
bool heldLonger = m_held.m_end - m_held.m_start >= burst.m_end - burst.m_start;
const Burst& longer = heldLonger ? m_held : burst;
Burst joined = burst;
joined.m_start = m_held.m_start;
joined.m_startSample = m_held.m_startSample;
joined.m_offset = longer.m_offset;
joined.m_consistent = longer.m_consistent;
joined.m_overlong = m_held.m_overlong || burst.m_overlong;
joined.m_snr = std::max(m_held.m_snr, burst.m_snr);
joined.m_valid = validBurst(joined);
m_held = joined;
if (completesCall(m_held)) {
releaseHeld();
}
return;
}
// Brief detections, from noise or the overlap of two pairs within the
// analysis window, don't end a burst that may continue. Of brief
// detections, the longest is the most likely to be part of a burst.
if (brief(burst))
{
if (brief(m_held) && (burst.m_end - burst.m_start > m_held.m_end - m_held.m_start)) {
m_held = burst;
}
return;
}
releaseHeld();
}
// A burst that completes a call is decoded without waiting for it to
// continue. Others, including brief ones, are held in case they do.
if (completesCall(burst))
{
burstEnded(burst);
return;
}
m_held = burst;
m_holding = true;
}
void SELCALDecoder::releaseHeld()
{
Burst burst = m_held;
m_holding = false;
m_held = Burst();
burstEnded(burst);
}
void SELCALDecoder::burstEnded(const Burst& burst)
{
if (!burst.m_valid)
{
// Brief detections, from noise or the overlap of two pairs within the
// analysis window, do not interrupt a sequence.
if (burst.m_end - burst.m_start >= m_minBurst / 2 * m_sampleRate) {
m_pending.m_valid = false;
}
return;
}
if (completesCall(burst))
{
Burst firstBurst = m_pending;
m_pending.m_valid = false;
m_called = burst;
emitCall(firstBurst, burst);
return;
}
m_pending = burst;
}
bool SELCALDecoder::completesCall(const Burst& burst) const
{
if (!burst.m_valid || !m_pending.m_valid) {
return false;
}
double gap = (burst.m_start - m_pending.m_end) / m_sampleRate;
double firstDuration = (m_pending.m_end - m_pending.m_start) / m_sampleRate;
double secondDuration = (burst.m_end - burst.m_start) / m_sampleRate;
double shortfall = std::max(0.0, m_nominalBurst - firstDuration) + std::max(0.0, m_nominalBurst - secondDuration);
// A fade may shorten one burst, but not both.
bool durations = std::max(firstDuration, secondDuration) >= m_minBurst;
const Pair& first = m_pending.m_pair;
const Pair& second = burst.m_pair;
bool distinct = second[0] != first[0] && second[0] != first[1] && second[1] != first[0] && second[1] != first[1];
// Both pairs come from the same transmitter, so share a tone offset. A pair's
// offset is a weighted mean of its tones' offsets, so may differ from the
// transmitter's by up to the tolerance of its higher tone.
double allowed = maxOffsetDifference(std::max(tones()[first[0]].m_frequency, tones()[first[1]].m_frequency),
std::max(tones()[second[0]].m_frequency, tones()[second[1]].m_frequency));
bool sameOffset = std::abs(burst.m_offset - m_pending.m_offset) <= allowed / m_binWidth;
return gap >= m_minGap && gap <= m_maxGap + shortfall && durations && distinct && sameOffset;
}
void SELCALDecoder::emitCall(const Burst& first, const Burst& second)
{
if (!m_handler) {
return;
}
Call call;
call.m_code = {tones()[first.m_pair[0]].m_symbol, tones()[first.m_pair[1]].m_symbol, '-', tones()[second.m_pair[0]].m_symbol,
tones()[second.m_pair[1]].m_symbol};
call.m_startSample = first.m_startSample;
call.m_firstEndSample = sampleIndex(first.m_end);
call.m_secondStartSample = sampleIndex(second.m_start);
call.m_endSample = sampleIndex(second.m_end);
call.m_snr = std::min(first.m_snr, second.m_snr);
call.m_frequencyOffset = (first.m_offset + second.m_offset) / 2 * m_binWidth;
m_handler(call);
}

268
plugins/channelrx/demodselcal/selcaldecoder.h

@ -0,0 +1,268 @@ @@ -0,0 +1,268 @@
///////////////////////////////////////////////////////////////////////////////////
// Copyright (C) 2026 Jon Beniston, M7RCE <jon@beniston.com> //
// Some code by AI //
// //
// This program is free software; you can redistribute it and/or modify //
// it under the terms of the GNU General Public License as published by //
// the Free Software Foundation as version 3 of the License, or //
// (at your option) any later version. //
// //
// This program is distributed in the hope that it will be useful, //
// but WITHOUT ANY WARRANTY; without even the implied warranty of //
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //
// GNU General Public License V3 for more details. //
// //
// You should have received a copy of the GNU General Public License //
// along with this program. If not, see <http://www.gnu.org/licenses/>. //
///////////////////////////////////////////////////////////////////////////////////
#ifndef INCLUDE_SELCALDECODER_H
#define INCLUDE_SELCALDECODER_H
#include <array>
#include <cstdint>
#include <functional>
#include <memory>
#include <string>
#include <utility>
#include <vector>
class FFTEngine;
// Audio-only decoder. All timing is measured in samples, independently of the
// caller's block sizes, wall clock and audio output device.
//
// Tone levels are measured relative to the noise floor in the SELCAL band, so
// detection does not depend on the receive bandwidth or on the total audio
// power. A common tone offset is searched for around the expected offset, and
// both tone pairs of a call must share it.
class SELCALDecoder {
public:
static constexpr int m_sampleRate = 8000;
static constexpr int m_toneCount = 32;
static constexpr double m_defaultThreshold = 8.0; // dB above the noise in a tone bin
// Hz either side of the expected offset. Pairs of adjacent tones resemble
// their neighbours shifted by about 17.5 Hz, so a wider search would be
// ambiguous.
static constexpr double m_searchRange = 6.0;
static constexpr double m_maxFrequencyOffset = 100.0;
struct Tone {
char m_symbol;
double m_frequency;
};
struct Call {
std::string m_code;
std::uint64_t m_startSample;
std::uint64_t m_firstEndSample;
std::uint64_t m_secondStartSample;
std::uint64_t m_endSample;
double m_snr; // dB, weaker tone relative to the noise in a tone bin
double m_frequencyOffset; // Hz, common tone offset measured from the tones
};
enum class State { Idle, FirstPair, Gap, SecondPair, WaitForSilence };
using Pair = std::array<int, 2>;
SELCALDecoder();
~SELCALDecoder();
void reset();
void configure(double frequencyOffset, double threshold);
// Expected common tone offset and its uncertainty, in Hz. A call in
// progress keeps the offset it was acquired with.
void setFrequencyOffset(double frequencyOffset, double uncertainty = m_searchRange);
void feed(double sample);
// Don't learn steady signals from the next samples, e.g. audio received
// before retuning that is still being delivered.
void holdLearning(std::uint64_t samples);
void setCallHandler(std::function<void(const Call&)> handler)
{
m_handler = std::move(handler);
}
// Receives the decimated audio analysed by the decoder, for display.
void setSampleHandler(std::function<void(float)> handler)
{
m_sampleHandler = std::move(handler);
}
State state() const;
// Tone levels in dB relative to the noise in a tone bin.
const std::array<double, m_toneCount>& levels() const
{
return m_levels;
}
// Pair detected in the latest analysis, or {-1, -1}.
Pair pair() const
{
return m_detected;
}
// Tone offset of the call in progress, or of the latest analysis, in Hz.
double frequencyOffset() const;
static const std::array<Tone, m_toneCount>& tones();
static const char *stateName(State state);
static constexpr int m_analysisSampleRate = m_sampleRate / 2;
private:
static constexpr int m_decimatorTaps = 63;
static constexpr int m_halfbandTaps = (m_decimatorTaps + 1) / 4; // Non-zero taps either side of the centre
static constexpr int m_windowSize = 400; // 100 ms
static constexpr int m_hopSize = 80; // 20 ms
static constexpr int m_fftSize = 2048;
static constexpr double m_binWidth = static_cast<double>(m_analysisSampleRate) / m_fftSize;
static constexpr int m_holdHops = 3; // Dropouts tolerated within a burst
static constexpr int m_preRollHops = 8; // History kept to locate a burst's leading edge
static constexpr int m_anchorSearch = 2; // Bins either side of a call's offset
static constexpr int m_mainLobeBins = 10; // Half width of a tone's main lobe, and some
static constexpr int m_peakCount = 4;
static constexpr int m_backgroundHops = 50; // Time constant for learning steady signals
static constexpr double m_steadyLevel = 4.0; // Steady signal power relative to noise
static constexpr double m_steadyMargin = 1.25; // Proportion of a steady signal's power removed
// Lower bound for the noise estimate, so digital silence cannot produce tones.
static constexpr double m_noiseFloor = 1e-15;
// Burst and gap limits in seconds, with an allowance for edge measurement.
static constexpr double m_minBurst = 0.725;
static constexpr double m_maxBurst = 1.275;
static constexpr double m_minGap = 0.075;
static constexpr double m_maxGap = 0.325;
// Fades can only shorten bursts and lengthen gaps. One burst of a call may be
// measured as short as this, and the gap may grow by however much each burst
// is shorter than nominal.
static constexpr double m_nominalBurst = 1.0;
static constexpr double m_minFadedBurst = 0.45;
// A fade can split a burst. Parts of the same pair this close are joined.
static constexpr double m_maxFadeGap = 0.45;
// Impulse blanker: samples this much larger than the mean magnitude are
// removed, along with those around them.
static constexpr double m_impulseLevel = 5.0;
static constexpr int m_impulseHold = 8; // 2 ms at 4 kHz
static constexpr int m_impulseGap = 12; // 3 ms at 4 kHz, between impulses of the same rise
static constexpr double m_impulseAveraging = 1.0 / 64; // 16 ms at 4 kHz
static constexpr int m_maxImpulse = 64; // 16 ms, longer increases are new signals
// Each tone may differ from its nominal frequency by this proportion (0.15%),
// so the offsets of two tones may differ by this proportion of the sum of
// their frequencies, plus an allowance in Hz for measuring the offsets.
static constexpr double m_toneTolerance = 0.0015;
static constexpr double m_offsetMeasurementError = 2.5;
// Weaker tone of a pair relative to the stronger (-15 dB). The lowest tones are
// near the low end of SSB audio filters, so can be much weaker than their partner.
static constexpr double m_minBalance = 0.0316;
using Peaks = std::array<int, m_peakCount>;
struct Hop {
double m_time = 0;
double m_noise = 0;
std::vector<float> m_power;
};
struct Segment {
bool m_active = false;
bool m_overlong = false;
Pair m_pair{{-1, -1}};
double m_offset = 0; // Bins, follows the measured tone offset
double m_acquired = 0; // Bins, offset at acquisition
int m_first = 0;
int m_last = 0;
int m_missed = 0;
std::vector<double> m_power;
std::vector<double> m_times;
std::vector<bool> m_detected;
std::vector<double> m_snr;
double m_offsetSum = 0;
double m_offsetWeight = 0;
std::vector<float> m_spectrum; // Sum of levels relative to noise
int m_spectrumHops = 0;
double m_searchCentre = 0; // Offsets within which the burst was acquired
int m_searchBins = 0;
};
struct Burst {
bool m_valid = false;
bool m_consistent = false; // Both tones have the same offset
bool m_overlong = false;
Pair m_pair{{-1, -1}};
double m_start = 0;
double m_end = 0;
double m_offset = 0;
double m_snr = 0;
std::uint64_t m_startSample = 0;
};
static std::uint64_t sampleIndex(double time);
static double besselI0(double x);
static double median(std::vector<double> values);
static double maxOffsetDifference(double frequency1, double frequency2);
std::unique_ptr<FFTEngine> m_fft;
std::array<double, m_halfbandTaps> m_halfband{};
double m_halfbandCentre = 0.5;
std::array<double, 2 * m_decimatorTaps> m_history{};
int m_historyPosition = 0;
std::array<double, 2 * m_windowSize> m_samples{};
std::array<float, m_windowSize> m_window{};
double m_powerScale = 0;
int m_position = 0;
int m_bandStart = 0;
int m_bandEnd = 0;
std::array<double, m_toneCount> m_toneBins{};
std::vector<Hop> m_hops;
int m_hopIndex = 0;
std::vector<float> m_scratch;
std::vector<float> m_raw; // Power before background removal
std::vector<double> m_background; // Power of steady signals, learnt while idle
double m_backgroundNoise = 0;
int m_backgroundCount = 0;
std::uint64_t m_learnAfter = 0;
std::array<double, m_toneCount> m_levels{};
std::function<void(const Call&)> m_handler;
std::function<void(float)> m_sampleHandler;
double m_threshold = 0;
double m_baseOffset = 0; // Bins
int m_searchBins = 0;
double m_currentOffset = 0; // Bins
Pair m_detected{{-1, -1}};
std::uint64_t m_inputCount = 0;
std::uint64_t m_analysisCount = 0;
std::uint64_t m_hopCount = 0;
Segment m_segment;
Burst m_pending;
Burst m_held; // Burst that may continue after a fade
bool m_holding = false;
Burst m_called; // Second burst of the latest call, which may also continue
double m_blankLevel = 0; // Mean magnitude, for the impulse blanker
int m_blankCount = 0;
int m_blankRun = 0; // Samples since blanking started
int m_blankQuiet = 0; // Samples since the last impulse
std::array<double, m_maxImpulse> m_blanked{}; // Samples since blanking started, before blanking
void blank(double& sample);
void analyse();
const Hop& hop(int age) const;
double pairPower(const Hop& hop, const Pair& pair, double offset) const;
int bin(int tone, double offset) const;
void startSegment(const Pair& pair, double offset, double snr);
void findPeaks(const std::vector<float>& power, Peaks& peaks) const;
bool evaluate(const std::vector<float>& power, const Peaks& peaks, double scale, double offset, Pair& pair, double& snr) const;
int peakRange(int tone, int partner) const;
bool peaked(const std::vector<float>& power, int tone, int partner, double offset) const;
void accumulate(const Hop& current);
void learnBackground(double noise);
void measurePeak(const std::vector<float>& power, int tone, int partner, double offset, double& sum, double& weight) const;
bool identify(Pair& pair, double& offset) const;
void closeSegment();
void segmentClosed(const Burst& burst);
void releaseHeld();
bool validBurst(const Burst& burst) const;
bool completesCall(const Burst& burst) const;
bool continues(const Burst& burst, const Burst& previous) const;
bool brief(const Burst& burst) const;
const Burst *previousPair() const;
void burstEnded(const Burst& burst);
void emitCall(const Burst& first, const Burst& second);
};
#endif

727
plugins/channelrx/demodselcal/selcaldemod.cpp

@ -0,0 +1,727 @@ @@ -0,0 +1,727 @@
///////////////////////////////////////////////////////////////////////////////////
// Copyright (C) 2021-2022 Edouard Griffiths, F4EXB <f4exb06@gmail.com> //
// Copyright (C) 2026 Jon Beniston, M7RCE <jon@beniston.com> //
// Some code by AI //
// //
// This program is free software; you can redistribute it and/or modify //
// it under the terms of the GNU General Public License as published by //
// the Free Software Foundation as version 3 of the License, or //
// (at your option) any later version. //
// //
// This program is distributed in the hope that it will be useful, //
// but WITHOUT ANY WARRANTY; without even the implied warranty of //
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //
// GNU General Public License V3 for more details. //
// //
// You should have received a copy of the GNU General Public License //
// along with this program. If not, see <http://www.gnu.org/licenses/>. //
///////////////////////////////////////////////////////////////////////////////////
#include <QTime>
#include <QDebug>
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QBuffer>
#include <QThread>
#include <QJsonDocument>
#include <QJsonObject>
#include <algorithm>
#include <stdio.h>
#include <complex.h>
#include "SWGChannelSettings.h"
#include "SWGWorkspaceInfo.h"
#include "SWGSELCALDemodSettings.h"
#include "SWGChannelReport.h"
#include "dsp/dspcommands.h"
#include "device/deviceapi.h"
#include "settings/serializable.h"
#include "util/db.h"
#include "maincore.h"
#include "selcaldemod.h"
MESSAGE_CLASS_DEFINITION(SELCALDemod::MsgConfigureSELCALDemod, Message)
const char *const SELCALDemod::m_channelIdURI = "sdrangel.channel.selcaldemod";
const char *const SELCALDemod::m_channelId = "SELCALDemod";
SELCALDemod::SELCALDemod(DeviceAPI *deviceAPI) :
ChannelAPI(m_channelIdURI, ChannelAPI::StreamSingleSink),
m_deviceAPI(deviceAPI),
m_spectrumVis(SDR_RX_SCALEF),
m_basebandSampleRate(0),
m_centerFrequency(0)
{
setObjectName(m_channelId);
m_thread.setObjectName("SELCALDemodBB");
m_basebandSink = new SELCALDemodBaseband(this);
m_basebandSink->setMessageQueueToChannel(getInputMessageQueue());
m_basebandSink->setSpectrumSink(&m_spectrumVis);
m_basebandSink->setChannel(this);
m_basebandSink->moveToThread(&m_thread);
applySettings(QStringList(), m_settings, true);
m_deviceAPI->addChannelSink(this);
m_deviceAPI->addChannelSinkAPI(this);
m_networkManager = new QNetworkAccessManager();
QObject::connect(m_networkManager, &QNetworkAccessManager::finished, this, &SELCALDemod::networkManagerFinished);
QObject::connect(this, &ChannelAPI::indexInDeviceSetChanged, this, &SELCALDemod::handleIndexInDeviceSetChanged);
}
SELCALDemod::~SELCALDemod()
{
qDebug("SELCALDemod::~SELCALDemod");
QObject::disconnect(m_networkManager, &QNetworkAccessManager::finished, this, &SELCALDemod::networkManagerFinished);
delete m_networkManager;
m_deviceAPI->removeChannelSinkAPI(this);
m_deviceAPI->removeChannelSink(this, true, m_settings.m_streamIndex);
if (m_basebandSink->isRunning()) {
stop();
}
delete m_basebandSink;
}
void SELCALDemod::setDeviceAPI(DeviceAPI *deviceAPI)
{
if (deviceAPI != m_deviceAPI)
{
m_deviceAPI->removeChannelSinkAPI(this);
m_deviceAPI->removeChannelSink(this, false, m_settings.m_streamIndex);
m_deviceAPI = deviceAPI;
m_deviceAPI->addChannelSink(this, m_settings.m_streamIndex);
m_deviceAPI->addChannelSinkAPI(this);
}
}
uint32_t SELCALDemod::getNumberOfDeviceStreams() const
{
return m_deviceAPI->getNbSourceStreams();
}
void SELCALDemod::feed(const SampleVector::const_iterator& begin, const SampleVector::const_iterator& end, bool positiveOnly)
{
(void) positiveOnly;
m_basebandSink->feed(begin, end);
}
void SELCALDemod::start()
{
qDebug("SELCALDemod::start");
m_basebandSink->reset();
m_basebandSink->startWork();
m_thread.start();
DSPSignalNotification *dspMsg = new DSPSignalNotification(m_basebandSampleRate, m_centerFrequency);
m_basebandSink->getInputMessageQueue()->push(dspMsg);
SELCALDemodBaseband::MsgConfigureSELCALDemodBaseband *msg =
SELCALDemodBaseband::MsgConfigureSELCALDemodBaseband::create(QStringList(), m_settings, true);
m_basebandSink->getInputMessageQueue()->push(msg);
}
void SELCALDemod::stop()
{
qDebug("SELCALDemod::stop");
m_basebandSink->stopWork();
m_thread.quit();
m_thread.wait();
}
bool SELCALDemod::handleMessage(const Message& cmd)
{
if (MsgConfigureSELCALDemod::match(cmd))
{
MsgConfigureSELCALDemod& cfg = (MsgConfigureSELCALDemod&)cmd;
qDebug() << "SELCALDemod::handleMessage: MsgConfigureSELCALDemod";
applySettings(cfg.getSettingsKeys(), cfg.getSettings(), cfg.getForce());
return true;
}
else if (DSPSignalNotification::match(cmd))
{
DSPSignalNotification& notif = (DSPSignalNotification&)cmd;
m_basebandSampleRate = notif.getSampleRate();
m_centerFrequency = notif.getCenterFrequency();
// Forward to the sink
DSPSignalNotification *rep = new DSPSignalNotification(notif); // make a copy
qDebug() << "SELCALDemod::handleMessage: DSPSignalNotification";
m_basebandSink->getInputMessageQueue()->push(rep);
// Forward to GUI if any
if (m_guiMessageQueue) {
m_guiMessageQueue->push(new DSPSignalNotification(notif));
}
return true;
}
else if (MsgMessage::match(cmd))
{
const auto& call = static_cast<const MsgMessage&>(cmd).getMessage();
{
QMutexLocker lock(&m_reportMutex);
m_lastCall = call;
++m_callCount;
}
if (getMessageQueueToGUI()) {
getMessageQueueToGUI()->push(MsgMessage::create(call));
}
if (m_settings.m_udpEnabled)
{
QJsonObject json;
json["code"] = call.m_code;
json["utc"] = call.m_dateTime.toString(Qt::ISODateWithMs);
json["frequencyHz"] = call.m_frequency;
json["rssi"] = call.m_rssi;
json["snr"] = call.m_snr;
json["toneOffsetHz"] = call.m_toneFrequencyOffset;
if (m_udpHostAddress.isNull()) {
qWarning() << "SELCALDemod: Unable to send UDP to unresolved address" << m_settings.m_udpAddress;
} else {
m_udpSocket.writeDatagram(QJsonDocument(json).toJson(QJsonDocument::Compact), m_udpHostAddress, m_settings.m_udpPort);
}
}
if (m_logFile.isOpen())
{
m_logStream << call.m_dateTime.toString(Qt::ISODateWithMs) << "," << call.m_code << "," << call.m_frequency << ","
<< call.m_rssi << "," << call.m_snr << "\n";
m_logStream.flush();
}
return true;
}
else if (MsgStatus::match(cmd))
{
const auto& status = static_cast<const MsgStatus&>(cmd).getStatus();
{
QMutexLocker lock(&m_reportMutex);
m_status = status;
}
if (getMessageQueueToGUI()) {
getMessageQueueToGUI()->push(MsgStatus::create(status));
}
return true;
}
else if (MainCore::MsgChannelDemodQuery::match(cmd))
{
qDebug() << "SELCALDemod::handleMessage: MsgChannelDemodQuery";
sendSampleRateToDemodAnalyzer();
return true;
}
else
{
return false;
}
}
void SELCALDemod::setCenterFrequency(qint64 frequency)
{
SELCALDemodSettings settings = m_settings;
settings.m_inputFrequencyOffset = frequency;
applySettings(QStringList("inputFrequencyOffset"), settings, false);
if (m_guiMessageQueue) // forward to GUI if any
{
MsgConfigureSELCALDemod *msgToGUI = MsgConfigureSELCALDemod::create(QStringList("inputFrequencyOffset"), settings, false);
m_guiMessageQueue->push(msgToGUI);
}
}
void SELCALDemod::applySettings(const QStringList& settingsKeys, const SELCALDemodSettings& incomingSettings, bool force)
{
SELCALDemodSettings settings = incomingSettings;
settings.normalize();
settings.m_streamIndex = std::min(settings.m_streamIndex, std::max(0, static_cast<int>(getNumberOfDeviceStreams()) - 1));
qDebug() << "SELCALDemod::applySettings:" << settings.getDebugString(settingsKeys, force);
if ((settingsKeys.contains("streamIndex") || force) && (settings.m_streamIndex != m_settings.m_streamIndex)) {
if (m_deviceAPI->getSampleMIMO()) // change of stream is possible for MIMO devices only
{
m_deviceAPI->removeChannelSinkAPI(this);
m_deviceAPI->removeChannelSink(this, false, m_settings.m_streamIndex);
m_deviceAPI->addChannelSink(this, settings.m_streamIndex);
m_deviceAPI->addChannelSinkAPI(this);
m_settings.m_streamIndex = settings.m_streamIndex; // make sure ChannelAPI::getStreamIndex() is consistent
emit streamIndexChanged(settings.m_streamIndex);
}
}
SELCALDemodBaseband::MsgConfigureSELCALDemodBaseband *msg =
SELCALDemodBaseband::MsgConfigureSELCALDemodBaseband::create(settingsKeys, settings, force);
m_basebandSink->getInputMessageQueue()->push(msg);
if (settings.m_useReverseAPI)
{
bool fullUpdate =
((settingsKeys.contains("useReverseAPI") && (settings.m_useReverseAPI != m_settings.m_useReverseAPI)) &&
settings.m_useReverseAPI) ||
(settingsKeys.contains("reverseAPIAddress") && (settings.m_reverseAPIAddress != m_settings.m_reverseAPIAddress)) ||
(settingsKeys.contains("reverseAPIPort") && (settings.m_reverseAPIPort != m_settings.m_reverseAPIPort)) ||
(settingsKeys.contains("reverseAPIDeviceIndex") && (settings.m_reverseAPIDeviceIndex != m_settings.m_reverseAPIDeviceIndex)) ||
(settingsKeys.contains("reverseAPIChannelIndex") && (settings.m_reverseAPIChannelIndex != m_settings.m_reverseAPIChannelIndex));
webapiReverseSendSettings(settingsKeys, settings, fullUpdate || force);
}
if ((settingsKeys.contains("logEnabled") && (settings.m_logEnabled != m_settings.m_logEnabled)) ||
(settingsKeys.contains("logFilename") && (settings.m_logFilename != m_settings.m_logFilename)) || force)
{
if (m_logFile.isOpen())
{
m_logStream.flush();
m_logFile.close();
}
if (settings.m_logEnabled && !settings.m_logFilename.isEmpty())
{
m_logFile.setFileName(settings.m_logFilename);
if (m_logFile.open(QIODevice::WriteOnly | QIODevice::Append | QIODevice::Text))
{
qDebug() << "SELCALDemod::applySettings - Logging to: " << settings.m_logFilename;
bool newFile = m_logFile.size() == 0;
m_logStream.setDevice(&m_logFile);
if (newFile) {
// Write header
m_logStream << "UTC,Code,FrequencyHz,RSSI,SNR\n";
}
}
else
{
qWarning() << "SELCALDemod::applySettings - Unable to open log file: " << settings.m_logFilename << m_logFile.errorString();
}
}
}
bool resolve = (settingsKeys.contains("udpAddress") && (settings.m_udpAddress != m_settings.m_udpAddress)) || force;
if (force) {
m_settings = settings;
}
else
{
m_settings.applySettings(settingsKeys, settings);
}
if (resolve) {
resolveUDPAddress(m_settings.m_udpAddress);
}
}
// The UDP address may be a host name, which is looked up without blocking.
void SELCALDemod::resolveUDPAddress(const QString& address)
{
m_udpHostAddress = QHostAddress(address);
if (m_udpHostAddress.isNull() && !address.isEmpty()) {
QHostInfo::lookupHost(address, this, &SELCALDemod::udpAddressResolved);
}
}
void SELCALDemod::udpAddressResolved(const QHostInfo& info)
{
// Ignore the result of a lookup for an address since replaced
if (info.hostName() != m_settings.m_udpAddress) {
return;
}
if (info.error() != QHostInfo::NoError || info.addresses().isEmpty())
{
qWarning() << "SELCALDemod::udpAddressResolved: Unable to resolve" << info.hostName() << info.errorString();
return;
}
// Prefer IPv4, which receivers more commonly listen on
m_udpHostAddress = info.addresses().first();
for (const auto& address : info.addresses())
{
if (address.protocol() == QAbstractSocket::IPv4Protocol)
{
m_udpHostAddress = address;
break;
}
}
}
void SELCALDemod::sendSampleRateToDemodAnalyzer()
{
QList<ObjectPipe *> pipes;
MainCore::instance()->getMessagePipes().getMessagePipes(this, "reportdemod", pipes);
if (pipes.size() > 0) {
for (const auto& pipe : pipes)
{
MessageQueue *messageQueue = qobject_cast<MessageQueue *>(pipe->m_element);
// Sample rate of the demod stream, which is the audio output rate.
MainCore::MsgChannelDemodReport *msg = MainCore::MsgChannelDemodReport::create(this, getAudioSampleRate());
messageQueue->push(msg);
}
}
}
QByteArray SELCALDemod::serialize() const
{
return m_settings.serialize();
}
bool SELCALDemod::deserialize(const QByteArray& data)
{
if (m_settings.deserialize(data))
{
MsgConfigureSELCALDemod *msg = MsgConfigureSELCALDemod::create(QStringList(), m_settings, true);
m_inputMessageQueue.push(msg);
return true;
}
else
{
m_settings.resetToDefaults();
MsgConfigureSELCALDemod *msg = MsgConfigureSELCALDemod::create(QStringList(), m_settings, true);
m_inputMessageQueue.push(msg);
return false;
}
}
int SELCALDemod::webapiSettingsGet(SWGSDRangel::SWGChannelSettings& response, QString& errorMessage)
{
(void)errorMessage;
response.setSelcalDemodSettings(new SWGSDRangel::SWGSELCALDemodSettings());
response.getSelcalDemodSettings()->init();
webapiFormatChannelSettings(response, m_settings);
return 200;
}
int SELCALDemod::webapiWorkspaceGet(SWGSDRangel::SWGWorkspaceInfo& response, QString& errorMessage)
{
(void)errorMessage;
response.setIndex(m_settings.m_workspaceIndex);
return 200;
}
int SELCALDemod::webapiSettingsPutPatch(bool force, const QStringList& channelSettingsKeys, SWGSDRangel::SWGChannelSettings& response,
QString& errorMessage)
{
(void)errorMessage;
SELCALDemodSettings settings = m_settings;
webapiUpdateChannelSettings(settings, channelSettingsKeys, response);
settings.m_streamIndex = std::min(settings.m_streamIndex, std::max(0, static_cast<int>(getNumberOfDeviceStreams()) - 1));
MsgConfigureSELCALDemod *msg = MsgConfigureSELCALDemod::create(channelSettingsKeys, settings, force);
m_inputMessageQueue.push(msg);
qDebug("SELCALDemod::webapiSettingsPutPatch: forward to GUI: %p", m_guiMessageQueue);
if (m_guiMessageQueue) // forward to GUI if any
{
MsgConfigureSELCALDemod *msgToGUI = MsgConfigureSELCALDemod::create(channelSettingsKeys, settings, force);
m_guiMessageQueue->push(msgToGUI);
}
webapiFormatChannelSettings(response, settings);
return 200;
}
int SELCALDemod::webapiReportGet(SWGSDRangel::SWGChannelReport& response, QString& errorMessage)
{
(void)errorMessage;
response.setSelcalDemodReport(new SWGSDRangel::SWGSELCALDemodReport());
response.getSelcalDemodReport()->init();
webapiFormatChannelReport(response);
return 200;
}
void SELCALDemod::webapiUpdateChannelSettings(SELCALDemodSettings& settings, const QStringList& channelSettingsKeys,
SWGSDRangel::SWGChannelSettings& response)
{
auto *model = response.getSelcalDemodSettings();
if (!model) {
return;
}
if (channelSettingsKeys.contains("inputFrequencyOffset")) {
settings.m_inputFrequencyOffset = model->getInputFrequencyOffset();
}
if (channelSettingsKeys.contains("rfBandwidth")) {
settings.m_rfBandwidth = model->getRfBandwidth();
}
if (channelSettingsKeys.contains("modulation")) {
settings.m_modulation = model->getModulation();
}
if (channelSettingsKeys.contains("toneFrequencyOffset")) {
settings.m_toneFrequencyOffset = model->getToneFrequencyOffset();
}
if (channelSettingsKeys.contains("autoToneFrequencyOffset")) {
settings.m_autoToneFrequencyOffset = model->getAutoToneFrequencyOffset() != 0;
}
if (channelSettingsKeys.contains("threshold")) {
settings.m_threshold = model->getThreshold();
}
if (channelSettingsKeys.contains("volume")) {
settings.m_volume = model->getVolume();
}
if (channelSettingsKeys.contains("audioMute")) {
settings.m_audioMute = model->getAudioMute();
}
if (channelSettingsKeys.contains("squelch")) {
settings.m_squelch = model->getSquelch();
}
if (channelSettingsKeys.contains("audioDeviceName") && model->getAudioDeviceName()) {
settings.m_audioDeviceName = *model->getAudioDeviceName();
}
if (channelSettingsKeys.contains("filter") && model->getFilter()) {
settings.m_filter = *model->getFilter();
}
if (channelSettingsKeys.contains("udpEnabled")) {
settings.m_udpEnabled = model->getUdpEnabled();
}
if (channelSettingsKeys.contains("udpAddress") && model->getUdpAddress()) {
settings.m_udpAddress = *model->getUdpAddress();
}
if (channelSettingsKeys.contains("udpPort")) {
settings.m_udpPort = model->getUdpPort();
}
if (channelSettingsKeys.contains("logFilename") && model->getLogFilename()) {
settings.m_logFilename = *model->getLogFilename();
}
if (channelSettingsKeys.contains("logEnabled")) {
settings.m_logEnabled = model->getLogEnabled();
}
if (channelSettingsKeys.contains("rgbColor")) {
settings.m_rgbColor = model->getRgbColor();
}
if (channelSettingsKeys.contains("title") && model->getTitle()) {
settings.m_title = *model->getTitle();
}
if (channelSettingsKeys.contains("streamIndex")) {
settings.m_streamIndex = model->getStreamIndex();
}
if (channelSettingsKeys.contains("useReverseAPI")) {
settings.m_useReverseAPI = model->getUseReverseApi();
}
if (channelSettingsKeys.contains("reverseAPIAddress") && model->getReverseApiAddress()) {
settings.m_reverseAPIAddress = *model->getReverseApiAddress();
}
if (channelSettingsKeys.contains("reverseAPIPort")) {
settings.m_reverseAPIPort = model->getReverseApiPort();
}
if (channelSettingsKeys.contains("reverseAPIDeviceIndex")) {
settings.m_reverseAPIDeviceIndex = model->getReverseApiDeviceIndex();
}
if (channelSettingsKeys.contains("reverseAPIChannelIndex")) {
settings.m_reverseAPIChannelIndex = model->getReverseApiChannelIndex();
}
if (settings.m_channelMarker && channelSettingsKeys.contains("channelMarker") && model->getChannelMarker()) {
settings.m_channelMarker->updateFrom(channelSettingsKeys, model->getChannelMarker());
}
if (settings.m_rollupState && channelSettingsKeys.contains("rollupState") && model->getRollupState()) {
settings.m_rollupState->updateFrom(channelSettingsKeys, model->getRollupState());
}
settings.normalize();
}
void SELCALDemod::webapiFormatChannelSettings(SWGSDRangel::SWGChannelSettings& response, const SELCALDemodSettings& settings)
{
auto *model = response.getSelcalDemodSettings();
model->setInputFrequencyOffset(settings.m_inputFrequencyOffset);
model->setRfBandwidth(settings.m_rfBandwidth);
model->setModulation(settings.m_modulation);
model->setToneFrequencyOffset(settings.m_toneFrequencyOffset);
model->setAutoToneFrequencyOffset(settings.m_autoToneFrequencyOffset);
model->setThreshold(settings.m_threshold);
model->setVolume(settings.m_volume);
model->setAudioMute(settings.m_audioMute);
model->setSquelch(settings.m_squelch);
model->setAudioDeviceName(new QString(settings.m_audioDeviceName));
model->setFilter(new QString(settings.m_filter));
model->setUdpEnabled(settings.m_udpEnabled);
model->setUdpAddress(new QString(settings.m_udpAddress));
model->setUdpPort(settings.m_udpPort);
model->setLogFilename(new QString(settings.m_logFilename));
model->setLogEnabled(settings.m_logEnabled);
model->setRgbColor(settings.m_rgbColor);
model->setTitle(new QString(settings.m_title));
model->setStreamIndex(settings.m_streamIndex);
model->setUseReverseApi(settings.m_useReverseAPI);
model->setReverseApiAddress(new QString(settings.m_reverseAPIAddress));
model->setReverseApiPort(settings.m_reverseAPIPort);
model->setReverseApiDeviceIndex(settings.m_reverseAPIDeviceIndex);
model->setReverseApiChannelIndex(settings.m_reverseAPIChannelIndex);
if (settings.m_channelMarker)
{
auto *item = new SWGSDRangel::SWGChannelMarker();
settings.m_channelMarker->formatTo(item);
model->setChannelMarker(item);
}
if (settings.m_rollupState)
{
auto *item = new SWGSDRangel::SWGRollupState();
settings.m_rollupState->formatTo(item);
model->setRollupState(item);
}
}
void SELCALDemod::webapiFormatChannelReport(SWGSDRangel::SWGChannelReport& response)
{
double avg, peak;
int count;
getMagSqLevels(avg, peak, count);
auto *model = response.getSelcalDemodReport();
model->setChannelPowerDb(CalcDb::dbPower(avg));
model->setChannelSampleRate(getChannelSampleRate());
model->setAudioSampleRate(getAudioSampleRate());
QMutexLocker lock(&m_reportMutex);
model->setState(new QString(SELCALDecoder::stateName(m_status.m_state)));
model->setCarrierLocked(m_status.m_carrierLocked);
model->setSquelchOpen(m_status.m_squelchOpen);
model->setCarrierFrequencyOffset(m_status.m_carrierFrequencyOffset);
model->setToneFrequencyOffset(m_status.m_toneFrequencyOffset);
model->setLastCode(new QString(m_lastCall.m_code));
model->setLastTimestamp(new QString(m_lastCall.m_dateTime.toString(Qt::ISODateWithMs)));
model->setLastFrequency(m_lastCall.m_frequency);
model->setLastRssi(m_lastCall.m_rssi);
model->setLastSnr(m_lastCall.m_snr);
model->setCallCount(m_callCount);
}
void SELCALDemod::webapiReverseSendSettings(const QList<QString>& channelSettingsKeys, const SELCALDemodSettings& settings, bool force)
{
SWGSDRangel::SWGChannelSettings *swgChannelSettings = new SWGSDRangel::SWGChannelSettings();
webapiFormatChannelSettings(channelSettingsKeys, swgChannelSettings, settings, force);
QString channelSettingsURL = QString("http://%1:%2/sdrangel/deviceset/%3/channel/%4/settings")
.arg(settings.m_reverseAPIAddress)
.arg(settings.m_reverseAPIPort)
.arg(settings.m_reverseAPIDeviceIndex)
.arg(settings.m_reverseAPIChannelIndex);
m_networkRequest.setUrl(QUrl(channelSettingsURL));
m_networkRequest.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
QBuffer *buffer = new QBuffer();
buffer->open((QBuffer::ReadWrite));
buffer->write(swgChannelSettings->asJson().toUtf8());
buffer->seek(0);
// Always use PATCH to avoid passing reverse API settings
QNetworkReply *reply = m_networkManager->sendCustomRequest(m_networkRequest, "PATCH", buffer);
buffer->setParent(reply);
delete swgChannelSettings;
}
void SELCALDemod::webapiFormatChannelSettings(const QList<QString>& channelSettingsKeys,
SWGSDRangel::SWGChannelSettings *swgChannelSettings, const SELCALDemodSettings& settings,
bool force)
{
swgChannelSettings->setDirection(0);
swgChannelSettings->setOriginatorChannelIndex(getIndexInDeviceSet());
swgChannelSettings->setOriginatorDeviceSetIndex(getDeviceSetIndex());
swgChannelSettings->setChannelType(new QString("SELCALDemod"));
auto *model = new SWGSDRangel::SWGSELCALDemodSettings();
swgChannelSettings->setSelcalDemodSettings(model);
if (force || channelSettingsKeys.contains("inputFrequencyOffset")) {
model->setInputFrequencyOffset(settings.m_inputFrequencyOffset);
}
if (force || channelSettingsKeys.contains("rfBandwidth")) {
model->setRfBandwidth(settings.m_rfBandwidth);
}
if (force || channelSettingsKeys.contains("modulation")) {
model->setModulation(settings.m_modulation);
}
if (force || channelSettingsKeys.contains("toneFrequencyOffset")) {
model->setToneFrequencyOffset(settings.m_toneFrequencyOffset);
}
if (force || channelSettingsKeys.contains("autoToneFrequencyOffset")) {
model->setAutoToneFrequencyOffset(settings.m_autoToneFrequencyOffset);
}
if (force || channelSettingsKeys.contains("threshold")) {
model->setThreshold(settings.m_threshold);
}
if (force || channelSettingsKeys.contains("volume")) {
model->setVolume(settings.m_volume);
}
if (force || channelSettingsKeys.contains("audioMute")) {
model->setAudioMute(settings.m_audioMute);
}
if (force || channelSettingsKeys.contains("squelch")) {
model->setSquelch(settings.m_squelch);
}
if (force || channelSettingsKeys.contains("audioDeviceName")) {
model->setAudioDeviceName(new QString(settings.m_audioDeviceName));
}
if (force || channelSettingsKeys.contains("filter")) {
model->setFilter(new QString(settings.m_filter));
}
if (force || channelSettingsKeys.contains("udpEnabled")) {
model->setUdpEnabled(settings.m_udpEnabled);
}
if (force || channelSettingsKeys.contains("udpAddress")) {
model->setUdpAddress(new QString(settings.m_udpAddress));
}
if (force || channelSettingsKeys.contains("udpPort")) {
model->setUdpPort(settings.m_udpPort);
}
if (force || channelSettingsKeys.contains("logFilename")) {
model->setLogFilename(new QString(settings.m_logFilename));
}
if (force || channelSettingsKeys.contains("logEnabled")) {
model->setLogEnabled(settings.m_logEnabled);
}
if (force || channelSettingsKeys.contains("rgbColor")) {
model->setRgbColor(settings.m_rgbColor);
}
if (force || channelSettingsKeys.contains("title")) {
model->setTitle(new QString(settings.m_title));
}
if (force || channelSettingsKeys.contains("streamIndex")) {
model->setStreamIndex(settings.m_streamIndex);
}
if (settings.m_channelMarker && (force || channelSettingsKeys.contains("channelMarker")))
{
auto *item = new SWGSDRangel::SWGChannelMarker();
settings.m_channelMarker->formatTo(item);
model->setChannelMarker(item);
}
if (settings.m_rollupState && (force || channelSettingsKeys.contains("rollupState")))
{
auto *item = new SWGSDRangel::SWGRollupState();
settings.m_rollupState->formatTo(item);
model->setRollupState(item);
}
}
void SELCALDemod::networkManagerFinished(QNetworkReply *reply)
{
QNetworkReply::NetworkError replyError = reply->error();
if (replyError) {
qWarning() << "SELCALDemod::networkManagerFinished:"
<< " error(" << (int)replyError << "): " << replyError << ": " << reply->errorString();
}
else
{
QString answer = reply->readAll();
answer.chop(1); // remove last \n
qDebug("SELCALDemod::networkManagerFinished: reply:\n%s", answer.toStdString().c_str());
}
reply->deleteLater();
}
void SELCALDemod::handleIndexInDeviceSetChanged(int index)
{
if (index < 0) {
return;
}
QString fifoLabel = QString("%1 [%2:%3]").arg(m_channelId).arg(m_deviceAPI->getDeviceSetIndex()).arg(index);
m_basebandSink->setFifoLabel(fifoLabel);
}
int SELCALDemod::getChannelSampleRate() const
{
return m_basebandSink ? m_basebandSink->getChannelSampleRate() : 0;
}
int SELCALDemod::getAudioSampleRate() const
{
return m_basebandSink->getAudioSampleRate();
}

181
plugins/channelrx/demodselcal/selcaldemod.h

@ -0,0 +1,181 @@ @@ -0,0 +1,181 @@
///////////////////////////////////////////////////////////////////////////////////
// Copyright (C) 2021-2022 Edouard Griffiths, F4EXB <f4exb06@gmail.com> //
// Copyright (C) 2026 Jon Beniston, M7RCE <jon@beniston.com> //
// Some code by AI //
// //
// This program is free software; you can redistribute it and/or modify //
// it under the terms of the GNU General Public License as published by //
// the Free Software Foundation as version 3 of the License, or //
// (at your option) any later version. //
// //
// This program is distributed in the hope that it will be useful, //
// but WITHOUT ANY WARRANTY; without even the implied warranty of //
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //
// GNU General Public License V3 for more details. //
// //
// You should have received a copy of the GNU General Public License //
// along with this program. If not, see <http://www.gnu.org/licenses/>. //
///////////////////////////////////////////////////////////////////////////////////
#ifndef INCLUDE_SELCALDEMOD_H
#define INCLUDE_SELCALDEMOD_H
#include <vector>
#include <QNetworkRequest>
#include <QHostInfo>
#include <QUdpSocket>
#include <QThread>
#include <QFile>
#include <QTextStream>
#include <QRegularExpression>
#include <QDateTime>
#include <QMutex>
#include "selcalmessages.h"
#include "dsp/basebandsamplesink.h"
#include "channel/channelapi.h"
#include "dsp/spectrumvis.h"
#include "util/message.h"
#include "selcaldemodbaseband.h"
#include "selcaldemodsettings.h"
class QNetworkAccessManager;
class QNetworkReply;
class QThread;
class DeviceAPI;
class SELCALDemod : public BasebandSampleSink, public ChannelAPI {
public:
class MsgConfigureSELCALDemod : public Message {
MESSAGE_CLASS_DECLARATION
public:
const SELCALDemodSettings& getSettings() const { return m_settings; }
const QStringList& getSettingsKeys() const { return m_settingsKeys; }
bool getForce() const { return m_force; }
static MsgConfigureSELCALDemod *create(const QStringList& settingsKeys, const SELCALDemodSettings& settings, bool force)
{
return new MsgConfigureSELCALDemod(settingsKeys, settings, force);
}
private:
SELCALDemodSettings m_settings;
QStringList m_settingsKeys;
bool m_force;
MsgConfigureSELCALDemod(const QStringList& settingsKeys, const SELCALDemodSettings& settings, bool force) :
Message(),
m_settings(settings),
m_settingsKeys(settingsKeys),
m_force(force)
{
}
};
using MsgMessage = SELCALMessages::MsgCall;
using MsgStatus = SELCALMessages::MsgStatus;
SELCALDemod(DeviceAPI *deviceAPI);
virtual ~SELCALDemod();
virtual void destroy()
{
delete this;
}
virtual void setDeviceAPI(DeviceAPI *deviceAPI);
virtual DeviceAPI *getDeviceAPI()
{
return m_deviceAPI;
}
using BasebandSampleSink::feed;
virtual void feed(const SampleVector::const_iterator& begin, const SampleVector::const_iterator& end, bool po);
virtual void start();
virtual void stop();
virtual void pushMessage(Message *msg) { m_inputMessageQueue.push(msg); }
virtual QString getSinkName() { return objectName(); }
virtual void getIdentifier(QString& id) { id = objectName(); }
virtual QString getIdentifier() const { return objectName(); }
virtual const QString& getURI() const { return getName(); }
virtual void getTitle(QString& title) { title = m_settings.m_title; }
virtual qint64 getCenterFrequency() const { return m_settings.m_inputFrequencyOffset; }
int getChannelSampleRate() const override;
int getAudioSampleRate() const override;
virtual void setCenterFrequency(qint64 frequency);
virtual QByteArray serialize() const;
virtual bool deserialize(const QByteArray& data);
virtual int getNbSinkStreams() const { return 1; }
virtual int getNbSourceStreams() const { return 0; }
virtual int getStreamIndex() const { return m_settings.m_streamIndex; }
virtual qint64 getStreamCenterFrequency(int streamIndex, bool sinkElseSource) const
{
(void)streamIndex;
(void)sinkElseSource;
return 0;
}
virtual int webapiSettingsGet(SWGSDRangel::SWGChannelSettings& response, QString& errorMessage);
virtual int webapiWorkspaceGet(SWGSDRangel::SWGWorkspaceInfo& response, QString& errorMessage);
virtual int webapiSettingsPutPatch(bool force, const QStringList& channelSettingsKeys, SWGSDRangel::SWGChannelSettings& response,
QString& errorMessage);
virtual int webapiReportGet(SWGSDRangel::SWGChannelReport& response, QString& errorMessage);
static void webapiFormatChannelSettings(SWGSDRangel::SWGChannelSettings& response, const SELCALDemodSettings& settings);
static void webapiUpdateChannelSettings(SELCALDemodSettings& settings, const QStringList& channelSettingsKeys,
SWGSDRangel::SWGChannelSettings& response);
double getMagSq() const { return m_basebandSink->getMagSq(); }
SpectrumVis *getSpectrumVis() { return &m_spectrumVis; }
void getMagSqLevels(double& avg, double& peak, int& nbSamples) { m_basebandSink->getMagSqLevels(avg, peak, nbSamples); }
uint32_t getNumberOfDeviceStreams() const;
static const char *const m_channelIdURI;
static const char *const m_channelId;
private:
DeviceAPI *m_deviceAPI;
QThread m_thread;
SELCALDemodBaseband *m_basebandSink;
SpectrumVis m_spectrumVis;
SELCALDemodSettings m_settings;
int m_basebandSampleRate; //!< stored from device message used when starting baseband sink
qint64 m_centerFrequency;
QUdpSocket m_udpSocket;
QHostAddress m_udpHostAddress; // m_settings.m_udpAddress, resolved
void resolveUDPAddress(const QString& address);
void udpAddressResolved(const QHostInfo& info);
QMutex m_reportMutex;
SELCALMessages::Call m_lastCall;
SELCALMessages::Status m_status;
quint64 m_callCount = 0;
QFile m_logFile;
QTextStream m_logStream;
QNetworkAccessManager *m_networkManager;
QNetworkRequest m_networkRequest;
virtual bool handleMessage(const Message& cmd);
void applySettings(const QStringList& settingsKeys, const SELCALDemodSettings& settings, bool force = false);
void sendSampleRateToDemodAnalyzer();
void webapiReverseSendSettings(const QList<QString>& channelSettingsKeys, const SELCALDemodSettings& settings, bool force);
void webapiFormatChannelSettings(const QList<QString>& channelSettingsKeys, SWGSDRangel::SWGChannelSettings *swgChannelSettings,
const SELCALDemodSettings& settings, bool force);
void webapiFormatChannelReport(SWGSDRangel::SWGChannelReport& response);
private slots:
void networkManagerFinished(QNetworkReply *reply);
void handleIndexInDeviceSetChanged(int index);
};
#endif // INCLUDE_SELCALDEMOD_H

212
plugins/channelrx/demodselcal/selcaldemodbaseband.cpp

@ -0,0 +1,212 @@ @@ -0,0 +1,212 @@
///////////////////////////////////////////////////////////////////////////////////
// Copyright (C) 2021-2022 Edouard Griffiths, F4EXB <f4exb06@gmail.com> //
// Copyright (C) 2026 Jon Beniston, M7RCE <jon@beniston.com> //
// Some code by AI //
// //
// This program is free software; you can redistribute it and/or modify //
// it under the terms of the GNU General Public License as published by //
// the Free Software Foundation as version 3 of the License, or //
// (at your option) any later version. //
// //
// This program is distributed in the hope that it will be useful, //
// but WITHOUT ANY WARRANTY; without even the implied warranty of //
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //
// GNU General Public License V3 for more details. //
// //
// You should have received a copy of the GNU General Public License //
// along with this program. If not, see <http://www.gnu.org/licenses/>. //
///////////////////////////////////////////////////////////////////////////////////
#include <QDebug>
#include "dsp/dspcommands.h"
#include "dsp/downchannelizer.h"
#include "selcaldemodbaseband.h"
#include "dsp/dspengine.h"
#include "audio/audiodevicemanager.h"
MESSAGE_CLASS_DEFINITION(SELCALDemodBaseband::MsgConfigureSELCALDemodBaseband, Message)
SELCALDemodBaseband::SELCALDemodBaseband(SELCALDemod *selcalDemod) :
m_sink(selcalDemod),
m_running(false)
{
qDebug("SELCALDemodBaseband::SELCALDemodBaseband");
auto *audio = DSPEngine::instance()->getAudioDeviceManager();
audio->addAudioSink(m_sink.getAudioFifo(), getInputMessageQueue());
m_sink.applyAudioSampleRate(audio->getOutputSampleRate());
m_sampleFifo.setSize(SampleSinkFifo::getSizePolicy(48000));
m_channelizer = new DownChannelizer(&m_sink);
}
SELCALDemodBaseband::~SELCALDemodBaseband()
{
m_inputMessageQueue.clear();
DSPEngine::instance()->getAudioDeviceManager()->removeAudioSink(m_sink.getAudioFifo());
delete m_channelizer;
}
void SELCALDemodBaseband::reset()
{
QMutexLocker mutexLocker(&m_mutex);
m_inputMessageQueue.clear();
m_sampleFifo.reset();
m_sink.reset();
}
void SELCALDemodBaseband::startWork()
{
QMutexLocker mutexLocker(&m_mutex);
QObject::connect(&m_sampleFifo, &SampleSinkFifo::dataReady, this, &SELCALDemodBaseband::handleData, Qt::QueuedConnection);
connect(&m_inputMessageQueue, SIGNAL(messageEnqueued()), this, SLOT(handleInputMessages()));
m_running = true;
}
void SELCALDemodBaseband::stopWork()
{
QMutexLocker mutexLocker(&m_mutex);
disconnect(&m_inputMessageQueue, SIGNAL(messageEnqueued()), this, SLOT(handleInputMessages()));
QObject::disconnect(&m_sampleFifo, &SampleSinkFifo::dataReady, this, &SELCALDemodBaseband::handleData);
m_running = false;
}
void SELCALDemodBaseband::setChannel(ChannelAPI *channel)
{
m_sink.setChannel(channel);
}
void SELCALDemodBaseband::feed(const SampleVector::const_iterator& begin, const SampleVector::const_iterator& end)
{
m_sampleFifo.write(begin, end);
}
void SELCALDemodBaseband::handleData()
{
QMutexLocker mutexLocker(&m_mutex);
while ((m_sampleFifo.fill() > 0) && (m_inputMessageQueue.size() == 0) && m_channelizer->getBasebandSampleRate())
{
SampleVector::iterator part1begin;
SampleVector::iterator part1end;
SampleVector::iterator part2begin;
SampleVector::iterator part2end;
std::size_t count = m_sampleFifo.readBegin(m_sampleFifo.fill(), &part1begin, &part1end, &part2begin, &part2end);
// first part of FIFO data
if (part1begin != part1end) {
m_channelizer->feed(part1begin, part1end);
}
// second part of FIFO data (used when block wraps around)
if (part2begin != part2end) {
m_channelizer->feed(part2begin, part2end);
}
m_sampleFifo.readCommit((unsigned int)count);
}
}
void SELCALDemodBaseband::handleInputMessages()
{
Message *message;
while ((message = m_inputMessageQueue.pop()))
{
if (!handleMessage(*message)) {
qDebug("%s: unhandled message: %s", Q_FUNC_INFO, message->getIdentifier());
}
delete message;
}
}
bool SELCALDemodBaseband::handleMessage(const Message& cmd)
{
if (MsgConfigureSELCALDemodBaseband::match(cmd))
{
QMutexLocker mutexLocker(&m_mutex);
MsgConfigureSELCALDemodBaseband& cfg = (MsgConfigureSELCALDemodBaseband&)cmd;
qDebug() << "SELCALDemodBaseband::handleMessage: MsgConfigureSELCALDemodBaseband";
applySettings(cfg.getSettingsKeys(), cfg.getSettings(), cfg.getForce());
return true;
}
else if (DSPSignalNotification::match(cmd))
{
QMutexLocker mutexLocker(&m_mutex);
DSPSignalNotification& notif = (DSPSignalNotification&)cmd;
qDebug() << "SELCALDemodBaseband::handleMessage: DSPSignalNotification: basebandSampleRate: " << notif.getSampleRate();
// Queued samples are discarded when the stream changes. The notification sent when the
// channel starts repeats the current stream, and can be handled after the first samples
// have been queued, so they are kept then.
bool changed = (notif.getSampleRate() != m_channelizer->getBasebandSampleRate()) ||
(notif.getCenterFrequency() != m_centerFrequency);
m_centerFrequency = notif.getCenterFrequency();
m_sink.setCenterFrequency(notif.getCenterFrequency());
setBasebandSampleRate(notif.getSampleRate());
if (changed)
{
// A call in progress, the carrier measurement and learnt background
// belong to the old stream.
m_sink.reset();
// We can run with very slow sample rate (E.g. 4k), but we don't want FIFO getting too small
m_sampleFifo.setSize(SampleSinkFifo::getSizePolicy(std::max(notif.getSampleRate(), 48000)));
}
return true;
}
else if (DSPConfigureAudio::match(cmd))
{
QMutexLocker lock(&m_mutex);
const auto& audio = static_cast<const DSPConfigureAudio&>(cmd);
m_sink.applyAudioSampleRate(audio.getSampleRate());
return true;
}
else
{
return false;
}
}
void SELCALDemodBaseband::applySettings(const QStringList& settingsKeys, const SELCALDemodSettings& settings, bool force)
{
if ((settingsKeys.contains("inputFrequencyOffset") && (settings.m_inputFrequencyOffset != m_settings.m_inputFrequencyOffset)) || force)
{
m_channelizer->setChannelization(SELCALDemodSettings::SELCALDEMOD_CHANNEL_SAMPLE_RATE, settings.m_inputFrequencyOffset);
m_sink.applyChannelSettings(m_channelizer->getChannelSampleRate(), m_channelizer->getChannelFrequencyOffset());
}
if ((settingsKeys.contains("audioDeviceName") && (settings.m_audioDeviceName != m_settings.m_audioDeviceName)) || force)
{
auto *audio = DSPEngine::instance()->getAudioDeviceManager();
int index = audio->getOutputDeviceIndex(settings.m_audioDeviceName);
audio->removeAudioSink(m_sink.getAudioFifo());
audio->addAudioSink(m_sink.getAudioFifo(), getInputMessageQueue(), index);
m_sink.applyAudioSampleRate(audio->getOutputSampleRate(index));
}
m_sink.applySettings(settingsKeys, settings, force);
if (force) {
m_settings = settings;
}
else
{
m_settings.applySettings(settingsKeys, settings);
}
}
int SELCALDemodBaseband::getChannelSampleRate() const
{
return m_channelizer->getChannelSampleRate();
}
void SELCALDemodBaseband::setBasebandSampleRate(int sampleRate)
{
m_channelizer->setBasebandSampleRate(sampleRate);
m_sink.applyChannelSettings(m_channelizer->getChannelSampleRate(), m_channelizer->getChannelFrequencyOffset());
}

110
plugins/channelrx/demodselcal/selcaldemodbaseband.h

@ -0,0 +1,110 @@ @@ -0,0 +1,110 @@
///////////////////////////////////////////////////////////////////////////////////
// Copyright (C) 2021-2022 Edouard Griffiths, F4EXB <f4exb06@gmail.com> //
// Copyright (C) 2026 Jon Beniston, M7RCE <jon@beniston.com> //
// Some code by AI //
// //
// This program is free software; you can redistribute it and/or modify //
// it under the terms of the GNU General Public License as published by //
// the Free Software Foundation as version 3 of the License, or //
// (at your option) any later version. //
// //
// This program is distributed in the hope that it will be useful, //
// but WITHOUT ANY WARRANTY; without even the implied warranty of //
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //
// GNU General Public License V3 for more details. //
// //
// You should have received a copy of the GNU General Public License //
// along with this program. If not, see <http://www.gnu.org/licenses/>. //
///////////////////////////////////////////////////////////////////////////////////
#ifndef INCLUDE_SELCALDEMODBASEBAND_H
#define INCLUDE_SELCALDEMODBASEBAND_H
#include <QObject>
#include <QRecursiveMutex>
#include "dsp/samplesinkfifo.h"
#include "util/message.h"
#include "util/messagequeue.h"
#include "selcaldemodsink.h"
class DownChannelizer;
class ChannelAPI;
class SELCALDemod;
class SELCALDemodBaseband : public QObject {
Q_OBJECT
public:
class MsgConfigureSELCALDemodBaseband : public Message {
MESSAGE_CLASS_DECLARATION
public:
const SELCALDemodSettings& getSettings() const { return m_settings; }
const QStringList& getSettingsKeys() const { return m_settingsKeys; }
bool getForce() const { return m_force; }
static MsgConfigureSELCALDemodBaseband *create(const QStringList& settingsKeys, const SELCALDemodSettings& settings, bool force)
{
return new MsgConfigureSELCALDemodBaseband(settingsKeys, settings, force);
}
private:
SELCALDemodSettings m_settings;
QStringList m_settingsKeys;
bool m_force;
MsgConfigureSELCALDemodBaseband(const QStringList& settingsKeys, const SELCALDemodSettings& settings, bool force) :
Message(),
m_settings(settings),
m_settingsKeys(settingsKeys),
m_force(force)
{
}
};
SELCALDemodBaseband(SELCALDemod *selcalDemod);
~SELCALDemodBaseband();
void reset();
void startWork();
void stopWork();
void feed(const SampleVector::const_iterator& begin, const SampleVector::const_iterator& end);
MessageQueue *getInputMessageQueue() { return &m_inputMessageQueue; } //!< Get the queue for asynchronous inbound communication
// As in other demodulators, these don't wait for the worker, which holds
// the mutex while processing all queued samples.
void getMagSqLevels(double& avg, double& peak, int& nbSamples) { m_sink.getMagSqLevels(avg, peak, nbSamples); }
void setMessageQueueToChannel(MessageQueue *messageQueue) { m_sink.setMessageQueueToChannel(messageQueue); }
void setSpectrumSink(SpectrumVis *spectrumSink) { m_sink.setSpectrumSink(spectrumSink); }
void setBasebandSampleRate(int sampleRate);
int getChannelSampleRate() const;
int getAudioSampleRate() const { return m_sink.getAudioSampleRate(); }
void setChannel(ChannelAPI *channel);
double getMagSq() const { return m_sink.getMagSq(); }
bool isRunning() const { return m_running; }
void setFifoLabel(const QString& label) { m_sampleFifo.setLabel(label); }
private:
SampleSinkFifo m_sampleFifo;
DownChannelizer *m_channelizer;
SELCALDemodSink m_sink;
MessageQueue m_inputMessageQueue; //!< Queue for asynchronous inbound communication
SELCALDemodSettings m_settings;
qint64 m_centerFrequency = -1; //!< From the latest DSPSignalNotification
bool m_running;
mutable QRecursiveMutex m_mutex;
bool handleMessage(const Message& cmd);
void applySettings(const QStringList& settingsKeys, const SELCALDemodSettings& settings, bool force = false);
private slots:
void handleInputMessages();
void handleData(); //!< Handle data when samples have to be processed
};
#endif // INCLUDE_SELCALDEMODBASEBAND_H

1043
plugins/channelrx/demodselcal/selcaldemodgui.cpp

File diff suppressed because it is too large Load Diff

169
plugins/channelrx/demodselcal/selcaldemodgui.h

@ -0,0 +1,169 @@ @@ -0,0 +1,169 @@
///////////////////////////////////////////////////////////////////////////////////
// Copyright (C) 2021-2022 Edouard Griffiths, F4EXB <f4exb06@gmail.com> //
// Copyright (C) 2026 Jon Beniston, M7RCE <jon@beniston.com> //
// Some code by AI //
// //
// This program is free software; you can redistribute it and/or modify //
// it under the terms of the GNU General Public License as published by //
// the Free Software Foundation as version 3 of the License, or //
// (at your option) any later version. //
// //
// This program is distributed in the hope that it will be useful, //
// but WITHOUT ANY WARRANTY; without even the implied warranty of //
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //
// GNU General Public License V3 for more details. //
// //
// You should have received a copy of the GNU General Public License //
// along with this program. If not, see <http://www.gnu.org/licenses/>. //
///////////////////////////////////////////////////////////////////////////////////
#ifndef INCLUDE_SELCALDEMODGUI_H
#define INCLUDE_SELCALDEMODGUI_H
#include <QSharedPointer>
#include "channel/channelgui.h"
#include "dsp/channelmarker.h"
#include "dsp/spectrummarkers.h"
#include "util/messagequeue.h"
#include "settings/rollupstate.h"
#include "util/osndb.h"
#include "util/selcaldb.h"
#include "selcaldemod.h"
#include "selcaldemodsettings.h"
class PluginAPI;
class DeviceUISet;
class BasebandSampleSink;
class SELCALDemod;
class SELCALDemodGUI;
namespace Ui {
class SELCALDemodGUI;
}
class SpectrumVis;
class QProgressDialog;
class QMenu;
class SELCALDemodGUI;
class SELCALDemodGUI : public ChannelGUI {
Q_OBJECT
public:
static SELCALDemodGUI *create(PluginAPI *pluginAPI, DeviceUISet *deviceUISet, BasebandSampleSink *rxChannel);
virtual void destroy();
void resetToDefaults();
QByteArray serialize() const;
bool deserialize(const QByteArray& data);
virtual MessageQueue *getInputMessageQueue() { return &m_inputMessageQueue; }
virtual void setWorkspaceIndex(int index) { m_settings.m_workspaceIndex = index; };
virtual int getWorkspaceIndex() const { return m_settings.m_workspaceIndex; };
virtual void setGeometryBytes(const QByteArray& blob) { m_settings.m_geometryBytes = blob; };
virtual QByteArray getGeometryBytes() const { return m_settings.m_geometryBytes; };
virtual QString getTitle() const { return m_settings.m_title; };
virtual QColor getTitleColor() const { return m_settings.m_rgbColor; };
virtual void zetHidden(bool hidden) { m_settings.m_hidden = hidden; }
virtual bool getHidden() const { return m_settings.m_hidden; }
virtual ChannelMarker& getChannelMarker() { return m_channelMarker; }
virtual int getStreamIndex() const { return m_settings.m_streamIndex; }
virtual void setStreamIndex(int streamIndex) { m_settings.m_streamIndex = streamIndex; }
public slots:
void channelMarkerChangedByCursor();
void channelMarkerHighlightedByCursor();
private:
// Logical columns of the calls table
enum Column {
COL_UTC,
COL_CODE,
COL_REGISTRATION,
COL_TYPE,
COL_SIDEVIEW,
COL_COUNTRY,
COL_FREQUENCY,
COL_RSSI,
COL_SNR
};
Ui::SELCALDemodGUI *ui;
DeviceUISet *m_deviceUISet;
ChannelMarker m_channelMarker;
RollupState m_rollupState;
SELCALDemodSettings m_settings;
SELCALDemod *m_selcalDemod;
SpectrumVis *m_spectrumVis;
MessageQueue m_inputMessageQueue;
double m_markerOffset = 1e9;
SELCALDecoder::Pair m_markerPair{{-1, -1}};
QList<SpectrumAnnotationMarker> m_markers; // Tone markers last shown
QString m_cellText; // Of the table cell whose context menu is shown
QMenu *m_columnMenu = nullptr; // Selects the table columns shown
qint64 m_deviceCenterFrequency = 0;
int m_basebandSampleRate = 48000;
bool m_doApplySettings = true;
bool m_squelchOpen = false;
SELCALDB m_selcalDB;
OsnDB m_osnDB;
QProgressDialog *m_progressDialog = nullptr;
bool m_downloadAircraftDB = false;
QSharedPointer<const QHash<QString, AircraftInformation *>> m_aircraftInfoByReg;
explicit SELCALDemodGUI(PluginAPI *pluginAPI, DeviceUISet *deviceUISet, BasebandSampleSink *rxChannel, QWidget *parent = nullptr);
~SELCALDemodGUI() override;
void applySettings(const QStringList& keys, bool force = false);
void displaySettings();
void makeUIConnections();
void loadAircraftInformation();
void messageReceived(const SELCALMessages::Call& call, bool update = true);
void updateAudioMute();
void filter();
void updateAbsoluteCenterFrequency();
void exportCsv();
void copySelection();
void updateCarrierStatus(const SELCALMessages::Status& status);
void updateToneMarkers(double offset, const SELCALDecoder::Pair& pair);
static QString signedHz(double value);
void lookupAircraft(int row);
void updateAircraft();
void finishDownload();
private slots:
void on_getSELCALDB_clicked();
void downloadingURL(const QString& url);
void downloadProgress(qint64 bytesRead, qint64 totalBytes);
void downloadError(const QString& error);
void downloadSELCALInformationFinished();
void downloadAircraftInformationFinished();
void on_deltaFrequency_changed(qint64 value);
void on_modulation_currentIndexChanged(int index);
void on_rfBandwidth_valueChanged(int value);
void on_toneFrequencyOffset_valueChanged(double value);
void on_autoToneFrequencyOffset_toggled(bool checked);
void on_threshold_valueChanged(double value);
void on_volume_valueChanged(int value);
void on_audioMute_toggled(bool checked);
void on_squelch_valueChanged(int value);
void on_filter_textChanged(const QString& text);
void on_clearTable_clicked();
void on_logEnable_toggled(bool checked);
void on_logFilename_clicked();
void on_logOpen_clicked();
void on_udpEnabled_toggled(bool checked);
void on_udpAddress_editingFinished();
void on_udpPort_valueChanged(int value);
void messages_sectionMoved(int logicalIndex, int oldVisualIndex, int newVisualIndex);
void messages_sectionResized(int logicalIndex, int oldSize, int newSize);
void messages_customContextMenuRequested(QPoint pos);
void copyCell();
void messages_columnSelectMenu(QPoint pos);
void messages_columnSelectMenuChecked(bool checked);
void handleInputMessages();
void audioSelect(const QPoint& point);
void readLog(const QString& filename);
void tick();
void onMenuDialogCalled(const QPoint& point);
void onWidgetRolled(QWidget *widget, bool rollDown);
};
#endif

999
plugins/channelrx/demodselcal/selcaldemodgui.ui

@ -0,0 +1,999 @@ @@ -0,0 +1,999 @@
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>SELCALDemodGUI</class>
<widget class="RollupContents" name="SELCALDemodGUI">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>640</width>
<height>1014</height>
</rect>
</property>
<property name="minimumSize">
<size>
<width>500</width>
<height>450</height>
</size>
</property>
<property name="windowTitle">
<string>SELCAL Demodulator</string>
</property>
<widget class="QWidget" name="settingsContainer">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>640</width>
<height>218</height>
</rect>
</property>
<property name="minimumSize">
<size>
<width>500</width>
<height>200</height>
</size>
</property>
<property name="windowTitle">
<string>Settings</string>
</property>
<layout class="QVBoxLayout" name="settingsContainerLayout">
<property name="spacing">
<number>3</number>
</property>
<property name="leftMargin">
<number>3</number>
</property>
<property name="topMargin">
<number>3</number>
</property>
<property name="rightMargin">
<number>3</number>
</property>
<property name="bottomMargin">
<number>3</number>
</property>
<item>
<layout class="QHBoxLayout" name="frequencyLayout">
<item>
<widget class="QLabel" name="deltaFrequencyLabel">
<property name="text">
<string>Δf</string>
</property>
</widget>
</item>
<item>
<widget class="ValueDialZ" name="deltaFrequency" native="true">
<property name="font">
<font>
<family>Liberation Mono</family>
<pointsize>12</pointsize>
</font>
</property>
<property name="toolTip">
<string>Channel offset from device centre frequency in Hz</string>
</property>
</widget>
</item>
<item>
<widget class="QLabel" name="frequencyUnits">
<property name="text">
<string>Hz</string>
</property>
</widget>
</item>
<item>
<spacer name="horizontalSpacer">
<property name="orientation">
<enum>Qt::Orientation::Horizontal</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>40</width>
<height>20</height>
</size>
</property>
</spacer>
</item>
<item>
<widget class="QLabel" name="channelPower">
<property name="text">
<string>-120.0 dB</string>
</property>
</widget>
</item>
</layout>
</item>
<item>
<layout class="QHBoxLayout" name="powerLayout">
<item>
<widget class="LevelMeterSignalDB" name="channelPowerMeter" native="true">
<property name="sizePolicy">
<sizepolicy hsizetype="Expanding" vsizetype="Preferred">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="minimumSize">
<size>
<width>170</width>
<height>24</height>
</size>
</property>
<property name="maximumSize">
<size>
<width>16777215</width>
<height>24</height>
</size>
</property>
<property name="font">
<font>
<family>Liberation Mono</family>
<pointsize>8</pointsize>
</font>
</property>
</widget>
</item>
</layout>
</item>
<item>
<layout class="QHBoxLayout" name="carrierLayout">
<item>
<widget class="QComboBox" name="modulation">
<property name="minimumSize">
<size>
<width>60</width>
<height>0</height>
</size>
</property>
<item>
<property name="text">
<string>USB</string>
</property>
</item>
<item>
<property name="text">
<string>AM</string>
</property>
</item>
</widget>
</item>
<item>
<widget class="QLabel" name="bandwidthLabel">
<property name="text">
<string>BW</string>
</property>
</widget>
</item>
<item>
<widget class="QSlider" name="rfBandwidth">
<property name="toolTip">
<string>USB audio upper cutoff; AM full RF bandwidth</string>
</property>
<property name="minimum">
<number>20</number>
</property>
<property name="maximum">
<number>60</number>
</property>
<property name="pageStep">
<number>1</number>
</property>
<property name="value">
<number>30</number>
</property>
<property name="orientation">
<enum>Qt::Orientation::Horizontal</enum>
</property>
</widget>
</item>
<item>
<widget class="QLabel" name="rfBandwidthText">
<property name="minimumSize">
<size>
<width>50</width>
<height>0</height>
</size>
</property>
<property name="toolTip">
<string>USB audio upper cutoff; AM full RF bandwidth</string>
</property>
<property name="text">
<string>3.0 kHz</string>
</property>
<property name="alignment">
<set>Qt::AlignmentFlag::AlignRight|Qt::AlignmentFlag::AlignTrailing|Qt::AlignmentFlag::AlignVCenter</set>
</property>
</widget>
</item>
</layout>
</item>
<item>
<layout class="QHBoxLayout" name="decoderLayout">
<item>
<widget class="ButtonSwitch" name="autoToneFrequencyOffset">
<property name="maximumSize">
<size>
<width>24</width>
<height>24</height>
</size>
</property>
<property name="toolTip">
<string>Automatically calculate the USB tone offset from a residual carrier</string>
</property>
<property name="accessibleName">
<string>Automatically calculate the USB tone offset from a residual carrier</string>
</property>
<property name="text">
<string/>
</property>
<property name="icon">
<iconset>
<normaloff>:/carrier.png</normaloff>:/carrier.png</iconset>
</property>
</widget>
</item>
<item>
<widget class="QLabel" name="toneOffsetLabel">
<property name="text">
<string>Tone offset</string>
</property>
</widget>
</item>
<item>
<widget class="QDoubleSpinBox" name="toneFrequencyOffset">
<property name="toolTip">
<string>Expected common offset of the received tones. Without a carrier lock, tones are searched for within +/-6 Hz of this offset.</string>
</property>
<property name="suffix">
<string> Hz</string>
</property>
<property name="decimals">
<number>1</number>
</property>
<property name="minimum">
<double>-100.000000000000000</double>
</property>
<property name="maximum">
<double>100.000000000000000</double>
</property>
</widget>
</item>
<item>
<widget class="QLabel" name="thresholdLabel">
<property name="text">
<string>Threshold</string>
</property>
</widget>
</item>
<item>
<widget class="QDoubleSpinBox" name="threshold">
<property name="toolTip">
<string>Minimum level of each tone above the noise in a tone bin. Lower values detect weaker calls, but increase false detections.</string>
</property>
<property name="suffix">
<string> dB</string>
</property>
<property name="decimals">
<number>1</number>
</property>
<property name="minimum">
<double>6.000000000000000</double>
</property>
<property name="maximum">
<double>20.000000000000000</double>
</property>
<property name="singleStep">
<double>0.500000000000000</double>
</property>
<property name="value">
<double>8.000000000000000</double>
</property>
</widget>
</item>
<item>
<spacer name="horizontalSpacer_3">
<property name="orientation">
<enum>Qt::Orientation::Horizontal</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>40</width>
<height>20</height>
</size>
</property>
</spacer>
</item>
</layout>
</item>
<item>
<layout class="QHBoxLayout" name="audioLayout">
<item>
<widget class="QLabel" name="carrierStatus">
<property name="text">
<string>Searching for carrier</string>
</property>
</widget>
</item>
<item>
<spacer name="horizontalSpacer_2">
<property name="orientation">
<enum>Qt::Orientation::Horizontal</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>40</width>
<height>20</height>
</size>
</property>
</spacer>
</item>
<item>
<widget class="QLabel" name="volumeLabel">
<property name="text">
<string>Volume</string>
</property>
</widget>
</item>
<item>
<widget class="QDial" name="volume">
<property name="maximumSize">
<size>
<width>24</width>
<height>24</height>
</size>
</property>
<property name="toolTip">
<string>Monitoring audio volume</string>
</property>
<property name="maximum">
<number>100</number>
</property>
<property name="singleStep">
<number>1</number>
</property>
<property name="pageStep">
<number>1</number>
</property>
<property name="value">
<number>10</number>
</property>
</widget>
</item>
<item>
<widget class="QLabel" name="volumeText">
<property name="minimumSize">
<size>
<width>24</width>
<height>0</height>
</size>
</property>
<property name="toolTip">
<string>Monitoring audio volume</string>
</property>
<property name="text">
<string>1.0</string>
</property>
<property name="alignment">
<set>Qt::AlignmentFlag::AlignRight|Qt::AlignmentFlag::AlignTrailing|Qt::AlignmentFlag::AlignVCenter</set>
</property>
</widget>
</item>
<item>
<widget class="Line" name="line">
<property name="orientation">
<enum>Qt::Orientation::Vertical</enum>
</property>
</widget>
</item>
<item>
<widget class="QLabel" name="squelchLabel">
<property name="text">
<string>Sq</string>
</property>
</widget>
</item>
<item>
<widget class="QDial" name="squelch">
<property name="maximumSize">
<size>
<width>24</width>
<height>24</height>
</size>
</property>
<property name="toolTip">
<string>Monitoring audio squelch threshold (dBFS)</string>
</property>
<property name="minimum">
<number>-100</number>
</property>
<property name="maximum">
<number>0</number>
</property>
<property name="singleStep">
<number>1</number>
</property>
<property name="pageStep">
<number>1</number>
</property>
<property name="value">
<number>-80</number>
</property>
</widget>
</item>
<item>
<widget class="QLabel" name="squelchText">
<property name="text">
<string>-80 dB</string>
</property>
</widget>
</item>
<item>
<widget class="ButtonSwitch" name="audioMute">
<property name="maximumSize">
<size>
<width>24</width>
<height>24</height>
</size>
</property>
<property name="toolTip">
<string>Mute/unmute audio. Right click to select the audio output device.</string>
</property>
<property name="accessibleName">
<string>Mute/unmute audio. Right click to select the audio output device.</string>
</property>
<property name="text">
<string/>
</property>
<property name="icon">
<iconset>
<normaloff>:/sound_on.png</normaloff>
<normalon>:/sound_off.png</normalon>:/sound_on.png</iconset>
</property>
</widget>
</item>
</layout>
</item>
<item>
<layout class="QHBoxLayout" name="udpLayout">
<item>
<widget class="ButtonSwitch" name="udpEnabled">
<property name="maximumSize">
<size>
<width>1000</width>
<height>1000</height>
</size>
</property>
<property name="toolTip">
<string>Send decoded calls via UDP</string>
</property>
<property name="accessibleName">
<string>Send decoded calls via UDP</string>
</property>
<property name="text">
<string>UDP</string>
</property>
</widget>
</item>
<item>
<widget class="QLineEdit" name="udpAddress">
<property name="toolTip">
<string>Destination UDP address</string>
</property>
</widget>
</item>
<item>
<widget class="QLabel" name="udpPortLabel">
<property name="text">
<string>:</string>
</property>
</widget>
</item>
<item>
<widget class="QSpinBox" name="udpPort">
<property name="toolTip">
<string>Destination UDP port</string>
</property>
<property name="minimum">
<number>1</number>
</property>
<property name="maximum">
<number>65535</number>
</property>
</widget>
</item>
</layout>
</item>
<item>
<layout class="QHBoxLayout" name="historyLayout">
<item>
<widget class="QLabel" name="filterLabel">
<property name="text">
<string>Code filter</string>
</property>
</widget>
</item>
<item>
<widget class="QLineEdit" name="filter">
<property name="toolTip">
<string>Enter code to find in table</string>
</property>
<property name="placeholderText">
<string>All codes</string>
</property>
</widget>
</item>
<item>
<widget class="QToolButton" name="copy">
<property name="maximumSize">
<size>
<width>24</width>
<height>24</height>
</size>
</property>
<property name="toolTip">
<string>Copy selected calls</string>
</property>
<property name="accessibleName">
<string>Copy selected calls</string>
</property>
<property name="text">
<string/>
</property>
<property name="icon">
<iconset>
<normaloff>:/duplicate.png</normaloff>:/duplicate.png</iconset>
</property>
</widget>
</item>
<item>
<widget class="QToolButton" name="exportCsv">
<property name="maximumSize">
<size>
<width>24</width>
<height>24</height>
</size>
</property>
<property name="toolTip">
<string>Export visible calls to CSV</string>
</property>
<property name="accessibleName">
<string>Export visible calls to CSV</string>
</property>
<property name="text">
<string/>
</property>
<property name="icon">
<iconset>
<normaloff>:/export.png</normaloff>:/export.png</iconset>
</property>
</widget>
</item>
<item>
<widget class="ButtonSwitch" name="logEnable">
<property name="maximumSize">
<size>
<width>24</width>
<height>16777215</height>
</size>
</property>
<property name="toolTip">
<string>Start/stop logging of received messages to .csv file</string>
</property>
<property name="text">
<string/>
</property>
<property name="icon">
<iconset>
<normaloff>:/record_off.png</normaloff>:/record_off.png</iconset>
</property>
</widget>
</item>
<item>
<widget class="QToolButton" name="logFilename">
<property name="toolTip">
<string>Set log .csv filename</string>
</property>
<property name="text">
<string/>
</property>
<property name="icon">
<iconset>
<normaloff>:/save.png</normaloff>:/save.png</iconset>
</property>
<property name="checkable">
<bool>false</bool>
</property>
</widget>
</item>
<item>
<widget class="QToolButton" name="getSELCALDB">
<property name="toolTip">
<string>Download the SELCAL code database, used to display the aircraft assigned a code</string>
</property>
<property name="text">
<string/>
</property>
<property name="icon">
<iconset>
<normaloff>:/import.png</normaloff>:/import.png</iconset>
</property>
</widget>
</item>
<item>
<widget class="QToolButton" name="logOpen">
<property name="toolTip">
<string>Read messages from .csv log file</string>
</property>
<property name="text">
<string/>
</property>
<property name="icon">
<iconset>
<normaloff>:/load.png</normaloff>:/load.png</iconset>
</property>
<property name="checkable">
<bool>false</bool>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="clearTable">
<property name="maximumSize">
<size>
<width>24</width>
<height>24</height>
</size>
</property>
<property name="toolTip">
<string>Clear received calls</string>
</property>
<property name="accessibleName">
<string>Clear received calls</string>
</property>
<property name="text">
<string/>
</property>
<property name="icon">
<iconset>
<normaloff>:/bin.png</normaloff>:/bin.png</iconset>
</property>
</widget>
</item>
</layout>
</item>
</layout>
</widget>
<widget class="QWidget" name="messagesContainer">
<property name="geometry">
<rect>
<x>0</x>
<y>210</y>
<width>640</width>
<height>240</height>
</rect>
</property>
<property name="minimumSize">
<size>
<width>500</width>
<height>240</height>
</size>
</property>
<property name="windowTitle">
<string>Decoded calls</string>
</property>
<layout class="QVBoxLayout" name="messagesContainerLayout">
<property name="spacing">
<number>3</number>
</property>
<property name="leftMargin">
<number>3</number>
</property>
<property name="topMargin">
<number>3</number>
</property>
<property name="rightMargin">
<number>3</number>
</property>
<property name="bottomMargin">
<number>3</number>
</property>
<item>
<layout class="QHBoxLayout" name="lastCallLayout">
<item>
<widget class="QLabel" name="lastCode">
<property name="font">
<font>
<pointsize>24</pointsize>
<bold>true</bold>
</font>
</property>
<property name="text">
<string>----</string>
</property>
</widget>
</item>
</layout>
</item>
<item>
<widget class="QTableWidget" name="messages">
<property name="toolTip">
<string>Decoded calls</string>
</property>
<property name="editTriggers">
<set>QAbstractItemView::EditTrigger::NoEditTriggers</set>
</property>
<property name="selectionBehavior">
<enum>QAbstractItemView::SelectionBehavior::SelectRows</enum>
</property>
<column>
<property name="text">
<string>UTC</string>
</property>
<property name="toolTip">
<string>Date and time call was detected</string>
</property>
</column>
<column>
<property name="text">
<string>Code</string>
</property>
<property name="toolTip">
<string>SELCAL code</string>
</property>
</column>
<column>
<property name="text">
<string>Registration</string>
</property>
<property name="toolTip">
<string>Registrations of aircraft assigned the code</string>
</property>
</column>
<column>
<property name="text">
<string>Type</string>
</property>
<property name="toolTip">
<string>Aircraft type designators</string>
</property>
</column>
<column>
<property name="text">
<string>Aircraft</string>
</property>
</column>
<column>
<property name="text">
<string>Country</string>
</property>
</column>
<column>
<property name="text">
<string>Frequency (kHz)</string>
</property>
<property name="toolTip">
<string>Frequency on which code was detected</string>
</property>
</column>
<column>
<property name="text">
<string>RSSI (dB)</string>
</property>
<property name="toolTip">
<string>Received signal strength indication</string>
</property>
</column>
<column>
<property name="text">
<string>SNR (dB)</string>
</property>
<property name="toolTip">
<string>Signal to noise ratio</string>
</property>
</column>
</widget>
</item>
</layout>
</widget>
<widget class="QWidget" name="diagnosticsContainer">
<property name="geometry">
<rect>
<x>0</x>
<y>460</y>
<width>640</width>
<height>260</height>
</rect>
</property>
<property name="minimumSize">
<size>
<width>500</width>
<height>260</height>
</size>
</property>
<property name="windowTitle">
<string>Tone levels</string>
</property>
<layout class="QVBoxLayout" name="diagnosticsContainerLayout">
<property name="spacing">
<number>3</number>
</property>
<property name="leftMargin">
<number>3</number>
</property>
<property name="topMargin">
<number>3</number>
</property>
<property name="rightMargin">
<number>3</number>
</property>
<property name="bottomMargin">
<number>3</number>
</property>
<item>
<widget class="QTableWidget" name="toneLevels">
<property name="editTriggers">
<set>QAbstractItemView::EditTrigger::NoEditTriggers</set>
</property>
<property name="rowCount">
<number>32</number>
</property>
<row/>
<row/>
<row/>
<row/>
<row/>
<row/>
<row/>
<row/>
<row/>
<row/>
<row/>
<row/>
<row/>
<row/>
<row/>
<row/>
<row/>
<row/>
<row/>
<row/>
<row/>
<row/>
<row/>
<row/>
<row/>
<row/>
<row/>
<row/>
<row/>
<row/>
<row/>
<row/>
<column>
<property name="text">
<string>Tone</string>
</property>
</column>
<column>
<property name="text">
<string>Frequency (Hz)</string>
</property>
</column>
<column>
<property name="text">
<string>SNR (dB)</string>
</property>
</column>
</widget>
</item>
</layout>
</widget>
<widget class="QWidget" name="spectrumContainer" native="true">
<property name="geometry">
<rect>
<x>0</x>
<y>730</y>
<width>640</width>
<height>284</height>
</rect>
</property>
<property name="sizePolicy">
<sizepolicy hsizetype="Expanding" vsizetype="Expanding">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="minimumSize">
<size>
<width>500</width>
<height>0</height>
</size>
</property>
<property name="windowTitle">
<string>Audio spectrum</string>
</property>
<layout class="QVBoxLayout" name="spectrumContainerLayout">
<property name="spacing">
<number>2</number>
</property>
<property name="leftMargin">
<number>2</number>
</property>
<property name="topMargin">
<number>2</number>
</property>
<property name="rightMargin">
<number>2</number>
</property>
<property name="bottomMargin">
<number>2</number>
</property>
<item>
<widget class="GLSpectrum" name="glSpectrum" native="true">
<property name="sizePolicy">
<sizepolicy hsizetype="Expanding" vsizetype="Expanding">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="minimumSize">
<size>
<width>200</width>
<height>250</height>
</size>
</property>
<property name="font">
<font>
<family>Liberation Mono</family>
<pointsize>8</pointsize>
</font>
</property>
</widget>
</item>
<item>
<widget class="GLSpectrumGUI" name="spectrumGUI" native="true"/>
</item>
</layout>
</widget>
</widget>
<customwidgets>
<customwidget>
<class>RollupContents</class>
<extends>QWidget</extends>
<header>gui/rollupcontents.h</header>
<container>1</container>
</customwidget>
<customwidget>
<class>LevelMeterSignalDB</class>
<extends>QWidget</extends>
<header>gui/levelmeter.h</header>
<container>1</container>
</customwidget>
<customwidget>
<class>ValueDialZ</class>
<extends>QWidget</extends>
<header>gui/valuedialz.h</header>
<container>1</container>
</customwidget>
<customwidget>
<class>ButtonSwitch</class>
<extends>QToolButton</extends>
<header>gui/buttonswitch.h</header>
</customwidget>
<customwidget>
<class>GLSpectrum</class>
<extends>QWidget</extends>
<header>gui/glspectrum.h</header>
<container>1</container>
</customwidget>
<customwidget>
<class>GLSpectrumGUI</class>
<extends>QWidget</extends>
<header>gui/glspectrumgui.h</header>
<container>1</container>
</customwidget>
</customwidgets>
<resources/>
<connections/>
</ui>

91
plugins/channelrx/demodselcal/selcaldemodplugin.cpp

@ -0,0 +1,91 @@ @@ -0,0 +1,91 @@
///////////////////////////////////////////////////////////////////////////////////
// Copyright (C) 2021-2022 Edouard Griffiths, F4EXB <f4exb06@gmail.com> //
// Copyright (C) 2026 Jon Beniston, M7RCE <jon@beniston.com> //
// Some code by AI //
// //
// This program is free software; you can redistribute it and/or modify //
// it under the terms of the GNU General Public License as published by //
// the Free Software Foundation as version 3 of the License, or //
// (at your option) any later version. //
// //
// This program is distributed in the hope that it will be useful, //
// but WITHOUT ANY WARRANTY; without even the implied warranty of //
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //
// GNU General Public License V3 for more details. //
// //
// You should have received a copy of the GNU General Public License //
// along with this program. If not, see <http://www.gnu.org/licenses/>. //
///////////////////////////////////////////////////////////////////////////////////
#include <QtPlugin>
#include "plugin/pluginapi.h"
#ifndef SERVER_MODE
#include "selcaldemodgui.h"
#endif
#include "selcaldemod.h"
#include "selcaldemodwebapiadapter.h"
#include "selcaldemodplugin.h"
const PluginDescriptor SELCALDemodPlugin::m_pluginDescriptor = {
SELCALDemod::m_channelId,
QStringLiteral("SELCAL Demodulator"),
QStringLiteral("7.28.0"),
QStringLiteral("(c) Jon Beniston, M7RCE"),
QStringLiteral("https://github.com/f4exb/sdrangel"),
true,
QStringLiteral("https://github.com/f4exb/sdrangel")
};
SELCALDemodPlugin::SELCALDemodPlugin(QObject *parent) :
QObject(parent),
m_pluginAPI(0)
{
}
const PluginDescriptor& SELCALDemodPlugin::getPluginDescriptor() const
{
return m_pluginDescriptor;
}
void SELCALDemodPlugin::initPlugin(PluginAPI *pluginAPI)
{
m_pluginAPI = pluginAPI;
m_pluginAPI->registerRxChannel(SELCALDemod::m_channelIdURI, SELCALDemod::m_channelId, this);
}
void SELCALDemodPlugin::createRxChannel(DeviceAPI *deviceAPI, BasebandSampleSink **bs, ChannelAPI **cs) const
{
if (bs || cs)
{
SELCALDemod *instance = new SELCALDemod(deviceAPI);
if (bs) {
*bs = instance;
}
if (cs) {
*cs = instance;
}
}
}
#ifdef SERVER_MODE
ChannelGUI *SELCALDemodPlugin::createRxChannelGUI(DeviceUISet *deviceUISet, BasebandSampleSink *rxChannel) const
{
(void)deviceUISet;
(void)rxChannel;
return 0;
}
#else
ChannelGUI *SELCALDemodPlugin::createRxChannelGUI(DeviceUISet *deviceUISet, BasebandSampleSink *rxChannel) const
{
return SELCALDemodGUI::create(m_pluginAPI, deviceUISet, rxChannel);
}
#endif
ChannelWebAPIAdapter *SELCALDemodPlugin::createChannelWebAPIAdapter() const
{
return new SELCALDemodWebAPIAdapter();
}

50
plugins/channelrx/demodselcal/selcaldemodplugin.h

@ -0,0 +1,50 @@ @@ -0,0 +1,50 @@
///////////////////////////////////////////////////////////////////////////////////
// Copyright (C) 2021-2022 Edouard Griffiths, F4EXB <f4exb06@gmail.com> //
// Copyright (C) 2026 Jon Beniston, M7RCE <jon@beniston.com> //
// Some code by AI //
// //
// This program is free software; you can redistribute it and/or modify //
// it under the terms of the GNU General Public License as published by //
// the Free Software Foundation as version 3 of the License, or //
// (at your option) any later version. //
// //
// This program is distributed in the hope that it will be useful, //
// but WITHOUT ANY WARRANTY; without even the implied warranty of //
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //
// GNU General Public License V3 for more details. //
// //
// You should have received a copy of the GNU General Public License //
// along with this program. If not, see <http://www.gnu.org/licenses/>. //
///////////////////////////////////////////////////////////////////////////////////
#ifndef INCLUDE_SELCALDEMODPLUGIN_H
#define INCLUDE_SELCALDEMODPLUGIN_H
#include <QObject>
#include "plugin/plugininterface.h"
class DeviceUISet;
class BasebandSampleSink;
class SELCALDemodPlugin : public QObject, PluginInterface {
Q_OBJECT
Q_INTERFACES(PluginInterface)
Q_PLUGIN_METADATA(IID "sdrangel.channel.selcaldemod")
public:
explicit SELCALDemodPlugin(QObject *parent = NULL);
const PluginDescriptor& getPluginDescriptor() const;
void initPlugin(PluginAPI *pluginAPI);
virtual void createRxChannel(DeviceAPI *deviceAPI, BasebandSampleSink **bs, ChannelAPI **cs) const;
virtual ChannelGUI *createRxChannelGUI(DeviceUISet *deviceUISet, BasebandSampleSink *rxChannel) const;
virtual ChannelWebAPIAdapter *createChannelWebAPIAdapter() const;
private:
static const PluginDescriptor m_pluginDescriptor;
PluginAPI *m_pluginAPI;
};
#endif // INCLUDE_SELCALDEMODPLUGIN_H

397
plugins/channelrx/demodselcal/selcaldemodsettings.cpp

@ -0,0 +1,397 @@ @@ -0,0 +1,397 @@
///////////////////////////////////////////////////////////////////////////////////
// Copyright (C) 2021-2022 Edouard Griffiths, F4EXB <f4exb06@gmail.com> //
// Copyright (C) 2026 Jon Beniston, M7RCE <jon@beniston.com> //
// Some code by AI //
// //
// This program is free software; you can redistribute it and/or modify //
// it under the terms of the GNU General Public License as published by //
// the Free Software Foundation as version 3 of the License, or //
// (at your option) any later version. //
// //
// This program is distributed in the hope that it will be useful, //
// but WITHOUT ANY WARRANTY; without even the implied warranty of //
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //
// GNU General Public License V3 for more details. //
// //
// You should have received a copy of the GNU General Public License //
// along with this program. If not, see <http://www.gnu.org/licenses/>. //
///////////////////////////////////////////////////////////////////////////////////
#include <QColor>
#include <algorithm>
#include <cmath>
#include "audio/audiodevicemanager.h"
#include "settings/serializable.h"
#include "util/simpleserializer.h"
#include "selcaldemodsettings.h"
#include "selcaldecoder.h"
SELCALDemodSettings::SELCALDemodSettings()
{
resetToDefaults();
}
void SELCALDemodSettings::resetToDefaults()
{
m_inputFrequencyOffset = 0;
m_rfBandwidth = 3000.0f;
m_modulation = 0;
m_toneFrequencyOffset = 0.0f;
m_autoToneFrequencyOffset = true;
m_threshold = SELCALDecoder::m_defaultThreshold;
m_volume = 1.0f;
m_audioMute = false;
m_squelch = -80;
m_audioDeviceName = AudioDeviceManager::m_defaultDeviceName;
m_filter = QString();
m_udpEnabled = false;
m_udpAddress = QStringLiteral("127.0.0.1");
m_udpPort = 9999;
m_logFilename = QStringLiteral("selcal_log.csv");
m_logEnabled = false;
m_rgbColor = QColor(181, 230, 29).rgb();
m_title = QStringLiteral("SELCAL Demodulator");
m_streamIndex = 0;
m_useReverseAPI = false;
m_reverseAPIAddress = QStringLiteral("127.0.0.1");
m_reverseAPIPort = 8888;
m_reverseAPIDeviceIndex = 0;
m_reverseAPIChannelIndex = 0;
m_workspaceIndex = 0;
m_geometryBytes = QByteArray();
m_hidden = false;
m_columnIndexes.clear();
m_columnSizes.clear();
for (int i = 0; i < m_columns; ++i)
{
m_columnIndexes.append(i);
m_columnSizes.append(-1);
}
}
void SELCALDemodSettings::normalize()
{
m_modulation = m_modulation == AM ? AM : USB;
m_rfBandwidth = std::isfinite(m_rfBandwidth) ? std::clamp(m_rfBandwidth, 2000.0f, 6000.0f) : 3000.0f;
if (m_modulation == USB) {
m_rfBandwidth = std::min(m_rfBandwidth, 3600.0f);
}
m_toneFrequencyOffset = std::isfinite(m_toneFrequencyOffset) ? std::clamp(m_toneFrequencyOffset, -100.0f, 100.0f) : 0;
m_threshold = std::isfinite(m_threshold) ? std::clamp(m_threshold, 6.0f, 20.0f) : static_cast<Real>(SELCALDecoder::m_defaultThreshold);
m_volume = std::isfinite(m_volume) ? std::clamp(m_volume, 0.0f, 10.0f) : 1;
m_streamIndex = std::max(0, m_streamIndex);
m_squelch = std::clamp(m_squelch, -100, 0);
if (!m_udpPort || m_udpPort > 65535) {
m_udpPort = 9999;
}
if (!m_reverseAPIPort || m_reverseAPIPort > 65535) {
m_reverseAPIPort = 8888;
}
m_reverseAPIDeviceIndex = std::min(m_reverseAPIDeviceIndex, 99u);
m_reverseAPIChannelIndex = std::min(m_reverseAPIChannelIndex, 99u);
if (m_columnIndexes.size() != m_columns || m_columnSizes.size() != m_columns)
{
m_columnIndexes.clear();
m_columnSizes.clear();
for (int i = 0; i < m_columns; ++i)
{
m_columnIndexes.append(i);
m_columnSizes.append(-1);
}
}
bool used[m_columns] = {};
bool valid = true;
for (int i = 0; i < m_columns; ++i)
{
int index = m_columnIndexes[i];
if (index < 0 || index >= m_columns || used[index]) {
valid = false;
} else {
used[index] = true;
}
m_columnSizes[i] = std::clamp(m_columnSizes[i], -1, 10000);
}
if (!valid)
{
for (int i = 0; i < m_columns; ++i) {
m_columnIndexes[i] = i;
}
}
}
QByteArray SELCALDemodSettings::serialize() const
{
SimpleSerializer s(1);
s.writeS32(1, m_inputFrequencyOffset);
s.writeFloat(2, m_rfBandwidth);
s.writeS32(3, m_modulation);
s.writeFloat(4, m_toneFrequencyOffset);
s.writeBool(30, m_autoToneFrequencyOffset);
s.writeFloat(32, m_threshold);
s.writeFloat(6, m_volume);
s.writeBool(7, m_audioMute);
s.writeS32(31, m_squelch);
s.writeString(8, m_audioDeviceName);
s.writeString(9, m_filter);
s.writeBool(10, m_udpEnabled);
s.writeString(11, m_udpAddress);
s.writeU32(12, m_udpPort);
s.writeString(13, m_logFilename);
s.writeBool(14, m_logEnabled);
s.writeU32(15, m_rgbColor);
s.writeString(16, m_title);
s.writeS32(17, m_streamIndex);
s.writeBool(18, m_useReverseAPI);
s.writeString(19, m_reverseAPIAddress);
s.writeU32(20, m_reverseAPIPort);
s.writeU32(21, m_reverseAPIDeviceIndex);
s.writeU32(22, m_reverseAPIChannelIndex);
s.writeS32(23, m_workspaceIndex);
s.writeBlob(24, m_geometryBytes);
s.writeBool(25, m_hidden);
s.writeList(28, m_columnIndexes);
s.writeList(29, m_columnSizes);
if (m_channelMarker) {
s.writeBlob(40, m_channelMarker->serialize());
}
if (m_rollupState) {
s.writeBlob(41, m_rollupState->serialize());
}
if (m_spectrumGUI) {
s.writeBlob(42, m_spectrumGUI->serialize());
}
return s.final();
}
bool SELCALDemodSettings::deserialize(const QByteArray& data)
{
SimpleDeserializer d(data);
resetToDefaults();
if (!d.isValid() || d.getVersion() != 1) {
return false;
}
d.readS32(1, &m_inputFrequencyOffset, 0);
d.readFloat(2, &m_rfBandwidth, 3000.0f);
d.readS32(3, &m_modulation, 0);
d.readFloat(4, &m_toneFrequencyOffset, 0.0f);
d.readBool(30, &m_autoToneFrequencyOffset, true);
d.readFloat(32, &m_threshold, SELCALDecoder::m_defaultThreshold);
d.readFloat(6, &m_volume, 1.0f);
d.readBool(7, &m_audioMute, false);
d.readS32(31, &m_squelch, -80);
d.readString(8, &m_audioDeviceName, AudioDeviceManager::m_defaultDeviceName);
d.readString(9, &m_filter, QString());
d.readBool(10, &m_udpEnabled, false);
d.readString(11, &m_udpAddress, QStringLiteral("127.0.0.1"));
d.readU32(12, &m_udpPort, 9999);
d.readString(13, &m_logFilename, QStringLiteral("selcal_log.csv"));
d.readBool(14, &m_logEnabled, false);
d.readU32(15, &m_rgbColor, QColor(181, 230, 29).rgb());
d.readString(16, &m_title, QStringLiteral("SELCAL Demodulator"));
d.readS32(17, &m_streamIndex, 0);
d.readBool(18, &m_useReverseAPI, false);
d.readString(19, &m_reverseAPIAddress, QStringLiteral("127.0.0.1"));
d.readU32(20, &m_reverseAPIPort, 8888);
d.readU32(21, &m_reverseAPIDeviceIndex, 0);
d.readU32(22, &m_reverseAPIChannelIndex, 0);
d.readS32(23, &m_workspaceIndex, 0);
d.readBlob(24, &m_geometryBytes);
d.readBool(25, &m_hidden, false);
d.readList(28, &m_columnIndexes);
d.readList(29, &m_columnSizes);
QByteArray blob;
if (m_channelMarker && d.readBlob(40, &blob)) {
m_channelMarker->deserialize(blob);
}
if (m_rollupState && d.readBlob(41, &blob)) {
m_rollupState->deserialize(blob);
}
if (m_spectrumGUI && d.readBlob(42, &blob)) {
m_spectrumGUI->deserialize(blob);
}
normalize();
return true;
}
void SELCALDemodSettings::applySettings(const QStringList& keys, const SELCALDemodSettings& settings)
{
if (keys.contains("inputFrequencyOffset")) {
m_inputFrequencyOffset = settings.m_inputFrequencyOffset;
}
if (keys.contains("rfBandwidth")) {
m_rfBandwidth = settings.m_rfBandwidth;
}
if (keys.contains("modulation")) {
m_modulation = settings.m_modulation;
}
if (keys.contains("toneFrequencyOffset")) {
m_toneFrequencyOffset = settings.m_toneFrequencyOffset;
}
if (keys.contains("autoToneFrequencyOffset")) {
m_autoToneFrequencyOffset = settings.m_autoToneFrequencyOffset;
}
if (keys.contains("threshold")) {
m_threshold = settings.m_threshold;
}
if (keys.contains("volume")) {
m_volume = settings.m_volume;
}
if (keys.contains("audioMute")) {
m_audioMute = settings.m_audioMute;
}
if (keys.contains("squelch")) {
m_squelch = settings.m_squelch;
}
if (keys.contains("audioDeviceName")) {
m_audioDeviceName = settings.m_audioDeviceName;
}
if (keys.contains("filter")) {
m_filter = settings.m_filter;
}
if (keys.contains("udpEnabled")) {
m_udpEnabled = settings.m_udpEnabled;
}
if (keys.contains("udpAddress")) {
m_udpAddress = settings.m_udpAddress;
}
if (keys.contains("udpPort")) {
m_udpPort = settings.m_udpPort;
}
if (keys.contains("logFilename")) {
m_logFilename = settings.m_logFilename;
}
if (keys.contains("logEnabled")) {
m_logEnabled = settings.m_logEnabled;
}
if (keys.contains("rgbColor")) {
m_rgbColor = settings.m_rgbColor;
}
if (keys.contains("title")) {
m_title = settings.m_title;
}
if (keys.contains("streamIndex")) {
m_streamIndex = settings.m_streamIndex;
}
if (keys.contains("useReverseAPI")) {
m_useReverseAPI = settings.m_useReverseAPI;
}
if (keys.contains("reverseAPIAddress")) {
m_reverseAPIAddress = settings.m_reverseAPIAddress;
}
if (keys.contains("reverseAPIPort")) {
m_reverseAPIPort = settings.m_reverseAPIPort;
}
if (keys.contains("reverseAPIDeviceIndex")) {
m_reverseAPIDeviceIndex = settings.m_reverseAPIDeviceIndex;
}
if (keys.contains("reverseAPIChannelIndex")) {
m_reverseAPIChannelIndex = settings.m_reverseAPIChannelIndex;
}
if (keys.contains("workspaceIndex")) {
m_workspaceIndex = settings.m_workspaceIndex;
}
if (keys.contains("geometryBytes")) {
m_geometryBytes = settings.m_geometryBytes;
}
if (keys.contains("hidden")) {
m_hidden = settings.m_hidden;
}
normalize();
}
QString SELCALDemodSettings::getDebugString(const QStringList& keys, bool force) const
{
QStringList result;
if (force || keys.contains("inputFrequencyOffset")) {
result << QString("inputFrequencyOffset: %1").arg(m_inputFrequencyOffset);
}
if (force || keys.contains("rfBandwidth")) {
result << QString("rfBandwidth: %1").arg(m_rfBandwidth);
}
if (force || keys.contains("modulation")) {
result << QString("modulation: %1").arg(m_modulation);
}
if (force || keys.contains("toneFrequencyOffset")) {
result << QString("toneFrequencyOffset: %1").arg(m_toneFrequencyOffset);
}
if (force || keys.contains("autoToneFrequencyOffset")) {
result << QString("autoToneFrequencyOffset: %1").arg(m_autoToneFrequencyOffset);
}
if (force || keys.contains("threshold")) {
result << QString("threshold: %1").arg(m_threshold);
}
if (force || keys.contains("volume")) {
result << QString("volume: %1").arg(m_volume);
}
if (force || keys.contains("audioMute")) {
result << QString("audioMute: %1").arg(m_audioMute);
}
if (force || keys.contains("squelch")) {
result << QString("squelch: %1").arg(m_squelch);
}
if (force || keys.contains("audioDeviceName")) {
result << QString("audioDeviceName: %1").arg(m_audioDeviceName);
}
if (force || keys.contains("filter")) {
result << QString("filter: %1").arg(m_filter);
}
if (force || keys.contains("udpEnabled")) {
result << QString("udpEnabled: %1").arg(m_udpEnabled);
}
if (force || keys.contains("udpAddress")) {
result << QString("udpAddress: %1").arg(m_udpAddress);
}
if (force || keys.contains("udpPort")) {
result << QString("udpPort: %1").arg(m_udpPort);
}
if (force || keys.contains("logFilename")) {
result << QString("logFilename: %1").arg(m_logFilename);
}
if (force || keys.contains("logEnabled")) {
result << QString("logEnabled: %1").arg(m_logEnabled);
}
if (force || keys.contains("rgbColor")) {
result << QString("rgbColor: %1").arg(m_rgbColor);
}
if (force || keys.contains("title")) {
result << QString("title: %1").arg(m_title);
}
if (force || keys.contains("streamIndex")) {
result << QString("streamIndex: %1").arg(m_streamIndex);
}
if (force || keys.contains("useReverseAPI")) {
result << QString("useReverseAPI: %1").arg(m_useReverseAPI);
}
if (force || keys.contains("reverseAPIAddress")) {
result << QString("reverseAPIAddress: %1").arg(m_reverseAPIAddress);
}
if (force || keys.contains("reverseAPIPort")) {
result << QString("reverseAPIPort: %1").arg(m_reverseAPIPort);
}
if (force || keys.contains("reverseAPIDeviceIndex")) {
result << QString("reverseAPIDeviceIndex: %1").arg(m_reverseAPIDeviceIndex);
}
if (force || keys.contains("reverseAPIChannelIndex")) {
result << QString("reverseAPIChannelIndex: %1").arg(m_reverseAPIChannelIndex);
}
if (force || keys.contains("workspaceIndex")) {
result << QString("workspaceIndex: %1").arg(m_workspaceIndex);
}
if (force || keys.contains("hidden")) {
result << QString("hidden: %1").arg(m_hidden);
}
return result.join(" ");
}

99
plugins/channelrx/demodselcal/selcaldemodsettings.h

@ -0,0 +1,99 @@ @@ -0,0 +1,99 @@
///////////////////////////////////////////////////////////////////////////////////
// Copyright (C) 2021-2022 Edouard Griffiths, F4EXB <f4exb06@gmail.com> //
// Copyright (C) 2026 Jon Beniston, M7RCE <jon@beniston.com> //
// Some code by AI //
// //
// This program is free software; you can redistribute it and/or modify //
// it under the terms of the GNU General Public License as published by //
// the Free Software Foundation as version 3 of the License, or //
// (at your option) any later version. //
// //
// This program is distributed in the hope that it will be useful, //
// but WITHOUT ANY WARRANTY; without even the implied warranty of //
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //
// GNU General Public License V3 for more details. //
// //
// You should have received a copy of the GNU General Public License //
// along with this program. If not, see <http://www.gnu.org/licenses/>. //
///////////////////////////////////////////////////////////////////////////////////
#ifndef INCLUDE_SELCALDEMODSETTINGS_H
#define INCLUDE_SELCALDEMODSETTINGS_H
#include <QByteArray>
#include <QList>
#include <QStringList>
#include "dsp/dsptypes.h"
class Serializable;
struct SELCALDemodSettings {
enum Modulation {
USB = 0,
AM = 1
};
static constexpr int SELCALDEMOD_CHANNEL_SAMPLE_RATE = 8000;
static constexpr int m_columns = 9;
static constexpr int SELCALDEMOD_SPECTRUM_SAMPLE_RATE = 4000;
qint32 m_inputFrequencyOffset;
Real m_rfBandwidth;
int m_modulation;
Real m_toneFrequencyOffset;
bool m_autoToneFrequencyOffset;
Real m_threshold; // dB
Real m_volume;
bool m_audioMute;
int m_squelch;
QString m_audioDeviceName;
QString m_filter;
bool m_udpEnabled;
QString m_udpAddress;
quint32 m_udpPort;
QString m_logFilename;
bool m_logEnabled;
quint32 m_rgbColor;
QString m_title;
int m_streamIndex;
bool m_useReverseAPI;
QString m_reverseAPIAddress;
quint32 m_reverseAPIPort;
quint32 m_reverseAPIDeviceIndex;
quint32 m_reverseAPIChannelIndex;
int m_workspaceIndex;
QByteArray m_geometryBytes;
bool m_hidden;
Serializable *m_channelMarker = nullptr;
Serializable *m_rollupState = nullptr;
Serializable *m_spectrumGUI = nullptr;
QList<int> m_columnIndexes;
QList<int> m_columnSizes;
SELCALDemodSettings();
void resetToDefaults();
void normalize();
QByteArray serialize() const;
bool deserialize(const QByteArray& data);
void applySettings(const QStringList& keys, const SELCALDemodSettings& settings);
QString getDebugString(const QStringList& keys, bool force = false) const;
void setChannelMarker(Serializable *marker)
{
m_channelMarker = marker;
}
void setRollupState(Serializable *state)
{
m_rollupState = state;
}
void setSpectrumGUI(Serializable *spectrumGUI)
{
m_spectrumGUI = spectrumGUI;
}
};
#endif

536
plugins/channelrx/demodselcal/selcaldemodsink.cpp

@ -0,0 +1,536 @@ @@ -0,0 +1,536 @@
///////////////////////////////////////////////////////////////////////////////////
// Copyright (C) 2021-2022 Edouard Griffiths, F4EXB <f4exb06@gmail.com> //
// Copyright (C) 2026 Jon Beniston, M7RCE <jon@beniston.com> //
// Some code by AI //
// //
// This program is free software; you can redistribute it and/or modify //
// it under the terms of the GNU General Public License as published by //
// the Free Software Foundation as version 3 of the License, or //
// (at your option) any later version. //
// //
// This program is distributed in the hope that it will be useful, //
// but WITHOUT ANY WARRANTY; without even the implied warranty of //
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //
// GNU General Public License V3 for more details. //
// //
// You should have received a copy of the GNU General Public License //
// along with this program. If not, see <http://www.gnu.org/licenses/>. //
///////////////////////////////////////////////////////////////////////////////////
#include <algorithm>
#include <cmath>
#include <limits>
#include "selcaldemodsink.h"
#include "selcalmessages.h"
#include "dsp/fftfilt.h"
#include "dsp/spectrumvis.h"
#include "util/db.h"
#include "maincore.h"
#include "dsp/datafifo.h"
SELCALDemodSink::SELCALDemodSink(SELCALDemod *) :
m_audioFifo(48000)
{
m_demodBuffer.resize(4096);
m_spectrumBuffer.reserve(256);
m_decoder.setSampleHandler([this](float sample) {
if (!m_spectrumSink) {
return;
}
m_spectrumBuffer.emplace_back(static_cast<FixReal>(std::clamp(sample, -1.0f, 1.0f) * SDR_RX_SCALEF), 0);
if (m_spectrumBuffer.size() >= 256)
{
// Real audio, displayed from 0 Hz to half the sample rate (as in FT8DemodSink)
m_spectrumSink->feed(m_spectrumBuffer.begin(), m_spectrumBuffer.end(), true);
m_spectrumBuffer.clear();
}
});
m_decoder.setCallHandler([this](const SELCALDecoder::Call& result) {
if (!m_messageQueueToChannel) {
return;
}
SELCALMessages::Call call;
call.m_code = QString::fromStdString(result.m_code);
// Capture frequency at decode time, before a later retune can be applied.
call.m_frequency = m_centerFrequency + m_settings.m_inputFrequencyOffset;
call.m_dateTime = QDateTime::currentDateTimeUtc().addMSecs(
-static_cast<qint64>((m_audioSampleCount - result.m_startSample) * 1000 / SELCALDecoder::m_sampleRate));
if (trackingCarrier()) {
call.m_dateTime = call.m_dateTime.addMSecs(-static_cast<qint64>(m_carrierDelay.size() * 1000 / SELCALDecoder::m_sampleRate));
}
// Measured over the bursts, excluding the gap.
double first = burstPower(result.m_startSample, result.m_firstEndSample);
double second = burstPower(result.m_secondStartSample, result.m_endSample);
call.m_rssi = CalcDb::dbPower(first > 0 && second > 0 ? (first + second) / 2 : m_lastMagSq);
call.m_snr = result.m_snr;
call.m_toneFrequencyOffset = result.m_frequencyOffset;
m_messageQueueToChannel->push(SELCALMessages::MsgCall::create(call));
});
applyChannelSettings(48000, 0, true);
applyAudioSampleRate(48000);
}
SELCALDemodSink::~SELCALDemodSink() = default;
void SELCALDemodSink::configureFilter(bool recreate)
{
// Same fftfilt sideband extraction used by SSBDemodSink. The audio band
// includes the lowest legacy tone and the highest SELCAL-32 tone. Updating
// an existing filter keeps its buffered audio.
if (recreate || !m_filter) {
m_filter = std::make_unique<fftfilt>(m_filterLength);
}
if (m_settings.m_modulation == SELCALDemodSettings::USB) {
m_filter->create_filter(100.0f / 8000, m_settings.m_rfBandwidth / 8000);
}
else
{
m_filter->create_dsb_filter(m_settings.m_rfBandwidth / (2 * 8000));
}
}
bool SELCALDemodSink::trackingCarrier() const
{
// AM always has a carrier, used for coherent detection.
return m_settings.m_modulation == SELCALDemodSettings::AM || m_settings.m_autoToneFrequencyOffset;
}
void SELCALDemodSink::updateDecoderOffset()
{
double offset = m_settings.m_toneFrequencyOffset;
double uncertainty = 2.0;
if (m_settings.m_modulation == SELCALDemodSettings::USB)
{
// A measured carrier gives the tuning error precisely. Otherwise,
// search for the tones around the manual offset, or around the carrier
// offset for a while after a fade or the end of a transmission.
if (m_settings.m_autoToneFrequencyOffset && m_carrierTracker.locked())
{
offset = m_carrierOffset;
}
else
{
if (m_settings.m_autoToneFrequencyOffset && m_carrierHoldover > 0) {
offset = m_carrierOffset;
}
uncertainty = SELCALDecoder::m_searchRange;
}
}
if (offset != m_decoderOffset || uncertainty != m_decoderUncertainty)
{
m_decoderOffset = offset;
m_decoderUncertainty = uncertainty;
m_decoder.setFrequencyOffset(offset, uncertainty);
}
}
void SELCALDemodSink::resetTuning()
{
// Retuning invalidates the measured carrier and any call in progress, but
// monitoring audio continues uninterrupted.
m_decoderOffset = m_settings.m_toneFrequencyOffset;
m_decoderUncertainty = SELCALDecoder::m_searchRange;
m_decoder.setFrequencyOffset(m_decoderOffset, m_decoderUncertainty);
m_decoder.reset();
m_carrierTracker.setRange(m_settings.m_modulation == SELCALDemodSettings::AM ? 1000.0 : SELCALCarrierTracker::m_defaultRange);
m_carrierTracker.reset();
m_carrierOffset = 0;
m_carrierHoldover = 0;
m_carrierTail = 0;
m_carrierNco.setFreq(0, SELCALDecoder::m_sampleRate);
m_carrierPhasor = {};
m_amCarrier = {};
restartSampleCount();
if (m_messageQueueToChannel)
{
SELCALMessages::Status status;
status.m_toneFrequencyOffset = m_decoder.frequencyOffset();
m_messageQueueToChannel->push(SELCALMessages::MsgStatus::create(status));
}
}
void SELCALDemodSink::restartSampleCount()
{
// Follows a decoder reset, which restarts the decoder's sample count. Keep
// the samples buffered in the receive filter between the counts, and
// discard power history aligned with the old count.
std::uint64_t buffered = m_filterInputCount - m_audioSampleCount;
m_audioSampleCount = 0;
m_filterInputCount = buffered;
m_powerBlocks.fill(0);
m_powerBlockSum = 0;
m_powerBlockSamples = 0;
}
void SELCALDemodSink::reset()
{
resetTuning();
m_carrierDelay.fill({});
m_carrierDelayPosition = 0;
m_filterInputCount = 0;
m_statusCounter = 0;
m_dc = 0;
m_audioPower = 1e-6;
m_squelchPower = 1e-12;
m_squelchCount = 0;
m_squelchOpen = false;
m_distanceRemain = 0;
m_audioDistanceRemain = 0;
m_demodBufferFill = 0;
m_spectrumBuffer.clear();
m_audioBuffer.clear();
m_audioFifo.clear();
m_magSqSum = m_magSqPeak = 0;
m_magSqCount = 0;
m_lastMagSq = 1e-12;
configureFilter(true);
}
void SELCALDemodSink::applyChannelSettings(int sampleRate, int frequencyOffset, bool force)
{
if (sampleRate <= 0) {
return;
}
if (force || sampleRate != m_channelSampleRate)
{
m_channelSampleRate = sampleRate;
m_channelFrequencyOffset = frequencyOffset;
m_nco.setFreq(-frequencyOffset, sampleRate);
m_interpolator.create(16, sampleRate, std::min(3600.0f, sampleRate * 0.45f));
m_distance = static_cast<Real>(sampleRate) / SELCALDecoder::m_sampleRate;
reset();
}
else if (frequencyOffset != m_channelFrequencyOffset)
{
// As in SSBDemodSink, retuning only moves the NCO.
m_channelFrequencyOffset = frequencyOffset;
m_nco.setFreq(-frequencyOffset, sampleRate);
resetTuning();
// Audio from before retuning is still in the carrier delay and receive
// filter. Don't learn its steady signals as the new channel's background.
m_decoder.holdLearning((trackingCarrier() ? m_carrierDelay.size() : 0) + 512);
}
}
void SELCALDemodSink::applySettings(const QStringList& keys, const SELCALDemodSettings& settings, bool force)
{
SELCALDemodSettings next = m_settings;
if (force) {
next = settings;
}
else
{
next.applySettings(keys, settings);
}
next.normalize();
// Changing modulation or carrier tracking changes the signal path, so restarts it.
// Retuning is applied by applyChannelSettings.
bool changed = force || next.m_modulation != m_settings.m_modulation || next.m_autoToneFrequencyOffset != m_settings.m_autoToneFrequencyOffset ||
next.m_streamIndex != m_settings.m_streamIndex;
bool decoderChanged = next.m_toneFrequencyOffset != m_settings.m_toneFrequencyOffset || next.m_threshold != m_settings.m_threshold;
bool bandwidthChanged = next.m_rfBandwidth != m_settings.m_rfBandwidth;
m_squelchLevel = CalcDb::powerFromdB(next.m_squelch);
m_settings = next;
if (changed)
{
m_decoder.configure(next.m_toneFrequencyOffset, next.m_threshold);
reset();
}
else
{
if (decoderChanged)
{
// Restarts decoding, keeping the carrier measurement.
m_decoder.configure(next.m_toneFrequencyOffset, next.m_threshold);
restartSampleCount();
m_decoderOffset = std::numeric_limits<double>::quiet_NaN();
updateDecoderOffset();
}
if (bandwidthChanged) {
configureFilter(false);
}
}
}
void SELCALDemodSink::applyAudioSampleRate(int sampleRate)
{
if (sampleRate <= 0) {
return;
}
m_audioSampleRate = sampleRate;
m_audioInterpolator.create(16, 8000, 3300);
m_audioDistance = static_cast<Real>(8000) / sampleRate;
m_audioDistanceRemain = 0;
m_demodBufferFill = 0;
m_audioBuffer.clear();
m_audioFifo.clear();
// The demod stream is at the audio rate, so tell the Demod Analyzer and
// Denoiser features of a change, as AMDemodSink does.
if (m_channel)
{
QList<ObjectPipe *> pipes;
MainCore::instance()->getMessagePipes().getMessagePipes(m_channel, "reportdemod", pipes);
for (const auto& pipe : pipes)
{
auto *messageQueue = qobject_cast<MessageQueue *>(pipe->m_element);
if (messageQueue) {
messageQueue->push(MainCore::MsgChannelDemodReport::create(m_channel, sampleRate));
}
}
}
}
void SELCALDemodSink::feed(const SampleVector::const_iterator& begin, const SampleVector::const_iterator& end)
{
for (auto it = begin; it != end; ++it)
{
Complex sample(it->real() / static_cast<float>(SDR_RX_SCALEF), it->imag() / static_cast<float>(SDR_RX_SCALEF));
sample *= m_nco.nextIQ();
Complex output;
if (m_distance < 1) {
while (!m_interpolator.interpolate(&m_distanceRemain, sample, &output))
{
processOneSample(output);
m_distanceRemain += m_distance;
}
}
else if (m_interpolator.decimate(&m_distanceRemain, sample, &output))
{
processOneSample(output);
m_distanceRemain += m_distance;
}
}
if (!m_audioBuffer.empty())
{
m_audioFifo.write(reinterpret_cast<const quint8 *>(m_audioBuffer.data()), m_audioBuffer.size());
m_audioBuffer.clear();
}
}
void SELCALDemodSink::processOneSample(const Complex& sample)
{
bool usb = m_settings.m_modulation == SELCALDemodSettings::USB;
bool tracking = trackingCarrier();
Complex delayed = sample;
if (tracking)
{
m_carrierTracker.feed(sample);
if (m_carrierTracker.locked() && std::abs(m_carrierTracker.offset() - m_carrierOffset) > 0.05)
{
m_carrierOffset = m_carrierTracker.offset();
m_carrierNco.setFreq(-m_carrierOffset, SELCALDecoder::m_sampleRate);
}
if (m_carrierTracker.locked())
{
m_carrierHoldover = m_carrierHoldoverLength;
m_carrierTail = m_carrierDelay.size();
}
else
{
m_carrierHoldover = std::max(m_carrierHoldover - 1, 0);
m_carrierTail = std::max(m_carrierTail - 1, 0);
}
// Let carrier acquisition precede the corresponding audio. Otherwise
// the first pair could be acquired without the carrier's correction.
delayed = m_carrierDelay[m_carrierDelayPosition];
m_carrierDelay[m_carrierDelayPosition] = sample;
m_carrierDelayPosition = (m_carrierDelayPosition + 1) % m_carrierDelay.size();
}
updateDecoderOffset();
double power = std::norm(sample);
m_magSqSum += power;
m_magSqPeak = std::max(m_magSqPeak, power);
++m_magSqCount;
m_lastMagSq += (power - m_lastMagSq) * 0.001;
// Squelch gates the monitoring audio, which is delayed with the carrier.
m_squelchPower += (std::norm(delayed) - m_squelchPower) * 0.01;
// Power aligned with the decoder's audio, which is delayed with the carrier.
m_powerBlockSum += std::norm(delayed);
++m_powerBlockSamples;
if (++m_filterInputCount % m_powerBlockSize == 0)
{
m_powerBlocks[(m_filterInputCount / m_powerBlockSize - 1) % m_powerBlocks.size()] = m_powerBlockSum / m_powerBlockSamples;
m_powerBlockSum = 0;
m_powerBlockSamples = 0;
}
// The carrier is measured ahead of the delayed audio, so the audio still
// contains the carrier for the delay after it is lost.
bool locked = tracking && (m_carrierTracker.locked() || m_carrierTail > 0);
Complex filtered = delayed;
if (locked)
{
Complex rotation = m_carrierNco.nextIQ();
if (usb)
{
// Remove the measured carrier before sideband extraction. Near +100 Hz
// a strong carrier can otherwise leak through the USB filter's lower
// transition band and overwhelm the two audio tones.
m_carrierPhasor += (filtered * rotation - m_carrierPhasor) * 0.01f;
filtered -= m_carrierPhasor * std::conj(rotation);
}
else
{
// Move the AM carrier to 0 Hz for coherent detection.
filtered *= rotation;
}
}
else
{
m_carrierPhasor = {};
m_amCarrier = {};
}
fftfilt::cmplx *output = nullptr;
int count = usb ? m_filter->runSSB(filtered, &output, true, false) : m_filter->runDSB(filtered, &output, true);
for (int i = 0; i < count; ++i)
{
float audio;
if (usb)
{
// Recover the real audio from the analytic sideband.
audio = output[i].real() + output[i].imag();
}
else if (locked)
{
// Coherent AM detection: the component in phase with the carrier.
// Unlike envelope detection, it has no threshold at low SNR and
// rejects the quadrature noise.
m_amCarrier += (output[i] - m_amCarrier) * 0.002f;
float magnitude = std::abs(m_amCarrier);
audio = magnitude > 0 ? (output[i] * std::conj(m_amCarrier)).real() / magnitude : 0;
}
else
{
audio = std::abs(output[i]);
}
// Carrier/DC removal, as in AMDemodSink.
m_dc += (audio - m_dc) * 0.001;
processAudio(audio - m_dc);
}
}
void SELCALDemodSink::processAudio(float sample)
{
++m_audioSampleCount;
m_decoder.feed(sample);
monitor(sample);
if (++m_statusCounter >= 1600)
{
m_statusCounter = 0;
if (m_messageQueueToChannel)
{
SELCALMessages::Status status;
status.m_state = m_decoder.state();
status.m_carrierLocked = trackingCarrier() && m_carrierTracker.locked();
status.m_squelchOpen = m_squelchOpen;
status.m_carrierFrequencyOffset = m_carrierTracker.offset();
status.m_toneFrequencyOffset = m_decoder.frequencyOffset();
status.m_pair = m_decoder.pair();
status.m_levels = m_decoder.levels();
m_messageQueueToChannel->push(SELCALMessages::MsgStatus::create(status));
}
}
}
void SELCALDemodSink::monitor(float sample)
{
if (m_squelchPower >= m_squelchLevel) {
m_squelchCount = SELCALDecoder::m_sampleRate / 10;
}
else if (m_squelchCount > 0) {
--m_squelchCount;
}
m_squelchOpen = m_squelchCount > 0;
m_audioPower += (sample * sample - m_audioPower) * 0.0005;
float gain = std::min(1000.0, 0.15 / std::sqrt(std::max(m_audioPower, 1e-10)));
Complex input(!m_squelchOpen ? 0 : sample * gain * m_settings.m_volume, 0), output;
auto append = [this](const Complex& value) {
qint16 audio = std::clamp(value.real() * 32768.0f, -32768.0f, 32767.0f);
qint16 heard = m_settings.m_audioMute ? 0 : audio;
m_audioBuffer.push_back({heard, heard});
if (m_audioBuffer.size() >= 4096)
{
m_audioFifo.write(reinterpret_cast<const quint8 *>(m_audioBuffer.data()), m_audioBuffer.size());
m_audioBuffer.clear();
}
// As in AMDemodSink, the demod stream for the Demod Analyzer and Denoiser
// features carries the monitoring audio before muting.
m_demodBuffer[m_demodBufferFill++] = audio;
if (m_demodBufferFill == m_demodBuffer.size()) {
writeDemod();
}
};
if (m_audioDistance < 1) {
while (!m_audioInterpolator.interpolate(&m_audioDistanceRemain, input, &output))
{
append(output);
m_audioDistanceRemain += m_audioDistance;
}
}
else if (m_audioInterpolator.decimate(&m_audioDistanceRemain, input, &output))
{
append(output);
m_audioDistanceRemain += m_audioDistance;
}
}
double SELCALDemodSink::burstPower(std::uint64_t start, std::uint64_t end) const
{
// Decoder sample indices count the receive filter's output. Overlap-add
// filtering outputs each block for the inputs just received, delayed by the
// linear phase filter's group delay.
constexpr std::uint64_t groupDelay = m_filterLength / 4;
start = start > groupDelay ? start - groupDelay : 0;
end = end > groupDelay ? end - groupDelay : 0;
std::uint64_t blocks = m_filterInputCount / m_powerBlockSize;
std::uint64_t first = start / m_powerBlockSize;
std::uint64_t last = std::min(end / m_powerBlockSize, blocks);
first = std::max(first, blocks > m_powerBlocks.size() ? blocks - m_powerBlocks.size() : 0);
if (end <= start || first >= last) {
return 0;
}
double sum = 0;
for (std::uint64_t block = first; block < last; ++block) {
sum += m_powerBlocks[block % m_powerBlocks.size()];
}
return sum / (last - first);
}
void SELCALDemodSink::writeDemod()
{
if (m_channel)
{
QList<ObjectPipe *> pipes;
MainCore::instance()->getDataPipes().getDataPipes(m_channel, "demod", pipes);
for (auto *pipe : pipes)
{
auto *fifo = qobject_cast<DataFifo *>(pipe->m_element);
if (fifo) {
fifo->write(reinterpret_cast<const quint8 *>(m_demodBuffer.constData()), m_demodBuffer.size() * sizeof(qint16),
DataFifo::DataTypeI16);
}
}
}
m_demodBufferFill = 0;
}
void SELCALDemodSink::getMagSqLevels(double& average, double& peak, int& count)
{
count = m_magSqCount;
average = count ? m_magSqSum / count : m_lastMagSq;
peak = count ? m_magSqPeak : average;
m_magSqSum = m_magSqPeak = 0;
m_magSqCount = 0;
}

128
plugins/channelrx/demodselcal/selcaldemodsink.h

@ -0,0 +1,128 @@ @@ -0,0 +1,128 @@
///////////////////////////////////////////////////////////////////////////////////
// Copyright (C) 2021-2022 Edouard Griffiths, F4EXB <f4exb06@gmail.com> //
// Copyright (C) 2026 Jon Beniston, M7RCE <jon@beniston.com> //
// Some code by AI //
// //
// This program is free software; you can redistribute it and/or modify //
// it under the terms of the GNU General Public License as published by //
// the Free Software Foundation as version 3 of the License, or //
// (at your option) any later version. //
// //
// This program is distributed in the hope that it will be useful, //
// but WITHOUT ANY WARRANTY; without even the implied warranty of //
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //
// GNU General Public License V3 for more details. //
// //
// You should have received a copy of the GNU General Public License //
// along with this program. If not, see <http://www.gnu.org/licenses/>. //
///////////////////////////////////////////////////////////////////////////////////
#ifndef INCLUDE_SELCALDEMODSINK_H
#define INCLUDE_SELCALDEMODSINK_H
#include <array>
#include <memory>
#include "dsp/channelsamplesink.h"
#include "dsp/nco.h"
#include "dsp/interpolator.h"
#include "audio/audiofifo.h"
#include "util/messagequeue.h"
#include "selcaldemodsettings.h"
#include "selcaldecoder.h"
#include "selcalcarriertracker.h"
class fftfilt;
class ChannelAPI;
class SELCALDemod;
class SpectrumVis;
class SELCALDemodSink : public ChannelSampleSink {
public:
explicit SELCALDemodSink(SELCALDemod *demod = nullptr);
~SELCALDemodSink();
void feed(const SampleVector::const_iterator& begin, const SampleVector::const_iterator& end) override;
void applyChannelSettings(int sampleRate, int frequencyOffset, bool force = false);
void applySettings(const QStringList& keys, const SELCALDemodSettings& settings, bool force = false);
void applyAudioSampleRate(int sampleRate);
void reset();
void setMessageQueueToChannel(MessageQueue *queue) { m_messageQueueToChannel = queue; }
void setChannel(ChannelAPI *channel) { m_channel = channel; }
void setCenterFrequency(qint64 frequency) { m_centerFrequency = frequency; }
void setSpectrumSink(SpectrumVis *spectrumSink) { m_spectrumSink = spectrumSink; }
AudioFifo *getAudioFifo() { return &m_audioFifo; }
int getAudioSampleRate() const { return m_audioSampleRate; }
double getMagSq() const { return m_lastMagSq; }
void getMagSqLevels(double& average, double& peak, int& count);
private:
SELCALDemodSettings m_settings;
ChannelAPI *m_channel = nullptr;
MessageQueue *m_messageQueueToChannel = nullptr;
qint64 m_centerFrequency = 0;
int m_channelSampleRate = 48000;
int m_channelFrequencyOffset = 0;
NCO m_nco;
Interpolator m_interpolator;
Real m_distance = 6;
Real m_distanceRemain = 0;
std::unique_ptr<fftfilt> m_filter;
SELCALDecoder m_decoder;
double m_decoderOffset = 0;
double m_decoderUncertainty = 0;
SELCALCarrierTracker m_carrierTracker;
double m_carrierOffset = 0;
int m_carrierHoldover = 0; // Samples for which the last carrier offset is still used
int m_carrierTail = 0; // Delayed samples still to be processed with the lost carrier
NCO m_carrierNco;
Complex m_carrierPhasor{};
Complex m_amCarrier{};
std::array<Complex, SELCALCarrierTracker::latency()> m_carrierDelay{};
int m_carrierDelayPosition = 0;
SpectrumVis *m_spectrumSink = nullptr;
SampleVector m_spectrumBuffer;
double m_dc = 0;
double m_audioPower = 1e-6;
double m_squelchLevel = 1e-8;
double m_squelchPower = 1e-12;
int m_squelchCount = 0;
bool m_squelchOpen = false;
double m_magSqSum = 0;
double m_magSqPeak = 0;
double m_lastMagSq = 1e-12;
int m_magSqCount = 0;
std::uint64_t m_audioSampleCount = 0;
// Received power in 10 ms blocks, to measure the RSSI of each call's bursts.
static constexpr int m_powerBlockSize = 80;
static constexpr int m_filterLength = 512; // FFT length of the receive filter
static constexpr int m_carrierHoldoverLength = 10 * SELCALDecoder::m_sampleRate; // 10 s
std::array<double, 512> m_powerBlocks{};
double m_powerBlockSum = 0;
int m_powerBlockSamples = 0;
std::uint64_t m_filterInputCount = 0;
int m_statusCounter = 0;
AudioFifo m_audioFifo;
AudioVector m_audioBuffer;
int m_audioSampleRate = 48000;
Interpolator m_audioInterpolator;
Real m_audioDistance = 1.0f / 6;
Real m_audioDistanceRemain = 0;
QVector<qint16> m_demodBuffer;
int m_demodBufferFill = 0;
void processOneSample(const Complex& sample);
void processAudio(float sample);
void monitor(float sample);
void writeDemod();
void configureFilter(bool recreate);
void resetTuning();
void restartSampleCount();
double burstPower(std::uint64_t start, std::uint64_t end) const;
bool trackingCarrier() const;
void updateDecoderOffset();
};
#endif

52
plugins/channelrx/demodselcal/selcaldemodwebapiadapter.cpp

@ -0,0 +1,52 @@ @@ -0,0 +1,52 @@
///////////////////////////////////////////////////////////////////////////////////
// Copyright (C) 2021-2022 Edouard Griffiths, F4EXB <f4exb06@gmail.com> //
// Copyright (C) 2026 Jon Beniston, M7RCE <jon@beniston.com> //
// Some code by AI //
// //
// This program is free software; you can redistribute it and/or modify //
// it under the terms of the GNU General Public License as published by //
// the Free Software Foundation as version 3 of the License, or //
// (at your option) any later version. //
// //
// This program is distributed in the hope that it will be useful, //
// but WITHOUT ANY WARRANTY; without even the implied warranty of //
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //
// GNU General Public License V3 for more details. //
// //
// You should have received a copy of the GNU General Public License //
// along with this program. If not, see <http://www.gnu.org/licenses/>. //
///////////////////////////////////////////////////////////////////////////////////
#include "SWGChannelSettings.h"
#include "selcaldemod.h"
#include "selcaldemodwebapiadapter.h"
SELCALDemodWebAPIAdapter::SELCALDemodWebAPIAdapter()
{
}
SELCALDemodWebAPIAdapter::~SELCALDemodWebAPIAdapter()
{
}
int SELCALDemodWebAPIAdapter::webapiSettingsGet(SWGSDRangel::SWGChannelSettings& response, QString& errorMessage)
{
(void)errorMessage;
response.setSelcalDemodSettings(new SWGSDRangel::SWGSELCALDemodSettings());
response.getSelcalDemodSettings()->init();
SELCALDemod::webapiFormatChannelSettings(response, m_settings);
return 200;
}
int SELCALDemodWebAPIAdapter::webapiSettingsPutPatch(bool force, const QStringList& channelSettingsKeys,
SWGSDRangel::SWGChannelSettings& response, QString& errorMessage)
{
(void)force;
(void)errorMessage;
SELCALDemod::webapiUpdateChannelSettings(m_settings, channelSettingsKeys, response);
return 200;
}

50
plugins/channelrx/demodselcal/selcaldemodwebapiadapter.h

@ -0,0 +1,50 @@ @@ -0,0 +1,50 @@
///////////////////////////////////////////////////////////////////////////////////
// Copyright (C) 2021-2022 Edouard Griffiths, F4EXB <f4exb06@gmail.com> //
// Copyright (C) 2026 Jon Beniston, M7RCE <jon@beniston.com> //
// Some code by AI //
// //
// This program is free software; you can redistribute it and/or modify //
// it under the terms of the GNU General Public License as published by //
// the Free Software Foundation as version 3 of the License, or //
// (at your option) any later version. //
// //
// This program is distributed in the hope that it will be useful, //
// but WITHOUT ANY WARRANTY; without even the implied warranty of //
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //
// GNU General Public License V3 for more details. //
// //
// You should have received a copy of the GNU General Public License //
// along with this program. If not, see <http://www.gnu.org/licenses/>. //
///////////////////////////////////////////////////////////////////////////////////
#ifndef INCLUDE_SELCALDEMOD_WEBAPIADAPTER_H
#define INCLUDE_SELCALDEMOD_WEBAPIADAPTER_H
#include "channel/channelwebapiadapter.h"
#include "selcaldemodsettings.h"
class SELCALDemodWebAPIAdapter : public ChannelWebAPIAdapter {
public:
SELCALDemodWebAPIAdapter();
virtual ~SELCALDemodWebAPIAdapter();
virtual QByteArray serialize() const
{
return m_settings.serialize();
}
virtual bool deserialize(const QByteArray& data)
{
return m_settings.deserialize(data);
}
virtual int webapiSettingsGet(SWGSDRangel::SWGChannelSettings& response, QString& errorMessage);
virtual int webapiSettingsPutPatch(bool force, const QStringList& channelSettingsKeys, SWGSDRangel::SWGChannelSettings& response,
QString& errorMessage);
private:
SELCALDemodSettings m_settings;
};
#endif // INCLUDE_SELCALDEMOD_WEBAPIADAPTER_H

22
plugins/channelrx/demodselcal/selcalmessages.cpp

@ -0,0 +1,22 @@ @@ -0,0 +1,22 @@
///////////////////////////////////////////////////////////////////////////////////
// Copyright (C) 2026 Jon Beniston, M7RCE <jon@beniston.com> //
// Some code by AI //
// //
// This program is free software; you can redistribute it and/or modify //
// it under the terms of the GNU General Public License as published by //
// the Free Software Foundation as version 3 of the License, or //
// (at your option) any later version. //
// //
// This program is distributed in the hope that it will be useful, //
// but WITHOUT ANY WARRANTY; without even the implied warranty of //
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //
// GNU General Public License V3 for more details. //
// //
// You should have received a copy of the GNU General Public License //
// along with this program. If not, see <http://www.gnu.org/licenses/>. //
///////////////////////////////////////////////////////////////////////////////////
#include "selcalmessages.h"
MESSAGE_CLASS_DEFINITION(SELCALMessages::MsgCall, Message)
MESSAGE_CLASS_DEFINITION(SELCALMessages::MsgStatus, Message)

97
plugins/channelrx/demodselcal/selcalmessages.h

@ -0,0 +1,97 @@ @@ -0,0 +1,97 @@
///////////////////////////////////////////////////////////////////////////////////
// Copyright (C) 2021-2022 Edouard Griffiths, F4EXB <f4exb06@gmail.com> //
// Copyright (C) 2026 Jon Beniston, M7RCE <jon@beniston.com> //
// Some code by AI //
// //
// This program is free software; you can redistribute it and/or modify //
// it under the terms of the GNU General Public License as published by //
// the Free Software Foundation as version 3 of the License, or //
// (at your option) any later version. //
// //
// This program is distributed in the hope that it will be useful, //
// but WITHOUT ANY WARRANTY; without even the implied warranty of //
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //
// GNU General Public License V3 for more details. //
// //
// You should have received a copy of the GNU General Public License //
// along with this program. If not, see <http://www.gnu.org/licenses/>. //
///////////////////////////////////////////////////////////////////////////////////
#ifndef INCLUDE_SELCALMESSAGES_H
#define INCLUDE_SELCALMESSAGES_H
#include <QDateTime>
#include <QString>
#include "util/message.h"
#include "selcaldecoder.h"
namespace SELCALMessages {
struct Call {
QString m_code;
QDateTime m_dateTime;
qint64 m_frequency = 0;
float m_rssi = -120;
float m_snr = 0; // dB, weaker tone relative to the noise in a tone bin
float m_toneFrequencyOffset = 0; // Hz, measured from the tones
};
struct Status {
SELCALDecoder::State m_state = SELCALDecoder::State::Idle;
std::array<double, SELCALDecoder::m_toneCount> m_levels{}; // dB relative to noise
SELCALDecoder::Pair m_pair{{-1, -1}};
bool m_carrierLocked = false;
bool m_squelchOpen = false;
double m_carrierFrequencyOffset = 0;
double m_toneFrequencyOffset = 0;
};
class MsgCall : public Message {
MESSAGE_CLASS_DECLARATION
public:
static MsgCall *create(const Call& call)
{
return new MsgCall(call);
}
const Call& getMessage() const
{
return m_call;
}
private:
explicit MsgCall(const Call& call) :
m_call(call)
{
}
Call m_call;
};
class MsgStatus : public Message {
MESSAGE_CLASS_DECLARATION
public:
static MsgStatus *create(const Status& status)
{
return new MsgStatus(status);
}
const Status& getStatus() const
{
return m_status;
}
private:
explicit MsgStatus(const Status& status) :
m_status(status)
{
}
Status m_status;
};
} // namespace SELCALMessages
#endif

1
plugins/feature/demodanalyzer/demodanalyzersettings.cpp

@ -42,6 +42,7 @@ const QStringList DemodAnalyzerSettings::m_channelURIs = { @@ -42,6 +42,7 @@ const QStringList DemodAnalyzerSettings::m_channelURIs = {
QStringLiteral("sdrangel.channel.packetdemod"),
QStringLiteral("sdrangel.channeltx.modpacket"),
QStringLiteral("sdrangel.channel.radiosondedemod"),
QStringLiteral("sdrangel.channel.selcaldemod"),
QStringLiteral("sdrangel.channeltx.modpsk31"),
QStringLiteral("sdrangel.channeltx.modrtty"),
QStringLiteral("sdrangel.channel.ssbdemod"),

1
plugins/feature/demodanalyzer/readme.md

@ -18,6 +18,7 @@ Rx plugins are: @@ -18,6 +18,7 @@ Rx plugins are:
- NFM demodulator
- Packet demodulator
- Radiosonde demodulator
- SELCAL demodulator
- SSB demodulator
- WFM demodulator

1
plugins/feature/denoiser/denoisersettings.cpp

@ -31,6 +31,7 @@ const QStringList DenoiserSettings::m_channelURIs = { @@ -31,6 +31,7 @@ const QStringList DenoiserSettings::m_channelURIs = {
QStringLiteral("sdrangel.channel.dsddemod"),
QStringLiteral("sdrangel.channel.m17demod"),
QStringLiteral("sdrangel.channel.nfmdemod"),
QStringLiteral("sdrangel.channel.selcaldemod"),
QStringLiteral("sdrangel.channel.ssbdemod"),
QStringLiteral("sdrangel.channel.wfmdemod"),
QStringLiteral("sdrangel.channel.wdsprx"),

1
plugins/feature/denoiser/readme.md

@ -16,6 +16,7 @@ Supported sources include: @@ -16,6 +16,7 @@ Supported sources include:
- DAB demodulator
- DSD demodulator
- NFM demodulator
- SELCAL demodulator
- SSB demodulator
- WFM demodulator
- WDSP plugin (multimode)

2
plugins/feature/radiosonde/radiosondegui.h

@ -110,7 +110,7 @@ private: @@ -110,7 +110,7 @@ private:
QDateTime m_lastPositionUpdate;
QTimer m_positionUpdateTimer;
static const int m_minMobilePositionUpdateTime = 30; // In seconds
static const int m_minFixedPositionUpdateTime = 5 * 60;
static const int m_minFixedPositionUpdateTime = 3 * 60 * 60;
QTimer m_predicitionTimer;
QStringList m_predictions;

2
sdrbase/CMakeLists.txt

@ -268,6 +268,7 @@ set(sdrbase_SOURCES @@ -268,6 +268,7 @@ set(sdrbase_SOURCES
util/radiosonde.cpp
util/rainviewer.cpp
util/rtpsink.cpp
util/selcaldb.cpp
util/syncmessenger.cpp
util/samplesourceserializer.cpp
util/sdrangelserverlist.cpp
@ -545,6 +546,7 @@ set(sdrbase_HEADERS @@ -545,6 +546,7 @@ set(sdrbase_HEADERS
util/rds.h
util/rtpsink.h
util/rtty.h
util/selcaldb.h
util/syncmessenger.h
util/samplesourceserializer.h
util/sdrangelserverlist.h

1
sdrbase/resources/webapi.qrc

@ -48,6 +48,7 @@ @@ -48,6 +48,7 @@
<file>webapi/doc/swagger/include/DeviceSettings.yaml</file>
<file>webapi/doc/swagger/include/DOA2.yaml</file>
<file>webapi/doc/swagger/include/DSCDemod.yaml</file>
<file>webapi/doc/swagger/include/SELCALDemod.yaml</file>
<file>webapi/doc/swagger/include/DSDDemod.yaml</file>
<file>webapi/doc/swagger/include/DroneIDDemod.yaml</file>
<file>webapi/doc/swagger/include/EndOfTrainDemod.yaml</file>

2
sdrbase/resources/webapi/doc/swagger/include/ChannelReport.yaml

@ -203,3 +203,5 @@ ChannelReport: @@ -203,3 +203,5 @@ ChannelReport:
WFMModReport:
$ref: "/doc/swagger/include/WFMMod.yaml#/WFMModReport"
description: "Wfm mod report data for Channel."
SELCALDemodReport:
$ref: "/doc/swagger/include/SELCALDemod.yaml#/SELCALDemodReport"

2
sdrbase/resources/webapi/doc/swagger/include/ChannelSettings.yaml

@ -236,3 +236,5 @@ ChannelSettings: @@ -236,3 +236,5 @@ ChannelSettings:
WFMModSettings:
$ref: "/doc/swagger/include/WFMMod.yaml#/WFMModSettings"
description: "Wfm mod settings configuration for Channel."
SELCALDemodSettings:
$ref: "/doc/swagger/include/SELCALDemod.yaml#/SELCALDemodSettings"

139
sdrbase/resources/webapi/doc/swagger/include/SELCALDemod.yaml

@ -0,0 +1,139 @@ @@ -0,0 +1,139 @@
SELCALDemodSettings:
description: SELCAL settings
type: object
properties:
inputFrequencyOffset:
type: integer
format: int64
rfBandwidth:
type: number
format: float
modulation:
type: integer
format: int32
description: "0 = USB, 1 = AM"
enum: [0, 1]
toneFrequencyOffset:
type: number
format: float
description: Common received audio tone offset in Hz
minimum: -100
maximum: 100
autoToneFrequencyOffset:
type: integer
format: int32
description: Use a detected residual USB carrier within +/-100 Hz as the tone offset; otherwise tones are searched for within +/-6 Hz of the manual offset
default: 1
enum: [0, 1]
threshold:
type: number
format: float
description: Minimum level of each tone above the noise in a tone bin, in dB
default: 8
minimum: 6
maximum: 20
volume:
type: number
format: float
audioMute:
type: integer
format: int32
squelch:
type: integer
format: int32
description: Monitoring audio squelch threshold in dBFS; decoding is independent of squelch
default: -80
minimum: -100
maximum: 0
audioDeviceName:
type: string
filter:
type: string
udpEnabled:
type: integer
format: int32
udpAddress:
type: string
udpPort:
type: integer
format: int32
logFilename:
type: string
logEnabled:
type: integer
format: int32
rgbColor:
type: integer
format: int32
title:
type: string
streamIndex:
type: integer
format: int32
useReverseAPI:
type: integer
format: int32
reverseAPIAddress:
type: string
reverseAPIPort:
type: integer
format: int32
reverseAPIDeviceIndex:
type: integer
format: int32
reverseAPIChannelIndex:
type: integer
format: int32
channelMarker:
$ref: "/doc/swagger/include/ChannelMarker.yaml#/ChannelMarker"
rollupState:
$ref: "/doc/swagger/include/RollupState.yaml#/RollupState"
SELCALDemodReport:
description: SELCAL report
type: object
properties:
channelPowerDb:
type: number
format: double
channelSampleRate:
type: integer
format: int32
audioSampleRate:
type: integer
format: int32
squelchOpen:
type: integer
format: int32
description: Monitoring audio squelch is open
carrierLocked:
type: integer
format: int32
description: A reliable residual USB carrier, or an AM carrier, has been detected
carrierFrequencyOffset:
type: number
format: float
description: Measured carrier error from channel tuning in Hz; valid when carrierLocked is 1
toneFrequencyOffset:
type: number
format: float
description: Common tone offset measured by the decoder, or the expected offset when no tones are present, in Hz
state:
type: string
lastCode:
type: string
lastTimestamp:
type: string
lastFrequency:
type: integer
format: int64
lastRssi:
type: number
format: float
description: Average channel power during the tone bursts of the last call, in dB
lastSnr:
type: number
format: float
description: SNR of the weaker tone of the last call, relative to the noise in a tone bin, in dB
callCount:
type: integer
format: int64

203
sdrbase/util/selcaldb.cpp

@ -0,0 +1,203 @@ @@ -0,0 +1,203 @@
///////////////////////////////////////////////////////////////////////////////////
// Copyright (C) 2026 Jon Beniston, M7RCE <jon@beniston.com> //
// //
// This program is free software; you can redistribute it and/or modify //
// it under the terms of the GNU General Public License as published by //
// the Free Software Foundation as version 3 of the License, or //
// (at your option) any later version. //
// //
// This program is distributed in the hope that it will be useful, //
// but WITHOUT ANY WARRANTY; without even the implied warranty of //
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //
// GNU General Public License V3 for more details. //
// //
// You should have received a copy of the GNU General Public License //
// along with this program. If not, see <http://www.gnu.org/licenses/>. //
///////////////////////////////////////////////////////////////////////////////////
#include <algorithm>
#include <QDebug>
#include <QFile>
#include <QFileInfo>
#include <QMutexLocker>
#include <QTextStream>
#if (QT_VERSION < QT_VERSION_CHECK(6, 6, 0))
#include <QtGui/private/qzipreader_p.h>
#else
#include <QtCore/private/qzipreader_p.h>
#endif
#include "util/selcaldb.h"
#include "util/osndb.h"
#include "util/corsproxy.h"
#include "util/csv.h"
QSharedPointer<const QMultiHash<QString, QString>> SELCALDB::m_registrations;
QDateTime SELCALDB::m_modifiedDateTime;
QMutex SELCALDB::m_mutex;
SELCALDB::SELCALDB(QObject *parent) :
QObject(parent)
{
connect(&m_dlm, &HttpDownloadManager::downloadComplete, this, &SELCALDB::downloadFinished);
}
SELCALDB::~SELCALDB()
{
disconnect(&m_dlm, &HttpDownloadManager::downloadComplete, this, &SELCALDB::downloadFinished);
}
QString SELCALDB::getZipFilename()
{
return OsnDB::getDataDir() + "/selcal.zip";
}
QString SELCALDB::getCSVFilename()
{
return OsnDB::getDataDir() + "/selcal.csv";
}
void SELCALDB::downloadSELCALInformation()
{
QString filename = getZipFilename();
QString urlString = SELCALDB_URL;
QUrl dbURL(CORSProxy::adjustHost(urlString));
qDebug() << "SELCALDB::downloadSELCALInformation: Downloading " << urlString;
emit downloadingURL(urlString);
QNetworkReply *reply = m_dlm.download(dbURL, filename);
connect(reply, &QNetworkReply::downloadProgress, this, [this](qint64 bytesRead, qint64 totalBytes) {
emit downloadProgress(bytesRead, totalBytes);
});
}
void SELCALDB::downloadFinished(const QString& filename, bool success)
{
if (!success)
{
qWarning() << "SELCALDB::downloadFinished: Failed to download: " << filename;
emit downloadError(QString("Failed to download: %1").arg(filename));
}
else if (filename == getZipFilename())
{
// Extract .csv file from .zip file
QZipReader reader(filename);
if (reader.extractAll(OsnDB::getDataDir()))
{
emit downloadSELCALInformationFinished();
}
else
{
qWarning() << "SELCALDB::downloadFinished - Failed to extract files from " << filename;
emit downloadError(QString("Failed to extract files from %1").arg(filename));
}
}
else
{
qDebug() << "SELCALDB::downloadFinished: Unexpected filename: " << filename;
emit downloadError(QString("Unexpected filename: %1").arg(filename));
}
}
QString SELCALDB::normalizeCode(const QString& code)
{
// Tone designations, in the order used to write each pair
static const QString order = QStringLiteral("ABCDEFGHJKLMPQRSTUVWXYZ123456789");
QString symbols = code.toUpper().remove('-').remove(' ');
if (symbols.size() != 4) {
return QString();
}
for (const auto& symbol : symbols)
{
if (!order.contains(symbol)) {
return QString();
}
}
auto pair = [](QString pair) {
std::sort(pair.begin(), pair.end(), [](QChar a, QChar b) { return order.indexOf(a) < order.indexOf(b); });
return pair;
};
return pair(symbols.left(2)) + "-" + pair(symbols.mid(2));
}
QMultiHash<QString, QString> *SELCALDB::readCSV(const QString& filename)
{
QFile file(filename);
if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
{
qDebug() << "SELCALDB::readCSV: Could not open " << filename;
return nullptr;
}
QTextStream in(&file);
QString error;
QHash<QString, int> columns = CSV::readHeader(in, {"Code", "Registration"}, error);
if (!error.isEmpty())
{
qWarning() << "SELCALDB::readCSV: " << filename << ": " << error;
return nullptr;
}
int codeCol = columns["Code"];
int registrationCol = columns["Registration"];
int lastCol = std::max(codeCol, registrationCol);
QMultiHash<QString, QString> *registrations = new QMultiHash<QString, QString>();
QStringList row;
while (CSV::readRow(in, &row))
{
if (row.size() <= lastCol) {
continue;
}
QString code = normalizeCode(row[codeCol]);
QString registration = row[registrationCol].trimmed();
if (!code.isEmpty() && !registration.isEmpty()) {
registrations->insert(code, registration);
}
}
qDebug() << "SELCALDB::readCSV: Read " << registrations->size() << " SELCAL codes from " << filename;
return registrations;
}
QSharedPointer<const QMultiHash<QString, QString>> SELCALDB::getRegistrations()
{
QMutexLocker locker(&m_mutex);
QFileInfo fileInfo(getCSVFilename());
if (!fileInfo.exists()) {
return m_registrations;
}
// Reload if the file has been downloaded since it was read
QDateTime modifiedDateTime = fileInfo.lastModified();
if (!m_registrations || (modifiedDateTime > m_modifiedDateTime))
{
QMultiHash<QString, QString> *registrations = readCSV(getCSVFilename());
if (registrations)
{
m_registrations = QSharedPointer<const QMultiHash<QString, QString>>(registrations);
m_modifiedDateTime = modifiedDateTime;
}
}
return m_registrations;
}
QStringList SELCALDB::getRegistrations(const QString& code)
{
QSharedPointer<const QMultiHash<QString, QString>> registrations = getRegistrations();
if (!registrations) {
return QStringList();
}
// values() returns the most recently inserted first
QStringList list = registrations->values(normalizeCode(code));
std::reverse(list.begin(), list.end());
return list;
}

80
sdrbase/util/selcaldb.h

@ -0,0 +1,80 @@ @@ -0,0 +1,80 @@
///////////////////////////////////////////////////////////////////////////////////
// Copyright (C) 2026 Jon Beniston, M7RCE <jon@beniston.com> //
// //
// This program is free software; you can redistribute it and/or modify //
// it under the terms of the GNU General Public License as published by //
// the Free Software Foundation as version 3 of the License, or //
// (at your option) any later version. //
// //
// This program is distributed in the hope that it will be useful, //
// but WITHOUT ANY WARRANTY; without even the implied warranty of //
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //
// GNU General Public License V3 for more details. //
// //
// You should have received a copy of the GNU General Public License //
// along with this program. If not, see <http://www.gnu.org/licenses/>. //
///////////////////////////////////////////////////////////////////////////////////
#ifndef INCLUDE_SELCALDB_H
#define INCLUDE_SELCALDB_H
#include <QDateTime>
#include <QMultiHash>
#include <QMutex>
#include <QSharedPointer>
#include <QString>
#include <QStringList>
#include "util/httpdownloadmanager.h"
#include "export.h"
#define SELCALDB_URL "https://sdrangel.org/downloads/selcal.zip"
// Database of SELCAL codes assigned to aircraft, from a CSV file with Code and
// Registration columns. Codes are not unique, so a code can have several
// registrations.
class SDRBASE_API SELCALDB : public QObject {
Q_OBJECT
public:
SELCALDB(QObject* parent=nullptr);
~SELCALDB();
void downloadSELCALInformation();
// Registrations keyed by normalized code. Reloaded if the file has changed.
// Null if the database has not been downloaded.
static QSharedPointer<const QMultiHash<QString, QString>> getRegistrations();
// Registrations of aircraft assigned a code, in file order.
static QStringList getRegistrations(const QString& code);
// Code in the form AB-CD, with each pair in tone designation order, or an
// empty string if it is not a valid code.
static QString normalizeCode(const QString& code);
static QMultiHash<QString, QString> *readCSV(const QString& filename);
static QString getZipFilename();
static QString getCSVFilename();
private:
HttpDownloadManager m_dlm;
static QSharedPointer<const QMultiHash<QString, QString>> m_registrations;
static QDateTime m_modifiedDateTime;
static QMutex m_mutex;
private slots:
void downloadFinished(const QString& filename, bool success);
signals:
void downloadingURL(const QString& url);
void downloadError(const QString& error);
void downloadProgress(qint64 bytesReceived, qint64 bytesTotal);
void downloadSELCALInformationFinished();
};
#endif

41
sdrbase/util/sondehub.cpp

@ -29,6 +29,8 @@ SondeHub::SondeHub() @@ -29,6 +29,8 @@ SondeHub::SondeHub()
{
m_networkManager = new QNetworkAccessManager();
connect(m_networkManager, &QNetworkAccessManager::finished, this, &SondeHub::handleReply);
connect(&m_uploadTimer, &QTimer::timeout, this, &SondeHub::uploadQueuedTelemetry);
m_uploadTimer.start(m_uploadPeriodMs);
}
SondeHub::~SondeHub()
@ -128,11 +130,21 @@ void SondeHub::upload( @@ -128,11 +130,21 @@ void SondeHub::upload(
//obj.insert("dev", true);
//qDebug() << obj;
QJsonArray payloads {
obj
};
m_telemetryQueue.append(obj);
while (m_telemetryQueue.size() > m_maxQueueSize) {
m_telemetryQueue.removeFirst();
}
}
void SondeHub::uploadQueuedTelemetry()
{
if (m_telemetryQueue.isEmpty() || m_telemetryReply) {
return;
}
QJsonDocument doc(payloads);
m_telemetryInFlight = m_telemetryQueue;
m_telemetryQueue = QJsonArray();
QJsonDocument doc(m_telemetryInFlight);
QByteArray data = doc.toJson();
QUrl url(QString("https://api.v2.sondehub.org/sondes/telemetry"));
@ -142,7 +154,7 @@ void SondeHub::upload( @@ -142,7 +154,7 @@ void SondeHub::upload(
request.setHeader(QNetworkRequest::UserAgentHeader, "sdrangel");
request.setRawHeader("Date", QDateTime::currentDateTimeUtc().toString(Qt::ISODateWithMs).toLatin1());
m_networkManager->put(request, data);
m_telemetryReply = m_networkManager->put(request, data);
}
void SondeHub::updatePosition(
@ -196,6 +208,25 @@ void SondeHub::getPrediction(const QString& serial) @@ -196,6 +208,25 @@ void SondeHub::getPrediction(const QString& serial)
void SondeHub::handleReply(QNetworkReply* reply)
{
if (reply && (reply == m_telemetryReply))
{
int status = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
if (reply->error() || (status < 200) || (status >= 300))
{
// Requeue failed batch ahead of newer telemetry
for (const auto& value : m_telemetryQueue) {
m_telemetryInFlight.append(value);
}
m_telemetryQueue = m_telemetryInFlight;
while (m_telemetryQueue.size() > m_maxQueueSize) {
m_telemetryQueue.removeFirst();
}
}
m_telemetryInFlight = QJsonArray();
m_telemetryReply = nullptr;
}
if (reply)
{
if (!reply->error())

7
sdrbase/util/sondehub.h

@ -72,6 +72,7 @@ public: @@ -72,6 +72,7 @@ public:
private slots:
void handleReply(QNetworkReply* reply);
void uploadQueuedTelemetry();
signals:
void prediction(const QString& serial, const QList<Position>& path);
@ -79,6 +80,12 @@ signals: @@ -79,6 +80,12 @@ signals:
private:
QNetworkAccessManager *m_networkManager;
QJsonArray m_telemetryQueue;
QJsonArray m_telemetryInFlight;
QNetworkReply *m_telemetryReply = nullptr;
QTimer m_uploadTimer;
static const int m_uploadPeriodMs = 15000; // SondeHub asks for uploads no more often than every 15s
static const int m_maxQueueSize = 1000;
};

6
sdrbase/webapi/webapirequestmapper.cpp

@ -4990,6 +4990,12 @@ bool WebAPIRequestMapper::getChannelSettings( @@ -4990,6 +4990,12 @@ bool WebAPIRequestMapper::getChannelSettings(
channelSettings->getDscDemodSettings()->init();
channelSettings->getDscDemodSettings()->fromJsonObject(settingsJsonObject);
}
else if (channelSettingsKey == "SELCALDemodSettings")
{
channelSettings->setSelcalDemodSettings(new SWGSDRangel::SWGSELCALDemodSettings());
channelSettings->getSelcalDemodSettings()->init();
channelSettings->getSelcalDemodSettings()->fromJsonObject(settingsJsonObject);
}
else if (channelSettingsKey == "DSDDemodSettings")
{
channelSettings->setDsdDemodSettings(new SWGSDRangel::SWGDSDDemodSettings());

2
sdrbase/webapi/webapiutils.cpp

@ -49,6 +49,7 @@ const QMap<QString, QString> WebAPIUtils::m_channelURIToSettingsKey = { @@ -49,6 +49,7 @@ const QMap<QString, QString> WebAPIUtils::m_channelURIToSettingsKey = {
{"sdrangel.channel.drmdemod", "DRMDemodSettings"},
{"sdrangel.channel.doa2", "DOA2Settings"},
{"sdrangel.channel.dscdemod", "DSCDemodSettings"},
{"sdrangel.channel.selcaldemod", "SELCALDemodSettings"},
{"sdrangel.channel.dsddemod", "DSDDemodSettings"},
{"sdrangel.channel.droneiddemod", "DroneIDDemodSettings"},
{"sdrangel.channel.endoftraindemod", "EndOfTrainDemodSettings"},
@ -186,6 +187,7 @@ const QMap<QString, QString> WebAPIUtils::m_channelTypeToSettingsKey = { @@ -186,6 +187,7 @@ const QMap<QString, QString> WebAPIUtils::m_channelTypeToSettingsKey = {
{"DRMDemod", "DRMDemodSettings"},
{"DOA2", "DOA2Settings"},
{"DSCDemod", "DSCDemodSettings"},
{"SELCALDemod", "SELCALDemodSettings"},
{"DSDDemod", "DSDDemodSettings"},
{"DroneIDDemod", "DroneIDDemodSettings"},
{"EndOfTrainDemod", "EndOfTrainDemodSettings"},

2
swagger/sdrangel/api/swagger/include/ChannelReport.yaml

@ -203,3 +203,5 @@ ChannelReport: @@ -203,3 +203,5 @@ ChannelReport:
WFMModReport:
$ref: "http://swgserver:8081/api/swagger/include/WFMMod.yaml#/WFMModReport"
description: "Wfm mod report data for Channel."
SELCALDemodReport:
$ref: "http://swgserver:8081/api/swagger/include/SELCALDemod.yaml#/SELCALDemodReport"

2
swagger/sdrangel/api/swagger/include/ChannelSettings.yaml

@ -236,3 +236,5 @@ ChannelSettings: @@ -236,3 +236,5 @@ ChannelSettings:
WFMModSettings:
$ref: "http://swgserver:8081/api/swagger/include/WFMMod.yaml#/WFMModSettings"
description: "Wfm mod settings configuration for Channel."
SELCALDemodSettings:
$ref: "http://swgserver:8081/api/swagger/include/SELCALDemod.yaml#/SELCALDemodSettings"

140
swagger/sdrangel/api/swagger/include/SELCALDemod.yaml

@ -0,0 +1,140 @@ @@ -0,0 +1,140 @@
SELCALDemodSettings:
description: SELCAL settings
type: object
properties:
inputFrequencyOffset:
type: integer
format: int64
rfBandwidth:
type: number
format: float
modulation:
type: integer
format: int32
description: "0 = USB, 1 = AM"
enum: [0, 1]
toneFrequencyOffset:
type: number
format: float
description: Common received audio tone offset in Hz
minimum: -100
maximum: 100
autoToneFrequencyOffset:
type: integer
format: int32
description: Use a detected residual USB carrier within +/-100 Hz as the tone offset; otherwise tones are searched for within +/-6 Hz of the manual offset
default: 1
enum: [0, 1]
threshold:
type: number
format: float
description: Minimum level of each tone above the noise in a tone bin, in dB
default: 8
minimum: 6
maximum: 20
volume:
type: number
format: float
audioMute:
type: integer
format: int32
squelch:
type: integer
format: int32
description: Monitoring audio squelch threshold in dBFS; decoding is independent of squelch
default: -80
minimum: -100
maximum: 0
audioDeviceName:
type: string
filter:
type: string
udpEnabled:
type: integer
format: int32
udpAddress:
type: string
udpPort:
type: integer
format: int32
logFilename:
type: string
logEnabled:
type: integer
format: int32
rgbColor:
type: integer
format: int32
title:
type: string
streamIndex:
type: integer
format: int32
useReverseAPI:
type: integer
format: int32
reverseAPIAddress:
type: string
reverseAPIPort:
type: integer
format: int32
reverseAPIDeviceIndex:
type: integer
format: int32
reverseAPIChannelIndex:
type: integer
format: int32
channelMarker:
$ref: "http://swgserver:8081/api/swagger/include/ChannelMarker.yaml#/ChannelMarker"
rollupState:
$ref: "http://swgserver:8081/api/swagger/include/RollupState.yaml#/RollupState"
SELCALDemodReport:
description: SELCAL report
type: object
properties:
channelPowerDb:
type: number
format: double
channelSampleRate:
type: integer
format: int32
audioSampleRate:
type: integer
format: int32
squelchOpen:
type: integer
format: int32
description: Monitoring audio squelch is open
carrierLocked:
type: integer
format: int32
description: A reliable residual USB carrier, or an AM carrier, has been detected
carrierFrequencyOffset:
type: number
format: float
description: Measured carrier error from channel tuning in Hz; valid when carrierLocked is 1
toneFrequencyOffset:
type: number
format: float
description: Common tone offset measured by the decoder, or the expected offset when no tones are present, in Hz
state:
type: string
lastCode:
type: string
lastTimestamp:
type: string
lastFrequency:
type: integer
format: int64
lastRssi:
type: number
format: float
description: Average channel power during the tone bursts of the last call, in dB
lastSnr:
type: number
format: float
description: SNR of the weaker tone of the last call, relative to the noise in a tone bin, in dB
callCount:
type: integer
format: int64

27
swagger/sdrangel/code/qt5/client/SWGChannelReport.cpp

@ -69,7 +69,9 @@ SWGChannelReport::SWGChannelReport() { @@ -69,7 +69,9 @@ SWGChannelReport::SWGChannelReport() {
doa2_report = nullptr;
m_doa2_report_isSet = false;
dsc_demod_report = nullptr;
selcal_demod_report = nullptr;
m_dsc_demod_report_isSet = false;
m_selcal_demod_report_isSet = false;
dsd_demod_report = nullptr;
m_dsd_demod_report_isSet = false;
drone_id_demod_report = nullptr;
@ -207,7 +209,9 @@ SWGChannelReport::init() { @@ -207,7 +209,9 @@ SWGChannelReport::init() {
doa2_report = new SWGDOA2Report();
m_doa2_report_isSet = false;
dsc_demod_report = new SWGDSCDemodReport();
selcal_demod_report = new SWGSELCALDemodReport();
m_dsc_demod_report_isSet = false;
m_selcal_demod_report_isSet = false;
dsd_demod_report = new SWGDSDDemodReport();
m_dsd_demod_report_isSet = false;
drone_id_demod_report = new SWGDroneIDDemodReport();
@ -361,6 +365,9 @@ SWGChannelReport::cleanup() { @@ -361,6 +365,9 @@ SWGChannelReport::cleanup() {
if(dsc_demod_report != nullptr) {
delete dsc_demod_report;
}
if(selcal_demod_report != nullptr) {
delete selcal_demod_report;
}
if(dsd_demod_report != nullptr) {
delete dsd_demod_report;
}
@ -545,6 +552,7 @@ SWGChannelReport::fromJsonObject(QJsonObject &pJson) { @@ -545,6 +552,7 @@ SWGChannelReport::fromJsonObject(QJsonObject &pJson) {
::SWGSDRangel::setValue(&doa2_report, pJson["DOA2Report"], "SWGDOA2Report", "SWGDOA2Report");
::SWGSDRangel::setValue(&dsc_demod_report, pJson["DSCDemodReport"], "SWGDSCDemodReport", "SWGDSCDemodReport");
::SWGSDRangel::setValue(&selcal_demod_report, pJson["SELCALDemodReport"], "SWGSELCALDemodReport", "SWGSELCALDemodReport");
::SWGSDRangel::setValue(&dsd_demod_report, pJson["DSDDemodReport"], "SWGDSDDemodReport", "SWGDSDDemodReport");
@ -712,6 +720,9 @@ SWGChannelReport::asJsonObject() { @@ -712,6 +720,9 @@ SWGChannelReport::asJsonObject() {
if((dsc_demod_report != nullptr) && (dsc_demod_report->isSet())){
toJsonValue(QString("DSCDemodReport"), dsc_demod_report, obj, QString("SWGDSCDemodReport"));
}
if((selcal_demod_report != nullptr) && (selcal_demod_report->isSet())){
toJsonValue(QString("SELCALDemodReport"), selcal_demod_report, obj, QString("SWGSELCALDemodReport"));
}
if((dsd_demod_report != nullptr) && (dsd_demod_report->isSet())){
toJsonValue(QString("DSDDemodReport"), dsd_demod_report, obj, QString("SWGDSDDemodReport"));
}
@ -1058,6 +1069,19 @@ SWGChannelReport::setDscDemodReport(SWGDSCDemodReport* dsc_demod_report) { @@ -1058,6 +1069,19 @@ SWGChannelReport::setDscDemodReport(SWGDSCDemodReport* dsc_demod_report) {
this->m_dsc_demod_report_isSet = true;
}
SWGSELCALDemodReport*
SWGChannelReport::getSelcalDemodReport() {
return selcal_demod_report;
}
void
SWGChannelReport::setSelcalDemodReport(SWGSELCALDemodReport* selcal_demod_report) {
if (this->selcal_demod_report != selcal_demod_report) {
delete this->selcal_demod_report;
}
this->selcal_demod_report = selcal_demod_report;
this->m_selcal_demod_report_isSet = true;
}
SWGDSDDemodReport*
SWGChannelReport::getDsdDemodReport() {
return dsd_demod_report;
@ -1566,6 +1590,9 @@ SWGChannelReport::isSet(){ @@ -1566,6 +1590,9 @@ SWGChannelReport::isSet(){
if(dsc_demod_report && dsc_demod_report->isSet()){
isObjectUpdated = true; break;
}
if(selcal_demod_report && selcal_demod_report->isSet()){
isObjectUpdated = true; break;
}
if(dsd_demod_report && dsd_demod_report->isSet()){
isObjectUpdated = true; break;
}

5
swagger/sdrangel/code/qt5/client/SWGChannelReport.h

@ -41,6 +41,7 @@ @@ -41,6 +41,7 @@
#include "SWGDOA2Report.h"
#include "SWGDRMDemodReport.h"
#include "SWGDSCDemodReport.h"
#include "SWGSELCALDemodReport.h"
#include "SWGDSDDemodReport.h"
#include "SWGDroneIDDemodReport.h"
#include "SWGEndOfTrainDemodReport.h"
@ -166,7 +167,9 @@ public: @@ -166,7 +167,9 @@ public:
void setDoa2Report(SWGDOA2Report* doa2_report);
SWGDSCDemodReport* getDscDemodReport();
SWGSELCALDemodReport* getSelcalDemodReport();
void setDscDemodReport(SWGDSCDemodReport* dsc_demod_report);
void setSelcalDemodReport(SWGSELCALDemodReport* selcal_demod_report);
SWGDSDDemodReport* getDsdDemodReport();
void setDsdDemodReport(SWGDSDDemodReport* dsd_demod_report);
@ -365,7 +368,9 @@ private: @@ -365,7 +368,9 @@ private:
bool m_doa2_report_isSet;
SWGDSCDemodReport* dsc_demod_report;
SWGSELCALDemodReport* selcal_demod_report;
bool m_dsc_demod_report_isSet;
bool m_selcal_demod_report_isSet;
SWGDSDDemodReport* dsd_demod_report;
bool m_dsd_demod_report_isSet;

27
swagger/sdrangel/code/qt5/client/SWGChannelSettings.cpp

@ -81,7 +81,9 @@ SWGChannelSettings::SWGChannelSettings() { @@ -81,7 +81,9 @@ SWGChannelSettings::SWGChannelSettings() {
doa2_settings = nullptr;
m_doa2_settings_isSet = false;
dsc_demod_settings = nullptr;
selcal_demod_settings = nullptr;
m_dsc_demod_settings_isSet = false;
m_selcal_demod_settings_isSet = false;
dsd_demod_settings = nullptr;
m_dsd_demod_settings_isSet = false;
drone_id_demod_settings = nullptr;
@ -241,7 +243,9 @@ SWGChannelSettings::init() { @@ -241,7 +243,9 @@ SWGChannelSettings::init() {
doa2_settings = new SWGDOA2Settings();
m_doa2_settings_isSet = false;
dsc_demod_settings = new SWGDSCDemodSettings();
selcal_demod_settings = new SWGSELCALDemodSettings();
m_dsc_demod_settings_isSet = false;
m_selcal_demod_settings_isSet = false;
dsd_demod_settings = new SWGDSDDemodSettings();
m_dsd_demod_settings_isSet = false;
drone_id_demod_settings = new SWGDroneIDDemodSettings();
@ -419,6 +423,9 @@ SWGChannelSettings::cleanup() { @@ -419,6 +423,9 @@ SWGChannelSettings::cleanup() {
if(dsc_demod_settings != nullptr) {
delete dsc_demod_settings;
}
if(selcal_demod_settings != nullptr) {
delete selcal_demod_settings;
}
if(dsd_demod_settings != nullptr) {
delete dsd_demod_settings;
}
@ -630,6 +637,7 @@ SWGChannelSettings::fromJsonObject(QJsonObject &pJson) { @@ -630,6 +637,7 @@ SWGChannelSettings::fromJsonObject(QJsonObject &pJson) {
::SWGSDRangel::setValue(&doa2_settings, pJson["DOA2Settings"], "SWGDOA2Settings", "SWGDOA2Settings");
::SWGSDRangel::setValue(&dsc_demod_settings, pJson["DSCDemodSettings"], "SWGDSCDemodSettings", "SWGDSCDemodSettings");
::SWGSDRangel::setValue(&selcal_demod_settings, pJson["SELCALDemodSettings"], "SWGSELCALDemodSettings", "SWGSELCALDemodSettings");
::SWGSDRangel::setValue(&dsd_demod_settings, pJson["DSDDemodSettings"], "SWGDSDDemodSettings", "SWGDSDDemodSettings");
@ -825,6 +833,9 @@ SWGChannelSettings::asJsonObject() { @@ -825,6 +833,9 @@ SWGChannelSettings::asJsonObject() {
if((dsc_demod_settings != nullptr) && (dsc_demod_settings->isSet())){
toJsonValue(QString("DSCDemodSettings"), dsc_demod_settings, obj, QString("SWGDSCDemodSettings"));
}
if((selcal_demod_settings != nullptr) && (selcal_demod_settings->isSet())){
toJsonValue(QString("SELCALDemodSettings"), selcal_demod_settings, obj, QString("SWGSELCALDemodSettings"));
}
if((dsd_demod_settings != nullptr) && (dsd_demod_settings->isSet())){
toJsonValue(QString("DSDDemodSettings"), dsd_demod_settings, obj, QString("SWGDSDDemodSettings"));
}
@ -1246,6 +1257,19 @@ SWGChannelSettings::setDscDemodSettings(SWGDSCDemodSettings* dsc_demod_settings) @@ -1246,6 +1257,19 @@ SWGChannelSettings::setDscDemodSettings(SWGDSCDemodSettings* dsc_demod_settings)
this->m_dsc_demod_settings_isSet = true;
}
SWGSELCALDemodSettings*
SWGChannelSettings::getSelcalDemodSettings() {
return selcal_demod_settings;
}
void
SWGChannelSettings::setSelcalDemodSettings(SWGSELCALDemodSettings* selcal_demod_settings) {
if (this->selcal_demod_settings != selcal_demod_settings) {
delete this->selcal_demod_settings;
}
this->selcal_demod_settings = selcal_demod_settings;
this->m_selcal_demod_settings_isSet = true;
}
SWGDSDDemodSettings*
SWGChannelSettings::getDsdDemodSettings() {
return dsd_demod_settings;
@ -1822,6 +1846,9 @@ SWGChannelSettings::isSet(){ @@ -1822,6 +1846,9 @@ SWGChannelSettings::isSet(){
if(dsc_demod_settings && dsc_demod_settings->isSet()){
isObjectUpdated = true; break;
}
if(selcal_demod_settings && selcal_demod_settings->isSet()){
isObjectUpdated = true; break;
}
if(dsd_demod_settings && dsd_demod_settings->isSet()){
isObjectUpdated = true; break;
}

5
swagger/sdrangel/code/qt5/client/SWGChannelSettings.h

@ -45,6 +45,7 @@ @@ -45,6 +45,7 @@
#include "SWGDOA2Settings.h"
#include "SWGDRMDemodSettings.h"
#include "SWGDSCDemodSettings.h"
#include "SWGSELCALDemodSettings.h"
#include "SWGDSDDemodSettings.h"
#include "SWGDroneIDDemodSettings.h"
#include "SWGEndOfTrainDemodSettings.h"
@ -193,7 +194,9 @@ public: @@ -193,7 +194,9 @@ public:
void setDoa2Settings(SWGDOA2Settings* doa2_settings);
SWGDSCDemodSettings* getDscDemodSettings();
SWGSELCALDemodSettings* getSelcalDemodSettings();
void setDscDemodSettings(SWGDSCDemodSettings* dsc_demod_settings);
void setSelcalDemodSettings(SWGSELCALDemodSettings* selcal_demod_settings);
SWGDSDDemodSettings* getDsdDemodSettings();
void setDsdDemodSettings(SWGDSDDemodSettings* dsd_demod_settings);
@ -425,7 +428,9 @@ private: @@ -425,7 +428,9 @@ private:
bool m_doa2_settings_isSet;
SWGDSCDemodSettings* dsc_demod_settings;
SWGSELCALDemodSettings* selcal_demod_settings;
bool m_dsc_demod_settings_isSet;
bool m_selcal_demod_settings_isSet;
SWGDSDDemodSettings* dsd_demod_settings;
bool m_dsd_demod_settings_isSet;

12
swagger/sdrangel/code/qt5/client/SWGModelFactory.h

@ -134,7 +134,9 @@ @@ -134,7 +134,9 @@
#include "SWGDRMJournalineService.h"
#include "SWGDRMService.h"
#include "SWGDSCDemodReport.h"
#include "SWGSELCALDemodReport.h"
#include "SWGDSCDemodSettings.h"
#include "SWGSELCALDemodSettings.h"
#include "SWGDSDDemodReport.h"
#include "SWGDSDDemodSettings.h"
#include "SWGDroneIDDemodReport.h"
@ -1049,11 +1051,21 @@ namespace SWGSDRangel { @@ -1049,11 +1051,21 @@ namespace SWGSDRangel {
obj->init();
return obj;
}
if(QString("SWGSELCALDemodReport").compare(type) == 0) {
SWGSELCALDemodReport *obj = new SWGSELCALDemodReport();
obj->init();
return obj;
}
if(QString("SWGDSCDemodSettings").compare(type) == 0) {
SWGDSCDemodSettings *obj = new SWGDSCDemodSettings();
obj->init();
return obj;
}
if(QString("SWGSELCALDemodSettings").compare(type) == 0) {
SWGSELCALDemodSettings *obj = new SWGSELCALDemodSettings();
obj->init();
return obj;
}
if(QString("SWGDSDDemodReport").compare(type) == 0) {
SWGDSDDemodReport *obj = new SWGDSDDemodReport();
obj->init();

109
swagger/sdrangel/code/qt5/client/SWGSELCALDemodReport.cpp

@ -0,0 +1,109 @@ @@ -0,0 +1,109 @@
// SPDX-License-Identifier: GPL-3.0-or-later
#include "SWGSELCALDemodReport.h"
#include "SWGHelpers.h"
#include <QJsonDocument>
namespace SWGSDRangel {
SWGSELCALDemodReport::SWGSELCALDemodReport() = default;
SWGSELCALDemodReport::SWGSELCALDemodReport(QString* json) { init(); if (json) { fromJson(*json); } }
SWGSELCALDemodReport::~SWGSELCALDemodReport() { cleanup(); }
void SWGSELCALDemodReport::cleanup()
{
delete m_state; m_state = nullptr;
delete m_lastCode; m_lastCode = nullptr;
delete m_lastTimestamp; m_lastTimestamp = nullptr;
}
void SWGSELCALDemodReport::init()
{
cleanup();
m_squelchOpen = 0; m_squelchOpenIsSet = false;
m_toneFrequencyOffset = 0; m_toneFrequencyOffsetIsSet = false;
m_carrierFrequencyOffset = 0; m_carrierFrequencyOffsetIsSet = false;
m_carrierLocked = 0; m_carrierLockedIsSet = false;
m_channelPowerDb = 0; m_channelPowerDbIsSet = false;
m_channelSampleRate = 0; m_channelSampleRateIsSet = false;
m_audioSampleRate = 0; m_audioSampleRateIsSet = false;
m_state = new QString(); m_stateIsSet = false;
m_lastCode = new QString(); m_lastCodeIsSet = false;
m_lastTimestamp = new QString(); m_lastTimestampIsSet = false;
m_lastFrequency = 0; m_lastFrequencyIsSet = false;
m_lastRssi = 0; m_lastRssiIsSet = false;
m_lastSnr = 0; m_lastSnrIsSet = false;
m_callCount = 0; m_callCountIsSet = false;
}
SWGSELCALDemodReport* SWGSELCALDemodReport::fromJson(QString& json)
{
auto object = QJsonDocument::fromJson(json.toUtf8()).object(); fromJsonObject(object); return this;
}
void SWGSELCALDemodReport::fromJsonObject(QJsonObject& json)
{
if (json.contains("squelchOpen")) { ::SWGSDRangel::setValue(&m_squelchOpen,json["squelchOpen"],"qint32",""); m_squelchOpenIsSet = true; }
if (json.contains("toneFrequencyOffset")) { ::SWGSDRangel::setValue(&m_toneFrequencyOffset,json["toneFrequencyOffset"],"float",""); m_toneFrequencyOffsetIsSet = true; }
if (json.contains("carrierFrequencyOffset")) { ::SWGSDRangel::setValue(&m_carrierFrequencyOffset,json["carrierFrequencyOffset"],"float",""); m_carrierFrequencyOffsetIsSet = true; }
if (json.contains("carrierLocked")) { ::SWGSDRangel::setValue(&m_carrierLocked,json["carrierLocked"],"qint32",""); m_carrierLockedIsSet = true; }
if (json.contains("channelPowerDb")) { ::SWGSDRangel::setValue(&m_channelPowerDb,json["channelPowerDb"],"double",""); m_channelPowerDbIsSet = true; }
if (json.contains("channelSampleRate")) { ::SWGSDRangel::setValue(&m_channelSampleRate,json["channelSampleRate"],"qint32",""); m_channelSampleRateIsSet = true; }
if (json.contains("audioSampleRate")) { ::SWGSDRangel::setValue(&m_audioSampleRate,json["audioSampleRate"],"qint32",""); m_audioSampleRateIsSet = true; }
if (json.contains("state")) { ::SWGSDRangel::setValue(&m_state,json["state"],"QString","QString"); m_stateIsSet = true; }
if (json.contains("lastCode")) { ::SWGSDRangel::setValue(&m_lastCode,json["lastCode"],"QString","QString"); m_lastCodeIsSet = true; }
if (json.contains("lastTimestamp")) { ::SWGSDRangel::setValue(&m_lastTimestamp,json["lastTimestamp"],"QString","QString"); m_lastTimestampIsSet = true; }
if (json.contains("lastFrequency")) { ::SWGSDRangel::setValue(&m_lastFrequency,json["lastFrequency"],"qint64",""); m_lastFrequencyIsSet = true; }
if (json.contains("lastRssi")) { ::SWGSDRangel::setValue(&m_lastRssi,json["lastRssi"],"float",""); m_lastRssiIsSet = true; }
if (json.contains("lastSnr")) { ::SWGSDRangel::setValue(&m_lastSnr,json["lastSnr"],"float",""); m_lastSnrIsSet = true; }
if (json.contains("callCount")) { ::SWGSDRangel::setValue(&m_callCount,json["callCount"],"qint64",""); m_callCountIsSet = true; }
}
QString SWGSELCALDemodReport::asJson()
{
auto* object = asJsonObject(); QString result = QJsonDocument(*object).toJson(); delete object; return result;
}
QJsonObject* SWGSELCALDemodReport::asJsonObject()
{
auto* object = new QJsonObject();
if (m_squelchOpenIsSet) { object->insert("squelchOpen",QJsonValue(m_squelchOpen)); }
if (m_toneFrequencyOffsetIsSet) { object->insert("toneFrequencyOffset",QJsonValue(m_toneFrequencyOffset)); }
if (m_carrierFrequencyOffsetIsSet) { object->insert("carrierFrequencyOffset",QJsonValue(m_carrierFrequencyOffset)); }
if (m_carrierLockedIsSet) { object->insert("carrierLocked",QJsonValue(m_carrierLocked)); }
if (m_channelPowerDbIsSet) { object->insert("channelPowerDb",QJsonValue(m_channelPowerDb)); }
if (m_channelSampleRateIsSet) { object->insert("channelSampleRate",QJsonValue(m_channelSampleRate)); }
if (m_audioSampleRateIsSet) { object->insert("audioSampleRate",QJsonValue(m_audioSampleRate)); }
if (m_state && (m_stateIsSet || !m_state->isEmpty())) { toJsonValue(QString("state"),m_state,object,QString("QString")); }
if (m_lastCode && (m_lastCodeIsSet || !m_lastCode->isEmpty())) { toJsonValue(QString("lastCode"),m_lastCode,object,QString("QString")); }
if (m_lastTimestamp && (m_lastTimestampIsSet || !m_lastTimestamp->isEmpty())) { toJsonValue(QString("lastTimestamp"),m_lastTimestamp,object,QString("QString")); }
if (m_lastFrequencyIsSet) { object->insert("lastFrequency",QJsonValue(m_lastFrequency)); }
if (m_lastRssiIsSet) { object->insert("lastRssi",QJsonValue(m_lastRssi)); }
if (m_lastSnrIsSet) { object->insert("lastSnr",QJsonValue(m_lastSnr)); }
if (m_callCountIsSet) { object->insert("callCount",QJsonValue(m_callCount)); }
return object;
}
bool SWGSELCALDemodReport::isSet()
{
return m_squelchOpenIsSet || m_toneFrequencyOffsetIsSet || m_carrierFrequencyOffsetIsSet || m_carrierLockedIsSet || m_channelPowerDbIsSet || m_channelSampleRateIsSet || m_audioSampleRateIsSet || m_stateIsSet || m_lastCodeIsSet || m_lastTimestampIsSet || m_lastFrequencyIsSet || m_lastRssiIsSet || m_lastSnrIsSet || m_callCountIsSet;
}
double SWGSELCALDemodReport::getChannelPowerDb() { return m_channelPowerDb; }
void SWGSELCALDemodReport::setChannelPowerDb(double value) { m_channelPowerDb = value; m_channelPowerDbIsSet = true; }
qint32 SWGSELCALDemodReport::getChannelSampleRate() { return m_channelSampleRate; }
void SWGSELCALDemodReport::setChannelSampleRate(qint32 value) { m_channelSampleRate = value; m_channelSampleRateIsSet = true; }
qint32 SWGSELCALDemodReport::getAudioSampleRate() { return m_audioSampleRate; }
void SWGSELCALDemodReport::setAudioSampleRate(qint32 value) { m_audioSampleRate = value; m_audioSampleRateIsSet = true; }
QString* SWGSELCALDemodReport::getState() { return m_state; }
void SWGSELCALDemodReport::setState(QString* value) { if (m_state != value) { delete m_state; m_state = value; } m_stateIsSet = true; }
QString* SWGSELCALDemodReport::getLastCode() { return m_lastCode; }
void SWGSELCALDemodReport::setLastCode(QString* value) { if (m_lastCode != value) { delete m_lastCode; m_lastCode = value; } m_lastCodeIsSet = true; }
QString* SWGSELCALDemodReport::getLastTimestamp() { return m_lastTimestamp; }
void SWGSELCALDemodReport::setLastTimestamp(QString* value) { if (m_lastTimestamp != value) { delete m_lastTimestamp; m_lastTimestamp = value; } m_lastTimestampIsSet = true; }
qint64 SWGSELCALDemodReport::getLastFrequency() { return m_lastFrequency; }
void SWGSELCALDemodReport::setLastFrequency(qint64 value) { m_lastFrequency = value; m_lastFrequencyIsSet = true; }
float SWGSELCALDemodReport::getLastRssi() { return m_lastRssi; }
void SWGSELCALDemodReport::setLastRssi(float value) { m_lastRssi = value; m_lastRssiIsSet = true; }
float SWGSELCALDemodReport::getLastSnr() { return m_lastSnr; }
void SWGSELCALDemodReport::setLastSnr(float value) { m_lastSnr = value; m_lastSnrIsSet = true; }
qint64 SWGSELCALDemodReport::getCallCount() { return m_callCount; }
void SWGSELCALDemodReport::setCallCount(qint64 value) { m_callCount = value; m_callCountIsSet = true; }
qint32 SWGSELCALDemodReport::getCarrierLocked() { return m_carrierLocked; }
void SWGSELCALDemodReport::setCarrierLocked(qint32 value) { m_carrierLocked = value; m_carrierLockedIsSet = true; }
float SWGSELCALDemodReport::getCarrierFrequencyOffset() { return m_carrierFrequencyOffset; }
void SWGSELCALDemodReport::setCarrierFrequencyOffset(float value) { m_carrierFrequencyOffset = value; m_carrierFrequencyOffsetIsSet = true; }
float SWGSELCALDemodReport::getToneFrequencyOffset() { return m_toneFrequencyOffset; }
void SWGSELCALDemodReport::setToneFrequencyOffset(float value) { m_toneFrequencyOffset = value; m_toneFrequencyOffsetIsSet = true; }
qint32 SWGSELCALDemodReport::getSquelchOpen() { return m_squelchOpen; }
void SWGSELCALDemodReport::setSquelchOpen(qint32 value) { m_squelchOpen = value; m_squelchOpenIsSet = true; }
}

82
swagger/sdrangel/code/qt5/client/SWGSELCALDemodReport.h

@ -0,0 +1,82 @@ @@ -0,0 +1,82 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// Qt model for SELCALDemod.yaml, following the Swagger client model interface.
#ifndef SWGSELCALDemodReport_H_
#define SWGSELCALDemodReport_H_
#include <QJsonObject>
#include <QString>
#include "SWGObject.h"
#include "export.h"
namespace SWGSDRangel {
class SWG_API SWGSELCALDemodReport : public SWGObject {
public:
SWGSELCALDemodReport();
explicit SWGSELCALDemodReport(QString* json);
~SWGSELCALDemodReport() override;
void init();
void cleanup();
QString asJson() override;
QJsonObject* asJsonObject() override;
void fromJsonObject(QJsonObject& json) override;
SWGSELCALDemodReport* fromJson(QString& json) override;
bool isSet() override;
double getChannelPowerDb();
void setChannelPowerDb(double value);
qint32 getChannelSampleRate();
void setChannelSampleRate(qint32 value);
qint32 getAudioSampleRate();
void setAudioSampleRate(qint32 value);
QString* getState();
void setState(QString* value);
QString* getLastCode();
void setLastCode(QString* value);
QString* getLastTimestamp();
void setLastTimestamp(QString* value);
qint64 getLastFrequency();
void setLastFrequency(qint64 value);
float getLastRssi();
void setLastRssi(float value);
float getLastSnr();
void setLastSnr(float value);
qint64 getCallCount();
void setCallCount(qint64 value);
qint32 getCarrierLocked();
void setCarrierLocked(qint32 value);
float getCarrierFrequencyOffset();
void setCarrierFrequencyOffset(float value);
float getToneFrequencyOffset();
void setToneFrequencyOffset(float value);
qint32 getSquelchOpen();
void setSquelchOpen(qint32 value);
private:
qint32 m_squelchOpen = 0;
bool m_squelchOpenIsSet = false;
float m_toneFrequencyOffset = 0;
bool m_toneFrequencyOffsetIsSet = false;
float m_carrierFrequencyOffset = 0;
bool m_carrierFrequencyOffsetIsSet = false;
qint32 m_carrierLocked = 0;
bool m_carrierLockedIsSet = false;
double m_channelPowerDb = 0;
bool m_channelPowerDbIsSet = false;
qint32 m_channelSampleRate = 0;
bool m_channelSampleRateIsSet = false;
qint32 m_audioSampleRate = 0;
bool m_audioSampleRateIsSet = false;
QString* m_state = nullptr;
bool m_stateIsSet = false;
QString* m_lastCode = nullptr;
bool m_lastCodeIsSet = false;
QString* m_lastTimestamp = nullptr;
bool m_lastTimestampIsSet = false;
qint64 m_lastFrequency = 0;
bool m_lastFrequencyIsSet = false;
float m_lastRssi = 0;
bool m_lastRssiIsSet = false;
float m_lastSnr = 0;
bool m_lastSnrIsSet = false;
qint64 m_callCount = 0;
bool m_callCountIsSet = false;
};
}
#endif

174
swagger/sdrangel/code/qt5/client/SWGSELCALDemodSettings.cpp

@ -0,0 +1,174 @@ @@ -0,0 +1,174 @@
// SPDX-License-Identifier: GPL-3.0-or-later
#include "SWGSELCALDemodSettings.h"
#include "SWGHelpers.h"
#include <QJsonDocument>
namespace SWGSDRangel {
SWGSELCALDemodSettings::SWGSELCALDemodSettings() = default;
SWGSELCALDemodSettings::SWGSELCALDemodSettings(QString* json) { init(); if (json) { fromJson(*json); } }
SWGSELCALDemodSettings::~SWGSELCALDemodSettings() { cleanup(); }
void SWGSELCALDemodSettings::cleanup()
{
delete m_audioDeviceName; m_audioDeviceName = nullptr;
delete m_filter; m_filter = nullptr;
delete m_udpAddress; m_udpAddress = nullptr;
delete m_logFilename; m_logFilename = nullptr;
delete m_title; m_title = nullptr;
delete m_reverseAPIAddress; m_reverseAPIAddress = nullptr;
delete m_channelMarker; m_channelMarker = nullptr;
delete m_rollupState; m_rollupState = nullptr;
}
void SWGSELCALDemodSettings::init()
{
cleanup();
m_squelch = 0; m_squelchIsSet = false;
m_autoToneFrequencyOffset = 0; m_autoToneFrequencyOffsetIsSet = false;
m_inputFrequencyOffset = 0; m_inputFrequencyOffsetIsSet = false;
m_rfBandwidth = 0; m_rfBandwidthIsSet = false;
m_modulation = 0; m_modulationIsSet = false;
m_toneFrequencyOffset = 0; m_toneFrequencyOffsetIsSet = false;
m_threshold = 0; m_thresholdIsSet = false;
m_volume = 0; m_volumeIsSet = false;
m_audioMute = 0; m_audioMuteIsSet = false;
m_audioDeviceName = new QString(); m_audioDeviceNameIsSet = false;
m_filter = new QString(); m_filterIsSet = false;
m_udpEnabled = 0; m_udpEnabledIsSet = false;
m_udpAddress = new QString(); m_udpAddressIsSet = false;
m_udpPort = 0; m_udpPortIsSet = false;
m_logFilename = new QString(); m_logFilenameIsSet = false;
m_logEnabled = 0; m_logEnabledIsSet = false;
m_rgbColor = 0; m_rgbColorIsSet = false;
m_title = new QString(); m_titleIsSet = false;
m_streamIndex = 0; m_streamIndexIsSet = false;
m_useReverseAPI = 0; m_useReverseAPIIsSet = false;
m_reverseAPIAddress = new QString(); m_reverseAPIAddressIsSet = false;
m_reverseAPIPort = 0; m_reverseAPIPortIsSet = false;
m_reverseAPIDeviceIndex = 0; m_reverseAPIDeviceIndexIsSet = false;
m_reverseAPIChannelIndex = 0; m_reverseAPIChannelIndexIsSet = false;
m_channelMarker = new SWGChannelMarker(); m_channelMarkerIsSet = false;
m_rollupState = new SWGRollupState(); m_rollupStateIsSet = false;
}
SWGSELCALDemodSettings* SWGSELCALDemodSettings::fromJson(QString& json)
{
auto object = QJsonDocument::fromJson(json.toUtf8()).object(); fromJsonObject(object); return this;
}
void SWGSELCALDemodSettings::fromJsonObject(QJsonObject& json)
{
if (json.contains("squelch")) { ::SWGSDRangel::setValue(&m_squelch,json["squelch"],"qint32",""); m_squelchIsSet = true; }
if (json.contains("autoToneFrequencyOffset")) { ::SWGSDRangel::setValue(&m_autoToneFrequencyOffset,json["autoToneFrequencyOffset"],"qint32",""); m_autoToneFrequencyOffsetIsSet = true; }
if (json.contains("inputFrequencyOffset")) { ::SWGSDRangel::setValue(&m_inputFrequencyOffset,json["inputFrequencyOffset"],"qint64",""); m_inputFrequencyOffsetIsSet = true; }
if (json.contains("rfBandwidth")) { ::SWGSDRangel::setValue(&m_rfBandwidth,json["rfBandwidth"],"float",""); m_rfBandwidthIsSet = true; }
if (json.contains("modulation")) { ::SWGSDRangel::setValue(&m_modulation,json["modulation"],"qint32",""); m_modulationIsSet = true; }
if (json.contains("toneFrequencyOffset")) { ::SWGSDRangel::setValue(&m_toneFrequencyOffset,json["toneFrequencyOffset"],"float",""); m_toneFrequencyOffsetIsSet = true; }
if (json.contains("threshold")) { ::SWGSDRangel::setValue(&m_threshold,json["threshold"],"float",""); m_thresholdIsSet = true; }
if (json.contains("volume")) { ::SWGSDRangel::setValue(&m_volume,json["volume"],"float",""); m_volumeIsSet = true; }
if (json.contains("audioMute")) { ::SWGSDRangel::setValue(&m_audioMute,json["audioMute"],"qint32",""); m_audioMuteIsSet = true; }
if (json.contains("audioDeviceName")) { ::SWGSDRangel::setValue(&m_audioDeviceName,json["audioDeviceName"],"QString","QString"); m_audioDeviceNameIsSet = true; }
if (json.contains("filter")) { ::SWGSDRangel::setValue(&m_filter,json["filter"],"QString","QString"); m_filterIsSet = true; }
if (json.contains("udpEnabled")) { ::SWGSDRangel::setValue(&m_udpEnabled,json["udpEnabled"],"qint32",""); m_udpEnabledIsSet = true; }
if (json.contains("udpAddress")) { ::SWGSDRangel::setValue(&m_udpAddress,json["udpAddress"],"QString","QString"); m_udpAddressIsSet = true; }
if (json.contains("udpPort")) { ::SWGSDRangel::setValue(&m_udpPort,json["udpPort"],"qint32",""); m_udpPortIsSet = true; }
if (json.contains("logFilename")) { ::SWGSDRangel::setValue(&m_logFilename,json["logFilename"],"QString","QString"); m_logFilenameIsSet = true; }
if (json.contains("logEnabled")) { ::SWGSDRangel::setValue(&m_logEnabled,json["logEnabled"],"qint32",""); m_logEnabledIsSet = true; }
if (json.contains("rgbColor")) { ::SWGSDRangel::setValue(&m_rgbColor,json["rgbColor"],"qint32",""); m_rgbColorIsSet = true; }
if (json.contains("title")) { ::SWGSDRangel::setValue(&m_title,json["title"],"QString","QString"); m_titleIsSet = true; }
if (json.contains("streamIndex")) { ::SWGSDRangel::setValue(&m_streamIndex,json["streamIndex"],"qint32",""); m_streamIndexIsSet = true; }
if (json.contains("useReverseAPI")) { ::SWGSDRangel::setValue(&m_useReverseAPI,json["useReverseAPI"],"qint32",""); m_useReverseAPIIsSet = true; }
if (json.contains("reverseAPIAddress")) { ::SWGSDRangel::setValue(&m_reverseAPIAddress,json["reverseAPIAddress"],"QString","QString"); m_reverseAPIAddressIsSet = true; }
if (json.contains("reverseAPIPort")) { ::SWGSDRangel::setValue(&m_reverseAPIPort,json["reverseAPIPort"],"qint32",""); m_reverseAPIPortIsSet = true; }
if (json.contains("reverseAPIDeviceIndex")) { ::SWGSDRangel::setValue(&m_reverseAPIDeviceIndex,json["reverseAPIDeviceIndex"],"qint32",""); m_reverseAPIDeviceIndexIsSet = true; }
if (json.contains("reverseAPIChannelIndex")) { ::SWGSDRangel::setValue(&m_reverseAPIChannelIndex,json["reverseAPIChannelIndex"],"qint32",""); m_reverseAPIChannelIndexIsSet = true; }
if (json.contains("channelMarker")) { ::SWGSDRangel::setValue(&m_channelMarker,json["channelMarker"],"SWGChannelMarker","SWGChannelMarker"); m_channelMarkerIsSet = true; }
if (json.contains("rollupState")) { ::SWGSDRangel::setValue(&m_rollupState,json["rollupState"],"SWGRollupState","SWGRollupState"); m_rollupStateIsSet = true; }
}
QString SWGSELCALDemodSettings::asJson()
{
auto* object = asJsonObject(); QString result = QJsonDocument(*object).toJson(); delete object; return result;
}
QJsonObject* SWGSELCALDemodSettings::asJsonObject()
{
auto* object = new QJsonObject();
if (m_squelchIsSet) { object->insert("squelch",QJsonValue(m_squelch)); }
if (m_autoToneFrequencyOffsetIsSet) { object->insert("autoToneFrequencyOffset",QJsonValue(m_autoToneFrequencyOffset)); }
if (m_inputFrequencyOffsetIsSet) { object->insert("inputFrequencyOffset",QJsonValue(m_inputFrequencyOffset)); }
if (m_rfBandwidthIsSet) { object->insert("rfBandwidth",QJsonValue(m_rfBandwidth)); }
if (m_modulationIsSet) { object->insert("modulation",QJsonValue(m_modulation)); }
if (m_toneFrequencyOffsetIsSet) { object->insert("toneFrequencyOffset",QJsonValue(m_toneFrequencyOffset)); }
if (m_thresholdIsSet) { object->insert("threshold",QJsonValue(m_threshold)); }
if (m_volumeIsSet) { object->insert("volume",QJsonValue(m_volume)); }
if (m_audioMuteIsSet) { object->insert("audioMute",QJsonValue(m_audioMute)); }
if (m_audioDeviceName && (m_audioDeviceNameIsSet || !m_audioDeviceName->isEmpty())) { toJsonValue(QString("audioDeviceName"),m_audioDeviceName,object,QString("QString")); }
if (m_filter && (m_filterIsSet || !m_filter->isEmpty())) { toJsonValue(QString("filter"),m_filter,object,QString("QString")); }
if (m_udpEnabledIsSet) { object->insert("udpEnabled",QJsonValue(m_udpEnabled)); }
if (m_udpAddress && (m_udpAddressIsSet || !m_udpAddress->isEmpty())) { toJsonValue(QString("udpAddress"),m_udpAddress,object,QString("QString")); }
if (m_udpPortIsSet) { object->insert("udpPort",QJsonValue(m_udpPort)); }
if (m_logFilename && (m_logFilenameIsSet || !m_logFilename->isEmpty())) { toJsonValue(QString("logFilename"),m_logFilename,object,QString("QString")); }
if (m_logEnabledIsSet) { object->insert("logEnabled",QJsonValue(m_logEnabled)); }
if (m_rgbColorIsSet) { object->insert("rgbColor",QJsonValue(m_rgbColor)); }
if (m_title && (m_titleIsSet || !m_title->isEmpty())) { toJsonValue(QString("title"),m_title,object,QString("QString")); }
if (m_streamIndexIsSet) { object->insert("streamIndex",QJsonValue(m_streamIndex)); }
if (m_useReverseAPIIsSet) { object->insert("useReverseAPI",QJsonValue(m_useReverseAPI)); }
if (m_reverseAPIAddress && (m_reverseAPIAddressIsSet || !m_reverseAPIAddress->isEmpty())) { toJsonValue(QString("reverseAPIAddress"),m_reverseAPIAddress,object,QString("QString")); }
if (m_reverseAPIPortIsSet) { object->insert("reverseAPIPort",QJsonValue(m_reverseAPIPort)); }
if (m_reverseAPIDeviceIndexIsSet) { object->insert("reverseAPIDeviceIndex",QJsonValue(m_reverseAPIDeviceIndex)); }
if (m_reverseAPIChannelIndexIsSet) { object->insert("reverseAPIChannelIndex",QJsonValue(m_reverseAPIChannelIndex)); }
if (m_channelMarker && (m_channelMarkerIsSet || m_channelMarker->isSet())) { toJsonValue(QString("channelMarker"),m_channelMarker,object,QString("SWGChannelMarker")); }
if (m_rollupState && (m_rollupStateIsSet || m_rollupState->isSet())) { toJsonValue(QString("rollupState"),m_rollupState,object,QString("SWGRollupState")); }
return object;
}
bool SWGSELCALDemodSettings::isSet()
{
return m_squelchIsSet || m_autoToneFrequencyOffsetIsSet || m_inputFrequencyOffsetIsSet || m_rfBandwidthIsSet || m_modulationIsSet || m_toneFrequencyOffsetIsSet || m_thresholdIsSet || m_volumeIsSet || m_audioMuteIsSet || m_audioDeviceNameIsSet || m_filterIsSet || m_udpEnabledIsSet || m_udpAddressIsSet || m_udpPortIsSet || m_logFilenameIsSet || m_logEnabledIsSet || m_rgbColorIsSet || m_titleIsSet || m_streamIndexIsSet || m_useReverseAPIIsSet || m_reverseAPIAddressIsSet || m_reverseAPIPortIsSet || m_reverseAPIDeviceIndexIsSet || m_reverseAPIChannelIndexIsSet || m_channelMarkerIsSet || m_rollupStateIsSet;
}
qint64 SWGSELCALDemodSettings::getInputFrequencyOffset() { return m_inputFrequencyOffset; }
void SWGSELCALDemodSettings::setInputFrequencyOffset(qint64 value) { m_inputFrequencyOffset = value; m_inputFrequencyOffsetIsSet = true; }
float SWGSELCALDemodSettings::getRfBandwidth() { return m_rfBandwidth; }
void SWGSELCALDemodSettings::setRfBandwidth(float value) { m_rfBandwidth = value; m_rfBandwidthIsSet = true; }
qint32 SWGSELCALDemodSettings::getModulation() { return m_modulation; }
void SWGSELCALDemodSettings::setModulation(qint32 value) { m_modulation = value; m_modulationIsSet = true; }
float SWGSELCALDemodSettings::getToneFrequencyOffset() { return m_toneFrequencyOffset; }
void SWGSELCALDemodSettings::setToneFrequencyOffset(float value) { m_toneFrequencyOffset = value; m_toneFrequencyOffsetIsSet = true; }
float SWGSELCALDemodSettings::getThreshold() { return m_threshold; }
void SWGSELCALDemodSettings::setThreshold(float value) { m_threshold = value; m_thresholdIsSet = true; }
float SWGSELCALDemodSettings::getVolume() { return m_volume; }
void SWGSELCALDemodSettings::setVolume(float value) { m_volume = value; m_volumeIsSet = true; }
qint32 SWGSELCALDemodSettings::getAudioMute() { return m_audioMute; }
void SWGSELCALDemodSettings::setAudioMute(qint32 value) { m_audioMute = value; m_audioMuteIsSet = true; }
QString* SWGSELCALDemodSettings::getAudioDeviceName() { return m_audioDeviceName; }
void SWGSELCALDemodSettings::setAudioDeviceName(QString* value) { if (m_audioDeviceName != value) { delete m_audioDeviceName; m_audioDeviceName = value; } m_audioDeviceNameIsSet = true; }
QString* SWGSELCALDemodSettings::getFilter() { return m_filter; }
void SWGSELCALDemodSettings::setFilter(QString* value) { if (m_filter != value) { delete m_filter; m_filter = value; } m_filterIsSet = true; }
qint32 SWGSELCALDemodSettings::getUdpEnabled() { return m_udpEnabled; }
void SWGSELCALDemodSettings::setUdpEnabled(qint32 value) { m_udpEnabled = value; m_udpEnabledIsSet = true; }
QString* SWGSELCALDemodSettings::getUdpAddress() { return m_udpAddress; }
void SWGSELCALDemodSettings::setUdpAddress(QString* value) { if (m_udpAddress != value) { delete m_udpAddress; m_udpAddress = value; } m_udpAddressIsSet = true; }
qint32 SWGSELCALDemodSettings::getUdpPort() { return m_udpPort; }
void SWGSELCALDemodSettings::setUdpPort(qint32 value) { m_udpPort = value; m_udpPortIsSet = true; }
QString* SWGSELCALDemodSettings::getLogFilename() { return m_logFilename; }
void SWGSELCALDemodSettings::setLogFilename(QString* value) { if (m_logFilename != value) { delete m_logFilename; m_logFilename = value; } m_logFilenameIsSet = true; }
qint32 SWGSELCALDemodSettings::getLogEnabled() { return m_logEnabled; }
void SWGSELCALDemodSettings::setLogEnabled(qint32 value) { m_logEnabled = value; m_logEnabledIsSet = true; }
qint32 SWGSELCALDemodSettings::getRgbColor() { return m_rgbColor; }
void SWGSELCALDemodSettings::setRgbColor(qint32 value) { m_rgbColor = value; m_rgbColorIsSet = true; }
QString* SWGSELCALDemodSettings::getTitle() { return m_title; }
void SWGSELCALDemodSettings::setTitle(QString* value) { if (m_title != value) { delete m_title; m_title = value; } m_titleIsSet = true; }
qint32 SWGSELCALDemodSettings::getStreamIndex() { return m_streamIndex; }
void SWGSELCALDemodSettings::setStreamIndex(qint32 value) { m_streamIndex = value; m_streamIndexIsSet = true; }
qint32 SWGSELCALDemodSettings::getUseReverseApi() { return m_useReverseAPI; }
void SWGSELCALDemodSettings::setUseReverseApi(qint32 value) { m_useReverseAPI = value; m_useReverseAPIIsSet = true; }
QString* SWGSELCALDemodSettings::getReverseApiAddress() { return m_reverseAPIAddress; }
void SWGSELCALDemodSettings::setReverseApiAddress(QString* value) { if (m_reverseAPIAddress != value) { delete m_reverseAPIAddress; m_reverseAPIAddress = value; } m_reverseAPIAddressIsSet = true; }
qint32 SWGSELCALDemodSettings::getReverseApiPort() { return m_reverseAPIPort; }
void SWGSELCALDemodSettings::setReverseApiPort(qint32 value) { m_reverseAPIPort = value; m_reverseAPIPortIsSet = true; }
qint32 SWGSELCALDemodSettings::getReverseApiDeviceIndex() { return m_reverseAPIDeviceIndex; }
void SWGSELCALDemodSettings::setReverseApiDeviceIndex(qint32 value) { m_reverseAPIDeviceIndex = value; m_reverseAPIDeviceIndexIsSet = true; }
qint32 SWGSELCALDemodSettings::getReverseApiChannelIndex() { return m_reverseAPIChannelIndex; }
void SWGSELCALDemodSettings::setReverseApiChannelIndex(qint32 value) { m_reverseAPIChannelIndex = value; m_reverseAPIChannelIndexIsSet = true; }
SWGChannelMarker* SWGSELCALDemodSettings::getChannelMarker() { return m_channelMarker; }
void SWGSELCALDemodSettings::setChannelMarker(SWGChannelMarker* value) { if (m_channelMarker != value) { delete m_channelMarker; m_channelMarker = value; } m_channelMarkerIsSet = true; }
SWGRollupState* SWGSELCALDemodSettings::getRollupState() { return m_rollupState; }
void SWGSELCALDemodSettings::setRollupState(SWGRollupState* value) { if (m_rollupState != value) { delete m_rollupState; m_rollupState = value; } m_rollupStateIsSet = true; }
qint32 SWGSELCALDemodSettings::getAutoToneFrequencyOffset() { return m_autoToneFrequencyOffset; }
void SWGSELCALDemodSettings::setAutoToneFrequencyOffset(qint32 value) { m_autoToneFrequencyOffset = value; m_autoToneFrequencyOffsetIsSet = true; }
qint32 SWGSELCALDemodSettings::getSquelch() { return m_squelch; }
void SWGSELCALDemodSettings::setSquelch(qint32 value) { m_squelch = value; m_squelchIsSet = true; }
}

132
swagger/sdrangel/code/qt5/client/SWGSELCALDemodSettings.h

@ -0,0 +1,132 @@ @@ -0,0 +1,132 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// Qt model for SELCALDemod.yaml, following the Swagger client model interface.
#ifndef SWGSELCALDemodSettings_H_
#define SWGSELCALDemodSettings_H_
#include <QJsonObject>
#include <QString>
#include "SWGObject.h"
#include "export.h"
#include "SWGChannelMarker.h"
#include "SWGRollupState.h"
namespace SWGSDRangel {
class SWG_API SWGSELCALDemodSettings : public SWGObject {
public:
SWGSELCALDemodSettings();
explicit SWGSELCALDemodSettings(QString* json);
~SWGSELCALDemodSettings() override;
void init();
void cleanup();
QString asJson() override;
QJsonObject* asJsonObject() override;
void fromJsonObject(QJsonObject& json) override;
SWGSELCALDemodSettings* fromJson(QString& json) override;
bool isSet() override;
qint64 getInputFrequencyOffset();
void setInputFrequencyOffset(qint64 value);
float getRfBandwidth();
void setRfBandwidth(float value);
qint32 getModulation();
void setModulation(qint32 value);
float getToneFrequencyOffset();
void setToneFrequencyOffset(float value);
float getThreshold();
void setThreshold(float value);
float getVolume();
void setVolume(float value);
qint32 getAudioMute();
void setAudioMute(qint32 value);
QString* getAudioDeviceName();
void setAudioDeviceName(QString* value);
QString* getFilter();
void setFilter(QString* value);
qint32 getUdpEnabled();
void setUdpEnabled(qint32 value);
QString* getUdpAddress();
void setUdpAddress(QString* value);
qint32 getUdpPort();
void setUdpPort(qint32 value);
QString* getLogFilename();
void setLogFilename(QString* value);
qint32 getLogEnabled();
void setLogEnabled(qint32 value);
qint32 getRgbColor();
void setRgbColor(qint32 value);
QString* getTitle();
void setTitle(QString* value);
qint32 getStreamIndex();
void setStreamIndex(qint32 value);
qint32 getUseReverseApi();
void setUseReverseApi(qint32 value);
QString* getReverseApiAddress();
void setReverseApiAddress(QString* value);
qint32 getReverseApiPort();
void setReverseApiPort(qint32 value);
qint32 getReverseApiDeviceIndex();
void setReverseApiDeviceIndex(qint32 value);
qint32 getReverseApiChannelIndex();
void setReverseApiChannelIndex(qint32 value);
SWGChannelMarker* getChannelMarker();
void setChannelMarker(SWGChannelMarker* value);
SWGRollupState* getRollupState();
void setRollupState(SWGRollupState* value);
qint32 getAutoToneFrequencyOffset();
void setAutoToneFrequencyOffset(qint32 value);
qint32 getSquelch();
void setSquelch(qint32 value);
private:
qint32 m_squelch = 0;
bool m_squelchIsSet = false;
qint32 m_autoToneFrequencyOffset = 0;
bool m_autoToneFrequencyOffsetIsSet = false;
qint64 m_inputFrequencyOffset = 0;
bool m_inputFrequencyOffsetIsSet = false;
float m_rfBandwidth = 0;
bool m_rfBandwidthIsSet = false;
qint32 m_modulation = 0;
bool m_modulationIsSet = false;
float m_toneFrequencyOffset = 0;
bool m_toneFrequencyOffsetIsSet = false;
float m_threshold = 0;
bool m_thresholdIsSet = false;
float m_volume = 0;
bool m_volumeIsSet = false;
qint32 m_audioMute = 0;
bool m_audioMuteIsSet = false;
QString* m_audioDeviceName = nullptr;
bool m_audioDeviceNameIsSet = false;
QString* m_filter = nullptr;
bool m_filterIsSet = false;
qint32 m_udpEnabled = 0;
bool m_udpEnabledIsSet = false;
QString* m_udpAddress = nullptr;
bool m_udpAddressIsSet = false;
qint32 m_udpPort = 0;
bool m_udpPortIsSet = false;
QString* m_logFilename = nullptr;
bool m_logFilenameIsSet = false;
qint32 m_logEnabled = 0;
bool m_logEnabledIsSet = false;
qint32 m_rgbColor = 0;
bool m_rgbColorIsSet = false;
QString* m_title = nullptr;
bool m_titleIsSet = false;
qint32 m_streamIndex = 0;
bool m_streamIndexIsSet = false;
qint32 m_useReverseAPI = 0;
bool m_useReverseAPIIsSet = false;
QString* m_reverseAPIAddress = nullptr;
bool m_reverseAPIAddressIsSet = false;
qint32 m_reverseAPIPort = 0;
bool m_reverseAPIPortIsSet = false;
qint32 m_reverseAPIDeviceIndex = 0;
bool m_reverseAPIDeviceIndexIsSet = false;
qint32 m_reverseAPIChannelIndex = 0;
bool m_reverseAPIChannelIndexIsSet = false;
SWGChannelMarker* m_channelMarker = nullptr;
bool m_channelMarkerIsSet = false;
SWGRollupState* m_rollupState = nullptr;
bool m_rollupStateIsSet = false;
};
}
#endif
Loading…
Cancel
Save