Browse Source

ADSB: Add colour aircraft icons. Add API key for CartoDB. Run in server mode. Support Aircraft feature.

ACARS: Add Web API support. Add additional reporting to Aircraft feature. Add Iridium support.
Aircraft feature: Add Web API support. Add additional fields and data. Add coverage map. Support feeding. Archive messages.
SELCAL: Report calls to Aircraft feature.
Map: Update Cesium. Add flyby mode. Add ND, EFIS, RMP, DCDU. Add Boeing styling. Fix z-ordering on 2D map. Support sounds on 3D map. Save/restore splitter state. Hide quota using Cesium options when API not set. Link aircraft with Aircraft feature.
chirpmodem-v8.1.0
Jon Beniston 4 weeks ago
parent
commit
750d0b3856
  1. 4
      CMakeLists.txt
  2. 17
      CMakePresets.json
  3. 13
      app/main.cpp
  4. BIN
      doc/img/AcarsDemod_chart.png
  5. BIN
      doc/img/AcarsDemod_decode.png
  6. BIN
      doc/img/AcarsDemod_plugin.png
  7. BIN
      doc/img/AcarsDemod_table.png
  8. BIN
      doc/img/AircraftFeature_aircraft_tab.png
  9. BIN
      doc/img/AircraftFeature_aircraft_table.png
  10. BIN
      doc/img/AircraftFeature_clearance.png
  11. BIN
      doc/img/AircraftFeature_flight_plan.png
  12. BIN
      doc/img/AircraftFeature_flight_profile.png
  13. BIN
      doc/img/AircraftFeature_flights_table.png
  14. BIN
      doc/img/AircraftFeature_loadsheet.png
  15. BIN
      doc/img/AircraftFeature_statistics.png
  16. 12
      plugins/channelrx/CMakeLists.txt
  17. 11
      plugins/channelrx/demodacars/CMakeLists.txt
  18. 6449
      plugins/channelrx/demodacars/acarsaero.h
  19. 1283
      plugins/channelrx/demodacars/acarsdemod.cpp
  20. 38
      plugins/channelrx/demodacars/acarsdemod.h
  21. 34
      plugins/channelrx/demodacars/acarsdemodbaseband.cpp
  22. 160
      plugins/channelrx/demodacars/acarsdemodgui.cpp
  23. 11
      plugins/channelrx/demodacars/acarsdemodgui.h
  24. 71
      plugins/channelrx/demodacars/acarsdemodgui.ui
  25. 1
      plugins/channelrx/demodacars/acarsdemodicons.qrc
  26. 46
      plugins/channelrx/demodacars/acarsdemodsettings.cpp
  27. 273
      plugins/channelrx/demodacars/acarsdemodsettings.h
  28. 871
      plugins/channelrx/demodacars/acarsdemodsink.cpp
  29. 36
      plugins/channelrx/demodacars/acarsdemodsink.h
  30. 6
      plugins/channelrx/demodacars/acarsdemodwebapiadapter.cpp
  31. 4938
      plugins/channelrx/demodacars/acarsdemodworker.cpp
  32. 54
      plugins/channelrx/demodacars/acarsdemodworker.h
  33. 137
      plugins/channelrx/demodacars/acarshfdl.h
  34. 849
      plugins/channelrx/demodacars/acarsiridium.h
  35. 346
      plugins/channelrx/demodacars/acarsiridiumchannelizer.h
  36. 147
      plugins/channelrx/demodacars/acarsiridiumfft.h
  37. 1118
      plugins/channelrx/demodacars/acarsiridiumframe.h
  38. 315
      plugins/channelrx/demodacars/acarsiridiumscanner.h
  39. 2216
      plugins/channelrx/demodacars/acarsmessage.cpp
  40. BIN
      plugins/channelrx/demodacars/icons/forward.png
  41. 174
      plugins/channelrx/demodacars/readme.md
  42. 101
      plugins/channelrx/demodacars/vdl2atn.cpp
  43. 10
      plugins/channelrx/demodacars/vdl2atn.h
  44. 12
      plugins/channelrx/demodadsb/CMakeLists.txt
  45. 474
      plugins/channelrx/demodadsb/adsbaircraft.cpp
  46. 389
      plugins/channelrx/demodadsb/adsbaircraft.h
  47. 471
      plugins/channelrx/demodadsb/adsbaircrafttablemodel.cpp
  48. 91
      plugins/channelrx/demodadsb/adsbaircrafttablemodel.h
  49. 45
      plugins/channelrx/demodadsb/adsbdemod.cpp
  50. 10
      plugins/channelrx/demodadsb/adsbdemod.h
  51. 18
      plugins/channelrx/demodadsb/adsbdemoddisplaydialog.cpp
  52. 67
      plugins/channelrx/demodadsb/adsbdemoddisplaydialog.ui
  53. 6475
      plugins/channelrx/demodadsb/adsbdemodgui.cpp
  54. 708
      plugins/channelrx/demodadsb/adsbdemodgui.h
  55. 620
      plugins/channelrx/demodadsb/adsbdemodgui.ui
  56. 3932
      plugins/channelrx/demodadsb/adsbdemodmapliveries.qrc
  57. 3
      plugins/channelrx/demodadsb/adsbdemodnotificationdialog.cpp
  58. 101
      plugins/channelrx/demodadsb/adsbdemodsettings.cpp
  59. 10
      plugins/channelrx/demodadsb/adsbdemodsettings.h
  60. 14
      plugins/channelrx/demodadsb/adsbdemodsinkworker.cpp
  61. 387
      plugins/channelrx/demodadsb/adsbdemodtracker.cpp
  62. 374
      plugins/channelrx/demodadsb/adsbdemodtracker.h
  63. 5466
      plugins/channelrx/demodadsb/adsbdemodtrackerdecode.cpp
  64. 118
      plugins/channelrx/demodadsb/adsbdemodworker.cpp
  65. 19
      plugins/channelrx/demodadsb/adsbdemodworker.h
  66. 11
      plugins/channelrx/demodadsb/adsbosmtemplateserver.h
  67. BIN
      plugins/channelrx/demodadsb/map/liveries/A20N.png
  68. BIN
      plugins/channelrx/demodadsb/map/liveries/A20N_AAN.png
  69. BIN
      plugins/channelrx/demodadsb/map/liveries/A20N_ACI.png
  70. BIN
      plugins/channelrx/demodadsb/map/liveries/A20N_ADH.png
  71. BIN
      plugins/channelrx/demodadsb/map/liveries/A20N_AEE.png
  72. BIN
      plugins/channelrx/demodadsb/map/liveries/A20N_AFL.png
  73. BIN
      plugins/channelrx/demodadsb/map/liveries/A20N_AFX.png
  74. BIN
      plugins/channelrx/demodadsb/map/liveries/A20N_AHY.png
  75. BIN
      plugins/channelrx/demodadsb/map/liveries/A20N_AIC.png
  76. BIN
      plugins/channelrx/demodadsb/map/liveries/A20N_AIC_VTI.png
  77. BIN
      plugins/channelrx/demodadsb/map/liveries/A20N_AIQ.png
  78. BIN
      plugins/channelrx/demodadsb/map/liveries/A20N_ALK.png
  79. BIN
      plugins/channelrx/demodadsb/map/liveries/A20N_AMC.png
  80. BIN
      plugins/channelrx/demodadsb/map/liveries/A20N_AMU.png
  81. BIN
      plugins/channelrx/demodadsb/map/liveries/A20N_AMV.png
  82. BIN
      plugins/channelrx/demodadsb/map/liveries/A20N_ANA.png
  83. BIN
      plugins/channelrx/demodadsb/map/liveries/A20N_ANZ.png
  84. BIN
      plugins/channelrx/demodadsb/map/liveries/A20N_APJ.png
  85. BIN
      plugins/channelrx/demodadsb/map/liveries/A20N_AUA.png
  86. BIN
      plugins/channelrx/demodadsb/map/liveries/A20N_AUL.png
  87. BIN
      plugins/channelrx/demodadsb/map/liveries/A20N_AVA.png
  88. BIN
      plugins/channelrx/demodadsb/map/liveries/A20N_AXM.png
  89. BIN
      plugins/channelrx/demodadsb/map/liveries/A20N_AZU.png
  90. BIN
      plugins/channelrx/demodadsb/map/liveries/A20N_BAV.png
  91. BIN
      plugins/channelrx/demodadsb/map/liveries/A20N_BAW.png
  92. BIN
      plugins/channelrx/demodadsb/map/liveries/A20N_BEL.png
  93. BIN
      plugins/channelrx/demodadsb/map/liveries/A20N_BHE.png
  94. BIN
      plugins/channelrx/demodadsb/map/liveries/A20N_BTK.png
  95. BIN
      plugins/channelrx/demodadsb/map/liveries/A20N_BVX.png
  96. BIN
      plugins/channelrx/demodadsb/map/liveries/A20N_CBJ.png
  97. BIN
      plugins/channelrx/demodadsb/map/liveries/A20N_CCA.png
  98. BIN
      plugins/channelrx/demodadsb/map/liveries/A20N_CCM.png
  99. BIN
      plugins/channelrx/demodadsb/map/liveries/A20N_CDC.png
  100. BIN
      plugins/channelrx/demodadsb/map/liveries/A20N_CEB.png
  101. Some files were not shown because too many files have changed in this diff Show More

4
CMakeLists.txt

@ -1348,13 +1348,13 @@ endif() @@ -1348,13 +1348,13 @@ endif()
if (LINUX AND ENABLE_EXTERNAL_LIBRARIES)
install(DIRECTORY ${EXTERNAL_BUILD_LIBRARIES}/lib${LIB_SUFFIX}/ DESTINATION ${INSTALL_LIB_DIR})
endif()
if(WIN32)
if(WIN32 AND BUILD_GUI)
include(DeployQt)
windeployqt(${CMAKE_PROJECT_NAME} ${SDRANGEL_BINARY_BIN_DIR} ${PROJECT_SOURCE_DIR}/sdrgui/resources)
endif()
# Install debug symbols
if (WIN32)
if (WIN32 AND BUILD_GUI)
install(FILES $<TARGET_PROPERTY:${CMAKE_PROJECT_NAME},RUNTIME_OUTPUT_DIRECTORY>/${CMAKE_PROJECT_NAME}stripped.pdb CONFIGURATIONS Release DESTINATION ${INSTALL_LIB_DIR} RENAME ${CMAKE_PROJECT_NAME}.pdb)
install(FILES $<TARGET_PDB_FILE:${CMAKE_PROJECT_NAME}> CONFIGURATIONS Debug RelWithDebInfo DESTINATION ${INSTALL_BIN_DIR} )
endif()

17
CMakePresets.json

@ -53,20 +53,21 @@ @@ -53,20 +53,21 @@
"RX_SAMPLE_24BIT": "ON",
"ARCH_OPT": "SSE4_2",
"HIDE_CONSOLE": "OFF",
"ENABLE_AIRSPY": "ON",
"ENABLE_AIRSPY": "OFF",
"ENABLE_AIRSPYHF": "ON",
"ENABLE_BLADERF": "ON",
"ENABLE_BLADERF": "OFF",
"ENABLE_HACKRF": "ON",
"ENABLE_IIO": "ON",
"ENABLE_MIRISDR": "OFF",
"ENABLE_PERSEUS": "ON",
"ENABLE_PERSEUS": "OFF",
"ENABLE_RTLSDR": "ON",
"ENABLE_SDRPLAY": "ON",
"ENABLE_SOAPYSDR": "ON",
"ENABLE_XTRX": "ON",
"ENABLE_SOAPYSDR": "OFF",
"ENABLE_XTRX": "OFF",
"ENABLE_USRP": "ON",
"BUILD_SERVER": "OFF",
"BUILD_MCP_BUNDLE": "ON",
"ENABLE_PROFILER": "ON",
"CMAKE_PREFIX_PATH": "C:/Qt/5.15.2/msvc2019_64;C:/Applications/boost_1_81_0"
},
"warnings": {
@ -103,7 +104,8 @@ @@ -103,7 +104,8 @@
},
{
"name": "default-windows",
"configurePreset": "default-windows"
"configurePreset": "default-windows",
"jobs": 12
},
{
"name": "default-qt6",
@ -111,7 +113,8 @@ @@ -111,7 +113,8 @@
},
{
"name": "default-qt6-windows",
"configurePreset": "default-qt6-windows"
"configurePreset": "default-qt6-windows",
"jobs": 12
}
]
}

13
app/main.cpp

@ -330,6 +330,19 @@ static int runQtApplication(int argc, char* argv[], qtwebapp::LoggerWithFile *lo @@ -330,6 +330,19 @@ static int runQtApplication(int argc, char* argv[], qtwebapp::LoggerWithFile *lo
int main(int argc, char* argv[])
{
// Chromium (in QtWebEngine) is limited to 60 FPS - disable that, so we can run at monitor's refresh rate
if (qgetenv("SDRANGEL_FRAME_RATE_LIMIT") != "1")
{
const QByteArray flags = qgetenv("QTWEBENGINE_CHROMIUM_FLAGS");
if (!flags.contains("disable-frame-rate-limit"))
{
qputenv("QTWEBENGINE_CHROMIUM_FLAGS",
flags.isEmpty() ? QByteArray("--disable-frame-rate-limit")
: flags + " --disable-frame-rate-limit");
}
}
#ifdef __APPLE__
// Request OpenGL 3.3 context, needed for glspectrum and 3D Map feature
// Note that Mac only supports CoreProfile, so any deprecated OpenGL 2 features

BIN
doc/img/AcarsDemod_chart.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 31 KiB

BIN
doc/img/AcarsDemod_decode.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 115 KiB

BIN
doc/img/AcarsDemod_plugin.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 21 KiB

BIN
doc/img/AcarsDemod_table.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 87 KiB

BIN
doc/img/AircraftFeature_aircraft_tab.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 68 KiB

BIN
doc/img/AircraftFeature_aircraft_table.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 242 KiB

BIN
doc/img/AircraftFeature_clearance.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 28 KiB

BIN
doc/img/AircraftFeature_flight_plan.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 233 KiB

BIN
doc/img/AircraftFeature_flight_profile.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 26 KiB

BIN
doc/img/AircraftFeature_flights_table.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 76 KiB

BIN
doc/img/AircraftFeature_loadsheet.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 30 KiB

BIN
doc/img/AircraftFeature_statistics.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 70 KiB

12
plugins/channelrx/CMakeLists.txt

@ -22,7 +22,17 @@ if (ENABLE_CHANNELRX_FREQSCANNER) @@ -22,7 +22,17 @@ if (ENABLE_CHANNELRX_FREQSCANNER)
add_subdirectory(freqscanner)
endif()
if (ENABLE_CHANNELRX_DEMODADSB AND Qt${QT_DEFAULT_MAJOR_VERSION}Quick_FOUND AND Qt${QT_DEFAULT_MAJOR_VERSION}QuickWidgets_FOUND AND Qt${QT_DEFAULT_MAJOR_VERSION}Positioning_FOUND AND Qt${QT_DEFAULT_MAJOR_VERSION}TextToSpeech_FOUND)
if (SERVER_MODE)
set(DEMODADSB_GUI_DEPS_FOUND TRUE)
else()
if (Qt${QT_DEFAULT_MAJOR_VERSION}Quick_FOUND AND Qt${QT_DEFAULT_MAJOR_VERSION}QuickWidgets_FOUND AND Qt${QT_DEFAULT_MAJOR_VERSION}TextToSpeech_FOUND)
set(DEMODADSB_GUI_DEPS_FOUND TRUE)
else()
set(DEMODADSB_GUI_DEPS_FOUND FALSE)
endif()
endif()
if (ENABLE_CHANNELRX_DEMODADSB AND DEMODADSB_GUI_DEPS_FOUND AND Qt${QT_DEFAULT_MAJOR_VERSION}Positioning_FOUND)
add_subdirectory(demodadsb)
# add_subdirectory(demodvormc)
else()

11
plugins/channelrx/demodacars/CMakeLists.txt

@ -9,8 +9,6 @@ set(demodacars_SOURCES @@ -9,8 +9,6 @@ set(demodacars_SOURCES
acarsdemodwebapiadapter.cpp
acarsdemodworker.cpp
acarsdemoddata.qrc
acarsmessage.cpp
acarsmultipartassembler.cpp
)
set(demodacars_HEADERS
@ -21,14 +19,15 @@ set(demodacars_HEADERS @@ -21,14 +19,15 @@ set(demodacars_HEADERS
acarsdemodplugin.h
acarsdemodwebapiadapter.h
acarsdemodworker.h
acarsmessage.h
acarsmultipartassembler.h
acarstextformat.h
acarsoqpsk.h
acarsvdl2.h
acarshfdl.h
acarsaero.h
do219.h
acarsiridium.h
acarsiridiumframe.h
acarsiridiumfft.h
acarsiridiumchannelizer.h
acarsiridiumscanner.h
vdl2atn.h
)

6449
plugins/channelrx/demodacars/acarsaero.h

File diff suppressed because it is too large Load Diff

1283
plugins/channelrx/demodacars/acarsdemod.cpp

File diff suppressed because it is too large Load Diff

38
plugins/channelrx/demodacars/acarsdemod.h

@ -31,6 +31,7 @@ @@ -31,6 +31,7 @@
#include "dsp/basebandsamplesink.h"
#include "channel/channelapi.h"
#include "util/message.h"
#include "maincore.h" // MsgAcarsPacket subclasses MainCore::MsgPacket
#include "acarsdemodbaseband.h"
#include "acarsdemodsettings.h"
@ -150,6 +151,37 @@ public: @@ -150,6 +151,37 @@ public:
{ }
};
// An ACARS block, plus what the bearer knew about it that the block itself does not
// say. VDL-2 puts the aircraft's 24 bit ICAO address in the AVLC header of the frame
// the block came out of, where the block names only a registration.
//
// A subclass rather than a separate message so that the address travels WITH its
// packet: there is then no ordering to get right and no way for an address to be
// applied to the wrong block. MainCore::MsgPacket::match() matches this too, because
// Message::matchIdentifier defers to the base class, so the existing packet handling
// - the APRS pipe, the UDP feed, the log - needs no change and sees a plain packet.
class MsgAcarsPacket : public MainCore::MsgPacket {
MESSAGE_CLASS_DECLARATION
public:
//!< 0 when the bearer gave no address, which is every bearer but VDL-2
quint32 getIcao() const { return m_icao; }
static MsgAcarsPacket* create(const QObject *pipeSource, QByteArray packet, quint32 icao)
{
return new MsgAcarsPacket(pipeSource, packet, QDateTime::currentDateTime(), icao);
}
private:
quint32 m_icao;
MsgAcarsPacket(const QObject *pipeSource, QByteArray packet, QDateTime dateTime,
quint32 icao) :
MainCore::MsgPacket(pipeSource, packet, dateTime),
m_icao(icao)
{ }
};
// A demodulated VDL-2 AVLC frame that does not carry an ACARS message (XID/GSIF,
// X.25, supervisory frames). ACARS frames go out as MainCore::MsgPacket instead, so
// downstream consumers of that message always see pure ACARS bytes.
@ -224,11 +256,17 @@ public: @@ -224,11 +256,17 @@ public:
SWGSDRangel::SWGChannelSettings& response,
const AcarsDemodSettings& settings);
virtual int webapiReportGet(
SWGSDRangel::SWGChannelReport& response,
QString& errorMessage);
static void webapiUpdateChannelSettings(
AcarsDemodSettings& settings,
const QStringList& channelSettingsKeys,
SWGSDRangel::SWGChannelSettings& response);
void webapiFormatChannelReport(SWGSDRangel::SWGChannelReport& response);
ScopeVis *getScopeSink() { return m_basebandSink->getScopeSink(); }
double getMagSq() const { return m_basebandSink->getMagSq(); }

34
plugins/channelrx/demodacars/acarsdemodbaseband.cpp

@ -18,6 +18,8 @@ @@ -18,6 +18,8 @@
#include <QDebug>
#include <algorithm>
#include "dsp/dspengine.h"
#include "dsp/dspcommands.h"
#include "dsp/downchannelizer.h"
@ -26,6 +28,21 @@ @@ -26,6 +28,21 @@
MESSAGE_CLASS_DEFINITION(AcarsDemodBaseband::MsgConfigureAcarsDemodBaseband, Message)
// Up to 16x the standard policy (10 s of nominal samples): a burst's decode chain
// (multiple Viterbi attempts, turbo re-estimation, header repair) runs synchronously at
// the end of the burst and can take tens of milliseconds - and clusters of bursts
// compound it - which at accelerated file replay (10x and beyond) would overflow the
// 0.64 s standard FIFO. But capped in samples, since the FIFO is allocated in full: at
// 16x an 8 MS/s Iridium channel took 655 MB for its FIFO alone, and several channels on
// a wideband device took gigabytes. The cap is 8M samples (64 MB with 24 bit samples), still over a
// second at 8 MS/s.
static unsigned int fifoSize(unsigned int sampleRate)
{
const unsigned int standard = SampleSinkFifo::getSizePolicy(sampleRate);
const unsigned int maxSamples = 8 * 1024 * 1024;
return std::max(standard, std::min(standard * 16, maxSamples));
}
AcarsDemodBaseband::AcarsDemodBaseband(AcarsDemod *packetDemod) :
m_sink(packetDemod),
m_running(false)
@ -33,12 +50,7 @@ AcarsDemodBaseband::AcarsDemodBaseband(AcarsDemod *packetDemod) : @@ -33,12 +50,7 @@ AcarsDemodBaseband::AcarsDemodBaseband(AcarsDemod *packetDemod) :
qDebug("AcarsDemodBaseband::AcarsDemodBaseband");
m_sink.setScopeSink(&m_scopeSink);
// 16x the standard policy (10 s of nominal samples): a burst's decode chain
// (multiple Viterbi attempts, turbo re-estimation, header repair) runs
// synchronously at the end of the burst and can take tens of milliseconds -
// and clusters of bursts compound it - which at accelerated file replay (10x
// and beyond) would overflow the 0.64 s standard FIFO
m_sampleFifo.setSize(SampleSinkFifo::getSizePolicy(48000) * 16);
m_sampleFifo.setSize(fifoSize(48000));
m_channelizer = new DownChannelizer(&m_sink);
}
@ -150,8 +162,7 @@ bool AcarsDemodBaseband::handleMessage(const Message& cmd) @@ -150,8 +162,7 @@ bool AcarsDemodBaseband::handleMessage(const Message& cmd)
DSPSignalNotification& notif = (DSPSignalNotification&) cmd;
qDebug() << "AcarsDemodBaseband::handleMessage: DSPSignalNotification: basebandSampleRate: " << notif.getSampleRate();
setBasebandSampleRate(notif.getSampleRate());
// 16x the standard policy - see the constructor
m_sampleFifo.setSize(SampleSinkFifo::getSizePolicy(notif.getSampleRate()) * 16);
m_sampleFifo.setSize(fifoSize(notif.getSampleRate()));
return true;
}
@ -163,12 +174,7 @@ bool AcarsDemodBaseband::handleMessage(const Message& cmd) @@ -163,12 +174,7 @@ bool AcarsDemodBaseband::handleMessage(const Message& cmd)
void AcarsDemodBaseband::applySettings(const AcarsDemodSettings& settings, bool force)
{
// An Aero submode change moves the channel rate exactly as a mode change does, so
// it has to count here too - otherwise switching rate leaves the channelizer where
// it was and the receiver runs at the wrong sample rate
bool modeChanged = (settings.m_mode != m_settings.m_mode)
|| ((settings.m_mode == AcarsDemodSettings::Aero)
&& (settings.m_aeroChannel != m_settings.m_aeroChannel));
bool modeChanged = AcarsDemodSettings::rateChanged(settings, m_settings);
// The sink has to know the mode before the channelization moves, as the mode sets
// the rate it resamples the channelizer output to

160
plugins/channelrx/demodacars/acarsdemodgui.cpp

@ -1,7 +1,6 @@ @@ -1,7 +1,6 @@
///////////////////////////////////////////////////////////////////////////////////
// Copyright (C) 2016 Edouard Griffiths, F4EXB //
// Copyright (C) 2021 Jon Beniston, M7RCE //
// Copyright (c) 2018-2021 Tomasz Lemiech <szpajder@gmail.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 //
@ -19,6 +18,8 @@ @@ -19,6 +18,8 @@
#include <limits>
#include <cstdint>
#include <algorithm>
#include <iterator>
#include <QDockWidget>
#include <QMainWindow>
#include <QDebug>
@ -63,7 +64,9 @@ @@ -63,7 +64,9 @@
#include "acarsdemod.h"
#include "acarsdemodsink.h"
#include "acarstextformat.h"
#include "util/acarstextformat.h"
#include "gui/fastheaderview.h"
#include "gui/fastitemdelegate.h"
@ -137,9 +140,17 @@ void AcarsDemodGUI::resizeTable() @@ -137,9 +140,17 @@ void AcarsDemodGUI::resizeTable()
// Columns in table reordered
void AcarsDemodGUI::messages_sectionMoved(int logicalIndex, int oldVisualIndex, int newVisualIndex)
{
(void) logicalIndex;
(void) oldVisualIndex;
(void) newVisualIndex;
m_settings.m_columnIndexes[logicalIndex] = newVisualIndex;
// Every column between the two positions moved too, so record them all. Recording
// only the one dragged left the others stale, and replaying them in displaySettings()
// gave a different order after more than one move.
QHeaderView *header = ui->messages->horizontalHeader();
for (int i = 0; i < ACARSDEMOD_COLUMNS; i++) {
m_settings.m_columnIndexes[i] = header->visualIndex(i);
}
}
// Column in table resized (when hidden size is 0)
@ -411,7 +422,15 @@ bool AcarsDemodGUI::handleMessage(const Message& message) @@ -411,7 +422,15 @@ bool AcarsDemodGUI::handleMessage(const Message& message)
{
qDebug("AcarsDemodGUI::handleMessage: AcarsDemod::MsgConfigureAcarsDemod");
const AcarsDemod::MsgConfigureAcarsDemod& cfg = (AcarsDemod::MsgConfigureAcarsDemod&) message;
m_settings = cfg.getSettings();
// The table layout and the splitter are the GUI's own: changed here without being
// applied, so the channel's copy of them is stale, and taking it moved columns,
// widths and the splitter back whenever the channel echoed its settings (a REST
// PATCH, a centre frequency change)
AcarsDemodSettings settings = cfg.getSettings();
std::copy(std::begin(m_settings.m_columnIndexes), std::end(m_settings.m_columnIndexes), std::begin(settings.m_columnIndexes));
std::copy(std::begin(m_settings.m_columnSizes), std::end(m_settings.m_columnSizes), std::begin(settings.m_columnSizes));
settings.m_splitterState = ui->splitter->saveState();
m_settings = settings;
blockApplySettings(true);
ui->scopeGUI->updateSettings();
m_channelMarker.updateSettings(static_cast<const ChannelMarker*>(m_settings.m_channelMarker));
@ -472,6 +491,7 @@ void AcarsDemodGUI::on_mode_currentIndexChanged(int value) @@ -472,6 +491,7 @@ void AcarsDemodGUI::on_mode_currentIndexChanged(int value)
case 1: m_settings.m_mode = AcarsDemodSettings::VDL2; break;
case 2: m_settings.m_mode = AcarsDemodSettings::HFDL; break;
case 3: m_settings.m_mode = AcarsDemodSettings::Aero; break;
case 4: m_settings.m_mode = AcarsDemodSettings::Iridium; break;
default: m_settings.m_mode = AcarsDemodSettings::ACARS; break;
}
@ -479,6 +499,13 @@ void AcarsDemodGUI::on_mode_currentIndexChanged(int value) @@ -479,6 +499,13 @@ void AcarsDemodGUI::on_mode_currentIndexChanged(int value)
applyModeBandwidth();
}
void AcarsDemodGUI::on_iridiumBandwidth_currentIndexChanged(int value)
{
m_settings.m_iridiumBandwidth = value;
// The channel sample rate is the width scanned, so changing it restarts the channel
applySettings();
}
void AcarsDemodGUI::on_aeroChannel_currentIndexChanged(int value)
{
m_settings.m_aeroChannel = value;
@ -512,6 +539,9 @@ void AcarsDemodGUI::applyModeBandwidth() @@ -512,6 +539,9 @@ void AcarsDemodGUI::applyModeBandwidth()
case AcarsDemodSettings::Aero:
bw = AcarsAeroReceiver::submodeBandwidth(m_settings.m_aeroChannel) / 100;
break;
// Ignored: Iridium scans the whole tuned width, and the sink passes all of it
// rather than filtering to a channel. The control is hidden in this mode
case AcarsDemodSettings::Iridium: bw = ui->rfBW->maximum(); break;
default: bw = 125; break;
}
if (ui->rfBW->value() != bw) {
@ -864,6 +894,19 @@ AcarsDemodGUI::AcarsDemodGUI(PluginAPI* pluginAPI, DeviceUISet *deviceUISet, Bas @@ -864,6 +894,19 @@ AcarsDemodGUI::AcarsDemodGUI(PluginAPI* pluginAPI, DeviceUISet *deviceUISet, Bas
m_helpURL = "plugins/channelrx/demodacars/readme.md";
RollupContents *rollupContents = getRollupContents();
ui->setupUi(rollupContents);
ui->messages->setItemDelegate(new FastItemDelegate(ui->messages));
ui->channelPower->setFixedSize(
ui->channelPower->fontMetrics().horizontalAdvance("-100.0") + 2,
ui->channelPower->sizeHint().height());
ui->channelPower->setAlignment(Qt::AlignRight | Qt::AlignVCenter);
ui->quality->setFixedSize(
ui->quality->fontMetrics().horizontalAdvance("100.0% SU 100%") + 2,
ui->quality->sizeHint().height());
// Before any header configuration below: setHorizontalHeader() resets column state
ui->messages->setHorizontalHeader(new FastHeaderView(Qt::Horizontal, ui->messages));
setSizePolicy(rollupContents->sizePolicy());
rollupContents->arrangeRollups();
connect(rollupContents, SIGNAL(widgetRolled(QWidget*,bool)), this, SLOT(onWidgetRolled(QWidget*,bool)));
@ -991,11 +1034,6 @@ AcarsDemodGUI::AcarsDemodGUI(PluginAPI* pluginAPI, DeviceUISet *deviceUISet, Bas @@ -991,11 +1034,6 @@ AcarsDemodGUI::AcarsDemodGUI(PluginAPI* pluginAPI, DeviceUISet *deviceUISet, Bas
connect(&m_osnDB, &OsnDB::downloadProgress, this, &AcarsDemodGUI::downloadProgress);
connect(&m_osnDB, &OsnDB::downloadAircraftInformationFinished, this, &AcarsDemodGUI::downloadAircraftInformationFinished);
m_aircraftInfo = OsnDB::getAircraftInformationByReg();
m_aircraftInfoByIcao = OsnDB::getAircraftInformation();
m_navAids = OpenAIP::getNavAids();
m_airports = OurAirportsDB::getAirportsByIdent();
m_waypoints = Waypoints::getWaypoints();
connect(&m_planeSpotters, &PlaneSpotters::aircraftPhoto, this, &AcarsDemodGUI::aircraftPhoto);
connect(ui->photo, &ClickableLabel::clicked, this, &AcarsDemodGUI::photoClicked);
@ -1018,6 +1056,10 @@ AcarsDemodGUI::AcarsDemodGUI(PluginAPI* pluginAPI, DeviceUISet *deviceUISet, Bas @@ -1018,6 +1056,10 @@ AcarsDemodGUI::AcarsDemodGUI(PluginAPI* pluginAPI, DeviceUISet *deviceUISet, Bas
}
plotChart();
// The splitter saves a hidden pane as size 0, and restoreState() collapses a
// collapsible pane restored at 0, so the chart button showed a chart with no height.
// Not collapsible, a 0 is raised to the chart's minimum height instead.
ui->splitter->setCollapsible(ui->splitter->indexOf(ui->chart), false);
CRightClickEnabler *displayChartClickEnabler = new CRightClickEnabler(ui->displayChart);
connect(displayChartClickEnabler, SIGNAL(rightClick(const QPoint &)), this, SLOT(clearChart(const QPoint &)));
@ -1065,71 +1107,6 @@ void AcarsDemodGUI::applySettings(bool force) @@ -1065,71 +1107,6 @@ void AcarsDemodGUI::applySettings(bool force)
}
}
void AcarsDemodGUI::on_feed_clicked(bool checked)
{
m_settings.m_feedEnabled = checked;
applySettings();
}
// Feed settings dialog: station ident plus per-aggregator enable, host and port
void AcarsDemodGUI::feedSelect(const QPoint& p)
{
QDialog dialog(this);
dialog.setWindowTitle("ACARS Feed Settings");
QLineEdit *stationId = new QLineEdit(m_settings.m_feedStationId);
stationId->setToolTip("Station identifier sent with each message (e.g. XX-JBLOGGS-VHF1). Register it with the aggregator to claim your feed");
QCheckBox *airframes = new QCheckBox("Feed airframes.io");
airframes->setChecked(m_settings.m_feedAirframes);
QLineEdit *airframesHost = new QLineEdit(m_settings.m_feedAirframesHost);
QSpinBox *airframesPort = new QSpinBox();
airframesPort->setRange(1, 65535);
airframesPort->setValue(m_settings.m_feedAirframesPort);
QComboBox *airframesProtocol = new QComboBox();
airframesProtocol->addItems({"TCP", "UDP"});
airframesProtocol->setCurrentIndex(m_settings.m_feedAirframesTcp ? 0 : 1);
airframesProtocol->setToolTip("Use the protocol, host and port the airframes.io Add Ground Station wizard assigns to your station");
QCheckBox *avdelphi = new QCheckBox("Feed avdelphi.com");
avdelphi->setChecked(m_settings.m_feedAvdelphi);
QLineEdit *avdelphiHost = new QLineEdit(m_settings.m_feedAvdelphiHost);
QSpinBox *avdelphiPort = new QSpinBox();
avdelphiPort->setRange(1, 65535);
avdelphiPort->setValue(m_settings.m_feedAvdelphiPort);
QComboBox *avdelphiProtocol = new QComboBox();
avdelphiProtocol->addItems({"TCP", "UDP"});
avdelphiProtocol->setCurrentIndex(m_settings.m_feedAvdelphiTcp ? 0 : 1);
QFormLayout *form = new QFormLayout(&dialog);
form->addRow("Station ID", stationId);
form->addRow(airframes);
form->addRow("Host", airframesHost);
form->addRow("Port", airframesPort);
form->addRow("Protocol", airframesProtocol);
form->addRow(avdelphi);
form->addRow("Host", avdelphiHost);
form->addRow("Port", avdelphiPort);
form->addRow("Protocol", avdelphiProtocol);
QDialogButtonBox *buttons = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel);
form->addRow(buttons);
connect(buttons, &QDialogButtonBox::accepted, &dialog, &QDialog::accept);
connect(buttons, &QDialogButtonBox::rejected, &dialog, &QDialog::reject);
dialog.move(p);
if (dialog.exec() == QDialog::Accepted)
{
m_settings.m_feedStationId = stationId->text().trimmed();
m_settings.m_feedAirframes = airframes->isChecked();
m_settings.m_feedAirframesHost = airframesHost->text().trimmed();
m_settings.m_feedAirframesPort = airframesPort->value();
m_settings.m_feedAirframesTcp = airframesProtocol->currentIndex() == 0;
m_settings.m_feedAvdelphi = avdelphi->isChecked();
m_settings.m_feedAvdelphiHost = avdelphiHost->text().trimmed();
m_settings.m_feedAvdelphiPort = avdelphiPort->value();
m_settings.m_feedAvdelphiTcp = avdelphiProtocol->currentIndex() == 0;
applySettings();
}
}
// Ground stations heard in HFDL squitters, one row per station and announced
// frequency, with a context menu to find the station on the Map or tune to it
void AcarsDemodGUI::on_gsTable_clicked()
@ -1258,6 +1235,12 @@ void AcarsDemodGUI::updateModeDependentWidgets() @@ -1258,6 +1235,12 @@ void AcarsDemodGUI::updateModeDependentWidgets()
// The rate and channel selector only means anything in Aero mode, and so does the
// link quality readout - it needs a continuous carrier to average over
ui->aeroChannel->setVisible(aero);
// Iridium scans the whole tuned width rather than one channel
ui->iridiumBandwidth->setVisible(m_settings.m_mode == AcarsDemodSettings::Iridium);
const bool iridium = (m_settings.m_mode == AcarsDemodSettings::Iridium);
ui->rfBW->setVisible(!iridium);
ui->rfBWLabel->setVisible(!iridium);
ui->rfBWText->setVisible(!iridium);
ui->qualityLabel->setVisible(aero);
ui->quality->setVisible(aero);
if (!aero) {
@ -1311,12 +1294,10 @@ void AcarsDemodGUI::displaySettings() @@ -1311,12 +1294,10 @@ void AcarsDemodGUI::displaySettings()
ui->deltaFrequency->setValue(m_channelMarker.getCenterFrequency());
ui->mode->setCurrentIndex(m_settings.m_mode == AcarsDemodSettings::VDL2 ? 1
: m_settings.m_mode == AcarsDemodSettings::HFDL ? 2
: m_settings.m_mode == AcarsDemodSettings::Aero ? 3 : 0);
ui->mode->setCurrentIndex(m_settings.m_mode);
ui->aeroChannel->setCurrentIndex(m_settings.m_aeroChannel);
ui->iridiumBandwidth->setCurrentIndex(m_settings.m_iridiumBandwidth);
updateModeDependentWidgets();
ui->feed->setChecked(m_settings.m_feedEnabled);
ui->rfBWText->setText(QString("%1k").arg(m_settings.m_rfBandwidth / 1000.0, 0, 'f', 1));
ui->rfBW->setValue(m_settings.m_rfBandwidth / 100.0);
@ -1520,6 +1501,7 @@ void AcarsDemodGUI::makeUIConnections() @@ -1520,6 +1501,7 @@ void AcarsDemodGUI::makeUIConnections()
QObject::connect(ui->deltaFrequency, &ValueDialZ::changed, this, &AcarsDemodGUI::on_deltaFrequency_changed);
QObject::connect(ui->mode, QOverload<int>::of(&QComboBox::currentIndexChanged), this, &AcarsDemodGUI::on_mode_currentIndexChanged);
QObject::connect(ui->aeroChannel, QOverload<int>::of(&QComboBox::currentIndexChanged), this, &AcarsDemodGUI::on_aeroChannel_currentIndexChanged);
QObject::connect(ui->iridiumBandwidth, QOverload<int>::of(&QComboBox::currentIndexChanged), this, &AcarsDemodGUI::on_iridiumBandwidth_currentIndexChanged);
QObject::connect(ui->rfBW, &QSlider::valueChanged, this, &AcarsDemodGUI::on_rfBW_valueChanged);
QObject::connect(ui->threshold, &QDial::valueChanged, this, &AcarsDemodGUI::on_threshold_valueChanged);
QObject::connect(ui->filter, QOverload<int>::of(&QComboBox::currentIndexChanged), this, &AcarsDemodGUI::on_filter_currentIndexChanged);
@ -1531,12 +1513,6 @@ void AcarsDemodGUI::makeUIConnections() @@ -1531,12 +1513,6 @@ void AcarsDemodGUI::makeUIConnections()
QObject::connect(ui->channel1, QOverload<int>::of(&QComboBox::currentIndexChanged), this, &AcarsDemodGUI::on_channel1_currentIndexChanged);
QObject::connect(ui->channel2, QOverload<int>::of(&QComboBox::currentIndexChanged), this, &AcarsDemodGUI::on_channel2_currentIndexChanged);
QObject::connect(ui->gsTable, &QToolButton::clicked, this, &AcarsDemodGUI::on_gsTable_clicked);
QObject::connect(ui->feed, &ButtonSwitch::clicked, this, &AcarsDemodGUI::on_feed_clicked);
CRightClickEnabler *feedRightClickEnabler = new CRightClickEnabler(ui->feed);
connect(feedRightClickEnabler, &CRightClickEnabler::rightClick, this, &AcarsDemodGUI::feedSelect);
// Log the feed connections' lifecycle, so a misconfigured host/port or a
// dropped aggregator connection is visible in the debug output
QObject::connect(ui->messages->selectionModel(), &QItemSelectionModel::selectionChanged,
this, &AcarsDemodGUI::messagesSelectionChanged);
QObject::connect(ui->logEnable, &ButtonSwitch::clicked, this, &AcarsDemodGUI::on_logEnable_clicked);
@ -1917,7 +1893,6 @@ void AcarsDemodGUI::on_logOpen_clicked() @@ -1917,7 +1893,6 @@ void AcarsDemodGUI::on_logOpen_clicked()
QDateTime startTime = QDateTime::currentDateTime();
// Sorting stays on: the proxy places each row as it arrives
//ui->messages->setUpdatesEnabled(false);
ui->messages->blockSignals(true);
QTextStream in(&file);
QString error;
QHash<QString, int> colIndexes = CSV::readHeader(in, {"DateTime", "Data"}, error);
@ -1943,9 +1918,12 @@ void AcarsDemodGUI::on_logOpen_clicked() @@ -1943,9 +1918,12 @@ void AcarsDemodGUI::on_logOpen_clicked()
QDateTime dateTime = QDateTime::fromString(cols[dateTimeCol], Qt::ISODateWithMs);
QByteArray bytes = QByteArray::fromHex(cols[dataCol].toLatin1());
// Decoded by the worker, which echoes display events back here
m_acarsDemod->getWorker()->getInputMessageQueue()->push(
MainCore::MsgPacket::create(m_acarsDemod, bytes, dateTime));
// Decoded by the worker, which echoes display events back here.
// As a replay, so it is not sent out again as live traffic.
if (!bytes.isEmpty()) {
m_acarsDemod->getWorker()->getInputMessageQueue()->push(
AcarsDemodWorker::MsgReplayPacket::create(bytes, dateTime));
}
if (count % 50000 == 0)
{
@ -1958,7 +1936,6 @@ void AcarsDemodGUI::on_logOpen_clicked() @@ -1958,7 +1936,6 @@ void AcarsDemodGUI::on_logOpen_clicked()
}
}
dialog.close();
ui->messages->blockSignals(false);
//ui->messages->setUpdatesEnabled(true);
// Nothing to re-sort: the proxy kept the order as the rows arrived
}
@ -2102,7 +2079,10 @@ void AcarsDemodGUI::downloadAircraftInformationFinished() @@ -2102,7 +2079,10 @@ void AcarsDemodGUI::downloadAircraftInformationFinished()
QApplication::processEvents();
}
m_aircraftInfo = OsnDB::getAircraftInformationByReg();
m_aircraftInfoByIcao = OsnDB::getAircraftInformation();
// The worker holds its own copy, for the registration lookups
if (m_acarsDemod->getWorker()) {
m_acarsDemod->getWorker()->getInputMessageQueue()->push(AcarsDemodWorker::MsgReloadAircraftDatabase::create());
}
if (m_progressDialog)
{
m_progressDialog->close();

11
plugins/channelrx/demodacars/acarsdemodgui.h

@ -33,12 +33,10 @@ @@ -33,12 +33,10 @@
#include "channel/channelgui.h"
#include "dsp/channelmarker.h"
#include "util/waypoints.h"
#include "util/messagequeue.h"
#include "util/planespotters.h"
#include "util/openaip.h"
#include "settings/rollupstate.h"
#include "acarsmessage.h"
#include "util/acarsmessage.h"
#include "gui/acarsmessageview.h"
#include "acarsdemodsettings.h"
#include "acarsdemodworker.h"
@ -108,13 +106,9 @@ private: @@ -108,13 +106,9 @@ private:
uint32_t m_tickCount;
MessageQueue m_inputMessageQueue;
QSharedPointer<const QList<NavAid *>> m_navAids;
QSharedPointer<const QHash<QString, AirportInformation *>> m_airports;
QSharedPointer<const QMultiHash<QString, Waypoint *>> m_waypoints;
PlaneSpotters m_planeSpotters;
QString m_photoLink;
QSharedPointer<const QHash<QString, AircraftInformation *>> m_aircraftInfo;
QSharedPointer<const QHash<int, AircraftInformation *>> m_aircraftInfoByIcao;
OsnDB m_osnDB;
QProgressDialog *m_progressDialog;
@ -201,10 +195,9 @@ private slots: @@ -201,10 +195,9 @@ private slots:
void on_deltaFrequency_changed(qint64 value);
void on_mode_currentIndexChanged(int value);
void on_aeroChannel_currentIndexChanged(int value);
void on_iridiumBandwidth_currentIndexChanged(int value);
void on_gsTable_clicked();
void gsTableContextMenu(QPoint pos);
void on_feed_clicked(bool checked);
void feedSelect(const QPoint& p);
void on_rfBW_valueChanged(int index);
void on_threshold_valueChanged(int value);
void on_filter_currentIndexChanged(int index);

71
plugins/channelrx/demodacars/acarsdemodgui.ui

@ -224,7 +224,7 @@ @@ -224,7 +224,7 @@
</size>
</property>
<property name="toolTip">
<string>Mode: ACARS (2400 baud MSK), VDL Mode 2 (10500 baud D8PSK), HFDL (1800 baud PSK; tune to the published channel frequency) or Aero (Inmarsat Classic Aero, L band satellite)</string>
<string>Mode: ACARS (2400 baud MSK), VDL Mode 2 (10500 baud D8PSK), HFDL (1800 baud PSK; tune to the published channel frequency) Aero (Inmarsat Classic Aero, L band satellite) or Iridium (L band satellite, burst DQPSK - prototype: ring alert and short burst data frames are decoded, ACARS reassembly untested)</string>
</property>
<item>
<property name="text">
@ -246,6 +246,11 @@ @@ -246,6 +246,11 @@
<string>Aero</string>
</property>
</item>
<item>
<property name="text">
<string>Iridium</string>
</property>
</item>
</widget>
</item>
<item>
@ -296,6 +301,39 @@ @@ -296,6 +301,39 @@
</item>
</widget>
</item>
<item>
<widget class="QComboBox" name="iridiumBandwidth">
<property name="minimumSize">
<size>
<width>85</width>
<height>0</height>
</size>
</property>
<property name="toolTip">
<string>How much of the band the Iridium scanner covers. Iridium assigns a duplex channel when a call is set up, out of about 240 across 7 MHz, so watching a single channel sees only a few percent of the traffic. The whole width is split into channels and a receiver run on each, which costs proportionally more CPU. There is no point choosing a width the device cannot supply.</string>
</property>
<item>
<property name="text">
<string>1 MHz</string>
</property>
</item>
<item>
<property name="text">
<string>2 MHz</string>
</property>
</item>
<item>
<property name="text">
<string>4 MHz</string>
</property>
</item>
<item>
<property name="text">
<string>8 MHz</string>
</property>
</item>
</widget>
</item>
<item>
<spacer name="horizontalSpacer_2">
<property name="orientation">
@ -528,8 +566,8 @@ @@ -528,8 +566,8 @@
<string/>
</property>
<property name="icon">
<iconset resource="../../../sdrgui/resources/res.qrc">
<normaloff>:/txon.png</normaloff>:/txon.png</iconset>
<iconset resource="acarsdemodicons.qrc">
<normaloff>:/icons/forward.png</normaloff>:/icons/forward.png</iconset>
</property>
<property name="checkable">
<bool>true</bool>
@ -562,7 +600,7 @@ @@ -562,7 +600,7 @@
<string/>
</property>
<property name="icon">
<iconset>
<iconset resource="acarsdemodicons.qrc">
<normaloff>:/icons/chart.png</normaloff>:/icons/chart.png</iconset>
</property>
<property name="checkable">
@ -579,38 +617,21 @@ @@ -579,38 +617,21 @@
<string>...</string>
</property>
<property name="icon">
<iconset>
<iconset resource="acarsdemodicons.qrc">
<normaloff>:/icons/gs.png</normaloff>:/icons/gs.png</iconset>
</property>
</widget>
</item>
<item>
<widget class="ButtonSwitch" name="feed">
<property name="toolTip">
<string>Enable feeding of received ACARS messages to aggregators (airframes.io / avdelphi.com). Right click for settings.</string>
</property>
<property name="text">
<string>...</string>
</property>
<property name="icon">
<iconset resource="../../../sdrgui/resources/res.qrc">
<normaloff>:/txon.png</normaloff>:/txon.png</iconset>
</property>
<property name="checkable">
<bool>true</bool>
</property>
</widget>
</item>
<item>
<widget class="QToolButton" name="getOSNDB">
<property name="toolTip">
<string>Download the latest Opensky-Network aircraft database (130MB)</string>
<string>Download the latest aircraft database (45MB)</string>
</property>
<property name="text">
<string>...</string>
</property>
<property name="icon">
<iconset>
<iconset resource="acarsdemodicons.qrc">
<normaloff>:/icons/aircraft.png</normaloff>:/icons/aircraft.png</iconset>
</property>
</widget>
@ -1122,7 +1143,7 @@ @@ -1122,7 +1143,7 @@
</tabstops>
<resources>
<include location="../../../sdrgui/resources/res.qrc"/>
<include location="icons.qrc"/>
<include location="acarsdemodicons.qrc"/>
</resources>
<connections/>
</ui>

1
plugins/channelrx/demodacars/acarsdemodicons.qrc

@ -3,5 +3,6 @@ @@ -3,5 +3,6 @@
<file>icons/aircraft.png</file>
<file>icons/chart.png</file>
<file>icons/gs.png</file>
<file>icons/forward.png</file>
</qresource>
</RCC>

46
plugins/channelrx/demodacars/acarsdemodsettings.cpp

@ -37,6 +37,7 @@ void AcarsDemodSettings::resetToDefaults() @@ -37,6 +37,7 @@ void AcarsDemodSettings::resetToDefaults()
m_inputFrequencyOffset = 0;
m_mode = ACARS;
m_aeroChannel = AcarsAeroReceiver::Submode600P;
m_iridiumBandwidth = AcarsDemodSettings::IridiumScanWidths - 1;
m_rfBandwidth = 12500.0f;
// Pre-key detection threshold, as a fraction of the AM modulation index seen at 2400 Hz.
// A real pre-key reads about 0.85 (ARINC 618 section 4.4.3 asks for at least 85 percent
@ -57,18 +58,8 @@ void AcarsDemodSettings::resetToDefaults() @@ -57,18 +58,8 @@ void AcarsDemodSettings::resetToDefaults()
m_displayChart = false;
m_logFilename = "acars_log.csv";
m_logEnabled = false;
m_feedEnabled = false;
m_feedStationId = "";
m_feedAirframes = true;
m_feedAirframesHost = "feed.airframes.io";
m_feedAirframesPort = 5550;
// The airframes.io ACARS (acarsdec) station type ingests UDP on 5550; only some
// other station types (e.g. VDL2/vdlm2dec on 5555) are TCP
m_feedAirframesTcp = false;
m_feedAvdelphi = false;
m_feedAvdelphiHost = "data.avdelphi.com";
m_feedAvdelphiPort = 5556;
m_feedAvdelphiTcp = false;
m_rgbColor = QColor(25, 205, 2).rgb();
m_title = "ACARS Demodulator";
@ -129,6 +120,7 @@ QByteArray AcarsDemodSettings::serialize() const @@ -129,6 +120,7 @@ QByteArray AcarsDemodSettings::serialize() const
s.writeBool(38, m_logEnabled);
s.writeS32(39, m_mode);
s.writeS32(53, m_aeroChannel);
s.writeS32(56, m_iridiumBandwidth);
// Key 40 stored the opposite question, "show these frames", so it is written
// inverted rather than moved to a new key - that way an existing preset keeps
// behaving exactly as it did, whichever way it was set
@ -136,16 +128,6 @@ QByteArray AcarsDemodSettings::serialize() const @@ -136,16 +128,6 @@ QByteArray AcarsDemodSettings::serialize() const
s.writeBool(54, m_showDate);
s.writeBlob(55, m_splitterState);
s.writeBool(41, m_displayChart);
s.writeBool(42, m_feedEnabled);
s.writeString(43, m_feedStationId);
s.writeBool(44, m_feedAirframes);
s.writeString(45, m_feedAirframesHost);
s.writeS32(46, m_feedAirframesPort);
s.writeBool(47, m_feedAvdelphi);
s.writeString(48, m_feedAvdelphiHost);
s.writeS32(49, m_feedAvdelphiPort);
s.writeBool(50, m_feedAirframesTcp);
s.writeBool(51, m_feedAvdelphiTcp);
for (int i = 0; i < ACARSDEMOD_COLUMNS; i++)
s.writeS32(100 + i, m_columnIndexes[i]);
@ -248,36 +230,24 @@ bool AcarsDemodSettings::deserialize(const QByteArray& data) @@ -248,36 +230,24 @@ bool AcarsDemodSettings::deserialize(const QByteArray& data)
d.readString(37, &m_logFilename, "acars_log.csv");
d.readBool(38, &m_logEnabled, false);
d.readS32(39, &m_mode, (int)ACARS);
if ((m_mode != (int)ACARS) && (m_mode != (int)VDL2) && (m_mode != (int)HFDL)
&& (m_mode != (int)Aero)) {
if ((m_mode < 0) || (m_mode >= (int)ModeCount)) {
m_mode = (int)ACARS;
}
d.readS32(53, &m_aeroChannel, AcarsAeroReceiver::Submode600P);
if ((m_aeroChannel < 0) || (m_aeroChannel >= AcarsAeroReceiver::SubmodeCount)) {
m_aeroChannel = AcarsAeroReceiver::Submode600P;
}
d.readS32(56, &m_iridiumBandwidth, AcarsDemodSettings::IridiumScanWidths - 1);
if ((m_iridiumBandwidth < 0) || (m_iridiumBandwidth >= AcarsDemodSettings::IridiumScanWidths)) {
m_iridiumBandwidth = AcarsDemodSettings::IridiumScanWidths - 1;
}
bool displayNoInfo = false;
d.readBool(40, &displayNoInfo, false);
m_hideNoInfo = !displayNoInfo;
d.readBool(54, &m_showDate, true);
d.readBlob(55, &m_splitterState);
d.readBool(41, &m_displayChart, false);
d.readBool(42, &m_feedEnabled, false);
d.readString(43, &m_feedStationId, "");
d.readBool(44, &m_feedAirframes, true);
d.readString(45, &m_feedAirframesHost, "feed.airframes.io");
d.readS32(46, &m_feedAirframesPort, 5550);
if ((m_feedAirframesPort <= 1023) || (m_feedAirframesPort >= 65535)) {
m_feedAirframesPort = 5550;
}
d.readBool(47, &m_feedAvdelphi, false);
d.readString(48, &m_feedAvdelphiHost, "data.avdelphi.com");
d.readS32(49, &m_feedAvdelphiPort, 5556);
if ((m_feedAvdelphiPort <= 1023) || (m_feedAvdelphiPort >= 65535)) {
m_feedAvdelphiPort = 5556;
}
d.readBool(50, &m_feedAirframesTcp, false);
d.readBool(51, &m_feedAvdelphiTcp, false);
// Both of these are fed to the table header - moveSection() and setColumnWidth() -
// so a preset from a build with a different column count, or a corrupt one, would

273
plugins/channelrx/demodacars/acarsdemodsettings.h

@ -1,123 +1,150 @@ @@ -1,123 +1,150 @@
///////////////////////////////////////////////////////////////////////////////////
// Copyright (C) 2017 Edouard Griffiths, F4EXB. //
// Copyright (C) 2021 Jon Beniston, M7RCE //
// //
// 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_ACARSDEMODSETTINGS_H
#define INCLUDE_ACARSDEMODSETTINGS_H
#include <QByteArray>
#include <QHash>
#include "dsp/dsptypes.h"
#include "util/aircraftreport.h"
class Serializable;
// Number of columns in the table.
#define ACARSDEMOD_COLUMNS 23
struct AcarsDemodSettings
{
enum Mode {
ACARS = 0, //!< Plain old ACARS: 2400 baud MSK on AM
VDL2 = 1, //!< VDL Mode 2: 10500 baud D8PSK, ACARS over AVLC
HFDL = 2, //!< HFDL: 1800 baud M-PSK on a 1440 Hz subcarrier, ACARS over MPDU/LPDU
Aero = 3 //!< Inmarsat Classic Aero: L band satellite, ACARS over signal units
};
// The protocol tag an AircraftReport gets for a given mode.
static AircraftReport::Protocol protocolForMode(int mode)
{
switch (mode)
{
case VDL2: return AircraftReport::VDL2;
case HFDL: return AircraftReport::HFDL;
case Aero: return AircraftReport::AERO;
default: return AircraftReport::ACARS;
}
}
qint32 m_inputFrequencyOffset;
int m_mode; //!< One of enum Mode
//!< Which Aero rate and channel is tuned, an AcarsAeroReceiver::Submode. Unlike
//!< HFDL, where the M1 sequence identifies the rate, these are properties of the
//!< frequency tuned, so they are a setting rather than something detected.
int m_aeroChannel;
Real m_rfBandwidth;
Real m_correlationThreshold; //!< Pre-key detection threshold, 0 to 1
QString m_filter; // Regular expression the filtered column must match
int m_filterColumn; // Which column to filter: 0 Registration, 1 Flight, 2 Label, 3 Message
bool m_udpEnabled;
QString m_udpAddress;
uint16_t m_udpPort;
int m_scopeCh1;
int m_scopeCh2;
bool m_displayPhotos;
//!< Hide frames carrying no usable information from the table - VDL-2
//!< supervisory/ack frames (RR etc) and Aero satellite housekeeping. They are
//!< still received and still held in the table, only not shown
bool m_hideNoInfo;
//!< Show the date as well as the time in the Date/Time column. The date is only
//!< worth the width once a session has run past midnight
bool m_showDate;
//!< How the table and the decode view divide the space, from QSplitter::saveState
QByteArray m_splitterState;
bool m_displayChart; //!< Show the frames-per-second chart
QString m_logFilename;
bool m_logEnabled;
// Feeding of received ACARS messages to aggregators, in acarsdec-style JSON
bool m_feedEnabled;
QString m_feedStationId; //!< Station ident sent with each message
bool m_feedAirframes;
QString m_feedAirframesHost;
int m_feedAirframesPort;
bool m_feedAirframesTcp; //!< TCP (as the airframes.io wizard assigns) or UDP
bool m_feedAvdelphi;
QString m_feedAvdelphiHost;
int m_feedAvdelphiPort;
bool m_feedAvdelphiTcp;
quint32 m_rgbColor;
QString m_title;
Serializable *m_channelMarker;
QString m_audioDeviceName;
int m_streamIndex; //!< MIMO channel. Not relevant when connected to SI (single Rx).
bool m_useReverseAPI;
QString m_reverseAPIAddress;
uint16_t m_reverseAPIPort;
uint16_t m_reverseAPIDeviceIndex;
uint16_t m_reverseAPIChannelIndex;
Serializable *m_scopeGUI;
Serializable *m_rollupState;
int m_workspaceIndex;
QByteArray m_geometryBytes;
bool m_hidden;
int m_columnIndexes[ACARSDEMOD_COLUMNS];//!< How the columns are ordered in the table
int m_columnSizes[ACARSDEMOD_COLUMNS]; //!< Size of the columns in the table
AcarsDemodSettings();
void resetToDefaults();
void setChannelMarker(Serializable *channelMarker) { m_channelMarker = channelMarker; }
void setRollupState(Serializable *rollupState) { m_rollupState = rollupState; }
void setScopeGUI(Serializable *scopeGUI) { m_scopeGUI = scopeGUI; }
QByteArray serialize() const;
bool deserialize(const QByteArray& data);
};
#endif /* INCLUDE_ACARSDEMODSETTINGS_H */
///////////////////////////////////////////////////////////////////////////////////
// Copyright (C) 2017 Edouard Griffiths, F4EXB. //
// Copyright (C) 2021 Jon Beniston, M7RCE //
// //
// 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_ACARSDEMODSETTINGS_H
#define INCLUDE_ACARSDEMODSETTINGS_H
#include <QByteArray>
#include <QHash>
#include "dsp/dsptypes.h"
#include "util/aircraftreport.h"
class Serializable;
// Number of columns in the table.
#define ACARSDEMOD_COLUMNS 23
struct AcarsDemodSettings
{
enum Mode {
ACARS = 0, //!< Plain old ACARS: 2400 baud MSK on AM
VDL2 = 1, //!< VDL Mode 2: 10500 baud D8PSK, ACARS over AVLC
HFDL = 2, //!< HFDL: 1800 baud M-PSK on a 1440 Hz subcarrier, ACARS over MPDU/LPDU
Aero = 3, //!< Inmarsat Classic Aero: L band satellite, ACARS over signal units
Iridium = 4, //!< Iridium: L band satellite, burst DQPSK from low earth orbit.
ModeCount
};
// The protocol tag an AircraftReport gets for a given mode.
static AircraftReport::Protocol protocolForMode(int mode)
{
switch (mode)
{
case VDL2: return AircraftReport::VDL2;
case HFDL: return AircraftReport::HFDL;
case Aero: return AircraftReport::AERO;
case Iridium: return AircraftReport::IRIDIUM;
default: return AircraftReport::ACARS;
}
}
//! Whether a change moves the channel sample rate, and so needs the channelizer
//! retuned, the resampler rebuilt and the receivers restarted.
static bool rateChanged(const AcarsDemodSettings& a, const AcarsDemodSettings& b)
{
if (a.m_mode != b.m_mode) {
return true;
}
switch (a.m_mode)
{
case Aero: return a.m_aeroChannel != b.m_aeroChannel;
case Iridium: return a.m_iridiumBandwidth != b.m_iridiumBandwidth;
default: return false;
}
}
//! How many channelizer outputs each Iridium scan width uses. They have to be powers
//! of two, and the sample rate the channel needs is this times the 31.25 kHz channel
//! spacing - so 256 channels is 8 MS/s and covers 8 MHz, the whole Iridium band.
static int iridiumScanChannels(int bandwidth)
{
static const int channels[] = { 32, 64, 128, 256 };
const int count = (int) (sizeof(channels) / sizeof(channels[0]));
return channels[((bandwidth < 0) || (bandwidth >= count)) ? (count - 1) : bandwidth];
}
static const int IridiumScanWidths = 4;
qint32 m_inputFrequencyOffset;
int m_mode; //!< One of enum Mode
//!< Which Aero rate and channel is tuned, an AcarsAeroReceiver::Submode. Unlike
//!< HFDL, where the M1 sequence identifies the rate, these are properties of the
//!< frequency tuned, so they are a setting rather than something detected.
int m_aeroChannel;
//!< How much of the band the Iridium scanner covers. Iridium assigns a duplex channel
//!< when a call is set up, out of about 240 across 7 MHz, so watching one channel sees
//!< a few percent of the traffic - the scanner splits the whole width with a polyphase
//!< channelizer instead and runs a receiver on every output. An index into the table
//!< in iridiumScanChannels() below
int m_iridiumBandwidth;
Real m_rfBandwidth;
Real m_correlationThreshold; //!< Pre-key detection threshold, 0 to 1
QString m_filter; // Regular expression the filtered column must match
int m_filterColumn; // Which column to filter: 0 Registration, 1 Flight, 2 Label, 3 Message
bool m_udpEnabled;
QString m_udpAddress;
uint16_t m_udpPort;
int m_scopeCh1;
int m_scopeCh2;
bool m_displayPhotos;
//!< Hide frames carrying no usable information from the table - VDL-2
//!< supervisory/ack frames (RR etc) and Aero satellite housekeeping. They are
//!< still received and still held in the table, only not shown
bool m_hideNoInfo;
//!< Show the date as well as the time in the Date/Time column. The date is only
//!< worth the width once a session has run past midnight
bool m_showDate;
//!< How the table and the decode view divide the space, from QSplitter::saveState
QByteArray m_splitterState;
bool m_displayChart; //!< Show the frames-per-second chart
QString m_logFilename;
bool m_logEnabled;
quint32 m_rgbColor;
QString m_title;
Serializable *m_channelMarker;
QString m_audioDeviceName;
int m_streamIndex; //!< MIMO channel. Not relevant when connected to SI (single Rx).
bool m_useReverseAPI;
QString m_reverseAPIAddress;
uint16_t m_reverseAPIPort;
uint16_t m_reverseAPIDeviceIndex;
uint16_t m_reverseAPIChannelIndex;
Serializable *m_scopeGUI;
Serializable *m_rollupState;
int m_workspaceIndex;
QByteArray m_geometryBytes;
bool m_hidden;
int m_columnIndexes[ACARSDEMOD_COLUMNS];//!< How the columns are ordered in the table
int m_columnSizes[ACARSDEMOD_COLUMNS]; //!< Size of the columns in the table
AcarsDemodSettings();
void resetToDefaults();
void setChannelMarker(Serializable *channelMarker) { m_channelMarker = channelMarker; }
void setRollupState(Serializable *rollupState) { m_rollupState = rollupState; }
void setScopeGUI(Serializable *scopeGUI) { m_scopeGUI = scopeGUI; }
QByteArray serialize() const;
bool deserialize(const QByteArray& data);
};
#endif /* INCLUDE_ACARSDEMODSETTINGS_H */

871
plugins/channelrx/demodacars/acarsdemodsink.cpp

@ -1,349 +1,522 @@ @@ -1,349 +1,522 @@
///////////////////////////////////////////////////////////////////////////////////
// Copyright (C) 2019 Edouard Griffiths, F4EXB //
// Copyright (C) 2021-2026 Jon Beniston, M7RCE //
// 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 <algorithm>
#include "dsp/dspengine.h"
#include "dsp/datafifo.h"
#include "dsp/scopevis.h"
#include "util/db.h"
#include "maincore.h"
#include "acarsdemod.h"
#include "acarsdemodsink.h"
AcarsDemodSink::AcarsDemodSink(AcarsDemod *acarsDemod) :
m_scopeSink(nullptr),
m_acarsDemod(acarsDemod),
m_channel(nullptr),
m_channelSampleRate(ACARSDEMOD_CHANNEL_SAMPLE_RATE),
m_channelFrequencyOffset(0),
m_interpolatorDistance(1.0f),
m_interpolatorDistanceRemain(0.0f),
m_magsq(0.0),
m_magsqSum(0.0f),
m_magsqPeak(0.0f),
m_magsqCount(0),
m_messageQueueToChannel(nullptr),
m_scopeBufferIndex(0),
m_demodBufferFill(0)
{
m_demodBuffer.resize(1<<12);
m_scopeBuffer.resize(m_scopeBufferSize);
m_scopeBegin.resize(1);
applySettings(m_settings, true);
applyChannelSettings(m_channelSampleRate, m_channelFrequencyOffset, true);
}
AcarsDemodSink::~AcarsDemodSink()
{
}
void AcarsDemodSink::feed(const SampleVector::const_iterator& begin, const SampleVector::const_iterator& end)
{
Complex ci;
for (SampleVector::const_iterator it = begin; it != end; ++it)
{
Complex c(it->real(), it->imag());
c *= m_nco.nextIQ();
if (m_interpolatorDistance < 1.0f)
{
while (!m_interpolator.interpolate(&m_interpolatorDistanceRemain, c, &ci))
{
processOneSample(ci);
m_interpolatorDistanceRemain += m_interpolatorDistance;
}
}
else
{
if (m_interpolator.decimate(&m_interpolatorDistanceRemain, c, &ci))
{
processOneSample(ci);
m_interpolatorDistanceRemain += m_interpolatorDistance;
}
}
}
}
void AcarsDemodSink::sampleToScope(Real ch1, Real ch2)
{
m_scopeBuffer[m_scopeBufferIndex++] = Sample(ch1 * SDR_RX_SCALEF, ch2 * SDR_RX_SCALEF);
if (m_scopeBufferIndex == m_scopeBufferSize)
{
m_scopeBegin[0] = m_scopeBuffer.begin();
m_scopeSink->feed(m_scopeBegin, m_scopeBufferSize);
m_scopeBufferIndex = 0;
}
}
Real AcarsDemodSink::scopeChannel(int selection, const Complex& ci, Real magsq) const
{
bool vdl2 = m_settings.m_mode == AcarsDemodSettings::VDL2;
bool hfdl = m_settings.m_mode == AcarsDemodSettings::HFDL;
bool aero = m_settings.m_mode == AcarsDemodSettings::Aero;
switch (selection)
{
case 0: return ci.real() / SDR_RX_SCALEF;
case 1: return ci.imag() / SDR_RX_SCALEF;
case 2: return magsq;
case 3: return sqrt(magsq);
case 4: return vdl2 ? (Real) std::min(m_vdl2Receiver.syncStatistic(), 10.0)
: hfdl ? (Real) m_hfdlReceiver.lastSyncError()
: aero ? (Real) m_aeroReceiver.lastSyncError()
: (Real) m_receiver.detectStatistic();
case 5: return vdl2 ? (m_vdl2Receiver.synced() ? 1.0f : 0.0f)
: hfdl ? (m_hfdlReceiver.synced() ? 1.0f : 0.0f)
: aero ? (m_aeroReceiver.synced() ? 1.0f : 0.0f)
: (m_receiver.detected() ? 1.0f : 0.0f);
default: return 0.0f;
}
}
void AcarsDemodSink::processOneSample(Complex &ci)
{
Real re = ci.real() / SDR_RX_SCALEF;
Real im = ci.imag() / SDR_RX_SCALEF;
Real magsq = re*re + im*im;
m_movingAverage(magsq);
m_magsq = m_movingAverage.asDouble();
m_magsqSum += magsq;
if (magsq > m_magsqPeak) {
m_magsqPeak = magsq;
}
m_magsqCount++;
if (m_settings.m_mode == AcarsDemodSettings::VDL2)
{
if (m_vdl2Receiver.processSample(std::complex<double>(re, im)))
{
while (m_vdl2Receiver.hasFrame())
{
AcarsVdl2Receiver::Frame frame = m_vdl2Receiver.popFrame();
if (!getMessageQueueToChannel()) {
continue;
}
if (frame.m_isAcars)
{
// ACARS over AVLC carries the message from the mode character to the
// DEL, so prepending an SOH gives the exact VHF ACARS byte layout and
// the whole existing message path (GUI, UDP, log) works unchanged
QByteArray rxPacket;
rxPacket.append((char) 0x01);
rxPacket.append((const char *) frame.m_bytes.data() + frame.m_infoOffset + 3, frame.m_infoLength - 3);
getMessageQueueToChannel()->push(MainCore::MsgPacket::create(m_acarsDemod, rxPacket));
}
else
{
getMessageQueueToChannel()->push(AcarsDemod::MsgVdl2Frame::create(frame));
}
}
}
}
else if (m_settings.m_mode == AcarsDemodSettings::HFDL)
{
if (m_hfdlReceiver.processSample(std::complex<double>(re, im)))
{
while (m_hfdlReceiver.hasFrame())
{
AcarsHfdlReceiver::Frame frame = m_hfdlReceiver.popFrame();
if (!getMessageQueueToChannel()) {
continue;
}
if (frame.m_isAcars)
{
// The LPDU carries the ACARS message from its SOH onwards, so the
// bytes from the mode character with an SOH prepended give the
// exact VHF ACARS layout and the existing message path works
QByteArray rxPacket;
rxPacket.append((char) 0x01);
rxPacket.append((const char *) frame.m_bytes.data() + frame.m_acarsOffset,
(int) (frame.m_bytes.size() - frame.m_acarsOffset));
getMessageQueueToChannel()->push(MainCore::MsgPacket::create(m_acarsDemod, rxPacket));
}
else
{
getMessageQueueToChannel()->push(AcarsDemod::MsgHfdlFrame::create(frame));
}
}
}
}
else if (m_settings.m_mode == AcarsDemodSettings::Aero)
{
if (m_aeroReceiver.processSample(std::complex<double>(re, im)))
{
while (m_aeroReceiver.hasFrame())
{
AcarsAeroReceiver::Frame frame = m_aeroReceiver.popFrame();
if (!getMessageQueueToChannel()) {
continue;
}
if (frame.m_isAcars)
{
// Unlike VDL-2 and HFDL, an Aero signal unit chain reassembles to a
// COMPLETE ARINC 618 block starting at its own SOH, so there is no
// SOH to prepend here. Parity is left on, as on the other protocols.
// Verified against AcarsMessage::decode on a real recording.
QByteArray rxPacket((const char *) frame.m_bytes.data(), (int) frame.m_bytes.size());
getMessageQueueToChannel()->push(MainCore::MsgPacket::create(m_acarsDemod, rxPacket));
}
else
{
getMessageQueueToChannel()->push(AcarsDemod::MsgAeroFrame::create(frame));
}
}
}
}
// Tested explicitly rather than left as a bare else: an unrecognised mode used to
// fall through to the VHF MSK demodulator, so a mode added without touching this
// line failed by quietly running the wrong receiver
else if (m_settings.m_mode == AcarsDemodSettings::ACARS)
{
if (m_receiver.processSample(std::complex<double>(re, im)))
{
QByteArray rxPacket((const char *) m_receiver.message(), m_receiver.messageLength());
if (getMessageQueueToChannel())
{
MainCore::MsgPacket *msg = MainCore::MsgPacket::create(m_acarsDemod, rxPacket);
getMessageQueueToChannel()->push(msg);
}
}
}
if (m_scopeSink)
{
sampleToScope(scopeChannel(m_settings.m_scopeCh1, ci, magsq),
scopeChannel(m_settings.m_scopeCh2, ci, magsq));
}
// Demod Analyzer feature
m_demodBuffer[m_demodBufferFill++] = (qint16)(sqrt(magsq) * std::numeric_limits<int16_t>::max());
if (m_demodBufferFill >= m_demodBuffer.size())
{
QList<ObjectPipe*> dataPipes;
MainCore::instance()->getDataPipes().getDataPipes(m_channel, "demod", dataPipes);
for (const auto& pipe : dataPipes)
{
DataFifo *fifo = qobject_cast<DataFifo*>(pipe->m_element);
if (fifo) {
fifo->write((quint8*) &m_demodBuffer[0], m_demodBuffer.size() * sizeof(qint16), DataFifo::DataTypeI16);
}
}
m_demodBufferFill = 0;
}
}
void AcarsDemodSink::applyChannelSettings(int channelSampleRate, int channelFrequencyOffset, bool force)
{
qDebug() << "AcarsDemodSink::applyChannelSettings:"
<< " channelSampleRate: " << channelSampleRate
<< " channelFrequencyOffset: " << channelFrequencyOffset;
if ((m_channelFrequencyOffset != channelFrequencyOffset) ||
(m_channelSampleRate != channelSampleRate) || force)
{
// The published HFDL channel frequency is the (suppressed) SSB carrier; the PSK
// subcarrier sits 1440 Hz above it, so tuning to the published frequency needs
// an extra shift down onto the subcarrier
int subcarrier = m_settings.m_mode == AcarsDemodSettings::HFDL ? ACARSHFDL_SUBCARRIER_HZ : 0;
m_nco.setFreq(-(channelFrequencyOffset + subcarrier), channelSampleRate);
}
if ((m_channelSampleRate != channelSampleRate) || force)
{
// VDL-2, HFDL and Aero need a sharper filter: the root raised cosine skirt sits
// close to the channel edge and the default 4.5 taps per phase dents it enough
// to cause symbol errors
m_interpolator.create(16, channelSampleRate, m_settings.m_rfBandwidth / 2.2f,
m_settings.m_mode == AcarsDemodSettings::ACARS ? 4.5 : 18.0);
m_interpolatorDistance = (Real) channelSampleRate / (Real) AcarsDemodSink::channelSampleRate(m_settings);
m_interpolatorDistanceRemain = m_interpolatorDistance;
}
m_channelSampleRate = channelSampleRate;
m_channelFrequencyOffset = channelFrequencyOffset;
}
void AcarsDemodSink::applySettings(const AcarsDemodSettings& settings, bool force)
{
qDebug() << "AcarsDemodSink::applySettings: force: " << force;
// An Aero submode change moves the rate just as a mode change does
bool modeChanged = (settings.m_mode != m_settings.m_mode)
|| ((settings.m_mode == AcarsDemodSettings::Aero)
&& (settings.m_aeroChannel != m_settings.m_aeroChannel));
if ((settings.m_rfBandwidth != m_settings.m_rfBandwidth) || modeChanged || force)
{
m_interpolator.create(16, m_channelSampleRate, settings.m_rfBandwidth / 2.2f,
settings.m_mode == AcarsDemodSettings::ACARS ? 4.5 : 18.0);
m_interpolatorDistance = (Real) m_channelSampleRate / (Real) AcarsDemodSink::channelSampleRate(settings);
m_interpolatorDistanceRemain = m_interpolatorDistance;
int subcarrier = settings.m_mode == AcarsDemodSettings::HFDL ? ACARSHFDL_SUBCARRIER_HZ : 0;
m_nco.setFreq(-(m_channelFrequencyOffset + subcarrier), m_channelSampleRate);
}
// Reconfiguring reallocates and resets the receiver, which throws away a transmission in
// progress, so only do it when something it cares about has actually moved
if ((settings.m_correlationThreshold != m_settings.m_correlationThreshold) || force)
{
AcarsOqpskReceiver::Config config = m_receiver.config();
config.m_detectThreshold = settings.m_correlationThreshold;
m_receiver.configure(config);
}
if (modeChanged || force)
{
// Stamp the protocol into the SAME queue the packets go to, so the worker applies
// it in stream order with them rather than from its own separately delivered
// settings - see AcarsDemod::MsgProtocolChange
if (m_messageQueueToChannel) {
m_messageQueueToChannel->push(AcarsDemod::MsgProtocolChange::create(settings.m_mode));
}
m_vdl2Receiver.reset();
m_hfdlReceiver.reset();
// setMode reconfigures the matched filter and buffers for the new rate, and
// resets, so it has to be called rather than reset() alone
m_aeroReceiver.setMode(AcarsAeroReceiver::submodeRate(settings.m_aeroChannel),
AcarsAeroReceiver::submodeChannel(settings.m_aeroChannel));
}
m_settings = settings;
}
///////////////////////////////////////////////////////////////////////////////////
// Copyright (C) 2019 Edouard Griffiths, F4EXB //
// Copyright (C) 2021-2026 Jon Beniston, M7RCE //
// 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 <algorithm>
#include "dsp/dspengine.h"
#include "dsp/datafifo.h"
#include "dsp/scopevis.h"
#include "util/db.h"
#include "maincore.h"
#include "acarsdemod.h"
#include "acarsdemodsink.h"
AcarsDemodSink::AcarsDemodSink(AcarsDemod *acarsDemod) :
m_scopeSink(nullptr),
m_acarsDemod(acarsDemod),
m_channel(nullptr),
m_channelSampleRate(ACARSDEMOD_CHANNEL_SAMPLE_RATE),
m_channelFrequencyOffset(0),
m_interpolatorDistance(1.0f),
m_interpolatorDistanceRemain(0.0f),
m_magsq(0.0),
m_magsqSum(0.0f),
m_magsqPeak(0.0f),
m_magsqCount(0),
m_messageQueueToChannel(nullptr),
m_scopeBufferIndex(0),
m_demodBufferFill(0),
m_iridiumChannels(0), // Configured on the first Iridium sample
m_iridiumLogCount(0),
m_iridiumCarrierCount(0),
m_demodPipesPresent(false),
m_demodPipeCheck(1)
{
m_demodBuffer.resize(1<<12);
m_scopeBuffer.resize(m_scopeBufferSize);
m_scopeBegin.resize(1);
applySettings(m_settings, true);
applyChannelSettings(m_channelSampleRate, m_channelFrequencyOffset, true);
}
AcarsDemodSink::~AcarsDemodSink()
{
}
void AcarsDemodSink::feed(const SampleVector::const_iterator& begin, const SampleVector::const_iterator& end)
{
Complex ci;
if ((m_settings.m_mode == AcarsDemodSettings::Iridium)
&& (std::fabs(m_interpolatorDistance - 1.0f) < 1e-6f))
{
for (SampleVector::const_iterator it = begin; it != end; ++it)
{
Complex c(it->real(), it->imag());
c *= m_nco.nextIQ();
processOneSample(c);
}
return;
}
for (SampleVector::const_iterator it = begin; it != end; ++it)
{
Complex c(it->real(), it->imag());
c *= m_nco.nextIQ();
if (m_interpolatorDistance < 1.0f)
{
while (!m_interpolator.interpolate(&m_interpolatorDistanceRemain, c, &ci))
{
processOneSample(ci);
m_interpolatorDistanceRemain += m_interpolatorDistance;
}
}
else
{
if (m_interpolator.decimate(&m_interpolatorDistanceRemain, c, &ci))
{
processOneSample(ci);
m_interpolatorDistanceRemain += m_interpolatorDistance;
}
}
}
}
void AcarsDemodSink::sampleToScope(Real ch1, Real ch2)
{
m_scopeBuffer[m_scopeBufferIndex++] = Sample(ch1 * SDR_RX_SCALEF, ch2 * SDR_RX_SCALEF);
if (m_scopeBufferIndex == m_scopeBufferSize)
{
m_scopeBegin[0] = m_scopeBuffer.begin();
m_scopeSink->feed(m_scopeBegin, m_scopeBufferSize);
m_scopeBufferIndex = 0;
}
}
Real AcarsDemodSink::scopeChannel(int selection, const Complex& ci, Real magsq) const
{
bool vdl2 = m_settings.m_mode == AcarsDemodSettings::VDL2;
bool hfdl = m_settings.m_mode == AcarsDemodSettings::HFDL;
bool aero = m_settings.m_mode == AcarsDemodSettings::Aero;
switch (selection)
{
case 0: return ci.real() / SDR_RX_SCALEF;
case 1: return ci.imag() / SDR_RX_SCALEF;
case 2: return magsq;
case 3: return sqrt(magsq);
case 4: return vdl2 ? (Real) std::min(m_vdl2Receiver.syncStatistic(), 10.0)
: hfdl ? (Real) m_hfdlReceiver.lastSyncError()
: aero ? (Real) m_aeroReceiver.lastSyncError()
: (Real) m_receiver.detectStatistic();
case 5: return vdl2 ? (m_vdl2Receiver.synced() ? 1.0f : 0.0f)
: hfdl ? (m_hfdlReceiver.synced() ? 1.0f : 0.0f)
: aero ? (m_aeroReceiver.synced() ? 1.0f : 0.0f)
: (m_receiver.detected() ? 1.0f : 0.0f);
default: return 0.0f;
}
}
void AcarsDemodSink::processOneSample(Complex &ci)
{
Real re = ci.real() / SDR_RX_SCALEF;
Real im = ci.imag() / SDR_RX_SCALEF;
Real magsq = re*re + im*im;
m_movingAverage(magsq);
m_magsq = m_movingAverage.asDouble();
m_magsqSum += magsq;
if (magsq > m_magsqPeak) {
m_magsqPeak = magsq;
}
m_magsqCount++;
if (m_settings.m_mode == AcarsDemodSettings::VDL2)
{
if (m_vdl2Receiver.processSample(std::complex<double>(re, im)))
{
while (m_vdl2Receiver.hasFrame())
{
AcarsVdl2Receiver::Frame frame = m_vdl2Receiver.popFrame();
if (!getMessageQueueToChannel()) {
continue;
}
if (frame.m_isAcars)
{
// ACARS over AVLC carries the message from the mode character to the
// DEL, so prepending an SOH gives the exact VHF ACARS byte layout and
// the whole existing message path (GUI, UDP, log) works unchanged
QByteArray rxPacket;
rxPacket.append((char) 0x01);
rxPacket.append((const char *) frame.m_bytes.data() + frame.m_infoOffset + 3, frame.m_infoLength - 3);
// The AVLC header names the airframe by its ICAO address, where the
// block inside names it by registration. Both are worth having: the
// address collates this aircraft with its ADS-B, and the pair is the
// only evidence we ever receive that the two belong together
uint32_t acAddress = frame.m_fromAircraft ? frame.m_srcAddress : frame.m_dstAddress;
int acType = frame.m_fromAircraft ? frame.m_srcType : frame.m_dstType;
getMessageQueueToChannel()->push(AcarsDemod::MsgAcarsPacket::create(
m_acarsDemod, rxPacket, (acType == 1) ? acAddress : 0));
}
else
{
getMessageQueueToChannel()->push(AcarsDemod::MsgVdl2Frame::create(frame));
}
}
}
}
else if (m_settings.m_mode == AcarsDemodSettings::HFDL)
{
if (m_hfdlReceiver.processSample(std::complex<double>(re, im)))
{
while (m_hfdlReceiver.hasFrame())
{
AcarsHfdlReceiver::Frame frame = m_hfdlReceiver.popFrame();
if (!getMessageQueueToChannel()) {
continue;
}
if (frame.m_isAcars)
{
// The LPDU carries the ACARS message from its SOH onwards, so the
// bytes from the mode character with an SOH prepended give the
// exact VHF ACARS layout and the existing message path works
QByteArray rxPacket;
rxPacket.append((char) 0x01);
rxPacket.append((const char *) frame.m_bytes.data() + frame.m_acarsOffset,
(int) (frame.m_bytes.size() - frame.m_acarsOffset));
getMessageQueueToChannel()->push(MainCore::MsgPacket::create(m_acarsDemod, rxPacket));
}
else
{
getMessageQueueToChannel()->push(AcarsDemod::MsgHfdlFrame::create(frame));
}
}
}
}
else if (m_settings.m_mode == AcarsDemodSettings::Aero)
{
if (m_aeroReceiver.processSample(std::complex<double>(re, im)))
{
while (m_aeroReceiver.hasFrame())
{
AcarsAeroReceiver::Frame frame = m_aeroReceiver.popFrame();
if (!getMessageQueueToChannel()) {
continue;
}
if (frame.m_isAcars)
{
// Unlike VDL-2 and HFDL, an Aero signal unit chain reassembles to a
// COMPLETE ARINC 618 block starting at its own SOH, so there is no
// SOH to prepend here. Parity is left on, as on the other protocols.
// Verified against AcarsMessage::decode on a real recording.
QByteArray rxPacket((const char *) frame.m_bytes.data(), (int) frame.m_bytes.size());
getMessageQueueToChannel()->push(MainCore::MsgPacket::create(m_acarsDemod, rxPacket));
}
else
{
getMessageQueueToChannel()->push(AcarsDemod::MsgAeroFrame::create(frame));
}
}
}
}
// Tested explicitly rather than left as a bare else: an unrecognised mode used to
// fall through to the VHF MSK demodulator, so a mode added without touching this
// line failed by quietly running the wrong receiver
else if (m_settings.m_mode == AcarsDemodSettings::Iridium)
{
// Unlike the other modes this one scans: the channelizer in the scanner splits
// the whole tuned width into Iridium channels and runs a receiver on each, so the
// samples arriving here are the band rather than a channel
const int channels = AcarsDemodSettings::iridiumScanChannels(m_settings.m_iridiumBandwidth);
if (channels != m_iridiumChannels)
{
m_iridiumScanner.configure(channels);
m_iridiumChannels = channels;
m_iridiumCarrierCount = 0;
m_iridiumLogCount = 0;
m_iridiumLog = IridiumLog();
}
m_iridiumScanner.processSample(std::complex<double>(re, im));
if (++m_iridiumLogCount >= (qint64) (m_iridiumLogSeconds * m_iridiumScanner.inputRate()))
{
m_iridiumLogCount = 0;
logIridiumSummary();
}
while (m_iridiumScanner.hasDetection())
{
AcarsIridiumScanner::Detection detection = m_iridiumScanner.popDetection();
if (!detection.m_message.isEmpty())
{
QByteArray payload;
if (AcarsIridiumReassembler::sbdPayload(detection.m_message,
detection.m_frame.m_uplink, payload))
{
m_iridiumCarrierCount++;
if (detection.m_acars.isEmpty())
{
// Both type bytes, because the first on its own does not say
// whether a message could carry ACARS: 0x7608 does and 0x7605
// does not, and they look the same from the leading byte
const quint8 type0 = (quint8) detection.m_message[0];
const quint8 type1 = (detection.m_message.size() > 1)
? (quint8) detection.m_message[1] : 0;
qInfo() << "Iridium short burst data message," << detection.m_message.size()
<< "bytes, type" << QString("0x%1%2").arg(type0, 2, 16, QChar('0'))
.arg(type1, 2, 16, QChar('0'))
<< ":" << detection.m_message.toHex('.')
<< "(payload is not ACARS)";
}
}
}
if (detection.m_acars.isEmpty()) {
continue;
}
if (getMessageQueueToChannel())
{
MainCore::MsgPacket *msg = MainCore::MsgPacket::create(m_acarsDemod, detection.m_acars);
getMessageQueueToChannel()->push(msg);
}
}
}
else if (m_settings.m_mode == AcarsDemodSettings::ACARS)
{
if (m_receiver.processSample(std::complex<double>(re, im)))
{
QByteArray rxPacket((const char *) m_receiver.message(), m_receiver.messageLength());
if (getMessageQueueToChannel())
{
MainCore::MsgPacket *msg = MainCore::MsgPacket::create(m_acarsDemod, rxPacket);
getMessageQueueToChannel()->push(msg);
}
}
}
if (m_scopeSink)
{
sampleToScope(scopeChannel(m_settings.m_scopeCh1, ci, magsq),
scopeChannel(m_settings.m_scopeCh2, ci, magsq));
}
// Demod Analyzer feature.
//
// Whether anything is listening is rechecked periodically rather than assumed, so
// that the square root below is not paid for when nothing is. That mattered little
// while every mode ran at 105 kS/s or less, but Iridium scans the band at up to
// 8 MS/s, where this was eight million square roots a second and a pipe lookup two
// thousand times a second for a feature that is usually not attached
if (--m_demodPipeCheck <= 0)
{
QList<ObjectPipe*> dataPipes;
MainCore::instance()->getDataPipes().getDataPipes(m_channel, "demod", dataPipes);
m_demodPipesPresent = !dataPipes.isEmpty();
m_demodPipeCheck = m_demodPipeCheckInterval;
}
if (!m_demodPipesPresent)
{
m_demodBufferFill = 0;
return;
}
m_demodBuffer[m_demodBufferFill++] = (qint16)(sqrt(magsq) * std::numeric_limits<int16_t>::max());
if (m_demodBufferFill >= m_demodBuffer.size())
{
QList<ObjectPipe*> dataPipes;
MainCore::instance()->getDataPipes().getDataPipes(m_channel, "demod", dataPipes);
for (const auto& pipe : dataPipes)
{
DataFifo *fifo = qobject_cast<DataFifo*>(pipe->m_element);
if (fifo) {
fifo->write((quint8*) &m_demodBuffer[0], m_demodBuffer.size() * sizeof(qint16), DataFifo::DataTypeI16);
}
}
m_demodBufferFill = 0;
}
}
//! Taps per phase for the input resampler. The sharp filter the other modes need is to
//! keep the root raised cosine skirt intact right up to the channel edge. Iridium does not
//! want a channel filter at all - it passes the whole scanned width and lets its own
//! channelizer do the filtering - so the cheap setting is enough, and at several MS/s the
//! difference between 4.5 and 18 taps per phase is a large part of the whole cost
static Real inputFilterTaps(const AcarsDemodSettings& settings)
{
return ((settings.m_mode == AcarsDemodSettings::ACARS)
|| (settings.m_mode == AcarsDemodSettings::Iridium)) ? 4.5 : 18.0;
}
static Real effectiveRfBandwidth(const AcarsDemodSettings& settings)
{
if (settings.m_mode == AcarsDemodSettings::Iridium) {
return (Real) AcarsDemodSink::channelSampleRate(settings);
}
return settings.m_rfBandwidth;
}
void AcarsDemodSink::logIridiumSummary()
{
const int bursts = m_iridiumScanner.burstCount();
if (bursts == m_iridiumLog.m_bursts) {
return;
}
qInfo() << "Iridium:" << (bursts - m_iridiumLog.m_bursts) << "bursts in the last"
<< m_iridiumLogSeconds << "s on" << m_iridiumChannels << "channels,"
<< (m_iridiumScanner.duplicateCount() - m_iridiumLog.m_duplicates) << "duplicated,"
<< (m_iridiumScanner.frameCount() - m_iridiumLog.m_frames) << "frames decoded of which"
<< (m_iridiumScanner.idaCount() - m_iridiumLog.m_ida) << "short burst data,"
<< (m_iridiumScanner.messageCount() - m_iridiumLog.m_messages) << "messages reassembled of which"
<< (m_iridiumCarrierCount - m_iridiumLog.m_carriers) << "carry a payload,"
<< (m_iridiumScanner.acarsCount() - m_iridiumLog.m_acars) << "ACARS";
m_iridiumLog.m_bursts = bursts;
m_iridiumLog.m_duplicates = m_iridiumScanner.duplicateCount();
m_iridiumLog.m_frames = m_iridiumScanner.frameCount();
m_iridiumLog.m_ida = m_iridiumScanner.idaCount();
m_iridiumLog.m_messages = m_iridiumScanner.messageCount();
m_iridiumLog.m_carriers = m_iridiumCarrierCount;
m_iridiumLog.m_acars = m_iridiumScanner.acarsCount();
}
void AcarsDemodSink::applyChannelSettings(int channelSampleRate, int channelFrequencyOffset, bool force)
{
qDebug() << "AcarsDemodSink::applyChannelSettings:"
<< " channelSampleRate: " << channelSampleRate
<< " channelFrequencyOffset: " << channelFrequencyOffset;
if ((m_channelFrequencyOffset != channelFrequencyOffset) ||
(m_channelSampleRate != channelSampleRate) || force)
{
// The published HFDL channel frequency is the (suppressed) SSB carrier; the PSK
// subcarrier sits 1440 Hz above it, so tuning to the published frequency needs
// an extra shift down onto the subcarrier
int subcarrier = m_settings.m_mode == AcarsDemodSettings::HFDL ? ACARSHFDL_SUBCARRIER_HZ : 0;
m_nco.setFreq(-(channelFrequencyOffset + subcarrier), channelSampleRate);
// Retuning moves the signal, so everything a receiver has worked out about where
// it is - the carrier it is tracking, the symbol clock phase it has locked, the
// instant it expects the next frame at - describes the old position and not the
// new one. Only a mode or rate change used to reset them, which is why changing
// one was the way to get a demodulator going again after nudging the offset.
//
// Not on a sample rate change alone: that path already rebuilds the interpolator
// below and the receivers cope with it, and a reset there would throw away a
// transmission in progress for nothing.
if (m_channelFrequencyOffset != channelFrequencyOffset)
{
m_vdl2Receiver.reset();
m_hfdlReceiver.reset();
m_aeroReceiver.reset();
}
}
if ((m_channelSampleRate != channelSampleRate) || force)
{
// VDL-2, HFDL and Aero need a sharper filter: the root raised cosine skirt sits
// close to the channel edge and the default 4.5 taps per phase dents it enough
// to cause symbol errors
m_interpolator.create(16, channelSampleRate, effectiveRfBandwidth(m_settings) / 2.2f,
inputFilterTaps(m_settings));
m_interpolatorDistance = (Real) channelSampleRate / (Real) AcarsDemodSink::channelSampleRate(m_settings);
m_interpolatorDistanceRemain = m_interpolatorDistance;
}
m_channelSampleRate = channelSampleRate;
m_channelFrequencyOffset = channelFrequencyOffset;
}
void AcarsDemodSink::applySettings(const AcarsDemodSettings& settings, bool force)
{
qDebug() << "AcarsDemodSink::applySettings: force: " << force;
// An Aero submode or an Iridium scan width moves the rate just as a mode change does
bool modeChanged = AcarsDemodSettings::rateChanged(settings, m_settings);
if ((settings.m_rfBandwidth != m_settings.m_rfBandwidth) || modeChanged || force)
{
m_interpolator.create(16, m_channelSampleRate, effectiveRfBandwidth(settings) / 2.2f,
inputFilterTaps(settings));
m_interpolatorDistance = (Real) m_channelSampleRate / (Real) AcarsDemodSink::channelSampleRate(settings);
m_interpolatorDistanceRemain = m_interpolatorDistance;
int subcarrier = settings.m_mode == AcarsDemodSettings::HFDL ? ACARSHFDL_SUBCARRIER_HZ : 0;
m_nco.setFreq(-(m_channelFrequencyOffset + subcarrier), m_channelSampleRate);
}
// Reconfiguring reallocates and resets the receiver, which throws away a transmission in
// progress, so only do it when something it cares about has actually moved
if ((settings.m_correlationThreshold != m_settings.m_correlationThreshold) || force)
{
AcarsOqpskReceiver::Config config = m_receiver.config();
config.m_detectThreshold = settings.m_correlationThreshold;
m_receiver.configure(config);
}
if (modeChanged || force)
{
// Stamp the protocol into the SAME queue the packets go to, so the worker applies
// it in stream order with them rather than from its own separately delivered
// settings - see AcarsDemod::MsgProtocolChange
if (m_messageQueueToChannel) {
m_messageQueueToChannel->push(AcarsDemod::MsgProtocolChange::create(settings.m_mode));
}
m_vdl2Receiver.reset();
m_hfdlReceiver.reset();
// setMode reconfigures the matched filter and buffers for the new rate, and
// resets, so it has to be called rather than reset() alone
m_aeroReceiver.setMode(AcarsAeroReceiver::submodeRate(settings.m_aeroChannel),
AcarsAeroReceiver::submodeChannel(settings.m_aeroChannel));
}
m_settings = settings;
}

36
plugins/channelrx/demodacars/acarsdemodsink.h

@ -34,6 +34,8 @@ @@ -34,6 +34,8 @@
#include "acarsvdl2.h"
#include "acarshfdl.h"
#include "acarsaero.h"
#include "acarsiridium.h"
#include "acarsiridiumscanner.h"
#define ACARSDEMOD_CHANNEL_SAMPLE_RATE ACARSOQPSK_CHANNEL_SAMPLE_RATE
@ -66,6 +68,11 @@ public: @@ -66,6 +68,11 @@ public:
case AcarsDemodSettings::Aero:
return AcarsAeroReceiver::channelSampleRate(
AcarsAeroReceiver::submodeRate(settings.m_aeroChannel));
// Iridium scans rather than tuning one channel, so the rate is the width of band
// it covers, not the rate one receiver runs at
case AcarsDemodSettings::Iridium:
return AcarsDemodSettings::iridiumScanChannels(settings.m_iridiumBandwidth)
* ACARSIRIDIUM_SCAN_SPACING;
default: return ACARSDEMOD_CHANNEL_SAMPLE_RATE;
}
}
@ -134,6 +141,34 @@ private: @@ -134,6 +141,34 @@ private:
AcarsVdl2Receiver m_vdl2Receiver;
AcarsHfdlReceiver m_hfdlReceiver;
AcarsAeroReceiver m_aeroReceiver;
AcarsIridiumScanner m_iridiumScanner;
int m_iridiumChannels; //!< What the scanner is currently configured for
//!< Scanning the whole band decodes a dozen frames a second, so none of them are
//!< logged individually - what the band is doing is summarised this often instead,
//!< as the change in the scanner's counters since the last one
static constexpr double m_iridiumLogSeconds = 60.0;
qint64 m_iridiumLogCount; //!< Input samples since the last summary
int m_iridiumCarrierCount; //!< Reassembled messages whose type carries a payload
struct IridiumLog
{
int m_bursts = 0;
int m_duplicates = 0;
int m_frames = 0;
int m_ida = 0;
int m_messages = 0;
int m_carriers = 0;
int m_acars = 0;
};
IridiumLog m_iridiumLog; //!< The counters as of the last summary
//!< Whether a Demod Analyzer is attached, rechecked every so many samples rather
//!< than per sample. A tenth of a second at the fastest rate the plugin runs at
bool m_demodPipesPresent;
int m_demodPipeCheck;
static const int m_demodPipeCheckInterval = 100000;
static const int m_scopeBufferSize = 512;
SampleVector m_scopeBuffer;
@ -144,6 +179,7 @@ private: @@ -144,6 +179,7 @@ private:
int m_demodBufferFill;
void processOneSample(Complex &ci);
void logIridiumSummary();
void sampleToScope(Real ch1, Real ch2);
Real scopeChannel(int selection, const Complex& ci, Real magsq) const;

6
plugins/channelrx/demodacars/acarsdemodwebapiadapter.cpp

@ -31,9 +31,9 @@ int AcarsDemodWebAPIAdapter::webapiSettingsGet( @@ -31,9 +31,9 @@ int AcarsDemodWebAPIAdapter::webapiSettingsGet(
QString& errorMessage)
{
(void) errorMessage;
/* response.setAcarsDemodSettings(new SWGSDRangel::SWGACARSDemodSettings());
response.setAcarsDemodSettings(new SWGSDRangel::SWGACARSDemodSettings());
response.getAcarsDemodSettings()->init();
AcarsDemod::webapiFormatChannelSettings(response, m_settings); */
AcarsDemod::webapiFormatChannelSettings(response, m_settings);
return 200;
}
@ -46,7 +46,7 @@ int AcarsDemodWebAPIAdapter::webapiSettingsPutPatch( @@ -46,7 +46,7 @@ int AcarsDemodWebAPIAdapter::webapiSettingsPutPatch(
{
(void) force;
(void) errorMessage;
// AcarsDemod::webapiUpdateChannelSettings(m_settings, channelSettingsKeys, response);
AcarsDemod::webapiUpdateChannelSettings(m_settings, channelSettingsKeys, response);
return 200;
}

4938
plugins/channelrx/demodacars/acarsdemodworker.cpp

File diff suppressed because it is too large Load Diff

54
plugins/channelrx/demodacars/acarsdemodworker.h

@ -39,8 +39,8 @@ @@ -39,8 +39,8 @@
#include <libacars/reassembly.h>
#include "acarsdemodsettings.h"
#include "acarsmessage.h"
#include "acarsmultipartassembler.h"
#include "util/acarsmessage.h"
#include "util/acarsmultipartassembler.h"
#include "acarsvdl2.h"
#include "acarshfdl.h"
#include "acarsaero.h"
@ -157,6 +157,39 @@ public: @@ -157,6 +157,39 @@ public:
{}
};
// The aircraft database has been downloaded again: pick up the new one
class MsgReloadAircraftDatabase : public Message {
MESSAGE_CLASS_DECLARATION
public:
static MsgReloadAircraftDatabase* create() {
return new MsgReloadAircraftDatabase();
}
private:
MsgReloadAircraftDatabase() :
Message()
{}
};
// An ACARS block read back from a .csv log. Decoded and shown like a received one,
// but kept off the outputs - UDP, the "packets" pipes, the log and the aggregator
// feed - which would otherwise send old traffic out again as if it were new, and
// append to the very log being read.
class MsgReplayPacket : public Message {
MESSAGE_CLASS_DECLARATION
public:
const QByteArray& getPacket() const { return m_packet; }
QDateTime getDateTime() const { return m_dateTime; }
static MsgReplayPacket* create(const QByteArray& packet, const QDateTime& dateTime) {
return new MsgReplayPacket(packet, dateTime);
}
private:
QByteArray m_packet;
QDateTime m_dateTime;
MsgReplayPacket(const QByteArray& packet, const QDateTime& dateTime) :
Message(), m_packet(packet), m_dateTime(dateTime)
{}
};
explicit AcarsDemodWorker(AcarsDemod *acarsDemod);
~AcarsDemodWorker();
@ -204,13 +237,6 @@ private: @@ -204,13 +237,6 @@ private:
int m_hfdlNewestReportSecs = -1; // Newest HFNPDU report time seen, for replay-aware freshness
// Aggregator feeds (sockets created on the worker thread)
QUdpSocket *m_feedSocket = nullptr;
QTcpSocket *m_feedAirframesTcpSocket = nullptr;
QTcpSocket *m_feedAvdelphiTcpSocket = nullptr;
QHostAddress m_feedAirframesAddr; // Cached DNS resolutions, for UDP
QString m_feedAirframesResolvedHost;
QHostAddress m_feedAvdelphiAddr;
QString m_feedAvdelphiResolvedHost;
// Databases for message decode and flight paths
QSharedPointer<const QHash<QString, AircraftInformation *>> m_aircraftInfo;
@ -225,8 +251,10 @@ private: @@ -225,8 +251,10 @@ private:
void applySettings(const AcarsDemodSettings& settings, bool force);
void forwardToGui(Message *message);
void processPacket(const QByteArray& packet, QDateTime dateTime);
void processAcarsMessage(QByteArray messageBytes, QDateTime received);
//!< icao is the address the bearer knew, or 0 - see AcarsDemod::MsgAcarsPacket
//!< replay is true for a block read back from a .csv log - see MsgReplayPacket
void processPacket(const QByteArray& packet, QDateTime dateTime, quint32 icao = 0, bool replay = false);
void processAcarsMessage(QByteArray messageBytes, QDateTime received, quint32 icao = 0, bool replay = false);
void processVdl2Frame(const AcarsVdl2Receiver::Frame& frame, QDateTime received);
void processHfdlFrame(const AcarsHfdlReceiver::Frame& frame, QDateTime received);
void processAeroFrame(const AcarsAeroReceiver::Frame& frame, QDateTime received);
@ -237,10 +265,8 @@ private: @@ -237,10 +265,8 @@ private:
// The protocol the packets currently in flight came off, stamped by the sink rather
// than read from m_settings - see AcarsDemod::MsgProtocolChange
int m_protocolMode = 0; // AcarsDemodSettings::ACARS
void feedMessage(const AcarsMessage& message);
void updateFeedConnections();
void feedMessage(const QByteArray& block, const QDateTime& received);
void sendAircraftReport(AircraftReport& report);
void sendGroundStationToMap(const QString& name, float latitude, float longitude, const QString& text, QDateTime dateTime);
void emitAssemblyState(const QSharedPointer<AcarsMultipartAssembler::Assembly>& assembly);
private slots:

137
plugins/channelrx/demodacars/acarshfdl.h

@ -2,6 +2,12 @@ @@ -2,6 +2,12 @@
// Copyright (C) 2026 Jon Beniston, M7RCE <jon@beniston.com> //
// Some code by AI //
// //
// The HFDL constants and conventions - the physical layer parameters and the //
// MPDU, LPDU and SPDU layouts - were cross-checked against dumphfdl by Tomasz //
// Lemiech, https://github.com/szpajder/dumphfdl, GPL-3.0, and the ARINC 635 //
// system table of ground station names, positions and frequency assignments //
// is the one dumphfdl ships. //
// //
// 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 //
@ -165,7 +171,9 @@ public: @@ -165,7 +171,9 @@ public:
// thread's time, which matters at accelerated file replay. 0 disables the
// limit (every failed burst runs the full chain).
double m_retryLimitFraction = 0.30;
// Decision directed per-symbol frequency update on the phase residual
// Decision directed per-symbol frequency update on the phase residual. Applied
// scaled by (1 - the reference blend in use), as the loop originally had it in
// effect - see updateRefLane()
double m_freqGain = 0.01;
// Reference phasor blending for decision-directed symbols...
double m_refGain = 0.15;
@ -990,7 +998,7 @@ private: @@ -990,7 +998,7 @@ private:
}
delta = std::max(-0.5, std::min(0.5, delta));
m_dphiSym = std::arg(m_bestD);
m_dphiSym = refineAcquisitionDphi(std::arg(m_bestD));
// First following symbol lands one symbol after the peak
if (delta >= 0.0)
@ -1081,6 +1089,71 @@ private: @@ -1081,6 +1089,71 @@ private:
m_laneMeta.clear();
}
// Refine the acquisition's per-symbol rotation by maximising the coherent sum over the
// whole A sequence, modulation removed - the maximum likelihood estimate given the
// known symbols. The differential correlation that found the burst multiplies noise
// by noise and averages only 126 products, so its estimate is far noisier: the
// coherent sum's error falls as N^-1.5 rather than N^-0.5.
//
// It matters because of how the carrier loop uses it. Any error in the rotation
// leaves the decision-directed reference lagging by error / gain - about seven times
// the error at the data gain - and the A2 gate, a coherent sum, is where that bites.
// The loop used to apply only (1 - gain) of the estimate (see updateRefLane()),
// which by accident shrank a noisy estimate towards zero and so suited the near-zero
// offsets of real recordings; applying it in full needs it to be accurate instead.
// Measured: the corrected loop order alone lost 2.5 percent of the LPDUs on the
// short real recordings, all at the A2 gate; with this as well it gains 5 percent
// on them, and 4 percent (3249 to 3375) on the overnight Reykjavik capture.
//
// A grid of quarter-bin steps around the coarse estimate, then a parabola through
// the best and its neighbours. Once per sync, so its cost does not matter
double refineAcquisitionDphi(double coarse) const
{
const int sps = ACARSHFDL_SAMPLES_PER_SYMBOL;
const int n = ACARSHFDL_A_LEN;
const int span = 8;
const double step = (2.0 * M_PI / n) / 4.0;
Cd stripped[ACARSHFDL_A_LEN];
for (int k = 0; k < n; k++)
{
int back = m_bestAgo + (n - 1 - k) * sps;
stripped[k] = tap(back) * (aBit(k) ? -1.0 : 1.0);
}
double power[2 * span + 1];
int best = span;
for (int i = 0; i <= 2 * span; i++)
{
const double d = coarse + (i - span) * step;
// Symbol k is (n - 1 - k) symbols before the newest, so rotating it on by
// that many steps lines every symbol up with the newest one
const Cd rot = std::polar(1.0, d);
Cd phasor(1.0, 0.0);
Cd sum(0.0, 0.0);
for (int k = n - 1; k >= 0; k--)
{
sum += stripped[k] * phasor;
phasor *= rot;
}
power[i] = std::norm(sum);
if (power[i] > power[best]) {
best = i;
}
}
double shift = 0.0;
if ((best > 0) && (best < 2 * span))
{
const double denom = power[best - 1] - 2.0 * power[best] + power[best + 1];
if (denom < -1e-20) {
shift = std::max(-0.5, std::min(0.5, 0.5 * (power[best - 1] - power[best + 1]) / denom));
}
}
return coarse + ((best - span) + shift) * step;
}
void abandonBurst()
{
m_state = StateSearch;
@ -1094,10 +1167,29 @@ private: @@ -1094,10 +1167,29 @@ private:
// ---------------------------------------------------------------------------------
// Update a lane's carrier reference with a symbol whose modulation is known or
// decided: the sample with the modulation removed is blended into the reference
static void updateRefLane(Cd& ref, double dphiSym, const Cd& yDemod, double gain)
// decided: the sample with the modulation removed is blended into the reference.
//
// The reference must already have been advanced to this symbol by advanceRef(),
// BEFORE the symbol was derotated and its residual taken - the order the VDL-2
// receiver uses. Advancing it here instead, after the residual, meant every residual
// was measured against last symbol's phase, so the loop carried the per-symbol
// rotation as a standing lead and the frequency estimate settled at
// rotation / (1 - gain) rather than at the rotation. That is harmless while the gain
// never changes, but it switches between the training and the data gains every 15
// and 30 symbols, so the estimate was always wrong for one of them, and the data
// symbols carried a phase bias that grew with the tuning error. Measured on
// generated bursts, 1200 and 1800 bps at 20 dB: nothing at all decoded from 150 Hz
// of tuning error either way - the 4PSK and 8PSK decisions slipped - and 8PSK was
// already losing a quarter of its messages at 100 Hz. In this order both decode
// every message out to 400 Hz.
//
// With the gain held constant the two orders are the same second order loop except
// for the integrator's gain, which the old order scaled by (1 - gain); the frequency
// updates below keep that scaling, so the loop's noise behaviour is the one the
// receiver was tuned with. Without it 600 bps lost 6 percent of its messages at the
// cliff
static void updateRefLane(Cd& ref, const Cd& yDemod, double gain)
{
ref *= std::polar(1.0, dphiSym);
double mag = std::abs(yDemod);
if (mag > 1e-12) {
ref = (1.0 - gain) * ref + gain * (yDemod / mag);
@ -1108,6 +1200,13 @@ private: @@ -1108,6 +1200,13 @@ private:
}
}
// Step a lane's carrier reference on by one symbol's rotation, so it predicts the
// phase of the symbol about to be derotated. Called once per symbol, first
static void advanceRef(Cd& ref, double dphiSym)
{
ref *= std::polar(1.0, dphiSym);
}
void gardner(const Cd& y0)
{
if ((m_config.m_timingGain == 0.0) || (m_symbolsSinceSync <= 2)) {
@ -1168,6 +1267,9 @@ private: @@ -1168,6 +1267,9 @@ private:
void laneSymbol(EqLane& lane, const Cd& y0)
{
const int sps = ACARSHFDL_SAMPLES_PER_SYMBOL;
// Advanced first, every symbol, warm-up included, so the derotation below and
// the residual further down are both against this symbol's predicted phase
advanceRef(lane.m_ref, lane.m_dphiSym);
Cd xHalf = interpAt(sps / 2, m_mu) * std::conj(lane.m_ref)
* std::polar(1.0, 0.5 * lane.m_dphiSym) * m_eqScale;
eqPush(lane, xHalf);
@ -1175,8 +1277,8 @@ private: @@ -1175,8 +1277,8 @@ private:
if ((int) m_laneMeta.size() <= lane.m_delay)
{
// Warm-up: keep the reference advancing until the first delayed decision
lane.m_ref *= std::polar(1.0, lane.m_dphiSym);
// Warm-up: nothing to decide until the first delayed decision, but the
// reference has still been advanced above
return;
}
@ -1202,9 +1304,9 @@ private: @@ -1202,9 +1304,9 @@ private:
Cd yDemod = meta.m_knownBit ? -y0d : y0d;
double res = std::arg(yDemod * std::conj(lane.m_ref));
if (m_config.m_freqGain != 0.0) {
lane.m_dphiSym += m_config.m_freqGain * res;
lane.m_dphiSym += m_config.m_freqGain * (1.0 - m_config.m_trainGain) * res;
}
updateRefLane(lane.m_ref, lane.m_dphiSym, yDemod, m_config.m_trainGain);
updateRefLane(lane.m_ref, yDemod, m_config.m_trainGain);
// The known symbols are also the equalizer's training: the taps update
// here and are frozen over the data frames
double mu = m_config.m_eqMu;
@ -1219,11 +1321,10 @@ private: @@ -1219,11 +1321,10 @@ private:
else
{
if (m_config.m_freqGain != 0.0) {
lane.m_dphiSym += m_config.m_freqGain * residual;
lane.m_dphiSym += m_config.m_freqGain * (1.0 - m_config.m_refGain) * residual;
}
double modPhase = phaseIdx * step + (meta.m_flip ? M_PI : 0.0);
updateRefLane(lane.m_ref, lane.m_dphiSym, y0d * std::polar(1.0, -modPhase),
m_config.m_refGain);
updateRefLane(lane.m_ref, y0d * std::polar(1.0, -modPhase), m_config.m_refGain);
}
// Soft chips for the delayed data symbols; they trail the raw lane's by the
@ -1255,7 +1356,9 @@ private: @@ -1255,7 +1356,9 @@ private:
m_symbolsSinceSync++;
Cd y0 = interpAt(0, m_mu);
// Raw lane: identical to the receiver without an equalizer, so its soft chips
// and its carrier trajectory are exactly the proven baseline
// and its carrier trajectory are exactly the proven baseline. The reference is
// stepped on to this symbol before it derotates anything - see updateRefLane()
advanceRef(m_ref, m_dphiSym);
Cd y = y0 * std::conj(m_ref);
gardner(y0);
@ -1306,9 +1409,9 @@ private: @@ -1306,9 +1409,9 @@ private:
Cd yDemod = knownBit ? -y0 : y0;
double res = std::arg(yDemod * std::conj(m_ref));
if (m_config.m_freqGain != 0.0) {
m_dphiSym += m_config.m_freqGain * res;
m_dphiSym += m_config.m_freqGain * (1.0 - m_config.m_trainGain) * res;
}
updateRefLane(m_ref, m_dphiSym, yDemod, m_config.m_trainGain);
updateRefLane(m_ref, yDemod, m_config.m_trainGain);
int rxBit = (std::abs(phi) > M_PI_2) ? 1 : 0;
m_stats.m_trainBitsTotal++;
m_trainTotalThisBurst++;
@ -1323,10 +1426,10 @@ private: @@ -1323,10 +1426,10 @@ private:
// Decision-directed: remove the decided modulation (constellation phase
// plus the scrambler flip) from the received sample and blend it in
if (m_config.m_freqGain != 0.0) {
m_dphiSym += m_config.m_freqGain * residual;
m_dphiSym += m_config.m_freqGain * (1.0 - m_config.m_refGain) * residual;
}
double modPhase = phaseIdx * step + (flip ? M_PI : 0.0);
updateRefLane(m_ref, m_dphiSym, y0 * std::polar(1.0, -modPhase), m_config.m_refGain);
updateRefLane(m_ref, y0 * std::polar(1.0, -modPhase), m_config.m_refGain);
}
// Equalizer lanes, active once the mode is known: each has its own carrier

849
plugins/channelrx/demodacars/acarsiridium.h

@ -0,0 +1,849 @@ @@ -0,0 +1,849 @@
///////////////////////////////////////////////////////////////////////////////////
// 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_ACARSIRIDIUM_H
#define INCLUDE_ACARSIRIDIUM_H
#include <QDebug>
#include <complex>
#include <cmath>
#include <cstdint>
#include <deque>
#include <algorithm>
#include <vector>
#include "acarsiridiumfft.h"
// Iridium L band burst receiver, physical layer.
//
// Iridium is unlike the other protocols this plugin decodes. ACARS, VDL-2 and HFDL are
// continuous narrowband channels, and Inmarsat Aero is a geostationary satellite whose
// Doppler barely moves. Iridium is burst TDMA from satellites in low earth orbit:
//
// - bursts of about 8.3 ms in a 90 ms frame, so the receiver sees silence most of the
// time and has nothing to hold a lock on between them
// - DQPSK at 25 kbaud, an order of magnitude faster than the Aero MSK rates
// - low earth orbit gives roughly 37 kHz of Doppler either way, and it moves while the
// burst is being received, so every burst needs its own frequency estimate
//
// This stage finds bursts, demodulates them to symbols, and hands the bit stream from the
// unique word onwards to AcarsIridiumFrameDecoder in acarsiridiumframe.h, which does
// frame classification, BCH and the field decoding.
//
// The constants and the processing order follow gr-iridium, which is the reference this
// was checked against: coarse frequency from the preamble, fine frequency from the whole
// burst, root raised cosine matched filter, symbol timing, then differential demodulation.
// Five samples per symbol at 25 kbaud. One Iridium channel is 41.67 kHz wide, so 125 kHz
// leaves room either side for a burst that Doppler has pushed off its nominal frequency.
//
// The rate is what it is because of the channelizer in acarsiridiumchannelizer.h, which
// scans the whole band: its output rate is four times its channel spacing, and 31.25 kHz
// spacing - close enough to the 41.67 kHz Iridium grid that every channel is covered -
// gives 125 kHz out. That it also divides the symbol rate exactly is what makes 31.25 kHz
// the spacing to pick
#define ACARSIRIDIUM_CHANNEL_SAMPLE_RATE 125000
#define ACARSIRIDIUM_SYMBOL_RATE 25000
#define ACARSIRIDIUM_SAMPLES_PER_SYMBOL (ACARSIRIDIUM_CHANNEL_SAMPLE_RATE / ACARSIRIDIUM_SYMBOL_RATE)
// A burst is nominally 8.28 ms, which is about 207 symbols, and a simplex burst about
// 20.6 ms. Accept a generous range either side: anything far outside it is interference
#define ACARSIRIDIUM_MIN_BURST_SYMBOLS 40
#define ACARSIRIDIUM_MAX_BURST_SYMBOLS 640
// From gr-iridium lib/iridium.h, which is the reference these were checked against.
// The unique word was then found at zero symbol error in 11 of 18 bursts of a recording
// of the ring alert channel, at symbol 66 every time - the 64 symbol preamble plus the
// two samples the burst detector picks up ahead of it
#define ACARSIRIDIUM_UW_LENGTH 12
#define ACARSIRIDIUM_PREAMBLE_SHORT 16 // Duplex
#define ACARSIRIDIUM_PREAMBLE_LONG 64 // Simplex, above 1626 MHz
// How far either side of the expected position the unique word is looked for, and how
// many of its symbols may be wrong before the burst is treated as having no sync.
//
// The window has to be tight, because the search is over two preamble lengths, two
// directions and four rotations, which is a lot of chances to match by luck: allowing two
// errors over a 24 symbol window gives roughly a one in ten chance of a false match on
// any burst, measured on a traffic channel recording where it produced 18 spurious syncs
// at scattered positions against 12 real ones. Over 8 symbols it is below one in a
// hundred, and a false sync is then thrown out by the BCH check in the frame layer, which
// is a far stronger test than the unique word - which is why two errors are allowed here.
// On a ring alert recording the bursts that need the second error are the ones at 10 to
// 18 dB; the strong ones match with no errors at all
#define ACARSIRIDIUM_UW_SEARCH 8
#define ACARSIRIDIUM_UW_MAX_ERRORS 2
// Root raised cosine matched filter, as gr-iridium designs it in burst_downmix_impl.cc:
//
// root_raised_cosine(1.0, d_output_sample_rate, SYMBOLS_PER_SECOND, .4, 51)
//
// Without it the preamble still demodulates perfectly, because it is one symbol repeated
// and so has no transitions to smear, but the data symbols that follow are corrupted by
// intersymbol interference. That showed up as bursts whose preamble was a clean run of
// zero differential symbols and whose unique word then failed to match
#define ACARSIRIDIUM_RRC_ALPHA 0.4
#define ACARSIRIDIUM_RRC_TAPS 51
// How much of the burst the coarse frequency estimate uses, in symbols. gr-iridium sizes
// its estimation FFT as PREAMBLE_LENGTH_SHORT + 10, which covers the whole short preamble
// plus the first symbols of the unique word, and for a long preamble is all preamble. The
// unique word is only symbols 0 and 2, so squaring the signal removes it as well as the
// preamble, leaving a single tone at twice the frequency offset
#define ACARSIRIDIUM_CFO_SYMBOLS (ACARSIRIDIUM_PREAMBLE_SHORT + 10)
class AcarsIridiumReceiver
{
public:
typedef std::complex<double> Cd;
enum Direction
{
DirectionUnknown = 0,
DirectionDownlink, //!< Satellite to ground, which is what is heard
DirectionUplink
};
struct Burst
{
qint64 m_sampleIndex = 0; //!< Where the burst started, in channel samples
double m_frequencyOffset = 0.0; //!< Hz from the centre of the channel, mostly Doppler
double m_coarseOffset = 0.0; //!< The preamble only estimate, before refinement
double m_snrDb = 0.0;
double m_powerDb = 0.0;
int m_symbolCount = 0;
std::vector<uint8_t> m_symbols; //!< Differential symbol, 0 to 3, rotation not removed
// Filled in when the unique word is found
Direction m_direction = DirectionUnknown;
int m_uwPosition = -1; //!< Index in m_symbols where the unique word starts
int m_uwErrors = 0;
int m_rotation = 0; //!< Quarter turns of residual frequency error removed
//!< The frame, as the bits the frame layer works on: two per differential symbol,
//!< Gray coded, starting with the 24 bit access code. Empty when there is no sync
std::vector<uint8_t> m_frameBits;
};
AcarsIridiumReceiver()
{
designRrc();
reset();
}
void reset()
{
m_sampleIndex = 0;
m_burstStart = 0;
m_noiseFloor = 0.0;
m_noiseValid = false;
m_inBurst = false;
m_belowCount = 0;
m_aboveCount = 0;
m_smoothedPower = 0.0;
m_preTrigger.assign(m_preTriggerLength, Cd(0.0, 0.0));
m_preTriggerWrite = 0;
m_preTriggerCount = 0;
m_burstSamples.clear();
// Reserved once rather than grown: the band scanner runs one of these per channel,
// so a reallocation here is a reallocation a couple of hundred times over
m_burstSamples.reserve(ACARSIRIDIUM_MAX_BURST_SYMBOLS * ACARSIRIDIUM_SAMPLES_PER_SYMBOL);
m_bursts.clear();
m_burstCount = 0;
m_rejectedCount = 0;
}
//! Two bits per differential symbol, Gray coded. The de_dqpsk() function in
//! iridium-toolkit reads the bit pair as a number and maps it through
//! imap[] = { 0, 1, 3, 2 } to recover the symbol, and that map is its own inverse, so
//! the same table encodes. It is what makes the differential form of the downlink
//! unique word come out as the access code "001100000011000011110011"
static uint8_t grayMap(uint8_t symbol)
{
static const uint8_t imap[4] = { 0, 1, 3, 2 };
return imap[symbol & 3];
}
//! Feeds one channel sample. Returns true when a burst has been completed and is
//! waiting to be popped
bool processSample(const Cd& sample)
{
const double power = std::norm(sample);
// Short smoothing, so one noisy sample neither starts nor ends a burst
m_smoothedPower += (power - m_smoothedPower) * 0.25;
if (!m_inBurst)
{
// The noise floor only tracks while nothing is being received: a long burst
// would otherwise drag it up and the burst would end early
if (!m_noiseValid)
{
m_noiseFloor = m_smoothedPower;
m_noiseValid = true;
}
else
{
m_noiseFloor += (m_smoothedPower - m_noiseFloor) * 0.0001;
}
if (m_smoothedPower > (m_noiseFloor * m_startThreshold))
{
m_aboveCount++;
if (m_aboveCount >= m_startSamples)
{
m_inBurst = true;
m_belowCount = 0;
m_burstStart = m_sampleIndex - (qint64) m_preTriggerCount;
m_burstSamples.clear();
// The samples from before the detector fired are part of the burst,
// and the preamble they hold is what the frequency estimate needs.
// Oldest first, which with a ring is wherever the next write would go
for (int i = 0; i < m_preTriggerCount; i++)
{
const int index = (m_preTriggerWrite + m_preTriggerLength - m_preTriggerCount + i)
% m_preTriggerLength;
m_burstSamples.push_back(m_preTrigger[index]);
}
}
}
else
{
m_aboveCount = 0;
}
}
else
{
m_burstSamples.push_back(sample);
if (m_smoothedPower < (m_noiseFloor * m_endThreshold))
{
m_belowCount++;
if (m_belowCount >= m_endSamples)
{
endBurst();
m_inBurst = false;
m_aboveCount = 0;
}
}
else
{
m_belowCount = 0;
}
if ((int) m_burstSamples.size() > (ACARSIRIDIUM_MAX_BURST_SYMBOLS * ACARSIRIDIUM_SAMPLES_PER_SYMBOL))
{
// Not a burst: something is transmitting continuously, so drop it and
// let the noise floor re-converge rather than growing the buffer for ever
m_burstSamples.clear();
m_inBurst = false;
m_aboveCount = 0;
m_noiseValid = false;
m_rejectedCount++;
}
}
m_preTrigger[m_preTriggerWrite] = sample;
m_preTriggerWrite = (m_preTriggerWrite + 1) % m_preTriggerLength;
if (m_preTriggerCount < m_preTriggerLength) {
m_preTriggerCount++;
}
m_sampleIndex++;
return !m_bursts.empty();
}
bool hasBurst() const { return !m_bursts.empty(); }
Burst popBurst()
{
Burst burst = m_bursts.front();
m_bursts.pop_front();
return burst;
}
int burstCount() const { return m_burstCount; }
int rejectedCount() const { return m_rejectedCount; }
double noiseFloor() const { return m_noiseFloor; }
private:
//! Root raised cosine taps, by the root_raised_cosine function in GNU Radio firdes,
//! so the matched filter is the same one gr-iridium uses
void designRrc()
{
const int ntaps = ACARSIRIDIUM_RRC_TAPS | 1;
const double alpha = ACARSIRIDIUM_RRC_ALPHA;
const double spb = (double) ACARSIRIDIUM_SAMPLES_PER_SYMBOL;
m_rrc.resize(ntaps);
double scale = 0.0;
for (int i = 0; i < ntaps; i++)
{
const double index = (double) (i - (ntaps / 2));
const double x1 = M_PI * index / spb;
double x2 = 4.0 * alpha * index / spb;
double x3 = (x2 * x2) - 1.0;
double num;
double den;
if (std::fabs(x3) >= 0.000001)
{
if (i != (ntaps / 2)) {
num = std::cos((1.0 + alpha) * x1) + (std::sin((1.0 - alpha) * x1) / (4.0 * alpha * index / spb));
} else {
num = std::cos((1.0 + alpha) * x1) + ((1.0 - alpha) * M_PI / (4.0 * alpha));
}
den = x3 * M_PI;
}
else
{
// The removable singularity, where index is plus or minus spb / (4 alpha)
x3 = (1.0 - alpha) * x1;
x2 = (1.0 + alpha) * x1;
num = (std::sin(x2) * (1.0 + alpha) * M_PI)
- (std::cos(x3) * ((1.0 - alpha) * M_PI * spb) / (4.0 * alpha * index))
+ (std::sin(x3) * spb * spb / (4.0 * alpha * index * index));
den = -32.0 * M_PI * alpha * alpha * index / spb;
}
m_rrc[i] = 4.0 * alpha * num / den;
scale += m_rrc[i];
}
for (int i = 0; i < ntaps; i++) {
m_rrc[i] /= scale;
}
}
//! Matched filter, with the group delay taken out so an output sample lines up with
//! the input sample of the same index and the unique word stays where it was found
std::vector<Cd> matchedFilter(const std::vector<Cd>& samples) const
{
const int ntaps = (int) m_rrc.size();
const int centre = ntaps / 2;
const int length = (int) samples.size();
std::vector<Cd> out(length);
for (int i = 0; i < length; i++)
{
Cd sum(0.0, 0.0);
for (int k = 0; k < ntaps; k++)
{
const int index = i + k - centre;
if ((index >= 0) && (index < length)) {
sum += samples[index] * m_rrc[k];
}
}
out[i] = sum;
}
return out;
}
//! Magnitude of the tone at power times offset, which is how the fine frequency
//! estimate below scores a candidate. The phasor is stepped rather than recomputed,
//! because this is searched over hundreds of candidates for every burst
double toneMagnitude(const std::vector<Cd>& raised, int power, double offset, int length) const
{
const double w = -2.0 * M_PI * ((double) power * offset) / ACARSIRIDIUM_CHANNEL_SAMPLE_RATE;
const Cd step = std::exp(Cd(0.0, w));
Cd phasor(1.0, 0.0);
Cd sum(0.0, 0.0);
for (int i = 0; i < length; i++)
{
sum += raised[i] * phasor;
phasor *= step;
}
return std::abs(sum);
}
//! Where the burst actually sits in the channel, from its power spectrum.
//!
//! This exists only to settle which alias the estimates below have landed on, and is
//! the one step in the chain that cannot be ambiguous. Raising the signal to a power
//! to strip the modulation also folds the frequency axis: squaring leaves the offset
//! known only modulo half the sample rate, and the fourth power modulo a quarter of
//! it. Neither fold matters to differential demodulation, because an offset that is a
//! whole number of symbol rates advances the phase by a whole turn per symbol, which
//! is why this went unnoticed until the matched filter was added. It matters a great
//! deal to the matched filter, which would otherwise be centred up to 50 kHz away
//! from the signal - at this sample rate, on the far side of Nyquist.
//!
//! The score is the power a matched filter centred on the candidate would pass, so
//! the whole occupied bandwidth votes rather than any single bin
double estimateFrequencyCentre(const std::vector<Cd>& samples)
{
const int length = (int) samples.size();
const double rate = ACARSIRIDIUM_CHANNEL_SAMPLE_RATE;
// The spectrum from a transform rather than a bin at a time. Scoring each
// candidate separately meant a pass over the whole burst per candidate, which for
// a few hundred candidates is most of the cost of handling a burst - and with the
// whole band being scanned there are a great many bursts
const int size = AcarsIridiumFft::nextPowerOfTwo(std::max(length, 1024));
m_fft.configure(size);
std::vector<Cd> spectrum(size, Cd(0.0, 0.0));
for (int i = 0; i < length; i++) {
spectrum[i] = samples[i];
}
m_fft.transform(spectrum);
// A 25 kbaud signal shaped at alpha 0.4 occupies about 35 kHz, so a filter centred
// on the signal passes roughly 17.5 kHz either side. The score for a candidate is
// how much power such a filter would pass, so the whole occupied bandwidth votes
const double binHz = rate / (double) size;
const int half = (int) std::lround(17500.0 / binHz);
// Running totals, so each candidate costs a subtraction rather than a sweep over
// its whole bandwidth
std::vector<double> prefix(size + 1, 0.0);
for (int k = 0; k < size; k++) {
prefix[k + 1] = prefix[k] + std::norm(spectrum[k]);
}
const double total = prefix[size];
int bestBin = 0;
double bestPower = -1.0;
for (int c = 0; c < size; c++)
{
const int from = c - half;
const int to = c + half + 1;
double sum;
if ((from >= 0) && (to <= size))
{
sum = prefix[to] - prefix[from];
}
else
{
// The spectrum is periodic at the sample rate, so a candidate near the
// edge takes the rest of its bandwidth from the other end
const int lo = ((from % size) + size) % size;
const int hi = ((to % size) + size) % size;
sum = (total - prefix[lo]) + prefix[hi];
}
if (sum > bestPower)
{
bestPower = sum;
bestBin = c;
}
}
return ((bestBin < (size / 2)) ? (double) bestBin : (double) (bestBin - size)) * binHz;
}
//! Fine frequency from the whole burst, raised to the fourth power so the QPSK data
//! cancels as well as the preamble, and read off a transform of the result.
//!
//! The fourth power puts a tone at four times the frequency offset, and its peak is
//! only about 1/T wide - some tens of Hz for a burst this long. Searching for it by
//! scoring candidate offsets one at a time therefore needs a step of a few Hz over
//! the whole range, which is thousands of passes over the burst: with a few hundred
//! channels being scanned at once that was most of the time the scanner spent, and
//! coarsening the step simply steps over the peak and misses it. A transform gives
//! every candidate at once instead.
//!
//! The result is still ambiguous - a tone at four times the offset repeats every
//! quarter of the sample rate - so the answer taken is the one nearest the coarse
//! estimate, which is what that estimate is for
double estimateFrequencyFine(const std::vector<Cd>& samples, double coarse)
{
const int length = (int) samples.size();
const double rate = ACARSIRIDIUM_CHANNEL_SAMPLE_RATE;
// Sized to the burst rather than fixed. A burst defines its own frequency only to
// about 1 / (4T), which is 30 Hz for a short duplex burst, and the bin spacing
// here is rate / (4 * size) - so a transform the length of the burst already
// resolves it as finely as it can be resolved, and the interpolation below picks
// up the rest. Padding every burst out to a fixed large size was eight times the
// work for the short ones, which are most of them
const int size = AcarsIridiumFft::nextPowerOfTwo(std::max(length, 1024));
m_fft.configure(size);
std::vector<Cd> fourth(size, Cd(0.0, 0.0));
for (int i = 0; i < length; i++)
{
const Cd s2 = samples[i] * samples[i];
fourth[i] = s2 * s2;
}
m_fft.transform(fourth);
// One alias of the fourth power tone every quarter of the sample rate
const double aliasHz = rate / 4.0;
const double searchHz = aliasHz / 2.0;
int bestBin = -1;
double bestMagnitude = -1.0;
double best = coarse;
for (int k = 0; k < size; k++)
{
// Bin to the frequency of the tone, then to the offset that produced it
const double tone = ((k < (size / 2)) ? (double) k : (double) (k - size)) * rate / (double) size;
double offset = tone / 4.0;
// Slide to whichever alias sits nearest the coarse estimate
offset += std::round((coarse - offset) / aliasHz) * aliasHz;
if (std::fabs(offset - coarse) > searchHz) {
continue;
}
const double magnitude = std::norm(fourth[k]);
if (magnitude > bestMagnitude)
{
bestMagnitude = magnitude;
bestBin = k;
best = offset;
}
}
if (bestBin < 0) {
return coarse;
}
// Parabolic interpolation between the neighbouring bins, so the answer is not
// limited to the bin spacing
const double left = std::abs(fourth[(bestBin - 1 + size) % size]);
const double centre = std::abs(fourth[bestBin]);
const double right = std::abs(fourth[(bestBin + 1) % size]);
const double denominator = left - (2.0 * centre) + right;
if (std::fabs(denominator) > 1e-20)
{
const double shift = 0.5 * (left - right) / denominator;
if (std::fabs(shift) <= 1.0) {
best += shift * rate / (4.0 * (double) size);
}
}
return best;
}
//! Symbol timing by Oerder and Meyr: the squared magnitude carries a line at the
//! symbol rate, and its phase is the timing offset within a symbol.
//!
//! Mind the sign. If the squared magnitude peaks a fraction tau of the way into each
//! symbol, the sum below comes out proportional to e^(-j 2 pi tau / sps), so the
//! offset is MINUS its phase. Taking the phase as it stands gives -tau mod sps, which
//! is only right when tau happens to be zero or half a symbol - anywhere else it
//! samples as far the wrong side of the peak as the peak is from the symbol start
double estimateTiming(const std::vector<Cd>& samples) const
{
const int sps = ACARSIRIDIUM_SAMPLES_PER_SYMBOL;
Cd sum(0.0, 0.0);
// The phase only takes as many values as there are samples in a symbol, so a
// small table replaces a transcendental per sample
Cd rotations[ACARSIRIDIUM_SAMPLES_PER_SYMBOL];
for (int i = 0; i < sps; i++)
{
const double w = -2.0 * M_PI * (double) i / (double) sps;
rotations[i] = Cd(std::cos(w), std::sin(w));
}
int slot = 0;
for (size_t i = 0; i < samples.size(); i++)
{
sum += std::norm(samples[i]) * rotations[slot];
if (++slot == sps) {
slot = 0;
}
}
// Negated, as above, then wrapped into [0, 2 pi) so the offset is in [0, sps)
double phase = -std::arg(sum);
if (phase < 0.0) {
phase += 2.0 * M_PI;
}
return (phase / (2.0 * M_PI)) * (double) sps;
}
//! The unique words, as gr-iridium gives them: absolute symbols, only 0 and 2, so
//! the sync is effectively BPSK within the QPSK constellation
static const uint8_t *uniqueWord(Direction direction)
{
static const uint8_t downlink[ACARSIRIDIUM_UW_LENGTH] = { 0, 2, 2, 2, 2, 0, 0, 0, 2, 0, 0, 2 };
static const uint8_t uplink[ACARSIRIDIUM_UW_LENGTH] = { 2, 2, 0, 0, 0, 2, 0, 0, 2, 0, 2, 2 };
return (direction == DirectionUplink) ? uplink : downlink;
}
//! Looks for a unique word in the differential symbols and, when one is found, emits
//! the frame bit stream from it onwards.
//!
//! The search allows for a residual frequency error of a multiple of a quarter of the
//! symbol rate, which leaves a fixed quarter turn on every symbol and so adds a
//! constant to every differential symbol. Trying all four rotations resolves it
void findUniqueWord(Burst& burst) const
{
if (burst.m_symbolCount < (ACARSIRIDIUM_PREAMBLE_SHORT + ACARSIRIDIUM_UW_LENGTH)) {
return;
}
// A simplex burst carries the long preamble, a duplex burst the short one. Which
// this is depends on the frequency, which the receiver does not know, so both
// are looked for
const int expected[2] = { ACARSIRIDIUM_PREAMBLE_LONG, ACARSIRIDIUM_PREAMBLE_SHORT };
int bestErrors = ACARSIRIDIUM_UW_MAX_ERRORS + 1;
int bestPosition = -1;
int bestRotation = 0;
Direction bestDirection = DirectionUnknown;
for (int d = 0; d < 2; d++)
{
const Direction direction = (d == 0) ? DirectionDownlink : DirectionUplink;
const uint8_t *uw = uniqueWord(direction);
// The differential form of the unique word, which is what the symbols are
uint8_t wanted[ACARSIRIDIUM_UW_LENGTH - 1];
for (int i = 1; i < ACARSIRIDIUM_UW_LENGTH; i++) {
wanted[i-1] = (uint8_t) ((4 + uw[i] - uw[i-1]) % 4);
}
for (int p = 0; p < 2; p++)
{
for (int offset = -ACARSIRIDIUM_UW_SEARCH; offset <= ACARSIRIDIUM_UW_SEARCH; offset++)
{
// One differential symbol before the unique word is part of the access
// code, so the frame cannot start at symbol zero
const int start = expected[p] + offset;
if ((start < 1) || ((start + ACARSIRIDIUM_UW_LENGTH - 1) > burst.m_symbolCount)) {
continue;
}
for (int rotation = 0; rotation < 4; rotation++)
{
int errors = 0;
for (int i = 0; i < (ACARSIRIDIUM_UW_LENGTH - 1); i++)
{
if (burst.m_symbols[start + i] != ((wanted[i] + rotation) % 4))
{
errors++;
if (errors >= bestErrors) {
break;
}
}
}
if (errors < bestErrors)
{
bestErrors = errors;
bestPosition = start;
bestRotation = rotation;
bestDirection = direction;
}
}
}
}
}
if (bestPosition < 0) {
return;
}
burst.m_direction = bestDirection;
burst.m_uwPosition = bestPosition;
burst.m_uwErrors = bestErrors;
burst.m_rotation = bestRotation;
// The access code is the twelve differential symbols ending with the eleven of
// the unique word. The one before them is the step from the last preamble symbol
// into the unique word, and because the preamble is symbol 0 repeated and the
// downlink unique word also starts at symbol 0 it is a step of nothing - which is
// why the access code begins with two zero bits
for (int i = bestPosition - 1; i < burst.m_symbolCount; i++)
{
const uint8_t symbol = (uint8_t) ((4 + burst.m_symbols[i] - bestRotation) % 4);
const uint8_t mapped = grayMap(symbol);
burst.m_frameBits.push_back((uint8_t) ((mapped >> 1) & 1));
burst.m_frameBits.push_back((uint8_t) (mapped & 1));
}
}
void endBurst()
{
const int sps = ACARSIRIDIUM_SAMPLES_PER_SYMBOL;
const int symbols = (int) m_burstSamples.size() / sps;
if ((symbols < ACARSIRIDIUM_MIN_BURST_SYMBOLS) || (symbols > ACARSIRIDIUM_MAX_BURST_SYMBOLS))
{
m_rejectedCount++;
m_burstSamples.clear();
return;
}
Burst burst;
burst.m_sampleIndex = m_burstStart;
burst.m_coarseOffset = estimateFrequencyCentre(m_burstSamples);
burst.m_frequencyOffset = estimateFrequencyFine(m_burstSamples, burst.m_coarseOffset);
// De-rotate by the estimated offset, so what is left is the modulation
std::vector<Cd> corrected(m_burstSamples.size());
const double w = -2.0 * M_PI * burst.m_frequencyOffset / ACARSIRIDIUM_CHANNEL_SAMPLE_RATE;
double power = 0.0;
// Stepped rather than computed per sample: this used to be a transcendental for
// every sample of every burst, and when the whole band is scanned there are a
// great many bursts. The phasor is renormalised every so often, because repeated
// multiplication lets its magnitude drift
const Cd step(std::cos(w), std::sin(w));
Cd phasor(1.0, 0.0);
for (size_t i = 0; i < m_burstSamples.size(); i++)
{
corrected[i] = m_burstSamples[i] * phasor;
power += std::norm(m_burstSamples[i]);
phasor *= step;
if ((i & 0xff) == 0xff) {
phasor /= std::abs(phasor);
}
}
power /= (double) m_burstSamples.size();
burst.m_powerDb = 10.0 * std::log10(power + 1e-20);
burst.m_snrDb = 10.0 * std::log10((power / (m_noiseFloor + 1e-20)) + 1e-20);
// Matched filter, now the burst is centred. Doing it after the de-rotation rather
// than before is what lets the filter be centred on the signal
const std::vector<Cd> filtered = matchedFilter(corrected);
const double timing = estimateTiming(filtered);
// Differential demodulation: each symbol is the phase STEP from the one before,
// which is what lets a burst be read without ever knowing absolute phase, and is
// why the frequency estimate above only has to be good enough to stop the phase
// walking within a single symbol
Cd previous(0.0, 0.0);
bool havePrevious = false;
for (int s = 0; s < symbols; s++)
{
const int index = (int) std::lround((double) (s * sps) + timing);
if ((index < 0) || (index >= (int) filtered.size())) {
continue;
}
const Cd sample = filtered[index];
if (havePrevious)
{
const Cd difference = sample * std::conj(previous);
double angle = std::arg(difference);
if (angle < 0.0) {
angle += 2.0 * M_PI;
}
const int quadrant = ((int) std::floor((angle + (M_PI / 4.0)) / (M_PI / 2.0))) & 3;
burst.m_symbols.push_back((uint8_t) quadrant);
}
previous = sample;
havePrevious = true;
}
burst.m_symbolCount = (int) burst.m_symbols.size();
findUniqueWord(burst);
if (burst.m_symbolCount >= ACARSIRIDIUM_MIN_BURST_SYMBOLS)
{
m_bursts.push_back(burst);
m_burstCount++;
}
else
{
m_rejectedCount++;
}
m_burstSamples.clear();
}
// Detection thresholds, as ratios against the noise floor. The end one is lower than
// the start one so a fade within a burst does not chop it in two
const double m_startThreshold = 8.0;
const double m_endThreshold = 3.0;
const int m_startSamples = 8;
const int m_endSamples = 16;
const int m_preTriggerLength = 16;
std::vector<double> m_rrc;
AcarsIridiumFft m_fft;
qint64 m_sampleIndex;
qint64 m_burstStart;
double m_noiseFloor;
bool m_noiseValid;
double m_smoothedPower;
bool m_inBurst;
int m_aboveCount;
int m_belowCount;
std::vector<Cd> m_preTrigger;
int m_preTriggerWrite;
int m_preTriggerCount;
std::vector<Cd> m_burstSamples;
std::deque<Burst> m_bursts;
int m_burstCount;
int m_rejectedCount;
};
#endif // INCLUDE_ACARSIRIDIUM_H

346
plugins/channelrx/demodacars/acarsiridiumchannelizer.h

@ -0,0 +1,346 @@ @@ -0,0 +1,346 @@
///////////////////////////////////////////////////////////////////////////////////
// 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_ACARSIRIDIUMCHANNELIZER_H
#define INCLUDE_ACARSIRIDIUMCHANNELIZER_H
#include <complex>
#include <cmath>
#include <cstdint>
#include <algorithm>
#include <vector>
#if defined(USE_SSE4_1)
#include <smmintrin.h>
#endif
#include "acarsiridiumfft.h"
// Oversampled polyphase channelizer, so one Iridium receiver can watch the whole band.
//
// Iridium hops: a duplex channel is assigned when a call is set up, and over 240 channels
// spaced 41.67 kHz across roughly 1619 to 1626 MHz. Watching one 125 kHz channel sees
// only a few percent of the traffic - measured on a four minute recording, the busiest
// single channel carried 4% of the short burst data frames in the band. Covering it all
// with one demodulator per channel would mean dozens of them, so the band is split here
// instead, in one pass, and a receiver run on every output.
//
// A plain filter bank decimates by the number of channels, which puts the output rate
// equal to the channel spacing and leaves no room for a signal that does not sit exactly
// in the middle of its channel. This one decimates by a quarter of that, so each output
// runs at four times the channel spacing:
//
// channels M, decimate by D = M / 4, so the output rate is 4 * inputRate / M
//
// The channel spacing is then inputRate / M and the output rate four times it. At
// 31.25 kHz spacing and 125 kHz out, an Iridium burst - about 35 kHz wide, and up to
// 37 kHz off its nominal frequency once Doppler has had its way - is always wholly
// inside at least one output. It is often inside two, so the scanner above this has to
// throw the duplicates away.
//
// Oversampling by a whole number of channels is what keeps this simple: decimating by
// M / 4 rather than M leaves a phase step between output blocks of a quarter turn per
// channel per block, which is a power of -j and so costs nothing to apply.
class AcarsIridiumChannelizer
{
public:
typedef std::complex<double> Cd;
//! How much each channel is oversampled: the output rate is this many times the
//! channel spacing. Four leaves room for a burst anywhere in its channel
static const int Oversample = 4;
AcarsIridiumChannelizer() :
m_channels(0),
m_decimation(0),
m_tapsPerBranch(0),
m_length(0),
m_write(0),
m_count(0),
m_block(0)
{
}
//! channels must be a power of two and a multiple of Oversample. The input rate has
//! to be channels * spacing, and for Iridium the spacing wanted is 31.25 kHz, so
//! 8 MS/s gives 256 channels, 4 MS/s gives 128, and so on
void configure(int channels, int tapsPerBranch = 12)
{
m_channels = channels;
m_decimation = channels / Oversample;
m_tapsPerBranch = tapsPerBranch;
m_length = channels * tapsPerBranch;
designPrototype();
m_delay.assign(m_length, Cd(0.0, 0.0));
m_out.assign(m_channels, Cd(0.0, 0.0));
m_write = 0;
m_count = 0;
m_block = 0;
m_fft.configure(channels);
buildRotations();
}
int channels() const { return m_channels; }
int decimation() const { return m_decimation; }
//! Channel spacing, which is also how far apart the channel centres below are
double spacing(double inputRate) const { return inputRate / (double) m_channels; }
//! Output sample rate of every channel
double channelRate(double inputRate) const { return inputRate / (double) m_decimation; }
//! Where channel c sits relative to the centre of the band, in Hz. The upper half of
//! the channels are the negative frequencies, as they are in any transform
double channelOffset(int c, double inputRate) const
{
const double step = spacing(inputRate);
return (c < (m_channels / 2)) ? (c * step) : ((c - m_channels) * step);
}
//! Feeds one input sample. Returns true when a block of channel samples is ready,
//! one per channel, in channelSamples()
bool processSample(const Cd& sample)
{
m_delay[m_write] = sample;
m_write = (m_write + 1) % m_length;
m_count++;
if (m_count < m_decimation) {
return false;
}
m_count = 0;
computeBlock();
return true;
}
const std::vector<Cd>& channelSamples() const { return m_out; }
//! The prototype lowpass the bank is built from. Exposed so a test can filter a
//! channel directly with the same taps and check the bank against it
const std::vector<double>& prototype() const { return m_proto; }
private:
//! Prototype lowpass, Kaiser windowed sinc.
//!
//! The cutoff is a little wider than the channel spacing, so that a burst sitting
//! between two channel centres is still passed whole by one of them. That makes
//! neighbouring channels overlap, which is why the same burst can be found twice.
//! The stopband has to be inside the output Nyquist - two channel spacings away with
//! this much oversampling - or what is rejected would fold back in
void designPrototype()
{
const int taps = m_length;
const double cutoff = 1.05 / (double) m_channels; // Cycles per input sample
const double beta = 0.1102 * (60.0 - 8.7); // Kaiser, for 60 dB stopband
m_proto.assign(taps, 0.0);
double sum = 0.0;
for (int n = 0; n < taps; n++)
{
const double x = (double) n - ((double) (taps - 1) / 2.0);
const double sinc = (std::fabs(x) < 1e-12)
? (2.0 * cutoff)
: (std::sin(2.0 * M_PI * cutoff * x) / (M_PI * x));
const double t = ((2.0 * (double) n) / (double) (taps - 1)) - 1.0;
const double window = besselI0(beta * std::sqrt(std::max(0.0, 1.0 - (t * t)))) / besselI0(beta);
m_proto[n] = sinc * window;
sum += m_proto[n];
}
// Unit gain at DC, so a channel output has the same amplitude as its input
for (int n = 0; n < taps; n++) {
m_proto[n] *= (double) m_channels / sum;
}
}
static double besselI0(double x)
{
double sum = 1.0;
double term = 1.0;
for (int k = 1; k < 40; k++)
{
term *= (x * x) / (4.0 * (double) k * (double) k);
sum += term;
if (term < (1e-16 * sum)) {
break;
}
}
return sum;
}
void buildRotations()
{
// The phase each channel output carries, as a table indexed by the block counter
// and the channel.
//
// Decimating by M / Oversample rather than by M leaves a step of
// exp(-j2.pi.c.r / Oversample) on channel c at block r, which repeats every
// Oversample blocks. On top of that the first block is emitted once D samples
// have arrived, so it corresponds to input sample D - 1 rather than 0, and that
// offset puts a further constant exp(-j2.pi.c.(D - 1) / M) on each channel.
// Differential demodulation would not notice a constant phase, but folding it in
// costs nothing and makes a channel output exactly what mixing that channel down
// and filtering it would have given - which is what the test checks against
m_rotation.assign(Oversample * m_channels, Cd(0.0, 0.0));
for (int r = 0; r < Oversample; r++)
{
for (int c = 0; c < m_channels; c++)
{
const double angle = -2.0 * M_PI * (double) c
* (((double) (r * m_decimation)) + (double) (m_decimation - 1))
/ (double) m_channels;
m_rotation[(r * m_channels) + c] = Cd(std::cos(angle), std::sin(angle));
}
}
}
//! out[i] += in[-i] * h[i], for a run of i. The input walks backwards, because branch
//! p of the bank takes the sample p further back down the delay line, and the run has
//! already been cut so that neither side crosses the end of the buffer.
//!
//! A complex double is exactly one 128 bit register, so a vector unit does the
//! multiply and the add on the real and imaginary parts together rather than one
//! after the other. Two runs are kept going at once because each is a chain of
//! dependent adds, and one chain on its own leaves the pipeline waiting on itself
static void accumulate(Cd *out, const Cd *in, const double *h, int run)
{
#if defined(USE_SSE4_1)
int i = 0;
for (; (i + 1) < run; i += 2)
{
const __m128d a0 = _mm_loadu_pd((const double *) (in - i));
const __m128d a1 = _mm_loadu_pd((const double *) (in - i - 1));
const __m128d o0 = _mm_loadu_pd((double *) (out + i));
const __m128d o1 = _mm_loadu_pd((double *) (out + i + 1));
_mm_storeu_pd((double *) (out + i),
_mm_add_pd(o0, _mm_mul_pd(a0, _mm_set1_pd(h[i]))));
_mm_storeu_pd((double *) (out + i + 1),
_mm_add_pd(o1, _mm_mul_pd(a1, _mm_set1_pd(h[i + 1]))));
}
for (; i < run; i++)
{
const __m128d a = _mm_loadu_pd((const double *) (in - i));
const __m128d o = _mm_loadu_pd((double *) (out + i));
_mm_storeu_pd((double *) (out + i),
_mm_add_pd(o, _mm_mul_pd(a, _mm_set1_pd(h[i]))));
}
#else
for (int i = 0; i < run; i++)
{
const Cd& sample = in[-i];
const double tap = h[i];
out[i] += Cd(sample.real() * tap, sample.imag() * tap);
}
#endif
}
void computeBlock()
{
const int newest = (m_write - 1 + m_length) % m_length;
// Each branch filters every Mth sample of the delay line, which is what makes one
// prototype filter serve as the whole bank. Written straight into the output,
// because the transform below is in place and a copy of the whole bank every
// block is megabytes a second for nothing.
//
// The loop runs tap first and branch second, which looks the wrong way round -
// the branch accumulator cannot stay in a register, and the output is read and
// written once per tap instead of once per block. It is much faster anyway,
// because branch first walks both the delay line and the prototype in strides of
// a whole channel count: at 256 channels that is a 4 kB step per access, which no
// prefetcher will follow. This way all three arrays are walked one element at a
// time, which also makes the inner loop something a vector unit can do
std::fill(m_out.begin(), m_out.end(), Cd(0.0, 0.0));
for (int q = 0; q < m_tapsPerBranch; q++)
{
// Branch p reads the sample this far back, so p ascending walks backwards
// down the delay line from here
int index = newest - (q * m_channels);
while (index < 0) {
index += m_length;
}
const double *tap = &m_proto[q * m_channels];
int p = 0;
while (p < m_channels)
{
// As far as can be gone before the delay line wraps round to its end
const int run = std::min(m_channels - p, index + 1);
accumulate(&m_out[p], &m_delay[index], &tap[p], run);
p += run;
index -= run;
if (index < 0) {
index += m_length;
}
}
}
m_fft.transform(m_out, true);
// The phase for this block, which is where the oversampling is paid for
const int base = m_block * m_channels;
for (int c = 0; c < m_channels; c++) {
m_out[c] *= m_rotation[base + c];
}
m_block = (m_block + 1) % Oversample;
}
int m_channels;
int m_decimation;
int m_tapsPerBranch;
int m_length;
int m_write;
int m_count;
int m_block;
std::vector<double> m_proto;
std::vector<Cd> m_delay;
std::vector<Cd> m_out;
std::vector<Cd> m_rotation;
AcarsIridiumFft m_fft;
};
#endif // INCLUDE_ACARSIRIDIUMCHANNELIZER_H

147
plugins/channelrx/demodacars/acarsiridiumfft.h

@ -0,0 +1,147 @@ @@ -0,0 +1,147 @@
///////////////////////////////////////////////////////////////////////////////////
// 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_ACARSIRIDIUMFFT_H
#define INCLUDE_ACARSIRIDIUMFFT_H
#include <complex>
#include <cmath>
#include <vector>
#if defined(USE_SSE4_1)
#include <smmintrin.h>
#endif
// A small radix 2 transform, shared by the Iridium channelizer and the burst receiver.
//
// Both only ever need power of two sizes, and both are in a plugin that should not drag
// a transform library in behind it, so this is deliberately plain. It is not fast by the
// standards of a real FFT library; it is fast enough, and the sizes are small.
class AcarsIridiumFft
{
public:
typedef std::complex<double> Cd;
//! Prepares for transforms of the given size, which must be a power of two
void configure(int size)
{
if (m_size == size) {
return;
}
m_size = size;
m_twiddle.resize(size / 2);
m_twiddleInverse.resize(size / 2);
for (int k = 0; k < (size / 2); k++)
{
const double angle = -2.0 * M_PI * (double) k / (double) size;
m_twiddle[k] = Cd(std::cos(angle), std::sin(angle));
m_twiddleInverse[k] = std::conj(m_twiddle[k]);
}
}
int size() const { return m_size; }
//! In place transform. inverse runs the same butterflies with the conjugate twiddles
//! and no scaling, which is what a filter bank wants
void transform(std::vector<Cd>& data, bool inverse = false) const
{
const int n = m_size;
for (int i = 1, j = 0; i < n; i++)
{
int bit = n >> 1;
for (; j & bit; bit >>= 1) {
j ^= bit;
}
j ^= bit;
if (i < j) {
std::swap(data[i], data[j]);
}
}
// Both tables are precomputed: conjugating inside the butterfly meant doing it
// once per butterfly, which for a bank running tens of thousands of transforms a
// second is a great deal of work to repeat for a table that never changes
const Cd *twiddle = inverse ? m_twiddleInverse.data() : m_twiddle.data();
for (int len = 2; len <= n; len <<= 1)
{
const int step = n / len;
const int half = len / 2;
for (int i = 0; i < n; i += len)
{
Cd *lower = &data[i];
Cd *upper = &data[i + half];
for (int k = 0; k < half; k++)
{
#if defined(USE_SSE4_1)
// A complex double fills one 128 bit register. The product of two of
// them is the classic shuffle and alternating add: ac - bd in the
// real half and bc + ad in the imaginary half, which addsub does in
// one instruction instead of the sign juggling it would otherwise take
const __m128d x = _mm_loadu_pd((const double *) &upper[k]);
const __m128d y = _mm_loadu_pd((const double *) &twiddle[k * step]);
const __m128d t1 = _mm_mul_pd(x, _mm_unpacklo_pd(y, y));
const __m128d t2 = _mm_mul_pd(_mm_shuffle_pd(x, x, 1), _mm_unpackhi_pd(y, y));
const __m128d v = _mm_addsub_pd(t1, t2);
const __m128d u = _mm_loadu_pd((const double *) &lower[k]);
_mm_storeu_pd((double *) &lower[k], _mm_add_pd(u, v));
_mm_storeu_pd((double *) &upper[k], _mm_sub_pd(u, v));
#else
const Cd w = twiddle[k * step];
const Cd u = lower[k];
const Cd v = upper[k] * w;
lower[k] = u + v;
upper[k] = u - v;
#endif
}
}
}
}
//! The smallest power of two at least as large as n
static int nextPowerOfTwo(int n)
{
int size = 1;
while (size < n) {
size <<= 1;
}
return size;
}
private:
int m_size = 0;
std::vector<Cd> m_twiddle;
std::vector<Cd> m_twiddleInverse;
};
#endif // INCLUDE_ACARSIRIDIUMFFT_H

1118
plugins/channelrx/demodacars/acarsiridiumframe.h

File diff suppressed because it is too large Load Diff

315
plugins/channelrx/demodacars/acarsiridiumscanner.h

@ -0,0 +1,315 @@ @@ -0,0 +1,315 @@
///////////////////////////////////////////////////////////////////////////////////
// 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_ACARSIRIDIUMSCANNER_H
#define INCLUDE_ACARSIRIDIUMSCANNER_H
#include <QByteArray>
#include <QList>
#include <cmath>
#include <cstdlib>
#include <complex>
#include <deque>
#include <vector>
#include "acarsiridium.h"
#include "acarsiridiumframe.h"
#include "acarsiridiumchannelizer.h"
// Watches the whole Iridium band at once.
//
// Iridium assigns a duplex channel when a call is set up, out of about 240 spaced
// 41.67 kHz across roughly 1619 to 1626 MHz, so a receiver watching one channel sees a
// few percent of what is on the air - measured on a four minute recording of the whole
// band, the busiest single channel carried 4% of the short burst data frames in it. This
// splits the band with the polyphase channelizer and runs a burst receiver on every
// output, which is what makes scanning practical without the user adding a demodulator
// per channel.
//
// The channelizer spacing is 31.25 kHz rather than the 41.67 kHz of the Iridium grid.
// Lining the two up would need a channel count divisible by three, and a transform of
// that size is far more work than a power of two; nothing needs them aligned, because a
// burst is found by searching its channel rather than by being assumed to sit in the
// middle of one. The cost is that neighbouring channels overlap, so a burst is often
// found twice, and the duplicates have to go - a frame decoded twice would otherwise
// break the short burst data reassembly, whose fragments have to arrive in counter order.
//! The channelizer spacing, which with four times oversampling gives the 125 kHz the
//! receiver runs at. The input rate is this times the number of channels
#define ACARSIRIDIUM_SCAN_SPACING 31250
class AcarsIridiumScanner
{
public:
typedef std::complex<double> Cd;
struct Detection
{
AcarsIridiumFrame m_frame;
double m_frequency = 0.0; //!< Hz from the centre of the band
double m_snrDb = 0.0;
qint64 m_sampleIndex = 0; //!< Where the burst started, in input samples
int m_channel = 0;
//!< A short burst data message, once a run of frames has been put back together.
//!< Reported whether or not it turns out to hold ACARS, because the step that
//!< reads an ACARS block out of one is the only part of the chain never tested
//!< against real traffic - if it ever wrongly refuses a message, that has to be
//!< visible rather than silently dropped
QByteArray m_message;
QByteArray m_acars; //!< A complete ACARS block, when one came out
};
AcarsIridiumScanner() :
m_channels(0),
m_decimation(0),
m_inputRate(0.0),
m_holdSamples(0),
m_sameTimeSamples(0),
m_sampleIndex(0)
{
}
//! channels is the number of channelizer outputs, which fixes the input rate at
//! channels * ACARSIRIDIUM_SCAN_SPACING. It must be a power of two
void configure(int channels)
{
m_channels = channels;
m_inputRate = (double) channels * ACARSIRIDIUM_SCAN_SPACING;
m_holdSamples = (qint64) (HoldSeconds * m_inputRate);
m_sameTimeSamples = (qint64) (SameTimeSeconds * m_inputRate);
m_channelizer.configure(channels);
m_reassembler.setBandWidth(m_inputRate);
m_decimation = m_channelizer.decimation();
m_receivers.clear();
m_receivers.resize(channels);
m_pending.clear();
m_detections.clear();
m_sampleIndex = 0;
m_burstCount = 0;
m_duplicateCount = 0;
m_frameCount = 0;
m_idaCount = 0;
m_messageCount = 0;
m_acarsCount = 0;
}
int channels() const { return m_channels; }
double inputRate() const { return m_inputRate; }
//! Feeds one input sample at inputRate
void processSample(const Cd& sample)
{
m_sampleIndex++;
if (!m_channelizer.processSample(sample)) {
return;
}
const std::vector<Cd>& channelSamples = m_channelizer.channelSamples();
for (int c = 0; c < m_channels; c++)
{
if (!m_receivers[c].processSample(channelSamples[c])) {
continue;
}
while (m_receivers[c].hasBurst())
{
AcarsIridiumReceiver::Burst burst = m_receivers[c].popBurst();
if (burst.m_direction == AcarsIridiumReceiver::DirectionUnknown) {
continue;
}
Candidate candidate;
candidate.m_burst = burst;
candidate.m_channel = c;
candidate.m_frequency = m_channelizer.channelOffset(c, m_inputRate)
+ burst.m_frequencyOffset;
// The receiver counts in its own channel samples
candidate.m_sampleIndex = burst.m_sampleIndex * m_decimation;
candidate.m_detectedAt = m_sampleIndex;
m_pending.push_back(candidate);
m_burstCount++;
}
}
flush(false);
}
//! Call when the input ends, so anything still held for duplicate checking is emitted
void finish()
{
flush(true);
}
bool hasDetection() const { return !m_detections.empty(); }
Detection popDetection()
{
Detection detection = m_detections.front();
m_detections.pop_front();
return detection;
}
int burstCount() const { return m_burstCount; }
int duplicateCount() const { return m_duplicateCount; }
int frameCount() const { return m_frameCount; }
int idaCount() const { return m_idaCount; }
int messageCount() const { return m_messageCount; }
int acarsCount() const { return m_acarsCount; }
private:
struct Candidate
{
AcarsIridiumReceiver::Burst m_burst;
int m_channel = 0;
double m_frequency = 0.0;
qint64 m_sampleIndex = 0; //!< Where the burst started
qint64 m_detectedAt = 0; //!< When it finished and was handed over
};
// How long a burst is held before being decoded, so that the same burst found in a
// neighbouring channel has arrived too and the better of the two can be taken.
// Measured from when the burst was handed over, not from when it started: a burst
// runs to 20 ms, so by the time it ends its start is long past and holding against
// that would expire immediately and let every duplicate through.
//
// A duration rather than a count of input samples, because the input rate spans eight
// to one across the bandwidth settings: as a fixed count this was 8 ms at 32 channels
// but 1 ms at 256, which is the wrong way round - the widest setting has the most
// overlapping neighbours and so needs the hold most
static constexpr double HoldSeconds = 0.008;
// Two detections are the same burst when they start at about the same time and are at
// about the same frequency. Bursts on one channel are a time slot apart, roughly
// 9 ms, so this cannot merge two genuine transmissions; the channel spacing is
// 31.25 kHz, so the frequency tolerance is well inside it
static constexpr double SameTimeSeconds = 0.004;
static constexpr double SameFrequencyHz = 12000.0;
void flush(bool all)
{
while (!m_pending.empty())
{
if (!all && ((m_sampleIndex - m_pending.front().m_detectedAt) < m_holdSamples)) {
break;
}
// Take the oldest, then find every other pending detection that is the same
// burst heard in an overlapping channel, and keep whichever has the best
// signal to noise - that is the one whose channel the burst sat nearest the
// middle of
Candidate best = m_pending.front();
m_pending.pop_front();
for (size_t i = 0; i < m_pending.size(); )
{
const Candidate& other = m_pending[i];
// The band is circular, so the channels either side of the fold at its
// edge are neighbours and a burst in both has to be recognised as one
if ((std::llabs(other.m_sampleIndex - best.m_sampleIndex) < m_sameTimeSamples)
&& (AcarsIridiumReassembler::separation(other.m_frequency, best.m_frequency, m_inputRate) < SameFrequencyHz))
{
if (other.m_burst.m_snrDb > best.m_burst.m_snrDb) {
best = other;
}
m_pending.erase(m_pending.begin() + i);
m_duplicateCount++;
}
else
{
i++;
}
}
decode(best);
}
}
void decode(const Candidate& candidate)
{
Detection detection;
if (!m_decoder.decode(candidate.m_burst.m_frameBits, detection.m_frame)) {
return;
}
detection.m_frequency = candidate.m_frequency;
detection.m_snrDb = candidate.m_burst.m_snrDb;
detection.m_sampleIndex = candidate.m_sampleIndex;
detection.m_channel = candidate.m_channel;
m_frameCount++;
if (detection.m_frame.m_type == AcarsIridiumFrame::TypeIDA)
{
m_idaCount++;
const qint64 timeMs = (qint64) ((1000.0 * (double) candidate.m_sampleIndex) / m_inputRate);
QByteArray message;
// Short burst data is reassembled per transmitter, and the reassembler tells
// them apart by frequency, so it is given the absolute frequency in the band
// rather than the offset within a channel
if (m_reassembler.addFrame(detection.m_frame, timeMs, candidate.m_frequency, message))
{
QByteArray block;
detection.m_message = message;
m_messageCount++;
if (AcarsIridiumReassembler::acarsBlock(message, detection.m_frame.m_uplink, block))
{
detection.m_acars = block;
m_acarsCount++;
}
}
}
m_detections.push_back(detection);
}
int m_channels;
int m_decimation;
double m_inputRate;
qint64 m_holdSamples;
qint64 m_sameTimeSamples;
qint64 m_sampleIndex;
AcarsIridiumChannelizer m_channelizer;
std::vector<AcarsIridiumReceiver> m_receivers;
AcarsIridiumFrameDecoder m_decoder;
AcarsIridiumReassembler m_reassembler;
std::deque<Candidate> m_pending;
std::deque<Detection> m_detections;
int m_burstCount = 0;
int m_duplicateCount = 0;
int m_frameCount = 0;
int m_idaCount = 0;
int m_messageCount = 0;
int m_acarsCount = 0;
};
#endif // INCLUDE_ACARSIRIDIUMSCANNER_H

2216
plugins/channelrx/demodacars/acarsmessage.cpp

File diff suppressed because it is too large Load Diff

BIN
plugins/channelrx/demodacars/icons/forward.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 337 B

174
plugins/channelrx/demodacars/readme.md

@ -2,17 +2,17 @@ @@ -2,17 +2,17 @@
<h2>Introduction</h2>
This plugin can be used to demodulate ACARS, VDL-2, HFDL and Aero data packets, broadcast by aircraft and satellites.
These packets can contain flight plans as well as status information about the aircraft.
This plugin can be used to demodulate ACARS, VDL-2, HFDL, Aero and Iridium data packets, broadcast to and from aircraft.
These packets can contain flight plans and other operational data as well as status information about the aircraft.
ACARS uses MSK modulation at 2400 baud, which is then AM modulated on to the VHF carrier.
ACARS uses MSK modulation at 2,400 baud, which is then AM modulated on to the VHF carrier.
In Europe, the main ACARS frequencies are:
- 131.525 MHz (SITA - Europe secondary)
- 131.725 MHz (SITA - Europe primary)
- 131.825 MHz (ARINC/Collins)
VDL Mode 2 uses D8PSK modulation at 10500 baud (bit rate 31500 bps). It can contain ACARS or ATN packets.
VDL Mode 2 uses D8PSK modulation at 10,500 baud (bit rate 31,500 bps). It can contain ACARS or ATN packets.
VDL Mode 2 frequencies in Europe are:
- 136.675 MHz (ARINC)
@ -24,12 +24,12 @@ VDL Mode 2 frequencies in Europe are: @@ -24,12 +24,12 @@ VDL Mode 2 frequencies in Europe are:
- 136.900 MHz
- 136.975 MHz (SITA & ARINC, the common signalling channel)
HFDL uses M-PSK at 1800 baud and frequencies are between 2 and 21 MHz. The active frequencies vary with propagation, and the
frequencies in use are reported in squitters transmitted by the groundstations. These are combined by the demodulator and
HFDL uses M-PSK at 1,800 baud and frequencies are between 2 and 21 MHz. The active frequencies vary with propagation, and the
frequencies in use are reported in squitters transmitted by the ground stations. These are combined by the demodulator and
displayed in the Ground Station Table dialog. You can find an initial frequency to try on: https://hfdl.observer/
Inmarsat Classic Aero (aviation SATCOM). The ground station to aircraft
(P channel) downlink is in L band around:
Inmarsat Classic Aero (aviation SATCOM) uses MSK at 600 and 1,200 bps and OQPSK at 10,500 bps. The ground station to aircraft
(P channel) uplink is in L band around:
| Region | Id | Satellite | Longitude | G->A Frequency |
|---------------------|-------|---------------------------|-----------|------------------|
@ -38,6 +38,27 @@ Inmarsat Classic Aero (aviation SATCOM). The ground station to aircraft @@ -38,6 +38,27 @@ Inmarsat Classic Aero (aviation SATCOM). The ground station to aircraft
| Pacific Ocean | POR | Inmarsat 4-F1 | 178E | |
| Indian Ocean | IOR | Inmarsat 4A-F4 / Alphasat | 25E | |
Unlike the other modes, which are continuous narrowband channels, Iridium is burst TDMA from
satellites in low earth orbit: DQPSK at 25 kBd in bursts of about 8.3 ms within a 90 ms frame.
Channels are spaced 41.67 kHz apart.
| Channel | Frequency | Carries |
|--------------------------|------------------|--------------------------------------------------------|
| Ring alert | 1,626.270833 MHz | Satellite position and paging - always transmitting |
| Duplex traffic | 1,616 - 1,626 MHz| Short burst data, which is what carries ACARS |
Iridium does not tune a single channel like the other modes. A duplex channel is assigned when a call is set up, out of
about 240 spaced 41.67 kHz, so watching one channel sees only a few percent of the traffic. Instead the
whole tuned width is split by a polyphase channelizer and a burst receiver run on every output. The width is chosen with
the combo box next to the Mode selector:
| Scan width | Channels | Sample rate | Covers |
|------------|----------|-------------|-------------------------------------------|
| 1 MHz | 32 | 1 MS/s | part of the band |
| 2 MHz | 64 | 2 MS/s | part of the band |
| 4 MHz | 128 | 4 MS/s | about half the band |
| 8 MHz | 256 | 8 MS/s | all of it, tuned to 1623 MHz |
<h2>Interface</h2>
![ACARS Demodulator plugin GUI](../../../doc/img/AcarsDemod_plugin.png)
@ -58,37 +79,43 @@ Average total power in dB relative to a +/- 1.0 amplitude signal received in the @@ -58,37 +79,43 @@ Average total power in dB relative to a +/- 1.0 amplitude signal received in the
<h3>4: Mode and Aero rate</h3>
Selects the demodulator: ACARS, VDL-2, HFDL or Aero - and, in Aero mode
Selects the demodulator: ACARS, VDL-2, HFDL, Aero or Iridium - and, in Aero mode
only, the rate and channel selector appears beside it.
Changing either resets the demodulator and sets a default RF bandwidth to suit.
- ACARS: plain old ACARS, 2400 baud MSK amplitude modulated onto VHF
- VDL-2: VDL Mode 2, D8PSK at 10500 baud
- Aero: Inmarsat Classic Aero, at 600, 1200 or 10500 bps
- HFDL: HF Data Link, 1800 baud PSK at 300 to 1800 bps (Bitrate is automatically detected)
Changing either resets the demodulator and sets a default RF bandwidth.
Each demodulator runs at its own fixed channel sample rate, which the channelizer is
set to when the mode is selected.
<table>
<tr><th>Mode</th><th>Channel sample rate</th><th>Symbol rate</th><th>Samples per symbol</th></tr>
<tr><td>ACARS</td><td>48 kS/s</td><td>2400 Bd</td><td>20</td></tr>
<tr><td>VDL-2</td><td>105 kS/s</td><td>10500 Bd</td><td>10</td></tr>
<tr><td>HFDL</td><td>7.2 kS/s</td><td>1800 Bd</td><td>4</td></tr>
<tr><td>Aero, 600 bps</td><td>19.2 kS/s</td><td>600 Bd</td><td>32</td></tr>
<tr><td>Aero, 1200 bps</td><td>19.2 kS/s</td><td>1200 Bd</td><td>16</td></tr>
<tr><td>Aero, 10500 bps</td><td>105 kS/s</td><td>5250 Bd</td><td>20</td></tr>
</table>
| Mode | Sample rate | Symbol rate |Samples per symbol|
|------------------|-------------|-------------|------------------|
| ACARS | 48 kS/s | 2,400 Bd | 20 |
| VDL-2 | 105 kS/s | 10,500 Bd | 10 |
| HFDL | 7.2 kS/s | 1,800 Bd | 4 |
| Aero, 600 bps | 19.2 kS/s | 600 Bd | 32 |
| Aero, 1,200 bps | 19.2 kS/s | 1,200 Bd | 16 |
| Aero, 10,500 bps | 105 kS/s | 5,250 Bd | 20 |
| Iridium | 1-8 MS/s | 25,000 Bd | 5 |
<h3>5: RF Bandwidth</h3>
This specifies the bandwidth of a LPF that is applied to the input signal to limit the RF bandwidth.
A default value is automatically set when selecting the Mode, and in Aero mode the rate
and channel, from the combo boxes (4):
| Mode | Rate | Default RF bandwidth |
|-------|----------------------|----------------------|
| ACARS | 2,400 bps | 12.5 kHz |
| VDL-2 | 31,500 bps | 25.0 kHz |
| HFDL | 300 - 1,800 bps | 3.0 kHz |
| Aero | 600 bps, P, R or T | 1.2 kHz |
| Aero | 1,200 bps, P, R or T | 2.4 kHz |
| Aero | 10,500 bps P | 13.1 kHz |
| Iridium | 25,000 Bd | not used (see above) |
<h3>6: Threshold</h3>
ARACS pre-key (preamble) detection threshold, as a fraction from 0 to 1. The statistic it is compared against
is the depth of 2400 Hz modulation on the envelope. A real pre-key
is the depth of 2,400 Hz modulation on the envelope. A real pre-key
reads about 0.85 and noise reads near zero, so the default of 0.25 sits between them and is
a false alarm setting rather than something to tune per station. Lower it only if
transmissions are being missed entirely.
@ -115,63 +142,55 @@ received. @@ -115,63 +142,55 @@ received.
In **Aero**, these are the satellite housekeeping the ground earth station broadcasts
continuously, whether or not any aircraft is logged on: the system tables that describe
the satellite, its beams and its channels, the data EIRP table, the fill-in signal units
that pad a frame out to length, and the reserved types nobody has documented. On a
P channel these are most of what is transmitted.
the satellite, its beams and its channels.
In **VDL-2**, these are the supervisory and link management responses - `RR`, `RNR`,
`REJ`, `SREJ`, `DM`, `DISC`, `UA`, `FRMR` and `U`.
<h3>11: Display Chart</h3>
When checked, displays a chart plotting the number of frames received per second.
When checked, displays a chart plotting the number of frames received per second for each mode. See below.
<h3>12: Display Ground Station Table</h3>
When checked, displays a table of the ground stations heard in squitters and the frequencies each announced as in use.
Right clicking a row offers finding that station on the Map, or retuning the device so this channel receives that frequency.
<h3>13: Feed</h3>
<h3>13: Download Aircraft Database</h3>
When checked, forwards received ACARS messages to community aggregators, as acarsdec-style JSON - one object per UDP datagram, or a newline-delimited stream over TCP.
Right click the button for settings: a station identifier sent with every message, and per-service enables with host, port and protocol.
Click to download an aircraft database (45MB - same database as used by ADS-B demodulator).
<h3>14: Download OpenSky Database</h3>
This contains information such as the aircraft type, that will be displayed under the aircraft's image.
It also allows matching 24-bit ICAO addresses to registrations, for VDL-2, HFDL and Aero.
<h3>15: Start/stop Logging ACARS packets to .csv File</h3>
<h3>14: Start/stop Logging ACARS packets to .csv File</h3>
When checked, writes all received ACARS packets to a .csv file. The file has two columns,
`DateTime` and `Data`: the date and time as ISO 8601 with milliseconds, and the packet as
hexadecimal. Earlier versions wrote separate `Date` and `Time` columns in the local
format; those files are no longer read.
When checked, writes all received ACARS packets to a .csv file.
<h3>16: .csv Log Filename</h3>
<h3>15: .csv Log Filename</h3>
Click to specify the name of the .csv file which received ACARS packets are logged to.
<h3>17: Read Data from .csv File</h3>
<h3>16: Read Data from .csv File</h3>
Click to specify a previously written ACARS .csv log file, which is read and used to update the ACARS messages table.
<h3>18: Clear Messages from table</h3>
<h3>17: Clear Messages from table</h3>
Pressing this button clears all messages from the table.
<h3>Frames per Second Chart</h3>
The chart button toggles a chart plotting the number of frames received per second, as one
series per protocol:
![ACARS FPS Chart](../../../doc/img/AcarsDemod_chart.png)
- **ACARS** - ACARS messages, from whichever protocol is selected. A message carried over
VDL-2, HFDL or Aero counts here, not under its protocol, because it is the same kind of
message however it arrived.
- **ACARS** - ACARS messages, from whichever mode is selected (4). A message carried over
VDL-2, HFDL, Aero or Iridium counts here, not under its mode.
- **VDL-2 link** - AVLC link frames that are not ACARS: XID and GSIF link management, and
supervisory acknowledgements whether or not they are displayed in the table.
- **HFDL** - squitters and logons.
- **Aero** - log-ons, log-offs, channel assignments and acknowledgements.
Clicking a legend entry shows or hides that series; right clicking the
chart button clears the data.
Clicking a legend entry shows or hides that series; right clicking the chart button clears the data.
The mouse wheel zooms the time axis, or the rate axis with shift held, centred on the
cursor; dragging with the left button pans. The time axis follows the newest data whenever
its right edge is at the latest point. Data more than 10 minutes old is averaged over one
@ -181,12 +200,16 @@ minute intervals, so long sessions do not accumulate an excessive number of poin @@ -181,12 +200,16 @@ minute intervals, so long sessions do not accumulate an excessive number of poin
The received messages table displays the contents of the ACARS packets that have been received.
![ACARS Messages Table](../../../doc/img/AcarsDemod_table.png)
<h3>Message Decode</h3>
The decode field displays a decode of the ACARS message selected in the received messages table.
For multipart messages it shows the assembly status, the combined message - decoded once all
parts have arrived - and the selected block.
![ACARS Messages Decode](../../../doc/img/AcarsDemod_decode.png)
* Date/Time - The receiver's local date and time when the ACARS message was received, or the recorded date and time when reading a CSV log. Right click the table to choose between showing the date and time or the time alone; the column sorts by the full date and time either way.
* Dir - The transmission direction. An up arrow is an uplink from a ground station to an aircraft; a down arrow is a downlink from an aircraft to a ground station.
* GS - Ground Station Id. ACARS: ARINC 618 Mode character. VDL-2: Ground Station (GS). HFDL: Ground Station (GS). Aero: Ground Earth Station (GES).
@ -202,32 +225,22 @@ parts have arrived - and the selected block. @@ -202,32 +225,22 @@ parts have arrived - and the selected block.
* Block Seq. - For multipart downlinks, the block sequence character used to order the blocks.
* Flight - For downlinks, the six-character flight identifier carried in the message text header.
* Message - The ACARS message payload after the standard downlink header fields and any recognized sublabel have been removed.
* Message Decode - A structured, human-readable decode of the message payload, flattened to a single
semicolon-separated line so more fits in the column. Selecting the row displays the full multi-line
decode below the table, with field labels bolded; the same multi-line form is what the Aircraft
feature shows in its Map popups.
Beyond the ARINC 622/623 ATS messages (CPDLC, oceanic and departure clearances, ATIS), decoders are included for
position reports (labels 10, 12, 16, 22, 24, 44 and H1 FMS reports, which also feed the Lat/Lon columns),
airline operational reports (label 80 POSRPT/OPNORM/INRANG), OOOI event reports (labels 13-18 and QP-QT),
flight status reports (label 15 FST01), H1 FMS flight plans and route inserts,
weather requests (label 5U) and frequency autotune (label :;). Several of these are airline formats without public
documentation; the field layouts follow [airframes.io's community documentation](https://github.com/airframesio/acars-message-documentation) and observed traffic.
* Message Decode - A structured, human-readable decode of the message payload.
Selecting the row displays the full multi-line
decode below the table.
* ATC - Air Traffic Control communication extracted from supported ARINC 622/CPDLC messages.
* Lat (°) - Aircraft latitude extracted from an ADS-C or CPDLC position report or any decoded message carrying a position (position report labels, OOOI events, FST01 flight status, H1 FMS reports), in decimal degrees; north is positive and south is negative.
* Lon (°) - Aircraft longitude extracted from the same sources, in decimal degrees; east is positive and west is negative.
* Alt (ft) - Aircraft altitude extracted from an ADS-C or CPDLC position report, in feet.
* Hex - The complete received ACARS frame rendered as hexadecimal bytes, including its framing, header, payload, check sequence, and terminating byte.
* Protocol - Which link the frame arrived on: `ACARS`, `VDL-2`, `HFDL`, or `Aero` followed by the channel it came on - `Aero P`, `Aero R` or `Aero T` - since on Aero the channel is what says which link it was. This is kept separate from Label Decode, which describes what the Label means and nothing else.
* Rate (bps) - The bit rate the frame was sent at: 2400 for ACARS, 31500 for VDL-2, 300 to 1800 for HFDL and 600, 1200 or 10500 for Aero. Note that VDL-2's 31500 bps is carried by 10500 symbols per second of D8PSK, three bits to a symbol, so this figure and the symbol rate quoted under Mode (4) differ for that protocol alone.
Both columns are added at the right hand end rather than beside Dir where they belong, because saved column widths and positions are stored by column number and inserting in the middle would shift every one of them. Drag them wherever suits; the position is remembered.
* Protocol - Which link the frame arrived on: `ACARS`, `VDL-2`, `HFDL`, or `Aero` followed by the channel it came on - `Aero P`, `Aero R` or `Aero T`.
* Rate (bps) - The bit rate the frame was sent at: 2400 for ACARS, 31500 for VDL-2, 300 to 1800 for HFDL and 600, 1200 or 10500 for Aero.
<h3>VDL-2 Link Frames</h3>
In VDL-2 mode, ACARS messages carried over AVLC fill the table exactly as described above.
AVLC frames that do not carry an ACARS message (ATN data, XID/GSIF link management, and -
unless hidden by (10) - supervisory acknowledgements) have no ACARS header, so only the
following columns are used:
AVLC frames that do not carry an ACARS message (ATN data, XID/GSIF link management, and supervisory acknowledgements)
have no ACARS header, so only the following columns are used:
* Date/Time - The receiver's local date and time when the frame was received.
* Dir - The transmission direction. An up arrow is an uplink to an aircraft; a down arrow is a downlink from an aircraft.
@ -238,23 +251,18 @@ following columns are used: @@ -238,23 +251,18 @@ following columns are used:
* Label Decode - What the frame type means, for example `Information`, `Exchange identification (link management)`, `Receive ready` or `Selective reject - retransmit this frame`.
* Message - The source and destination addresses of the frame, followed for information frames by the decoded protocol stack, layer by layer, for example `X.25 DATA > CLNP > COTP DT > CPDLC`, and for XID frames by the message type, for example `XID: Handoff Initiation` or `XID: Ground Station Information Frame`. X.25 call setup, clear and supervisory packets, ES-IS and IDRP routing traffic are identified by name.
* Message Decode - For information frames carrying an ICAO ATN application, the full decode of the CM (context management logon), CPDLC or ADS-C version 2 message. For XID frames, the decoded public and VDL-specific link parameters: connection management, XID sequencing, frequency support, ground station location, destination airport, ATN router NETs and so on. Multi-line decodes are flattened with semicolons; hover over the cell (or select the row) for the original multi-line form.
* ATC - For frames carrying a CPDLC controller-pilot message, the expanded message elements and their arguments, for example `WILCO` or `REQUEST [level], Flight level: 370` - the ATN equivalent of the DO-219 expansion shown for ACARS ATC messages. Left blank for CPDLC frames with no message data.
* ATC - For frames carrying a CPDLC controller-pilot message, the expanded message elements and their arguments, for example `WILCO` or `REQUEST [level], Flight level: 370` - the ATN equivalent of the DO-219 expansion shown for ACARS ATC messages.
* Lat (°) / Lon (°) - The position from an XID aircraft or ground station location parameter, or from an ADS-C version 2 report, in decimal degrees. The XID encoding is coarse (0.1 degrees, roughly 10 km); ADS-C positions are precise.
* Alt (ft) - The altitude from an XID aircraft location parameter (1000 ft resolution) or an ADS-C version 2 report, in feet.
* Hex - The complete AVLC frame rendered as hexadecimal bytes: address fields, link control, information field and frame check sequence.
<h3>HFDL Frames</h3>
HFDL frames that are not carrying an ACARS message use the same columns as the VDL-2 link
frames below. The Label is the LPDU type as its hexadecimal octet and the Label Decode is
what that type is - `Logon request`, `Unnumbered data` and so on. A squitter is not an
LPDU and has no type octet, so it is labelled `Squitter`, decoded as
`Ground station frequency broadcast`.
HFDL frames that are not carrying an ACARS message use the same columns as the VDL-2 link frames.
<h3>Aero Signal Units</h3>
In Aero mode, ACARS messages carried over the satellite link are reassembled from their
signal units inside the demodulator and fill the table exactly as described above. Signal
In Aero mode, ACARS messages carried over the satellite link are as described above. Signal
units that are not carrying an ACARS message use only the following columns:
* Date/Time - The receiver's local date and time when the signal unit was received.
@ -264,21 +272,16 @@ units that are not carrying an ACARS message use only the following columns: @@ -264,21 +272,16 @@ units that are not carrying an ACARS message use only the following columns:
* GS - Ground Earth Station (GES) Id.
* GS Decode - Satellite name, for example 'AOR-E'. See frequency table above.
* Registration - The aircraft, when the signal unit names one. The AES ID is the
aircraft's 24-bit ICAO address - the same address it transmits in Mode S / ADS-B - so
the registration is looked up from the OpenSky database (14); when the address is not
in the database, the address itself is shown in hexadecimal. Blank for signal units
that name no aircraft.
* Label - The signal unit type as its hexadecimal octet, for example `10`, `32` or `0C`.
aircraft's 24-bit ICAO address - the same address it transmits in Mode S / ADS-B.
* Label - The signal unit type as its hexadecimal octet.
* Label Decode - What that type is, for example `Log-on request`, `C channel assignment,
flight safety` or `System table, satellite identification`.
* Message - The two ends of the exchange, as `GES 2A` and the aircraft, in the direction
of transmission. Signal units carrying neither an AES ID nor a GES ID show
`Broadcast` instead: the system and EIRP tables describe the satellite and its beams
rather than addressing any one aircraft, so there is no conversation to show. Most
`Broadcast` rows are hidden by default; uncheck (10) to see them.
rather than addressing any one aircraft, so there is no conversation to show.
* Message Decode - The decoded contents, where the unit has any: the pair of L band
frequencies and beam type in a voice channel assignment, the log-on parameters, and so
on.
frequencies and beam type in a voice channel assignment, the log-on parameters, and so on.
* Hex - The complete signal unit as hexadecimal bytes, with the type in the first octet.
<h2>Attribution</h2>
@ -302,4 +305,9 @@ reading [JAERO](https://github.com/jontio/JAERO) by Jonti Olds (MIT). @@ -302,4 +305,9 @@ reading [JAERO](https://github.com/jontio/JAERO) by Jonti Olds (MIT).
The community VDL Mode 2 ground station list is vendored from [acars-vdl2 @ Groups.io](https://acars-vdl2.groups.io/).
The frame formats, BCH polynomials and interleaving are from iridium-toolkit, and the physical layer constants from
gr-iridium: https://github.com/muccc/iridium-toolkit and https://github.com/muccc/gr-iridium
Forward icon by Pandu Bramantyo from Noun Project, licensed under [CC BY 3.0](https://creativecommons.org/licenses/by/3.0/).
Some code was written using AI.

101
plugins/channelrx/demodacars/vdl2atn.cpp

@ -23,6 +23,9 @@ @@ -23,6 +23,9 @@
#include <QRegularExpression>
// For xidDestinationAirport(), which the Aircraft feature reads too
#include "util/aircraftreport.h"
#include <libacars/libacars.h>
#include <libacars/vstring.h>
@ -281,6 +284,24 @@ Vdl2AtnDecoder::Result Vdl2AtnDecoder::decode(const QByteArray& info, quint32 sr @@ -281,6 +284,24 @@ Vdl2AtnDecoder::Result Vdl2AtnDecoder::decode(const QByteArray& info, quint32 sr
}
}
// The XID VDL parameter set carries the destination as a four letter ICAO ident:
//
// VDL params:
// Parameter set ID: V
// Connection management: 05
// ...
// Destination airport: EGCC
//
// Anchored to the end of the line so a longer value - the parameter is an octet string,
// so nothing guarantees four characters - is rejected rather than truncated to its first
// four. Only exactly four letters is an ICAO ident.
QString Vdl2AtnDecoder::xidDestinationAirport(const QString& decoded)
{
// One definition, in sdrbase, because the Aircraft feature reads the same field out
// of stored logons and cannot link this plugin
return ::xidDestinationAirport(decoded);
}
Vdl2AtnDecoder::Result Vdl2AtnDecoder::decodeXid(const QByteArray& info, bool cr, bool pf)
{
Result result;
@ -307,6 +328,8 @@ Vdl2AtnDecoder::Result Vdl2AtnDecoder::decodeXid(const QByteArray& info, bool cr @@ -307,6 +328,8 @@ Vdl2AtnDecoder::Result Vdl2AtnDecoder::decodeXid(const QByteArray& info, bool cr
result.m_summary = "XID";
}
result.m_destinationAirport = xidDestinationAirport(result.m_decoded);
// Pull the position out of a location parameter: "Aircraft location: 51.6N 2.7E
// 37000 ft" (aircraft, with altitude) or "Ground station location: 51.6N 2.7E"
static const QRegularExpression locRe(
@ -597,6 +620,12 @@ void Vdl2AtnDecoder::parseCotp(const uint8_t *buf, int len, quint32 srcAddr, qui @@ -597,6 +620,12 @@ void Vdl2AtnDecoder::parseCotp(const uint8_t *buf, int len, quint32 srcAddr, qui
// indented under "Message data:", which are the element text ("WILCO",
// "REQUEST [level]") followed by any argument lines ("Flight level: 370"). This is the
// ATN equivalent of the DO-219 expansion the ACARS path puts in the ATC column.
//
// The arguments are put into the element's own placeholders rather than listed after
// it, so "NEXT DATA AUTHORITY ([facility designation])" with "Facility designation:
// EDYY" under it reads "NEXT DATA AUTHORITY (EDYY)". Only the value is used: the
// placeholder is usually an abbreviation of the argument's name rather than something
// it adds to, so keeping both gives "PREFERRED LEVEL Flight level: 370"
static QString extractCpdlcMessageData(const QString& decoded)
{
auto indentOf = [](const QString& line)
@ -608,7 +637,7 @@ static QString extractCpdlcMessageData(const QString& decoded) @@ -608,7 +637,7 @@ static QString extractCpdlcMessageData(const QString& decoded)
return i;
};
QStringList out;
QStringList elements;
const QStringList lines = decoded.split('\n');
for (int i = 0; i < lines.size(); i++)
@ -616,15 +645,77 @@ static QString extractCpdlcMessageData(const QString& decoded) @@ -616,15 +645,77 @@ static QString extractCpdlcMessageData(const QString& decoded)
if (lines[i].trimmed() != "Message data:") {
continue;
}
int indent = indentOf(lines[i]);
while ((i + 1 < lines.size()) && (indentOf(lines[i+1]) > indent) && !lines[i+1].trimmed().isEmpty())
const int dataIndent = indentOf(lines[i]);
while ((i + 1 < lines.size()) && (indentOf(lines[i+1]) > dataIndent) && !lines[i+1].trimmed().isEmpty())
{
i++;
out.append(lines[i].trimmed());
const int elementIndent = indentOf(lines[i]);
QString element = lines[i].trimmed();
// Argument lines are indented under the element they belong to. If a decode
// ever puts them at the same level they are treated as elements of their
// own, which is what this did for every message before
QStringList names;
QStringList values;
while ((i + 1 < lines.size()) && (indentOf(lines[i+1]) > elementIndent) && !lines[i+1].trimmed().isEmpty())
{
i++;
const QString argument = lines[i].trimmed();
const int colon = argument.indexOf(':');
if (colon >= 0)
{
names.append(argument.left(colon).trimmed());
values.append(argument.mid(colon + 1).trimmed());
}
else
{
names.append(QString());
values.append(argument);
}
}
auto argumentText = [&names, &values](int index)
{
return names[index].isEmpty() ? values[index]
: names[index] + ": " + values[index];
};
// Placeholders are filled left to right, which is the order libacars lists
// the arguments in
int argument = 0;
int from = 0;
while (argument < names.size())
{
const int open = element.indexOf('[', from);
if (open < 0) {
break;
}
const int close = element.indexOf(']', open);
if (close < 0) {
break;
}
const QString& replacement = values[argument];
element.replace(open, close - open + 1, replacement);
from = open + replacement.size();
argument++;
}
// More arguments than placeholders, so the rest are listed as before rather
// than dropped
for (; argument < names.size(); argument++) {
element.append(", " + argumentText(argument));
}
elements.append(element.simplified());
}
}
return out.join(", ");
return elements.join(", ");
}
// The ICAO ULCS / application layer, decoded by the vendored dumpvdl2 ASN.1 decoder

10
plugins/channelrx/demodacars/vdl2atn.h

@ -60,8 +60,18 @@ public: @@ -60,8 +60,18 @@ public:
float m_longitude = 0.0f;
bool m_hasAltitude = false; //!< Aircraft locations carry an altitude, ground stations do not
int m_altitudeFt = 0;
//!< Where the aircraft told the ground station it was going, from the XID
//!< destination airport parameter. Frequently the only place a flight's
//!< destination is stated at all - a short sector may log on and land without
//!< ever filing a plan or sending a position report.
QString m_destinationAirport;
};
//!< Pulled out of the formatted decode rather than the parameter tree, as the
//!< position is. Static and public so it can be tested on its own: the text is what
//!< libacars produces and the pattern is the part that can be wrong.
static QString xidDestinationAirport(const QString& decoded);
// Decode the information field of one AVLC I frame
Result decode(const QByteArray& info, quint32 srcAddr, quint32 dstAddr, bool fromAircraft);

12
plugins/channelrx/demodadsb/CMakeLists.txt

@ -10,6 +10,9 @@ set(adsb_SOURCES @@ -10,6 +10,9 @@ set(adsb_SOURCES
adsbdemodbaseband.cpp
adsbdemodreport.cpp
adsbdemodworker.cpp
adsbdemodtracker.cpp
adsbdemodtrackerdecode.cpp
adsbaircraft.cpp
)
set(adsb_HEADERS
@ -22,6 +25,8 @@ set(adsb_HEADERS @@ -22,6 +25,8 @@ set(adsb_HEADERS
adsbdemodbaseband.h
adsbdemodreport.h
adsbdemodworker.h
adsbdemodtracker.h
adsbaircraft.h
adsbdemodstats.h
adsb.h
)
@ -35,6 +40,7 @@ if(NOT SERVER_MODE) @@ -35,6 +40,7 @@ if(NOT SERVER_MODE)
${adsb_SOURCES}
adsbdemodgui.cpp
adsbdemodgui.ui
adsbaircrafttablemodel.cpp
adsbdemodfeeddialog.cpp
adsbdemodfeeddialog.ui
adsbdemoddisplaydialog.cpp
@ -43,6 +49,7 @@ if(NOT SERVER_MODE) @@ -43,6 +49,7 @@ if(NOT SERVER_MODE)
adsbdemodnotificationdialog.ui
adsbosmtemplateserver.cpp
adsbdemodmap.qrc
adsbdemodmapliveries.qrc
adsbdemodicons.qrc
airlinelogos.qrc
flags.qrc
@ -51,12 +58,11 @@ if(NOT SERVER_MODE) @@ -51,12 +58,11 @@ if(NOT SERVER_MODE)
set(adsb_HEADERS
${adsb_HEADERS}
adsbdemodgui.h
adsbaircrafttablemodel.h
adsbdemodfeeddialog.h
adsbdemoddisplaydialog.h
adsbdemodnotificationdialog.h
adsbosmtemplateserver.h
ourairports.h
osndb.h
)
set(TARGET_NAME ${PLUGINS_PREFIX}demodadsb)
@ -97,7 +103,7 @@ target_link_libraries(${TARGET_NAME} PRIVATE @@ -97,7 +103,7 @@ target_link_libraries(${TARGET_NAME} PRIVATE
install(TARGETS ${TARGET_NAME} DESTINATION ${INSTALL_FOLDER})
if(WIN32)
if(WIN32 AND NOT SERVER_MODE)
# Run deployqt for QtGraphicalEffects, which isn't used in other plugins
include(DeployQt)
windeployqt(${TARGET_NAME} ${SDRANGEL_BINARY_BIN_DIR} ${PROJECT_SOURCE_DIR}/map)

474
plugins/channelrx/demodadsb/adsbaircraft.cpp

@ -0,0 +1,474 @@ @@ -0,0 +1,474 @@
///////////////////////////////////////////////////////////////////////////////////
// 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 <QCoreApplication>
#include <QDir>
#include <QFile>
#include <QFileInfo>
#include "util/units.h"
#include "util/aircraft3dmodels.h"
#include "util/aircraftreport.h"
#include "adsbaircraft.h"
#include "adsb.h"
QString ADSBAircraft::getImage() const
{
if (m_aircraftInfo && !m_aircraftInfo->m_type.isEmpty())
{
// https://www.icao.int/publications/doc8643/pages/search.aspx
static const QStringList fourEngineTypes = {"A388", "B741", "B742", "B743", "B744", "B748", "B74R", "B74S", "BLCF", "A342", "A343", "A345", "A346", "C17", "K35R"};
if (fourEngineTypes.contains(m_aircraftInfo->m_type)) {
return QString("aircraft_heavy_4engine.png");
} else if (m_aircraftInfo->m_type == "EUFI") {
return QString("eurofighter.png");
} else if (m_aircraftInfo->m_type == "VF35") {
return QString("f35.png");
} else if ((m_aircraftInfo->m_type == "SPIT") || (m_aircraftInfo->m_type == "HURI")) {
return QString("spitfire.png");
} else if ((m_aircraftInfo->m_type == "A400") || (m_aircraftInfo->m_type == "C30J")) {
return QString("a400m.png");
} else if (m_aircraftInfo->m_type == "H64") {
return QString("apache.png");
} else if (m_aircraftInfo->m_type == "H47") {
return QString("chinook.png");
}
}
if (m_emitterCategory.length() > 0)
{
if (!m_emitterCategory.compare("Heavy")) { // 777/787/A350 and 747/A380 - 4 engine handled above by type
return QString("aircraft_heavy_2engine.png");
} else if (!m_emitterCategory.compare("Large")) { // A320/737
return QString("aircraft_large.png");
} else if (!m_emitterCategory.compare("Small")) { // Private jets
return QString("aircraft_small.png");
} else if (!m_emitterCategory.compare("Rotorcraft")) {
return QString("aircraft_helicopter.png");
} else if (!m_emitterCategory.compare("High performance")) {
return QString("aircraft_fighter.png");
} else if (!m_emitterCategory.compare("Light")
|| !m_emitterCategory.compare("Ultralight")) {
return QString("aircraft_light.png");
} else if (!m_emitterCategory.compare("Glider/sailplane")) {
return QString("aircraft_glider.png");
} else if (!m_emitterCategory.compare("Space vehicle")) {
return QString("aircraft_space.png");
} else if (!m_emitterCategory.compare("UAV")) {
return QString("aircraft_drone.png");
} else if (!m_emitterCategory.compare("Emergency vehicle")
|| !m_emitterCategory.compare("Service vehicle")) {
return QString("truck.png");
} else {
return QString("aircraft_large.png");
}
}
else
{
return QString("aircraft_large.png");
}
}
// The two model sets disagree on case - Bluebell names the 777-300ER B77W, FSLTL B77w -
// and Qt looks resources up case sensitively, so 22 FSLTL liveries found no icon although
// the same one was sitting there under the other spelling. The icons are indexed once by
// lower case name, and that index is what the name is looked up in
static QString liveryIconFile(const QString& name)
{
static const QHash<QString, QString> icons = []
{
QHash<QString, QString> index;
const QStringList files = QDir(":/map/liveries").entryList({"*.png"}, QDir::Files);
index.reserve(files.size());
for (const QString& file : files) {
index.insert(QFileInfo(file).completeBaseName().toLower(), file);
}
return index;
}();
if (name.isEmpty()) {
return QString();
}
const QString file = icons.value(name.toLower());
return file.isEmpty() ? QString() : QString("liveries/" + file);
}
QString ADSBAircraft::getLiveryImage() const
{
// The 3D model matcher has already picked a model such as
// BB_Airbus_png/A320/A320_BAW.gltf from the type and operator, and the livery icons
// are named after the models, so the icon just follows the model's basename
for (const QString& model : {m_aircraft3DModel, m_aircraftCat3DModel})
{
if (!model.isEmpty())
{
const QString image = liveryIconFile(Aircraft3DModels::liveryIconName(model));
if (!image.isEmpty()) {
return image;
}
}
}
// No model match - use a white version of the plain icon, so the style stays
// consistent with the livery icons rather than dropping back to black
return liveryIconFile(QFileInfo(getImage()).completeBaseName());
}
QString ADSBAircraft::getText(const ADSBDemodSettings *settings, bool all, bool links) const
{
// Written as a link only where one would work; plain text otherwise, rather than
// something that looks clickable and is not
auto identity = [links](const QString& kind, const QString& value)
{
return links ? aircraftMapLink(kind, value) : value.toHtmlEscaped();
};
QStringList list;
if (all)
{
if (!m_flagIconURL.isEmpty() && !m_sideviewIconURL.isEmpty())
{
list.append(QString("<table width=100%><tr><td><img src=%1 width=85 height=20><td><img src=%2 align=right></table>").arg(m_sideviewIconURL).arg(m_flagIconURL));
}
else if (!m_flagIconURL.isEmpty() && !m_airlineIconURL.isEmpty())
{
list.append(QString("<table width=100%><tr><td><img src=%1><td><img src=%2 align=right></table>").arg(m_airlineIconURL).arg(m_flagIconURL));
}
else
{
if (!m_flagIconURL.isEmpty()) {
list.append(QString("<img src=%1>").arg(m_flagIconURL));
} else if (!m_sideviewIconURL.isEmpty()) {
list.append(QString("<img src=%1>").arg(m_sideviewIconURL));
} else if (!m_airlineIconURL.isEmpty()) {
list.append(QString("<img src=%1>").arg(m_airlineIconURL));
}
}
list.append(QString("ICAO: %1").arg(identity("icao", m_icaoHex)));
if ((m_aircraftInfo != nullptr) && !m_aircraftInfo->m_registration.isEmpty()) {
list.append(QString("Reg: %1").arg(identity("registration", m_aircraftInfo->m_registration)));
}
if (!m_callsign.isEmpty()) {
list.append(QString("Callsign: %1").arg(identity("flight", m_callsign.trimmed())));
}
QString atcCallsign = cellText(ADSB_COL_ATC_CALLSIGN);
if (!atcCallsign.isEmpty()) {
list.append(QString("ATC Callsign: %1").arg(atcCallsign));
}
bool typeKnown = false;
if (m_aircraftInfo != nullptr)
{
if (!m_aircraftInfo->m_model.isEmpty())
{
list.append(QString("Aircraft: %1").arg(m_aircraftInfo->m_model));
typeKnown = true;
}
}
// The emitter category is the coarse size class the aircraft broadcasts about
// itself - "Large", "Heavy", "Rotorcraft". Where the model is known it says the
// same thing less precisely, so it is only worth a line when it is not.
if (!m_emitterCategory.isEmpty() && !typeKnown) {
list.append(QString("Category: %1").arg(m_emitterCategory));
}
if (m_altitudeValid)
{
if (m_onSurface)
{
list.append(QString("Altitude: Surface"));
}
else
{
QString reference = m_altitudeGNSS ? "GNSS" : "Baro";
if (settings->m_siUnits) {
list.append(QString("Altitude: %1 (m %2)").arg(Units::feetToIntegerMetres(m_altitude)).arg(reference));
} else {
list.append(QString("Altitude: %1 (ft %2)").arg(m_altitude).arg(reference));
}
}
}
if (m_groundspeedValid)
{
if (settings->m_siUnits) {
list.append(QString("GS: %1 (kph)").arg(Units::knotsToIntegerKPH(m_groundspeed)));
} else {
list.append(QString("GS: %1 (kn)").arg(m_groundspeed));
}
}
if (m_verticalRateValid)
{
QString desc;
Real rate;
QString units;
if (settings->m_siUnits)
{
rate = Units::feetPerMinToIntegerMetresPerSecond(m_verticalRate);
units = QString("m/s");
}
else
{
rate = m_verticalRate;
units = QString("ft/min");
}
if (m_verticalRate == 0) {
desc = "Level flight";
} else if (rate > 0) {
desc = QString("Climbing: %1 (%2)").arg(rate).arg(units);
} else {
desc = QString("Descending: %1 (%2)").arg(rate).arg(units);
}
list.append(QString(desc));
}
if ((m_status.length() > 0) && m_status.compare("No emergency")) {
list.append(m_status);
}
QString flightStatus = cellText(ADSB_COL_FLIGHT_STATUS);
if (!flightStatus.isEmpty()) {
list.append(QString("Flight status: %1").arg(flightStatus));
}
QString dep = cellText(ADSB_COL_DEP);
if (!dep.isEmpty()) {
list.append(QString("Departed: %1").arg(dep));
}
QString std = cellText(ADSB_COL_STD);
if (!std.isEmpty()) {
list.append(QString("STD: %1").arg(std));
}
QString atd = cellText(ADSB_COL_ATD);
if (!atd.isEmpty())
{
list.append(QString("ATD: %1").arg(atd));
}
else
{
QString etd = cellText(ADSB_COL_ETD);
if (!etd.isEmpty()) {
list.append(QString("ETD: %1").arg(etd));
}
}
QString arr = cellText(ADSB_COL_ARR);
if (!arr.isEmpty()) {
list.append(QString("Arrival: %1").arg(arr));
}
QString sta = cellText(ADSB_COL_STA);
if (!sta.isEmpty()) {
list.append(QString("STA: %1").arg(sta));
}
QString ata = cellText(ADSB_COL_ATA);
if (!ata.isEmpty())
{
list.append(QString("ATA: %1").arg(ata));
}
else
{
QString eta = cellText(ADSB_COL_ETA);
if (!eta.isEmpty()) {
list.append(QString("ETA: %1").arg(eta));
}
}
}
else
{
QDateTime labelDateTime;
list.append(getLabel(settings, labelDateTime));
}
return list.join("<br>");
}
// See https://nats.aero/blog/2017/07/drone-disruption-gatwick/ for example of UK ATC display
QString ADSBAircraft::getLabel(const ADSBDemodSettings *settings, QDateTime& dateTime) const
{
QString id;
if (!m_callsign.isEmpty())
{
QString atcCallsign = cellText(ADSB_COL_ATC_CALLSIGN);
if (settings->m_atcCallsigns && !atcCallsign.isEmpty()) {
id = QString("%1 %2").arg(atcCallsign).arg(m_callsign.mid(3));
} else {
id = m_callsign;
}
}
else
{
id = m_icaoHex;
}
QStringList strings;
strings.append(id);
if (settings->m_atcLabels)
{
// Route
QString dep = cellText(ADSB_COL_DEP);
QString arr = cellText(ADSB_COL_ARR);
QString stops = cellText(ADSB_COL_STOPS);
if (!dep.isEmpty() && !arr.isEmpty())
{
if (stops.isEmpty()) {
strings.append(QString("%1-%2").arg(dep).arg(arr));
} else {
strings.append(QString("%1-%2-%3").arg(dep).arg(stops).arg(arr));
}
}
if (m_altitudeValid)
{
QStringList row1;
QChar c = m_altitude >= settings->m_transitionAlt ? 'F' : 'A';
// Convert altitude to flight level
int fl = m_altitude / 100;
row1.append(QString("%1%2").arg(c).arg(fl));
// Indicate whether climbing or descending
if (m_verticalRateValid && ((m_verticalRate != 0) || (m_selAltitudeValid && (m_altitude != m_selAltitude))))
{
QChar dir = m_verticalRate == 0 ? QChar('-') : (m_verticalRate > 0 ? QChar(0x2191) : QChar(0x2193));
row1.append(dir);
}
if (m_selAltitudeValid && (m_altitude != m_selAltitude))
{
int selfl = m_selAltitude / 100;
row1.append(QString::number(selfl));
}
strings.append(row1.join(" "));
dateTime = m_altitudeDateTime;
}
QStringList row2;
// Display speed
if (m_groundspeedValid)
{
row2.append(QString("G%2").arg(m_groundspeed));
}
else if (m_indicatedAirspeedValid)
{
row2.append(QString("I%1").arg(m_indicatedAirspeed));
if (!dateTime.isValid() || (m_indicatedAirspeedDateTime > dateTime)) {
dateTime = m_indicatedAirspeedDateTime;
}
}
// Aircraft type
if (m_aircraftInfo && !m_aircraftInfo->m_type.isEmpty())
{
row2.append(m_aircraftInfo->m_type);
}
else if (m_aircraftInfo && !m_aircraftInfo->m_model.isEmpty())
{
QString name = m_aircraftInfo->m_model;
int idx;
idx = name.indexOf(' ');
if (idx >= 0) {
name = name.left(idx);
}
idx = name.indexOf('-');
if (idx >= 0) {
name = name.left(idx);
}
row2.append(name);
}
strings.append(row2.join(" "));
// FIXME: Add ATC altitude and waypoint from ATC feature
}
return strings.join("<br>");
}
void ADSBAircraft::setOnSurface(const QDateTime& dateTime)
{
// There are a few airports that are below 0 MSL
// https://en.wikipedia.org/wiki/List_of_lowest_airports
// So we could set altitude to a negative value here, which should
// then get clipped to actual terrain elevation in 3D map
// But then PFD altimeter reads negative elsewhere
// Really, the altimeter would typically read airport elevation when on the surface
m_altitude = 0;
m_altitudeValid = true;
m_altitudeGNSS = false;
setCell(ADSB_COL_ALTITUDE, "Surface");
m_altitudeDateTime = dateTime;
}
void ADSBAircraft::setAltitude(int altitudeFt, bool gnss, const QDateTime& dateTime, const ADSBDemodSettings& settings)
{
m_altitude = altitudeFt;
m_altitudeValid = true;
if (!gnss)
{
m_pressureAltitude = altitudeFt;
m_pressureAltitudeValid = true;
}
else
{
m_pressureAltitudeValid = false;
}
m_altitudeGNSS = gnss;
setCell(ADSB_COL_ALTITUDE, settings.m_siUnits ? Units::feetToIntegerMetres(m_altitude) : m_altitude);
m_altitudeDateTime = dateTime;
}
void ADSBAircraft::setVerticalRate(int verticalRate, const ADSBDemodSettings& settings)
{
m_verticalRate = verticalRate;
m_verticalRateValid = true;
if (settings.m_siUnits) {
setCell(ADSB_COL_VERTICALRATE, Units::feetPerMinToIntegerMetresPerSecond(verticalRate));
} else {
setCell(ADSB_COL_VERTICALRATE, m_verticalRate);
}
}
void ADSBAircraft::setGroundspeed(float groundspeed, const ADSBDemodSettings& settings)
{
m_groundspeed = groundspeed;
m_groundspeedValid = true;
setCell(ADSB_COL_GROUND_SPEED, settings.m_siUnits ? Units::knotsToIntegerKPH(m_groundspeed) : (int)std::round(m_groundspeed));
// FIXME: dateTime?
}
void ADSBAircraft::setTrueAirspeed(int airspeed, const ADSBDemodSettings& settings)
{
m_trueAirspeed = airspeed;
m_trueAirspeedValid = true;
setCell(ADSB_COL_TRUE_AIRSPEED, settings.m_siUnits ? Units::knotsToIntegerKPH(m_trueAirspeed) : m_trueAirspeed);
}
void ADSBAircraft::setIndicatedAirspeed(int airspeed, const QDateTime& dateTime, const ADSBDemodSettings& settings)
{
m_indicatedAirspeed = airspeed;
m_indicatedAirspeedValid = true;
setCell(ADSB_COL_INDICATED_AIRSPEED, settings.m_siUnits ? Units::knotsToIntegerKPH(m_indicatedAirspeed) : m_indicatedAirspeed);
m_indicatedAirspeedDateTime = dateTime;
}
void ADSBAircraft::setTrack(float track, const QDateTime& dateTime)
{
m_track = track;
m_trackValid = true;
m_trackDateTime = dateTime;
setCell(ADSB_COL_TRACK, std::round(m_track));
m_orientationDateTime = dateTime;
}
void ADSBAircraft::setHeading(float heading, const QDateTime& dateTime)
{
m_heading = heading;
m_headingValid = true;
m_headingDateTime = dateTime;
setCell(ADSB_COL_HEADING, std::round(m_heading));
m_orientationDateTime = dateTime;
m_trackWhenHeadingSet = m_track;
}

389
plugins/channelrx/demodadsb/adsbaircraft.h

@ -0,0 +1,389 @@ @@ -0,0 +1,389 @@
///////////////////////////////////////////////////////////////////////////////////
// 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_ADSBAIRCRAFT_H
#define INCLUDE_ADSBAIRCRAFT_H
#include <QString>
#include <QDateTime>
#include <QList>
#include <QVariant>
#include <QGeoCoordinate>
#include "util/movingaverage.h"
#include "util/osndb.h"
#include "adsbdemodsettings.h"
// A position decoded since the last tracker-to-GUI flush. Keeping these samples
// separate from the coalesced aircraft state lets fast CSV replay rebuild tracks.
struct ADSBAircraftPosition {
Real m_latitude;
Real m_longitude;
int m_altitude;
QDateTime m_dateTime;
ADSBAircraftPosition(Real latitude, Real longitude, int altitude, const QDateTime& dateTime) :
m_latitude(latitude),
m_longitude(longitude),
m_altitude(altitude),
m_dateTime(dateTime)
{}
};
// Data about an aircraft extracted from ADS-B and Mode-S frames.
//
// This is what the decoder produces and owns. It deliberately knows nothing about the
// table or the map, so that it can be decoded on the channel's worker thread and in a
// headless server build. The GUI derives Aircraft from it for the display-only state.
struct ADSBAircraft {
int m_icao; // 24-bit ICAO aircraft address
QString m_icaoHex;
QString m_callsign; // Flight callsign
QString m_flight; // Guess at flight number
bool m_globalPosition; // The current local-CPR reference chain was established by a global decode
Real m_latitude; // Latitude in decimal degrees
Real m_longitude; // Longitude in decimal degrees
float m_radius; // Horizontal containment radius limit (Rc) in metres
int m_altitude; // Altitude in feet (will be 0 if on surface)
int m_pressureAltitude; // Pressure altitude in feet for Map PFD altimeter (can be negative on surface)
bool m_onSurface; // Indicates if on surface or airborne
bool m_altitudeGNSS; // Altitude is GNSS HAE (Height above WGS-84 ellipsoid) rather than barometric alitute (relative to 29.92 Hg)
float m_heading; // Heading in degrees magnetic
float m_track; // Track in degrees true?
int m_verticalRate; // Vertical climb rate in ft/min
QString m_emitterCategory; // Aircraft type
QString m_status; // Aircraft status
int m_squawk; // Mode-A code
bool m_spi; // Special position identification (IDENT) active
Real m_range; // Distance from station to aircraft
Real m_azimuth; // Azimuth from station to aircraft
Real m_elevation; // Elevation from station to aircraft
QDateTime m_rxTime; // When last frame received (can be long ago if reading from log file)
QDateTime m_updateTime; // Last time we updated data for this aircraft (used for determining when to remove an aircraft)
int m_selAltitude; // Selected altitude in MCP/FCU or FMS in feet
int m_selHeading; // Selected heading in MCP/FCU in degrees
float m_baro; // Aircraft baro setting in mb (Mode-S)
float m_roll; // In degrees
int m_groundspeed; // In knots
float m_turnRate; // In degrees per second
int m_trueAirspeed; // In knots
int m_indicatedAirspeed; // In knots
float m_mach; // Mach number
bool m_autopilot;
bool m_vnavMode;
bool m_altHoldMode;
bool m_approachMode;
bool m_lnavMode;
bool m_tcasOperational; // Appears only to be true if TA/RA, false if TA ONLY
bool m_bdsCapabilities[16][16]; // BDS capabilities are indicaited by BDS 1.7
int m_adsbVersion;
bool m_nicSupplementA;
bool m_nicSupplementB;
bool m_nicSupplementC;
bool m_positionValid; // Indicates if we have valid data for the above fields
bool m_positionOnSurface; // Air/surface state at the last accepted position
bool m_altitudeValid;
bool m_pressureAltitudeValid;
bool m_onSurfaceValid;
bool m_headingValid;
bool m_trackValid;
bool m_verticalRateValid;
bool m_selAltitudeValid;
bool m_selHeadingValid;
bool m_baroValid;
bool m_rollValid;
bool m_groundspeedValid;
bool m_turnRateValid;
bool m_trueAirspeedValid;
bool m_indicatedAirspeedValid;
bool m_machValid;
bool m_autopilotValid;
bool m_vnavModeValid;
bool m_altHoldModeValid;
bool m_approachModeValid;
bool m_lnavModeValid;
bool m_tcasOperationalValid;
bool m_bdsCapabilitiesValid;
bool m_adsbVersionValid;
bool m_nicSupplementAValid;
bool m_nicSupplementBValid;
bool m_nicSupplementCValid;
// State for calculating position using two CPR frames
bool m_cprValid[2];
double m_cprLat[2];
double m_cprLong[2];
QDateTime m_cprTime[2];
int m_adsbFrameCount; // Number of ADS-B frames for this aircraft
int m_modesFrameCount; // Number of Mode-S frames for this aircraft
int m_nonTransponderFrameCount;
int m_tisBFrameCount;
int m_adsrFrameCount;
float m_minCorrelation;
float m_maxCorrelation;
float m_correlation;
MovingAverageUtil<float, double, 100> m_correlationAvg;
AircraftInformation *m_aircraftInfo; // Info about the aircraft from the database
QString m_aircraft3DModel; // 3D model for map based on aircraft type
QString m_aircraftCat3DModel; // 3D model based on aircraft category
float m_modelAltitudeOffset; // Altitude adjustment so aircraft model doesn't go underground
float m_labelAltitudeOffset; // How height to position label above aircraft
QString m_flagName; // Country flag, for the GUI to resolve an icon from
// Resource paths of the icons shown in the table, resolved by the GUI
QString m_airlineIconPath;
QString m_sideviewIconPath;
QString m_flagIconPath;
QString m_flagIconURL;
QString m_airlineIconURL;
QString m_sideviewIconURL;
// For animation on 3D map
float m_runwayAltitude;
bool m_runwayAltitudeValid;
// Elevation of the airport the aircraft is nearest to, so heights above the ground
// can be worked out for an arrival - m_runwayAltitude only ever covers a departure
// we watched. Looked up when low, then kept until the aircraft moves away from it
float m_fieldElevation;
bool m_fieldElevationValid;
QDateTime m_fieldElevationTime; // When it was last looked up
bool m_gearDown;
bool m_tyresFlat; // Tyre deflection animation is at its start, where a newly loaded model sits
float m_flaps; // 0 - no flaps, 1 - full flaps
bool m_rotorStarted; // Rotors started on 'Rotorcraft'
bool m_engineStarted; // Engines started (typically propellors)
QDateTime m_engineAnimationTime; // When the engine/rotor animation was last sent, so it
// can be re-asserted for a map opened after the start
QDateTime m_positionDateTime;
QDateTime m_orientationDateTime; // FIXME
QDateTime m_headingDateTime;
QDateTime m_trackDateTime;
QDateTime m_altitudeDateTime;
QDateTime m_indicatedAirspeedDateTime;
QDateTime m_prevTrackDateTime;
int m_prevTrack;
float m_trackWhenHeadingSet;
float m_pitchEst; // Estimated pitch based on vertical rate
float m_rollEst; // Estimated roll based on rate of change in heading
bool m_notified; // Set when a notification has been made for this aircraft, so we don't repeat it
// Set while decoding, cleared when the state is sent to the GUI
bool m_isNew; // First frame from this aircraft
bool m_positionChanged; // A point should be added to the flight path
bool m_trailCleared; // The flight path should be thrown away and started again
bool m_mapTrailResetPending; // The external Map still needs the same reset
QList<ADSBAircraftPosition> m_positionUpdates; // Every position since the previous GUI flush
// Values shown in the table. These are the store for a good deal of decoded data,
// not merely a display copy - getText, getLabel and the notification substitution
// all read values back out of them
QVariant m_cells[ADSBDEMOD_COLUMNS];
quint64 m_dirtyCells[2]; // Cells changed since the table was last updated
bool m_tcasAlert; // Draw the TCAS cell in red
// Active TCAS Resolution Advisory, decoded from an RA broadcast (DF16 MV with
// VDS=0x30, DF17 TC=28 ST=2, or DF20/21 BDS 3,0 - decodeRABroadcast()). Broadcasts
// repeat while the RA is active, so the tracker's tick() expires the state when
// they stop, and the terminated flag shortly after it is seen
bool m_raActive = false;
bool m_raCorrective = false; // Corrective (fly the sense now) vs preventive
bool m_raDownward = false; // Downward sense (descend) vs upward (climb)
bool m_raPositive = false; // Positive (climb/descend) vs vertical speed limit
bool m_raTerminated = false; // RA terminated - clear of conflict
bool m_raMultipleThreats = false;
bool m_raOppositeSense = false; // Multiple threats require opposite-sense RAs
unsigned m_raThreatIcao = 0; // Threat's Mode S address, 0 if not identified
QDateTime m_raDateTime; // When the last RA broadcast was received
ADSBAircraft() :
m_icao(0),
m_globalPosition(false),
m_latitude(0),
m_longitude(0),
m_radius(0.0f),
m_altitude(0),
m_pressureAltitude(0),
m_onSurface(false),
m_altitudeGNSS(false),
m_heading(0),
m_track(0),
m_verticalRate(0),
m_squawk(0),
m_spi(false),
m_range(0.0f),
m_azimuth(0),
m_elevation(0),
m_selAltitude(0),
m_selHeading(0),
m_baro(0),
m_roll(0.0f),
m_groundspeed(0),
m_turnRate(0.0f),
m_trueAirspeed(0),
m_indicatedAirspeed(0),
m_mach(0.0f),
m_autopilot(false),
m_vnavMode(false),
m_altHoldMode(false),
m_approachMode(false),
m_lnavMode(false),
m_tcasOperational(false),
m_adsbVersion(0),
m_nicSupplementA(false),
m_nicSupplementB(false),
m_nicSupplementC(false),
m_positionValid(false),
m_positionOnSurface(false),
m_altitudeValid(false),
m_pressureAltitudeValid(false),
m_onSurfaceValid(false),
m_headingValid(false),
m_trackValid(false),
m_verticalRateValid(false),
m_selAltitudeValid(false),
m_selHeadingValid(false),
m_baroValid(false),
m_rollValid(false),
m_groundspeedValid(false),
m_turnRateValid(false),
m_trueAirspeedValid(false),
m_indicatedAirspeedValid(false),
m_machValid(false),
m_autopilotValid(false),
m_vnavModeValid(false),
m_altHoldModeValid(false),
m_approachModeValid(false),
m_lnavModeValid(false),
m_tcasOperationalValid(false),
m_bdsCapabilitiesValid(false),
m_adsbVersionValid(false),
m_nicSupplementAValid(false),
m_nicSupplementBValid(false),
m_nicSupplementCValid(false),
m_adsbFrameCount(0),
m_modesFrameCount(0),
m_nonTransponderFrameCount(0),
m_tisBFrameCount(0),
m_adsrFrameCount(0),
m_minCorrelation(INFINITY),
m_maxCorrelation(-INFINITY),
m_correlation(0.0f),
m_tcasAlert(false),
m_aircraftInfo(nullptr),
m_modelAltitudeOffset(0.0f),
m_labelAltitudeOffset(5.0f),
m_runwayAltitude(0.0),
m_runwayAltitudeValid(false),
m_fieldElevation(0.0),
m_fieldElevationValid(false),
m_gearDown(false),
m_tyresFlat(true),
m_flaps(0.0),
m_rotorStarted(false),
m_engineStarted(false),
m_prevTrack(0),
m_trackWhenHeadingSet(0.0f),
m_pitchEst(0.0),
m_rollEst(0.0),
m_notified(false),
m_isNew(true),
m_positionChanged(false),
m_trailCleared(false),
m_mapTrailResetPending(false)
{
for (int i = 0; i < 2; i++) {
m_cprValid[i] = false;
m_cprLat[i] = 0.0;
m_cprLong[i] = 0.0;
}
for (int i = 0; i < 16; i++) {
for (int j = 0; j < 16; j++) {
m_bdsCapabilities[i][j] = false;
}
}
for (int i = 0; i < 2; i++) {
m_dirtyCells[i] = 0;
}
}
// The table model reads these; setCell records which cells changed so only
// those are repainted
void setCell(int col, const QVariant& value)
{
if (m_cells[col] != value)
{
m_cells[col] = value;
m_dirtyCells[col >> 6] |= 1ULL << (col & 63);
}
}
const QVariant& cell(int col) const { return m_cells[col]; }
QString cellText(int col) const { return m_cells[col].toString(); }
bool cellsDirty() const { return m_dirtyCells[0] || m_dirtyCells[1]; }
bool cellDirty(int col) const { return (m_dirtyCells[col >> 6] >> (col & 63)) & 1; }
void clearDirtyCells() { m_dirtyCells[0] = 0; m_dirtyCells[1] = 0; }
void markAllCellsDirty() { m_dirtyCells[0] = ~0ULL; m_dirtyCells[1] = ~0ULL; }
// The range cell holds a number so that the table sorts it numerically; this is
// how it is shown, and how it reads in notifications
static QString rangeText(const QVariant& range)
{
return range.isNull() ? QString() : QString::number(range.toDouble(), 'f', 1);
}
QString getImage() const;
// Icon showing the airline's livery, derived from the matched 3D model.
// Empty when there is no model match or no icon for the livery
QString getLiveryImage() const;
// links makes the ICAO, registration and callsign clickable, selecting the
// aircraft in the Aircraft feature. Only passed where that can actually happen -
// this same text feeds the demodulator's own map, whose delegate has no link
// handler, and there may be no Aircraft feature to select anything in
QString getText(const ADSBDemodSettings *settings, bool all=false, bool links=false) const;
// Label to use for aircraft on map
QString getLabel(const ADSBDemodSettings *settings, QDateTime& dateTime) const;
// Name to use when selected as a target (E.g. for use as target name in Rotator Controller)
QString targetName() const
{
if (!m_callsign.isEmpty())
return QString("Callsign: %1").arg(m_callsign);
else
return QString("ICAO: %1").arg(m_icao, 0, 16);
}
void setOnSurface(const QDateTime& dateTime);
void setAltitude(int altitudeFt, bool gnss, const QDateTime& dateTime, const ADSBDemodSettings& settings);
void setVerticalRate(int verticalRate, const ADSBDemodSettings& settings);
void setGroundspeed(float groundspeed, const ADSBDemodSettings& settings);
void setTrueAirspeed(int airspeed, const ADSBDemodSettings& settings);
void setIndicatedAirspeed(int airspeed, const QDateTime& dateTime, const ADSBDemodSettings& settings);
void setTrack(float track, const QDateTime& dateTime);
void setHeading(float heading, const QDateTime& dateTime);
};
#endif // INCLUDE_ADSBAIRCRAFT_H

471
plugins/channelrx/demodadsb/adsbaircrafttablemodel.cpp

@ -0,0 +1,471 @@ @@ -0,0 +1,471 @@
///////////////////////////////////////////////////////////////////////////////////
// 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 <QIcon>
#include <QSize>
#include <QBrush>
#include "adsbaircrafttablemodel.h"
#include "adsbdemodgui.h"
static const QString g_columnNames[ADSBDEMOD_COLUMNS] = {
QStringLiteral("ICAO ID"),
QStringLiteral("Callsign"),
QStringLiteral("ATC Callsign"),
QStringLiteral("Aircraft"),
QStringLiteral("Type"),
QStringLiteral("Sideview"),
QStringLiteral("Airline"),
QStringLiteral("Country"),
QStringLiteral("GS (kn)"),
QStringLiteral("TAS (kn)"),
QStringLiteral("IAS (kn)"),
QStringLiteral("Mach"),
QStringLiteral("Sel Alt (ft)"),
QStringLiteral("Alt (ft)"),
QStringLiteral("VR (ft/m)"),
QStringLiteral("Sel Hd (\u00B0)"),
QStringLiteral("Hd (\u00B0)"),
QStringLiteral("Trk (\u00B0)"),
QStringLiteral("TR (\u00B0/s)"),
QStringLiteral("Roll (\u00B0)"),
QStringLiteral("D (km)"),
QStringLiteral("Az/El (\u00B0)"),
QStringLiteral("Cat"),
QStringLiteral("Status"),
QStringLiteral("Squawk"),
QStringLiteral("Ident"),
QStringLiteral("Reg"),
QStringLiteral("Registered"),
QStringLiteral("Manufacturer"),
QStringLiteral("Owner"),
QStringLiteral("Operator"),
QStringLiteral("AP"),
QStringLiteral("V Mode"),
QStringLiteral("L Mode"),
QStringLiteral("TCAS"),
QStringLiteral("ACAS"),
QStringLiteral("RA"),
QStringLiteral("Max AS (kn)"),
QStringLiteral("Version"),
QStringLiteral("L (m)"),
QStringLiteral("W (m)"),
QStringLiteral("QNH (mb)"),
QStringLiteral("H Wnd (kn)"),
QStringLiteral("OAT (C)"),
QStringLiteral("Wnd (kn)"),
QStringLiteral("Wnd (\u00B0)"),
QStringLiteral("P (hPa)"),
QStringLiteral("T (C)"),
QStringLiteral("U (%)"),
QStringLiteral("Lat (\u00B0)"),
QStringLiteral("Lon (\u00B0)"),
QStringLiteral("IC"),
QStringLiteral("Updated"),
QStringLiteral("Frames"),
QStringLiteral("ADS-B FC"),
QStringLiteral("Mode S FC"),
QStringLiteral("Non-transponder"),
QStringLiteral("TIS-B FC"),
QStringLiteral("ADS-R FC"),
QStringLiteral("Rc"),
QStringLiteral("NACp"),
QStringLiteral("NACv"),
QStringLiteral("GVA"),
QStringLiteral("NIC"),
QStringLiteral("NICbaro"),
QStringLiteral("SIL"),
QStringLiteral("Correlation"),
QStringLiteral("RSSI"),
QStringLiteral("Flight Status"),
QStringLiteral("Dep"),
QStringLiteral("Arr"),
QStringLiteral("Stops"),
QStringLiteral("STD"),
QStringLiteral("ETD"),
QStringLiteral("ATD"),
QStringLiteral("STA"),
QStringLiteral("ETA"),
QStringLiteral("ATA")
};
static const QString g_columnTips[ADSBDEMOD_COLUMNS] = {
QStringLiteral(""),
QStringLiteral("Callsign. Links to www.flightradar24.com"),
QStringLiteral("Airline callsign used by ATC"),
QStringLiteral("Aircraft model"),
QStringLiteral("ICAO aircraft type designator"),
QStringLiteral(""),
QStringLiteral("Airline logo"),
QStringLiteral("Country of registration"),
QStringLiteral("Groundspeed in knots or kilometers per hour"),
QStringLiteral("True airpeed in knots or kilometers per hour"),
QStringLiteral("Indicated airspeed in knots or kilometers per hour"),
QStringLiteral("Mach number"),
QStringLiteral("Selected altitude in feet or metres (As set on MCP/FCU or by FMS)"),
QStringLiteral("Altitude in feet or metres"),
QStringLiteral("Vertical climb rate in feet per minute or metres per second"),
QStringLiteral("Selected heading in degrees (As set on MCP/FCU or by FMS)"),
QStringLiteral("Aircraft heading in degrees"),
QStringLiteral("Aircraft track in degrees"),
QStringLiteral("Turn rate in degrees per second"),
QStringLiteral("Roll angle in degrees"),
QStringLiteral("Range or distance of aircraft from home location"),
QStringLiteral("Azimuth and elevation to aircraft from My Position. Double click to set as target."),
QStringLiteral("Aircraft standard category"),
QStringLiteral("Aircraft emergency status"),
QStringLiteral("Mode-A transponder code"),
QStringLiteral("Ident switch active"),
QStringLiteral("Aircraft registration"),
QStringLiteral("Date aircraft was registered"),
QStringLiteral("Aircraft manufacturer"),
QStringLiteral("Owner of the aircraft"),
QStringLiteral("Aircraft operator ICAO code"),
QStringLiteral("Autopilot enabled"),
QStringLiteral("MCP/FCU vertical mode"),
QStringLiteral("MCP/FCU lateral mode"),
QStringLiteral("TCAS operational. RA in red if active"),
QStringLiteral("Airborne collision avoidance system capability"),
QStringLiteral("ACAS active resolition advisory"),
QStringLiteral("Maximum speed in knots"),
QStringLiteral("ADS-B version"),
QStringLiteral("Aircraft length in metres"),
QStringLiteral("Aircraft width in metres"),
QStringLiteral("Barometer setting in millibars"),
QStringLiteral("Headwind in knots or kilometers per hour"),
QStringLiteral("Outside air temperature in degrees Celsius estimated from Mach and TAS"),
QStringLiteral("Wind speed in knots"),
QStringLiteral("Wind direction in degrees"),
QStringLiteral("Static air pressure in hectopascals"),
QStringLiteral("Static air temperature in degrees Celsius"),
QStringLiteral("Humidity in percent"),
QStringLiteral(""),
QStringLiteral(""),
QStringLiteral("Interrogator code (II/SI)"),
QStringLiteral("Time when the last ADS-B message from this aircraft was received."),
QStringLiteral("Number of ADS-B and Mode S frames received from this aircraft"),
QStringLiteral("Number of ADS-B frames received from this aircraft"),
QStringLiteral("Number of Mode S frames received from this aircraft"),
QStringLiteral("Non transponder device frame count"),
QStringLiteral("Number of TIS-B frames received with this aircraft's ICAO"),
QStringLiteral("Number of ADS-R frames received with this aircraft's ICAO"),
QStringLiteral("Horizontal containment radius limit"),
QStringLiteral("Navigation accuracy category - 95% horizontal position"),
QStringLiteral("Navigation accuracy category - velocity"),
QStringLiteral("Geometric vertical accuracy"),
QStringLiteral("Navigation integrity category"),
QStringLiteral("Barometric altitude integrity code"),
QStringLiteral("Surveillance integrity level"),
QStringLiteral("Correlation values for received frames. min/avg/max"),
QStringLiteral("Received Signal Strength Indicator (dBFS)"),
QStringLiteral("Status of flight"),
QStringLiteral("Departure airport"),
QStringLiteral("Arrival airport"),
QStringLiteral(""),
QStringLiteral("Scheduled time of departure"),
QStringLiteral("Estimated time of departure"),
QStringLiteral("Actual time of departure"),
QStringLiteral("Scheduled time of arrival"),
QStringLiteral("Estimated time of arrival"),
QStringLiteral("Actual time of arrival")
};
bool ADSBAircraftSortProxy::lessThan(const QModelIndex& left, const QModelIndex& right) const
{
// The values are compared here rather than by the base class, which would fetch
// them from the model a second time - and sorting runs on every update
const QVariant l = sourceModel()->data(left, ADSBAircraftTableModel::SortRole);
const QVariant r = sourceModel()->data(right, ADSBAircraftTableModel::SortRole);
const bool lString = l.userType() == QMetaType::QString;
const bool rString = r.userType() == QMetaType::QString;
const bool lEmpty = l.isNull() || (lString && l.toString().isEmpty());
const bool rEmpty = r.isNull() || (rString && r.toString().isEmpty());
// Empty cells sort before values in every column, however the column is typed
if (lEmpty || rEmpty) {
return lEmpty && !rEmpty;
}
if (!lString && !rString) {
return l.toDouble() < r.toDouble();
}
return QString::localeAwareCompare(l.toString(), r.toString()) < 0;
}
static qreal g_devicePixelRatio = 1.0;
static QHash<QString, QIcon> g_icons;
void ADSBAircraftTableModel::setDevicePixelRatio(qreal dpr)
{
if (dpr != g_devicePixelRatio)
{
g_devicePixelRatio = dpr;
g_icons.clear();
}
}
// Icons are loaded on demand and kept, as the same few appear on many rows
QVariant ADSBAircraftTableModel::icon(const QString& path, const QSize& size)
{
if (path.isEmpty()) {
return QVariant();
}
auto i = g_icons.find(path);
if (i == g_icons.end())
{
QPixmap pixmap(path);
if (!pixmap.isNull() && (g_devicePixelRatio > 1.0))
{
// Draw at the full size the table asks for, rather than being limited to
// the image's own pixel size on a scaled display
pixmap = pixmap.scaled(size * g_devicePixelRatio, Qt::KeepAspectRatio, Qt::SmoothTransformation);
pixmap.setDevicePixelRatio(g_devicePixelRatio);
}
i = g_icons.insert(path, QIcon(pixmap));
}
return QVariant(i.value());
}
// Row numbers are the position in the table, not in the underlying model, so they
// count up from one however the table is sorted
QVariant ADSBAircraftSortProxy::headerData(int section, Qt::Orientation orientation, int role) const
{
if ((orientation == Qt::Vertical) && (role == Qt::DisplayRole)) {
return section + 1;
}
return QSortFilterProxyModel::headerData(section, orientation, role);
}
const QString *ADSBAircraftTableModel::columnNames()
{
return g_columnNames;
}
ADSBAircraftTableModel::ADSBAircraftTableModel(QObject *parent) :
QAbstractTableModel(parent),
m_settings(nullptr)
{
}
void ADSBAircraftTableModel::addAircraft(Aircraft *aircraft)
{
beginInsertRows(QModelIndex(), m_aircraft.size(), m_aircraft.size());
m_aircraft.append(aircraft);
endInsertRows();
}
void ADSBAircraftTableModel::removeAircraft(Aircraft *aircraft)
{
int row = m_aircraft.indexOf(aircraft);
if (row >= 0)
{
beginRemoveRows(QModelIndex(), row, row);
m_aircraft.removeAt(row);
endRemoveRows();
}
}
void ADSBAircraftTableModel::clear()
{
beginResetModel();
m_aircraft.clear();
endResetModel();
}
int ADSBAircraftTableModel::rowForAircraft(const Aircraft *aircraft) const
{
return m_aircraft.indexOf(const_cast<Aircraft *>(aircraft));
}
void ADSBAircraftTableModel::flushDirty()
{
for (int row = 0; row < m_aircraft.size(); row++)
{
Aircraft *aircraft = m_aircraft[row];
if (!aircraft->cellsDirty()) {
continue;
}
// One dataChanged spanning the changed columns, rather than one per cell
int first = -1;
int last = -1;
for (int col = 0; col < ADSBDEMOD_COLUMNS; col++)
{
if (aircraft->cellDirty(col))
{
if (first < 0) {
first = col;
}
last = col;
}
}
aircraft->clearDirtyCells();
if (first >= 0) {
emit dataChanged(index(row, first), index(row, last));
}
}
}
void ADSBAircraftTableModel::allDataChanged()
{
if (!m_aircraft.isEmpty())
{
for (Aircraft *aircraft : m_aircraft) {
aircraft->clearDirtyCells();
}
emit dataChanged(index(0, 0), index(m_aircraft.size() - 1, ADSBDEMOD_COLUMNS - 1));
}
}
void ADSBAircraftTableModel::aircraftDataChanged(const Aircraft *aircraft)
{
int row = rowForAircraft(aircraft);
if (row >= 0) {
emit dataChanged(index(row, 0), index(row, ADSBDEMOD_COLUMNS - 1));
}
}
int ADSBAircraftTableModel::rowCount(const QModelIndex& parent) const
{
(void) parent;
return m_aircraft.size();
}
int ADSBAircraftTableModel::columnCount(const QModelIndex& parent) const
{
(void) parent;
return ADSBDEMOD_COLUMNS;
}
QVariant ADSBAircraftTableModel::data(const QModelIndex& index, int role) const
{
int row = index.row();
int col = index.column();
if ((row < 0) || (row >= m_aircraft.size()) || (col < 0) || (col >= ADSBDEMOD_COLUMNS)) {
return QVariant();
}
const Aircraft *aircraft = m_aircraft[row];
switch (role)
{
case Qt::DisplayRole:
case Qt::EditRole:
// Range is held as a number, so that it sorts numerically
if (col == ADSB_COL_RANGE) {
return ADSBAircraft::rangeText(aircraft->cell(col));
}
return aircraft->cell(col);
case SortRole:
return aircraft->cell(col);
case Qt::DecorationRole:
switch (col)
{
case ADSB_COL_AIRLINE: return icon(aircraft->m_airlineIconPath, QSize(85, 20));
case ADSB_COL_SIDEVIEW: return icon(aircraft->m_sideviewIconPath, QSize(85, 20));
case ADSB_COL_COUNTRY: return icon(aircraft->m_flagIconPath, QSize(40, 20));
default: return QVariant();
}
case Qt::SizeHintRole:
switch (col)
{
case ADSB_COL_AIRLINE:
case ADSB_COL_SIDEVIEW:
return QVariant(QSize(85, 20));
case ADSB_COL_COUNTRY:
return QVariant(QSize(40, 20));
default:
return QVariant();
}
case Qt::ForegroundRole:
if ((col == ADSB_COL_TCAS) && aircraft->m_tcasAlert) {
return QBrush(Qt::red);
}
return QVariant();
default:
return QVariant();
}
}
QVariant ADSBAircraftTableModel::headerData(int section, Qt::Orientation orientation, int role) const
{
if (orientation == Qt::Vertical)
{
// Row numbers, which are also the count of aircraft being tracked
if ((role == Qt::DisplayRole) && (section >= 0) && (section < m_aircraft.size())) {
return section + 1;
}
return QVariant();
}
if ((section < 0) || (section >= ADSBDEMOD_COLUMNS)) {
return QVariant();
}
if (role == Qt::DisplayRole)
{
// These headings carry the units, which the user can switch
if (m_settings && m_settings->m_siUnits)
{
switch (section)
{
case ADSB_COL_ALTITUDE: return QStringLiteral("Alt (m)");
case ADSB_COL_VERTICALRATE: return QStringLiteral("VR (m/s)");
case ADSB_COL_SEL_ALTITUDE: return QStringLiteral("Sel Alt (m)");
case ADSB_COL_GROUND_SPEED: return QStringLiteral("GS (kph)");
case ADSB_COL_TRUE_AIRSPEED: return QStringLiteral("TAS (kph)");
case ADSB_COL_INDICATED_AIRSPEED: return QStringLiteral("IAS (kph)");
case ADSB_COL_HEADWIND: return QStringLiteral("H Wnd (kph)");
case ADSB_COL_WIND_SPEED: return QStringLiteral("Wnd (kph)");
default: break;
}
}
else
{
switch (section)
{
case ADSB_COL_ALTITUDE: return QStringLiteral("Alt (ft)");
case ADSB_COL_VERTICALRATE: return QStringLiteral("VR (ft/m)");
case ADSB_COL_SEL_ALTITUDE: return QStringLiteral("Sel Alt (ft)");
case ADSB_COL_GROUND_SPEED: return QStringLiteral("GS (kn)");
case ADSB_COL_TRUE_AIRSPEED: return QStringLiteral("TAS (kn)");
case ADSB_COL_INDICATED_AIRSPEED: return QStringLiteral("IAS (kn)");
case ADSB_COL_HEADWIND: return QStringLiteral("H Wnd (kn)");
case ADSB_COL_WIND_SPEED: return QStringLiteral("Wnd (kn)");
default: break;
}
}
return g_columnNames[section];
}
else if ((role == Qt::ToolTipRole) && !g_columnTips[section].isEmpty()) {
return g_columnTips[section];
}
return QVariant();
}

91
plugins/channelrx/demodadsb/adsbaircrafttablemodel.h

@ -0,0 +1,91 @@ @@ -0,0 +1,91 @@
///////////////////////////////////////////////////////////////////////////////////
// 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_ADSBAIRCRAFTTABLEMODEL_H
#define INCLUDE_ADSBAIRCRAFTTABLEMODEL_H
#include <QAbstractTableModel>
#include <QSortFilterProxyModel>
#include <QList>
#include "adsbdemodsettings.h"
struct Aircraft;
// Model for the table of aircraft.
//
// The aircraft own their cell values; this presents them as rows. Changes are
// coalesced: decoding marks cells dirty and flushDirty() emits dataChanged for them
// periodically, rather than the table being repainted and re-sorted on every frame,
// which is what a busy sky used to cost.
// Sorts on the raw cell values, with empty cells always ordered before values, so that
// every column treats them the same way
class ADSBAircraftSortProxy : public QSortFilterProxyModel {
Q_OBJECT
public:
using QSortFilterProxyModel::QSortFilterProxyModel;
// Row numbers count the rows as displayed, so they say how many aircraft there are
QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const override;
protected:
bool lessThan(const QModelIndex& left, const QModelIndex& right) const override;
};
class ADSBAircraftTableModel : public QAbstractTableModel {
Q_OBJECT
public:
// Raw cell value, used for sorting, so formatted numbers still sort numerically
static const int SortRole = Qt::UserRole;
explicit ADSBAircraftTableModel(QObject *parent = nullptr);
void setSettings(const ADSBDemodSettings *settings) { m_settings = settings; }
void addAircraft(Aircraft *aircraft);
void removeAircraft(Aircraft *aircraft);
void clear();
int rowForAircraft(const Aircraft *aircraft) const;
Aircraft *aircraftAt(int row) const { return ((row >= 0) && (row < m_aircraft.size())) ? m_aircraft[row] : nullptr; }
// Repaint the cells that have changed since the last call
void flushDirty();
// Everything needs redrawing, e.g. after a change of units
void allDataChanged();
void aircraftDataChanged(const Aircraft *aircraft);
int rowCount(const QModelIndex& parent = QModelIndex()) const override;
int columnCount(const QModelIndex& parent = QModelIndex()) const override;
QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const override;
QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const override;
static const QString *columnNames();
// The icons are 85x20 pixel images. On a scaled display Qt will not draw them
// larger than that in device pixels, which leaves them undersized, so they are
// scaled for the display when they are loaded
static void setDevicePixelRatio(qreal dpr);
static QVariant icon(const QString& path, const QSize& size);
private:
QList<Aircraft *> m_aircraft;
const ADSBDemodSettings *m_settings;
};
#endif // INCLUDE_ADSBAIRCRAFTTABLEMODEL_H

45
plugins/channelrx/demodadsb/adsbdemod.cpp

@ -42,6 +42,7 @@ @@ -42,6 +42,7 @@
#include "adsbdemod.h"
#include "adsbdemodworker.h"
#include "adsbdemodtracker.h"
MESSAGE_CLASS_DEFINITION(ADSBDemod::MsgConfigureADSBDemod, Message)
MESSAGE_CLASS_DEFINITION(ADSBDemod::MsgAircraftReport, Message)
@ -68,8 +69,21 @@ ADSBDemod::ADSBDemod(DeviceAPI *devieAPI) : @@ -68,8 +69,21 @@ ADSBDemod::ADSBDemod(DeviceAPI *devieAPI) :
m_basebandSink = new ADSBDemodBaseband();
m_basebandSink->moveToThread(m_thread);
m_workerThread = new QThread();
m_worker = new ADSBDemodWorker();
m_basebandSink->setMessageQueueToWorker(m_worker->getInputMessageQueue());
m_tracker = new ADSBDemodTracker(this);
m_tracker->setExportWorker(m_worker);
m_worker->moveToThread(m_workerThread);
m_tracker->moveToThread(m_workerThread);
QObject::connect(m_workerThread, &QThread::started, m_worker, &ADSBDemodWorker::startWork);
QObject::connect(m_workerThread, &QThread::started, m_tracker, &ADSBDemodTracker::startWork);
QObject::connect(m_workerThread, &QThread::finished, m_worker, &QObject::deleteLater);
QObject::connect(m_workerThread, &QThread::finished, m_tracker, &QObject::deleteLater);
QObject::connect(m_workerThread, &QThread::finished, m_workerThread, &QThread::deleteLater);
m_workerThread->start();
// Frames are decoded by the tracker, which passes them on for export and logging
m_basebandSink->setMessageQueueToWorker(m_tracker->getInputMessageQueue());
applySettings(m_settings, QStringList(), true);
@ -93,9 +107,6 @@ ADSBDemod::ADSBDemod(DeviceAPI *devieAPI) : @@ -93,9 +107,6 @@ ADSBDemod::ADSBDemod(DeviceAPI *devieAPI) :
ADSBDemod::~ADSBDemod()
{
if (m_worker->isRunning()) {
stop();
}
QObject::disconnect(
m_networkManager,
&QNetworkAccessManager::finished,
@ -106,8 +117,21 @@ ADSBDemod::~ADSBDemod() @@ -106,8 +117,21 @@ ADSBDemod::~ADSBDemod()
m_deviceAPI->removeChannelSinkAPI(this);
m_deviceAPI->removeChannelSink(this, true);
delete m_basebandSink; // This results in a call to ADSBDemod::stop(), so need to delete before worker and thread
delete m_worker;
delete m_thread;
// Nothing pushes to the tracker any more, so the thread can go. The tracker and
// the worker delete themselves when it finishes
m_workerThread->quit();
m_workerThread->wait();
m_tracker = nullptr;
m_worker = nullptr;
}
void ADSBDemod::setMessageQueueToGUI(MessageQueue* queue)
{
ChannelAPI::setMessageQueueToGUI(queue);
m_basebandSink->setMessageQueueToGUI(queue);
m_tracker->setMessageQueueToGUI(queue);
}
void ADSBDemod::setDeviceAPI(DeviceAPI *deviceAPI)
@ -137,8 +161,6 @@ void ADSBDemod::start() @@ -137,8 +161,6 @@ void ADSBDemod::start()
{
qDebug() << "ADSBDemod::start";
m_worker->reset();
m_worker->startWork();
m_basebandSink->reset();
m_basebandSink->startWork();
m_thread->start();
@ -148,13 +170,15 @@ void ADSBDemod::start() @@ -148,13 +170,15 @@ void ADSBDemod::start()
ADSBDemodWorker::MsgConfigureADSBDemodWorker *msg = ADSBDemodWorker::MsgConfigureADSBDemodWorker::create(m_settings, QStringList(), true);
m_worker->getInputMessageQueue()->push(msg);
ADSBDemodTracker::MsgConfigureADSBDemodTracker *trackerMsg = ADSBDemodTracker::MsgConfigureADSBDemodTracker::create(m_settings, QStringList(), true);
m_tracker->getInputMessageQueue()->push(trackerMsg);
}
void ADSBDemod::stop()
{
qDebug() << "ADSBDemod::stop";
m_basebandSink->stopWork();
m_worker->stopWork();
m_thread->exit();
#ifndef __EMSCRIPTEN__
m_thread->wait();
@ -185,6 +209,8 @@ bool ADSBDemod::handleMessage(const Message& cmd) @@ -185,6 +209,8 @@ bool ADSBDemod::handleMessage(const Message& cmd)
if (m_guiMessageQueue) {
m_guiMessageQueue->push(new DSPSignalNotification(notif));
}
// And to the tracker, which needs the frequency for the reports it sends
m_tracker->getInputMessageQueue()->push(new DSPSignalNotification(notif));
return true;
}
@ -232,6 +258,9 @@ void ADSBDemod::applySettings(const ADSBDemodSettings& settings, const QStringLi @@ -232,6 +258,9 @@ void ADSBDemod::applySettings(const ADSBDemodSettings& settings, const QStringLi
ADSBDemodWorker::MsgConfigureADSBDemodWorker *workerMsg = ADSBDemodWorker::MsgConfigureADSBDemodWorker::create(settings, settingsKeys, force);
m_worker->getInputMessageQueue()->push(workerMsg);
ADSBDemodTracker::MsgConfigureADSBDemodTracker *trackerMsg = ADSBDemodTracker::MsgConfigureADSBDemodTracker::create(settings, settingsKeys, force);
m_tracker->getInputMessageQueue()->push(trackerMsg);
if (settings.m_useReverseAPI)
{
bool fullUpdate = (settingsKeys.contains("useReverseAPI") && settings.m_useReverseAPI) ||

10
plugins/channelrx/demodadsb/adsbdemod.h

@ -34,6 +34,7 @@ class QNetworkReply; @@ -34,6 +34,7 @@ class QNetworkReply;
class QThread;
class DeviceAPI;
class ADSBDemodWorker;
class ADSBDemodTracker;
class ADSBDemod : public BasebandSampleSink, public ChannelAPI {
public:
@ -174,10 +175,9 @@ public: @@ -174,10 +175,9 @@ public:
SWGSDRangel::SWGChannelSettings& response);
void getMagSqLevels(double& avg, double& peak, int& nbSamples) { m_basebandSink->getMagSqLevels(avg, peak, nbSamples); }
void setMessageQueueToGUI(MessageQueue* queue) final {
ChannelAPI::setMessageQueueToGUI(queue);
m_basebandSink->setMessageQueueToGUI(queue);
}
void setMessageQueueToGUI(MessageQueue* queue) final;
ADSBDemodTracker *getTracker() { return m_tracker; }
void setTarget(const QString& name, float targetAzimuth, float targetElevation, float targetRange);
void clearTarget() { m_targetAzElValid = false; }
@ -191,6 +191,8 @@ private: @@ -191,6 +191,8 @@ private:
DeviceAPI* m_deviceAPI;
QThread *m_thread;
ADSBDemodWorker *m_worker;
ADSBDemodTracker *m_tracker;
QThread *m_workerThread; //!< Runs the tracker and the export worker
ADSBDemodBaseband* m_basebandSink;
ADSBDemodSettings m_settings;
int m_basebandSampleRate; //!< stored from device message used when starting baseband sink

18
plugins/channelrx/demodadsb/adsbdemoddisplaydialog.cpp

@ -21,6 +21,8 @@ @@ -21,6 +21,8 @@
#endif
#include <QDebug>
#include "util/flightpathpalette.h"
#include "adsbdemoddisplaydialog.h"
ADSBDemodDisplayDialog::ADSBDemodDisplayDialog(ADSBDemodSettings *settings, QWidget* parent) :
@ -67,15 +69,15 @@ ADSBDemodDisplayDialog::ADSBDemodDisplayDialog(ADSBDemodSettings *settings, QWid @@ -67,15 +69,15 @@ ADSBDemodDisplayDialog::ADSBDemodDisplayDialog(ADSBDemodSettings *settings, QWid
}
ui->mapType->setCurrentIndex((int)settings->m_mapType);
ui->maptilerAPIKey->setText(m_settings->m_maptilerAPIKey);
ui->cartoDBAPIKey->setText(m_settings->m_cartoDBAPIKey);
ui->navAids->setChecked(settings->m_displayNavAids);
ui->atcCallsigns->setChecked(settings->m_atcCallsigns);
ui->photos->setChecked(settings->m_displayPhotos);
ui->verboseModelMatching->setChecked(settings->m_verboseModelMatching);
ui->favourLivery->setChecked(settings->m_favourLivery);
ui->useLiveryIcons->setChecked(settings->m_useLiveryIcons);
ui->transitionAltitude->setValue(settings->m_transitionAlt);
for (auto i = ADSBDemodSettings::m_palettes.cbegin(), end = ADSBDemodSettings::m_palettes.cend(); i != end; ++i) {
ui->flightPathPalette->addItem(i.key());
}
ui->flightPathPalette->addItems(FlightPathPalette::getPaletteNames());
ui->flightPathPalette->setCurrentText(settings->m_flightPathPaletteName);
}
@ -164,6 +166,11 @@ void ADSBDemodDisplayDialog::accept() @@ -164,6 +166,11 @@ void ADSBDemodDisplayDialog::accept()
m_settings->m_maptilerAPIKey = ui->maptilerAPIKey->text();
m_settingsKeys.append("maptilerAPIKey");
}
if (m_settings->m_cartoDBAPIKey != ui->cartoDBAPIKey->text())
{
m_settings->m_cartoDBAPIKey = ui->cartoDBAPIKey->text();
m_settingsKeys.append("cartoDBAPIKey");
}
if (m_settings->m_displayNavAids != ui->navAids->isChecked())
{
m_settings->m_displayNavAids = ui->navAids->isChecked();
@ -189,6 +196,11 @@ void ADSBDemodDisplayDialog::accept() @@ -189,6 +196,11 @@ void ADSBDemodDisplayDialog::accept()
m_settings->m_favourLivery = ui->favourLivery->isChecked();
m_settingsKeys.append("favourLivery");
}
if (m_settings->m_useLiveryIcons != ui->useLiveryIcons->isChecked())
{
m_settings->m_useLiveryIcons = ui->useLiveryIcons->isChecked();
m_settingsKeys.append("useLiveryIcons");
}
if (m_settings->m_transitionAlt != ui->transitionAltitude->value())
{
m_settings->m_transitionAlt = ui->transitionAltitude->value();

67
plugins/channelrx/demodadsb/adsbdemoddisplaydialog.ui

@ -277,14 +277,14 @@ @@ -277,14 +277,14 @@
</item>
</widget>
</item>
<item row="3" column="0">
<item row="4" column="0">
<widget class="QLabel" name="aircraftMinZoomLabel">
<property name="text">
<string>Zoom level for aircraft scaling</string>
</property>
</widget>
</item>
<item row="3" column="1">
<item row="4" column="1">
<widget class="QSpinBox" name="aircraftMinZoom">
<property name="toolTip">
<string>When map zoom (0 min zoom - 15 max zoom) is higher than this value, aircraft icon size will be scaled</string>
@ -294,14 +294,14 @@ @@ -294,14 +294,14 @@
</property>
</widget>
</item>
<item row="4" column="0">
<item row="5" column="0">
<widget class="QLabel" name="airportSizeLabel">
<property name="text">
<string>Display airports with size</string>
</property>
</widget>
</item>
<item row="4" column="1">
<item row="5" column="1">
<widget class="QComboBox" name="airportSize">
<property name="toolTip">
<string>Sets the minimum airport size that will be displayed on the map</string>
@ -323,14 +323,14 @@ @@ -323,14 +323,14 @@
</item>
</widget>
</item>
<item row="5" column="0">
<item row="6" column="0">
<widget class="QLabel" name="heliportsLabel">
<property name="text">
<string>Display heliports</string>
</property>
</widget>
</item>
<item row="5" column="1">
<item row="6" column="1">
<widget class="QCheckBox" name="heliports">
<property name="toolTip">
<string>When checked, heliports are displayed on the map</string>
@ -340,14 +340,14 @@ @@ -340,14 +340,14 @@
</property>
</widget>
</item>
<item row="6" column="0">
<item row="7" column="0">
<widget class="QLabel" name="airportRangeLabel">
<property name="text">
<string>Airport display distance (km)</string>
</property>
</widget>
</item>
<item row="6" column="1">
<item row="7" column="1">
<widget class="QSpinBox" name="airportRange">
<property name="toolTip">
<string>Displays airports within the specified distance in kilometres from My Position</string>
@ -357,14 +357,14 @@ @@ -357,14 +357,14 @@
</property>
</widget>
</item>
<item row="7" column="0">
<item row="8" column="0">
<widget class="QLabel" name="airspacesLabel">
<property name="text">
<string>Airspaces to display</string>
</property>
</widget>
</item>
<item row="7" column="1">
<item row="8" column="1">
<widget class="QListWidget" name="airspaces">
<property name="toolTip">
<string>Airspace categories to display</string>
@ -521,14 +521,14 @@ @@ -521,14 +521,14 @@
</item>
</widget>
</item>
<item row="8" column="0">
<item row="9" column="0">
<widget class="QLabel" name="airspaceRangeLabel">
<property name="text">
<string>Airspace display distance (km)</string>
</property>
</widget>
</item>
<item row="8" column="1">
<item row="9" column="1">
<widget class="QSpinBox" name="airspaceRange">
<property name="toolTip">
<string>Displays airspace within the specified distance in kilometres from My Position</string>
@ -538,14 +538,14 @@ @@ -538,14 +538,14 @@
</property>
</widget>
</item>
<item row="9" column="0">
<item row="10" column="0">
<widget class="QLabel" name="displayNavAids">
<property name="text">
<string>Display NAVAIDs</string>
</property>
</widget>
</item>
<item row="9" column="1">
<item row="10" column="1">
<widget class="QCheckBox" name="navAids">
<property name="toolTip">
<string>Display NAVAIDs such as VORs and NDBs</string>
@ -555,7 +555,7 @@ @@ -555,7 +555,7 @@
</property>
</widget>
</item>
<item row="10" column="1">
<item row="11" column="1">
<widget class="QCheckBox" name="atcCallsigns">
<property name="toolTip">
<string>Use ATC callsigns (SPEEDBIRD) rather than ICAO (BAW) for aircraft labels on map</string>
@ -565,21 +565,21 @@ @@ -565,21 +565,21 @@
</property>
</widget>
</item>
<item row="10" column="0">
<item row="11" column="0">
<widget class="QLabel" name="atcCallsignsLabel">
<property name="text">
<string>Use ATC callsigns on map</string>
</property>
</widget>
</item>
<item row="11" column="1">
<item row="12" column="1">
<widget class="QComboBox" name="flightPathPalette">
<property name="toolTip">
<string>Colour palette to use for aircraft flight paths</string>
</property>
</widget>
</item>
<item row="11" column="0">
<item row="12" column="0">
<widget class="QLabel" name="flightPathPaletteLabel">
<property name="text">
<string>Flight path palette</string>
@ -603,6 +603,37 @@ @@ -603,6 +603,37 @@
</property>
</widget>
</item>
<item row="3" column="0">
<widget class="QLabel" name="cartoDBAPIKeyLabel">
<property name="text">
<string>CartoDB API key</string>
</property>
</widget>
</item>
<item row="3" column="1">
<widget class="QLineEdit" name="cartoDBAPIKey">
<property name="toolTip">
<string>API key for CartoDB (https://carto.com), used by the aviation maps. Leave blank to use the built in key</string>
</property>
</widget>
</item>
<item row="13" column="0">
<widget class="QLabel" name="useLiveryIconsLabel">
<property name="text">
<string>Livery aircraft icons</string>
</property>
</widget>
</item>
<item row="13" column="1">
<widget class="QCheckBox" name="useLiveryIcons">
<property name="toolTip">
<string>Display aircraft icons showing airline liveries, matched from the aircraft type and operator, instead of black icons</string>
</property>
<property name="text">
<string/>
</property>
</widget>
</item>
</layout>
</item>
</layout>

6475
plugins/channelrx/demodadsb/adsbdemodgui.cpp

File diff suppressed because it is too large Load Diff

708
plugins/channelrx/demodadsb/adsbdemodgui.h

@ -20,6 +20,9 @@ @@ -20,6 +20,9 @@
#define INCLUDE_ADSBDEMODGUI_H
#include <QTableWidgetItem>
#include <QSortFilterProxyModel>
#include <QVariant>
#include <QIcon>
#include <QMenu>
#include <QGeoCoordinate>
#include <QDateTime>
@ -31,6 +34,9 @@ @@ -31,6 +34,9 @@
#include <QPointer>
#include <QtCharts>
#include "adsbaircraft.h"
#include "adsbaircrafttablemodel.h"
#include "adsbdemodtracker.h"
#include "channel/channelgui.h"
#include "dsp/dsptypes.h"
#include "dsp/channelmarker.h"
@ -69,122 +75,10 @@ namespace Ui { @@ -69,122 +75,10 @@ namespace Ui {
using namespace QtCharts;
#endif
// Custom widget to allow formatted decimal numbers to be sorted numerically
class CustomDoubleTableWidgetItem : public QTableWidgetItem
{
public:
CustomDoubleTableWidgetItem(const QString text = QString("")) :
QTableWidgetItem(text)
{
}
bool operator <(const QTableWidgetItem& other) const
{
// Treat "" as less than 0
QString thisText = text();
QString otherText = other.text();
if (thisText == "")
return true;
if (otherText == "")
return false;
return thisText.toDouble() < otherText.toDouble();
}
};
// Data about an aircraft extracted from ADS-B and Mode-S frames
struct Aircraft {
int m_icao; // 24-bit ICAO aircraft address
QString m_icaoHex;
QString m_callsign; // Flight callsign
QString m_flight; // Guess at flight number
bool m_globalPosition; // Position has been determined from global decode
Real m_latitude; // Latitude in decimal degrees
Real m_longitude; // Longitude in decimal degrees
float m_radius; // Horizontal containment radius limit (Rc) in metres
int m_altitude; // Altitude in feet (will be 0 if on surface)
int m_pressureAltitude; // Pressure altitude in feet for Map PFD altimeter (can be negative on surface)
bool m_onSurface; // Indicates if on surface or airborne
bool m_altitudeGNSS; // Altitude is GNSS HAE (Height above WGS-84 ellipsoid) rather than barometric alitute (relative to 29.92 Hg)
float m_heading; // Heading in degrees magnetic
float m_track; // Track in degrees true?
int m_verticalRate; // Vertical climb rate in ft/min
QString m_emitterCategory; // Aircraft type
QString m_status; // Aircraft status
int m_squawk; // Mode-A code
bool m_spi; // Special position identification (IDENT) active
Real m_range; // Distance from station to aircraft
Real m_azimuth; // Azimuth from station to aircraft
Real m_elevation; // Elevation from station to aircraft
QDateTime m_rxTime; // When last frame received (can be long ago if reading from log file)
QDateTime m_updateTime; // Last time we updated data for this aircraft (used for determining when to remove an aircraft)
int m_selAltitude; // Selected altitude in MCP/FCU or FMS in feet
int m_selHeading; // Selected heading in MCP/FCU in degrees
float m_baro; // Aircraft baro setting in mb (Mode-S)
float m_roll; // In degrees
int m_groundspeed; // In knots
float m_turnRate; // In degrees per second
int m_trueAirspeed; // In knots
int m_indicatedAirspeed; // In knots
float m_mach; // Mach number
bool m_autopilot;
bool m_vnavMode;
bool m_altHoldMode;
bool m_approachMode;
bool m_lnavMode;
bool m_tcasOperational; // Appears only to be true if TA/RA, false if TA ONLY
bool m_bdsCapabilities[16][16]; // BDS capabilities are indicaited by BDS 1.7
int m_adsbVersion;
bool m_nicSupplementA;
bool m_nicSupplementB;
bool m_nicSupplementC;
bool m_positionValid; // Indicates if we have valid data for the above fields
bool m_altitudeValid;
bool m_pressureAltitudeValid;
bool m_onSurfaceValid;
bool m_headingValid;
bool m_trackValid;
bool m_verticalRateValid;
bool m_selAltitudeValid;
bool m_selHeadingValid;
bool m_baroValid;
bool m_rollValid;
bool m_groundspeedValid;
bool m_turnRateValid;
bool m_trueAirspeedValid;
bool m_indicatedAirspeedValid;
bool m_machValid;
bool m_autopilotValid;
bool m_vnavModeValid;
bool m_altHoldModeValid;
bool m_approachModeValid;
bool m_lnavModeValid;
bool m_tcasOperationalValid;
bool m_bdsCapabilitiesValid;
bool m_adsbVersionValid;
bool m_nicSupplementAValid;
bool m_nicSupplementBValid;
bool m_nicSupplementCValid;
// State for calculating position using two CPR frames
bool m_cprValid[2];
double m_cprLat[2];
double m_cprLong[2];
QDateTime m_cprTime[2];
int m_adsbFrameCount; // Number of ADS-B frames for this aircraft
int m_modesFrameCount; // Number of Mode-S frames for this aircraft
int m_nonTransponderFrameCount;
int m_tisBFrameCount;
int m_adsrFrameCount;
float m_minCorrelation;
float m_maxCorrelation;
float m_correlation;
MovingAverageUtil<float, double, 100> m_correlationAvg;
// The aircraft as the GUI needs it: the decoded state, plus the flight path shown on
// the map and the icons shown in the table
struct Aircraft : ADSBAircraft {
// Selection state, which belongs to the user rather than to the decoder
bool m_isTarget; // Are we targeting this aircraft (sending az/el to rotator)
bool m_isHighlighted; // Are we highlighting this aircraft in the table and map
bool m_showAll;
@ -196,325 +90,20 @@ struct Aircraft { @@ -196,325 +90,20 @@ struct Aircraft {
QList<int> m_recentCoordinateColors;
int m_lastColor;
AircraftInformation *m_aircraftInfo; // Info about the aircraft from the database
QString m_aircraft3DModel; // 3D model for map based on aircraft type
QString m_aircraftCat3DModel; // 3D model based on aircraft category
float m_modelAltitudeOffset; // Altitude adjustment so aircraft model doesn't go underground
float m_labelAltitudeOffset; // How height to position label above aircraft
ADSBDemodGUI *m_gui;
QString m_flagIconURL;
QString m_airlineIconURL;
QString m_sideviewIconURL;
// For animation on 3D map
float m_runwayAltitude;
bool m_runwayAltitudeValid;
bool m_gearDown;
float m_flaps; // 0 - no flaps, 1 - full flaps
bool m_rotorStarted; // Rotors started on 'Rotorcraft'
bool m_engineStarted; // Engines started (typically propellors)
QDateTime m_positionDateTime;
QDateTime m_orientationDateTime; // FIXME
QDateTime m_headingDateTime;
QDateTime m_trackDateTime;
QDateTime m_altitudeDateTime;
QDateTime m_indicatedAirspeedDateTime;
QDateTime m_prevTrackDateTime;
int m_prevTrack;
float m_trackWhenHeadingSet;
float m_pitchEst; // Estimated pitch based on vertical rate
float m_rollEst; // Estimated roll based on rate of change in heading
bool m_notified; // Set when a notification has been made for this aircraft, so we don't repeat it
// GUI table items for above data
QTableWidgetItem *m_icaoItem;
QTableWidgetItem *m_callsignItem;
QTableWidgetItem* m_atcCallsignItem;
QTableWidgetItem *m_modelItem;
QTableWidgetItem *m_typeItem;
QTableWidgetItem *m_sideviewItem;
QTableWidgetItem *m_airlineItem;
QTableWidgetItem *m_latitudeItem;
QTableWidgetItem *m_longitudeItem;
QTableWidgetItem *m_altitudeItem;
QTableWidgetItem *m_headingItem;
QTableWidgetItem *m_trackItem;
QTableWidgetItem *m_verticalRateItem;
CustomDoubleTableWidgetItem *m_rangeItem;
QTableWidgetItem *m_azElItem;
QTableWidgetItem *m_emitterCategoryItem;
QTableWidgetItem *m_statusItem;
QTableWidgetItem *m_squawkItem;
QTableWidgetItem *m_identItem;
QTableWidgetItem *m_registrationItem;
QTableWidgetItem *m_countryItem;
QTableWidgetItem *m_registeredItem;
QTableWidgetItem *m_manufacturerNameItem;
QTableWidgetItem *m_ownerItem;
QTableWidgetItem *m_operatorICAOItem;
QTableWidgetItem *m_interogatorCodeItem;
QTableWidgetItem *m_timeItem;
QTableWidgetItem *m_totalFrameCountItem;
QTableWidgetItem *m_adsbFrameCountItem;
QTableWidgetItem *m_modesFrameCountItem;
QTableWidgetItem *m_nonTransponderItem;
QTableWidgetItem *m_tisBFrameCountItem;
QTableWidgetItem *m_adsrFrameCountItem;
QTableWidgetItem *m_radiusItem;
QTableWidgetItem *m_nacpItem;
QTableWidgetItem *m_nacvItem;
QTableWidgetItem *m_gvaItem;
QTableWidgetItem *m_nicItem;
QTableWidgetItem *m_nicBaroItem;
QTableWidgetItem *m_silItem;
QTableWidgetItem *m_correlationItem;
QTableWidgetItem *m_rssiItem;
QTableWidgetItem *m_flightStatusItem;
QTableWidgetItem *m_depItem;
QTableWidgetItem *m_arrItem;
QTableWidgetItem *m_stopsItem;
QTableWidgetItem *m_stdItem;
QTableWidgetItem *m_etdItem;
QTableWidgetItem *m_atdItem;
QTableWidgetItem *m_staItem;
QTableWidgetItem *m_etaItem;
QTableWidgetItem *m_ataItem;
QTableWidgetItem *m_selAltitudeItem;
QTableWidgetItem *m_selHeadingItem;
QTableWidgetItem *m_baroItem;
QTableWidgetItem *m_apItem;
QTableWidgetItem *m_vModeItem;
QTableWidgetItem *m_lModeItem;
QTableWidgetItem *m_tcasItem;
QTableWidgetItem *m_acasItem;
QTableWidgetItem *m_raItem;
QTableWidgetItem *m_maxSpeedItem;
QTableWidgetItem *m_versionItem;
QTableWidgetItem *m_lengthItem;
QTableWidgetItem *m_widthItem;
QTableWidgetItem *m_rollItem;
QTableWidgetItem *m_groundspeedItem;
QTableWidgetItem *m_turnRateItem;
QTableWidgetItem *m_trueAirspeedItem;
QTableWidgetItem *m_indicatedAirspeedItem;
QTableWidgetItem *m_machItem;
QTableWidgetItem *m_headwindItem;
QTableWidgetItem *m_estAirTempItem;
QTableWidgetItem *m_windSpeedItem;
QTableWidgetItem *m_windDirItem;
QTableWidgetItem *m_staticPressureItem;
QTableWidgetItem *m_staticAirTempItem;
QTableWidgetItem *m_humidityItem;
Aircraft(ADSBDemodGUI *gui) :
m_icao(0),
m_globalPosition(false),
m_latitude(0),
m_longitude(0),
m_radius(0.0f),
m_altitude(0),
m_pressureAltitude(0),
m_onSurface(false),
m_altitudeGNSS(false),
m_heading(0),
m_track(0),
m_verticalRate(0),
m_squawk(0),
m_spi(false),
m_range(0.0f),
m_azimuth(0),
m_elevation(0),
m_selAltitude(0),
m_selHeading(0),
m_baro(0),
m_roll(0.0f),
m_groundspeed(0),
m_turnRate(0.0f),
m_trueAirspeed(0),
m_indicatedAirspeed(0),
m_mach(0.0f),
m_autopilot(false),
m_vnavMode(false),
m_altHoldMode(false),
m_approachMode(false),
m_lnavMode(false),
m_tcasOperational(false),
m_adsbVersion(0),
m_nicSupplementA(false),
m_nicSupplementB(false),
m_nicSupplementC(false),
m_positionValid(false),
m_altitudeValid(false),
m_pressureAltitudeValid(false),
m_onSurfaceValid(false),
m_headingValid(false),
m_trackValid(false),
m_verticalRateValid(false),
m_selAltitudeValid(false),
m_selHeadingValid(false),
m_baroValid(false),
m_rollValid(false),
m_groundspeedValid(false),
m_turnRateValid(false),
m_trueAirspeedValid(false),
m_indicatedAirspeedValid(false),
m_machValid(false),
m_autopilotValid(false),
m_vnavModeValid(false),
m_altHoldModeValid(false),
m_approachModeValid(false),
m_lnavModeValid(false),
m_tcasOperationalValid(false),
m_bdsCapabilitiesValid(false),
m_adsbVersionValid(false),
m_nicSupplementAValid(false),
m_nicSupplementBValid(false),
m_nicSupplementCValid(false),
m_adsbFrameCount(0),
m_modesFrameCount(0),
m_nonTransponderFrameCount(0),
m_tisBFrameCount(0),
m_adsrFrameCount(0),
m_minCorrelation(INFINITY),
m_maxCorrelation(-INFINITY),
m_correlation(0.0f),
m_isTarget(false),
m_isHighlighted(false),
m_showAll(false),
m_lastColor(-1),
m_aircraftInfo(nullptr),
m_modelAltitudeOffset(0.0f),
m_labelAltitudeOffset(5.0f),
m_gui(gui),
m_runwayAltitude(0.0),
m_runwayAltitudeValid(false),
m_gearDown(false),
m_flaps(0.0),
m_rotorStarted(false),
m_engineStarted(false),
m_prevTrack(0),
m_trackWhenHeadingSet(0.0f),
m_pitchEst(0.0),
m_rollEst(0.0),
m_notified(false)
m_gui(gui)
{
for (int i = 0; i < 2; i++) {
m_cprValid[i] = false;
m_cprLat[i] = 0.0;
m_cprLong[i] = 0.0;
}
for (int i = 0; i < 16; i++) {
for (int j = 0; j < 16; j++) {
m_bdsCapabilities[i][j] = false;
}
}
// These are deleted by QTableWidget
m_icaoItem = new QTableWidgetItem();
m_callsignItem = new QTableWidgetItem();
m_atcCallsignItem = new QTableWidgetItem();
m_modelItem = new QTableWidgetItem();
m_typeItem = new QTableWidgetItem();
m_sideviewItem = new QTableWidgetItem();
m_airlineItem = new QTableWidgetItem();
m_altitudeItem = new QTableWidgetItem();
m_headingItem = new QTableWidgetItem();
m_trackItem = new QTableWidgetItem();
m_verticalRateItem = new QTableWidgetItem();
m_rangeItem = new CustomDoubleTableWidgetItem();
m_azElItem = new QTableWidgetItem();
m_latitudeItem = new QTableWidgetItem();
m_longitudeItem = new QTableWidgetItem();
m_emitterCategoryItem = new QTableWidgetItem();
m_statusItem = new QTableWidgetItem();
m_squawkItem = new QTableWidgetItem();
m_identItem = new QTableWidgetItem();
m_registrationItem = new QTableWidgetItem();
m_countryItem = new QTableWidgetItem();
m_registeredItem = new QTableWidgetItem();
m_manufacturerNameItem = new QTableWidgetItem();
m_ownerItem = new QTableWidgetItem();
m_operatorICAOItem = new QTableWidgetItem();
m_interogatorCodeItem = new QTableWidgetItem();
m_timeItem = new QTableWidgetItem();
m_totalFrameCountItem = new QTableWidgetItem();
m_adsbFrameCountItem = new QTableWidgetItem();
m_modesFrameCountItem = new QTableWidgetItem();
m_nonTransponderItem = new QTableWidgetItem();
m_tisBFrameCountItem = new QTableWidgetItem();
m_adsrFrameCountItem = new QTableWidgetItem();
m_radiusItem = new QTableWidgetItem();
m_nacpItem = new QTableWidgetItem();
m_nacvItem = new QTableWidgetItem();
m_gvaItem = new QTableWidgetItem();
m_nicItem = new QTableWidgetItem();
m_nicBaroItem = new QTableWidgetItem();
m_silItem = new QTableWidgetItem();
m_correlationItem = new QTableWidgetItem();
m_rssiItem = new QTableWidgetItem();
m_flightStatusItem = new QTableWidgetItem();
m_depItem = new QTableWidgetItem();
m_arrItem = new QTableWidgetItem();
m_stopsItem = new QTableWidgetItem();
m_stdItem = new QTableWidgetItem();
m_etdItem = new QTableWidgetItem();
m_atdItem = new QTableWidgetItem();
m_staItem = new QTableWidgetItem();
m_etaItem = new QTableWidgetItem();
m_ataItem = new QTableWidgetItem();
m_selAltitudeItem = new QTableWidgetItem();
m_selHeadingItem = new QTableWidgetItem();
m_baroItem = new QTableWidgetItem();
m_apItem = new QTableWidgetItem();
m_vModeItem = new QTableWidgetItem();
m_lModeItem = new QTableWidgetItem();
m_tcasItem = new QTableWidgetItem();
m_acasItem = new QTableWidgetItem();
m_raItem = new QTableWidgetItem();
m_maxSpeedItem = new QTableWidgetItem();
m_versionItem = new QTableWidgetItem();
m_lengthItem = new QTableWidgetItem();
m_widthItem = new QTableWidgetItem();
m_rollItem = new QTableWidgetItem();
m_groundspeedItem = new QTableWidgetItem();
m_turnRateItem = new QTableWidgetItem();
m_trueAirspeedItem = new QTableWidgetItem();
m_indicatedAirspeedItem = new QTableWidgetItem();
m_machItem = new QTableWidgetItem();
m_headwindItem = new QTableWidgetItem();
m_estAirTempItem = new QTableWidgetItem();
m_windSpeedItem = new QTableWidgetItem();
m_windDirItem = new QTableWidgetItem();
m_staticPressureItem = new QTableWidgetItem();
m_staticAirTempItem = new QTableWidgetItem();
m_humidityItem = new QTableWidgetItem();
}
Aircraft(const Aircraft&) = delete;
Aircraft& operator=(const Aircraft&) = delete;
QString getImage() const;
QString getText(const ADSBDemodSettings *settings, bool all=false) const;
// Label to use for aircraft on map
QString getLabel(const ADSBDemodSettings *settings, QDateTime& dateTime) const;
// Name to use when selected as a target (E.g. for use as target name in Rotator Controller)
QString targetName() const
{
if (!m_callsign.isEmpty())
return QString("Callsign: %1").arg(m_callsign);
else
return QString("ICAO: %1").arg(m_icao, 0, 16);
}
void setOnSurface(const QDateTime& dateTime);
void setAltitude(int altitudeFt, bool gnss, const QDateTime& dateTime, const ADSBDemodSettings& settings);
void setVerticalRate(int verticalRate, const ADSBDemodSettings& settings);
void setGroundspeed(float groundspeed, const ADSBDemodSettings& settings);
void setTrueAirspeed(int airspeed, const ADSBDemodSettings& settings);
void setIndicatedAirspeed(int airspeed, const QDateTime& dateTime, const ADSBDemodSettings& settings);
void setTrack(float track, const QDateTime& dateTime);
void setHeading(float heading, const QDateTime& dateTime);
void addCoordinate(const QDateTime& dateTime, AircraftModel *model);
void addCoordinate(const ADSBAircraftPosition& position, AircraftModel *model);
void clearCoordinates(AircraftModel *model);
};
@ -1087,67 +676,6 @@ private: @@ -1087,67 +676,6 @@ private:
// Match 3D models to Opensky-Network Aircraft database
// The database doesn't use consistent names for aircraft, so we use regexps
class ModelMatch {
public:
ModelMatch(const QString &aircraftRegExp, const QString &model) :
m_aircraftRegExp(aircraftRegExp),
m_model(model)
{
m_aircraftRegExp.optimize();
}
virtual ~ModelMatch() = default;
virtual bool match(const QString &aircraft, const QString &manufacturer, QString &model)
{
(void) manufacturer;
QRegularExpressionMatch match = m_aircraftRegExp.match(aircraft);
if (match.hasMatch())
{
model = m_model;
return true;
}
else
{
return false;
}
}
protected:
QRegularExpression m_aircraftRegExp;
QString m_model;
};
// For very generic aircraft names, also match against manufacturer name
class ManufacturerModelMatch : public ModelMatch {
public:
ManufacturerModelMatch(const QString &modelRegExp, const QString &manufacturerRegExp, const QString &model) :
ModelMatch(modelRegExp, model),
m_manufacturerRegExp(manufacturerRegExp)
{
m_manufacturerRegExp.optimize();
}
virtual bool match(const QString &aircraft, const QString &manufacturer, QString &model) override
{
QRegularExpressionMatch matchManufacturer = m_manufacturerRegExp.match(manufacturer);
if (matchManufacturer.hasMatch())
{
QRegularExpressionMatch matchAircraft = m_aircraftRegExp.match(aircraft);
if (matchAircraft.hasMatch())
{
model = m_model;
return true;
}
}
return false;
}
protected:
QRegularExpression m_manufacturerRegExp;
};
class ADSBDemodGUI : public ChannelGUI {
Q_OBJECT
@ -1199,15 +727,10 @@ public: @@ -1199,15 +727,10 @@ public:
bool setFrequency(qint64 frequency);
bool useSIUints() const { return m_settings.m_siUnits; }
Q_INVOKABLE void clearHighlighted();
QString get3DModel(const QString &aircraft, const QString &operatorICAO) const;
QString get3DModel(const QString &aircraft);
void get3DModel(Aircraft *aircraft);
void get3DModelBasedOnCategory(Aircraft *aircraft);
public slots:
void channelMarkerChangedByCursor();
void channelMarkerHighlightedByCursor();
void flightInformationUpdated(const FlightInformation::Flight& flight);
void aircraftPhoto(const PlaneSpottersPhoto *photo);
private:
@ -1224,14 +747,29 @@ private: @@ -1224,14 +747,29 @@ private:
bool m_doApplySettings;
ADSBDemod* m_adsbDemod;
public:
QString mapItemName(const Aircraft *aircraft) const;
private:
uint32_t m_tickCount;
MessageQueue m_inputMessageQueue;
QHash<int, Aircraft *> m_aircraft; // Hashed on ICAO
QSharedPointer<const QHash<int, AircraftInformation *>> m_aircraftInfo;
QSharedPointer<const QHash<QString, AircraftRouteInformation *>> m_routeInfo; // Hashed on callsign
QSharedPointer<const QHash<int, AirportInformation *>> m_airportInfo; // Hashed on id
AircraftModel m_aircraftModel;
AircraftModel m_aircraftModel; // Aircraft on the map
ADSBAircraftTableModel m_aircraftTableModel;
ADSBAircraftSortProxy *m_aircraftProxy;
// The GUI's copy of the aircraft, kept up to date by the tracker
QHash<int, Aircraft *> m_aircraft; // Hashed on ICAO
Aircraft *m_trackAircraft; // Aircraft being sent to a rotator
AzEl m_azEl; // Position of station, for the map overlays
QSharedPointer<const QHash<int, AircraftInformation *>> m_aircraftInfo;
QSharedPointer<const QHash<QString, AircraftRouteInformation *>> m_routeInfo;
Airspace m_coverageAirspace[2];
Interogator m_interogators[ADSB_IC_MAX];
bool m_loadingData;
// Aircraft whose map marker needs redrawing. Telling the QML model on every frame
// makes it re-evaluate bindings and repaint far more often than the eye can use
QSet<Aircraft *> m_dirtyMapAircraft;
AirportModel m_airportModel;
AirspaceModel m_airspaceModel;
NavAidModel m_navAidModel;
@ -1239,11 +777,6 @@ private: @@ -1239,11 +777,6 @@ private:
QSharedPointer<const QList<NavAid *>> m_navAids;
QGeoCoordinate m_lastFullUpdatePosition;
AzEl m_azEl; // Position of station
Aircraft *m_trackAircraft; // Aircraft we want to track in Channel Report
MovingAverageUtil<float, double, 10> m_correlationAvg;
MovingAverageUtil<float, double, 10> m_correlationOnesAvg;
MovingAverageUtil<float, double, 100> m_qnhAvg;
Aircraft *m_highlightAircraft; // Aircraft we want to highlight, when selected in table
@ -1251,68 +784,9 @@ private: @@ -1251,68 +784,9 @@ private:
ADSBDemodSettings::AirportType m_currentAirportMinimumSize;
bool m_currentDisplayHeliports;
static const int m_maxRangeDeg = 5;
QList<float> m_maxRange[2];
Airspace m_coverageAirspace[2];
Interogator m_interogators[ADSB_IC_MAX];
enum StatsRow {
ADSB_FRAMES,
MODE_S_FRAMES,
TOTAL_FRAMES,
ADSB_RATE,
MODE_S_RATE,
TOTAL_RATE,
DATA_RATE,
CORRELATOR_MATCHES,
PERCENT_VALID,
PREAMBLE_FAILS,
CRC_FAILS,
TYPE_FAILS,
INVALID_FAILS,
ICAO_FAILS,
RANGE_FAILS,
ALT_FAILS,
AVERAGE_CORRELATION,
TC_0,
TC_1_4,
TC_5_8,
TC_9_18,
TC_19,
TC_20_22,
TC_24,
TC_28,
TC_29,
TC_31,
TC_UNUSED,
DF0,
DF4,
DF5,
DF11,
DF16,
DF17,
DF18,
DF19,
DF20_21,
DF22,
DF24,
MAX_RANGE,
MAX_ALTITUDE,
MAX_RATE
};
qint64 m_rangeFails;
qint64 m_altFails;
QDateTime m_frameRateTime;
qint64 m_adsbFrameRateCount;
qint64 m_modesFrameRateCount;
qint64 m_totalBytes;
float m_maxRangeStat;
float m_maxAltitudeStat;
float m_maxRateState;
qint64 m_dfStats[32];
qint64 m_tcStats[32];
QChart *m_chart;
QLineSeries *m_adsbFrameRateSeries;
QLineSeries *m_modesFrameRateSeries;
@ -1326,7 +800,6 @@ private: @@ -1326,7 +800,6 @@ private:
QTextToSpeech *m_speech;
#endif
QMenu *menu; // Column select context menu
FlightInformation *m_flightInformation;
PlaneSpotters m_planeSpotters;
AviationWeather *m_aviationWeather;
QString m_photoLink;
@ -1337,38 +810,16 @@ private: @@ -1337,38 +810,16 @@ private:
OsnDB m_osnDB;
OurAirportsDB m_ourAirportsDB;
ADSBOSMTemplateServer *m_templateServer;
QRandomGenerator m_random;
QHash<QString, QString> m_3DModels; // Hashed aircraft_icao or just aircraft
QHash<QString, QStringList> m_3DModelsByType; // Hashed aircraft to list of all of that type
QList<ModelMatch *> m_3DModelMatch; // Map of database aircraft names to 3D model names
QHash<QString, float> m_modelAltitudeOffset;
QHash<QString, float> m_labelAltitudeOffset;
QTimer m_importTimer;
QTimer m_redrawMapTimer;
QNetworkAccessManager *m_networkManager;
QPointer<QNetworkReply> m_importTokenReply;
QPointer<QNetworkReply> m_importStatesReply;
QString m_importAccessToken;
QDateTime m_importAccessTokenExpiry;
int m_importRequestGeneration;
bool m_importAuthenticationRetry;
bool m_loadingData;
static const char m_idMap[];
static const QString m_categorySetA[];
static const QString m_categorySetB[];
static const QString m_categorySetC[];
static const QString m_emergencyStatus[];
static const QString m_flightStatuses[];
static const QString m_hazardSeverity[];
static const QString m_fomSources[];
static const QString m_nacvStrings[];
explicit ADSBDemodGUI(PluginAPI* pluginAPI, DeviceUISet *deviceUISet, BasebandSampleSink *rxChannel, QWidget* parent = 0);
virtual ~ADSBDemodGUI();
QString maptilerAPIKey() const;
QString cartoDBAPIKey() const;
void blockApplySettings(bool block);
void applySetting(const QString& settingsKey);
@ -1379,95 +830,36 @@ private: @@ -1379,95 +830,36 @@ private:
void makeUIConnections();
void updateAbsoluteCenterFrequency();
void clearFromMap(const QString& name);
void sendToMap(Aircraft *aircraft, QList<SWGSDRangel::SWGMapAnimation *> *animations);
Aircraft *getAircraft(int icao, bool &newAircraft);
void atcCallsign(Aircraft *aircraft);
void callsignToFlight(Aircraft *aircraft);
int roundTo50Feet(int alt);
bool calcAirTemp(Aircraft *aircraft);
void handleADSB(
const QByteArray data,
const QDateTime dateTime,
float correlation,
float correlationOnes,
unsigned crc,
bool updateModel);
void decodeID(const QByteArray& data, QString& emitterCategory, QString& callsign);
bool decodeGroundspeed(const QByteArray& data, float& v, float& h);
bool decodeAirspeed(const QByteArray& data, bool& tas, int& as, bool& hdgValid, float& hdg);
bool decodeVerticalRate(const QByteArray& data, int& verticalRate);
void updateAircraftPosition(Aircraft *aircraft, double latitude, double longitude, const QDateTime& dateTime);
bool validateGlobalPosition(double latitude, double longitude, bool countFailure);
bool validateLocalPosition(double latitude, double longitude, bool surfacePosition, bool countFailure);
bool decodeGlobalPosition(int f, const double cprLat[2], const double cprLong[2], const QDateTime cprTime[2], double& latitude, double& longitude, bool countFailure);
bool decodeLocalPosition(int f, double cprLat, double cprLong, bool onSurface, const Aircraft *aircraft, double& latitude, double& longitude, bool countFailure);
void decodeCpr(const QByteArray& data, int& f, double& latCpr, double& lonCpr) const;
bool decodeAltitude(const QByteArray& data, int& altFt) const;
void decodeModeSAltitude(const QByteArray& data, const QDateTime dateTime, Aircraft *aircraft);
void decodeModeS(const QByteArray data, const QDateTime dateTime, int df, Aircraft *aircraft);
void decodeCommB(const QByteArray data, const QDateTime dateTime, int df, Aircraft *aircraft, bool &updatedCallsign);
QList<SWGSDRangel::SWGMapAnimation *> *animate(QDateTime dateTime, Aircraft *aircraft);
SWGSDRangel::SWGMapAnimation *gearAnimation(QDateTime startDateTime, bool up);
SWGSDRangel::SWGMapAnimation *gearAngle(QDateTime startDateTime, bool flat);
SWGSDRangel::SWGMapAnimation *flapsAnimation(QDateTime startDateTime, float currentFlaps, float flaps);
SWGSDRangel::SWGMapAnimation *slatsAnimation(QDateTime startDateTime, bool retract);
SWGSDRangel::SWGMapAnimation *rotorAnimation(QDateTime startDateTime, bool stop);
SWGSDRangel::SWGMapAnimation *engineAnimation(QDateTime startDateTime, int engine, bool stop);
void checkStaticNotification(Aircraft *aircraft);
void checkDynamicNotification(Aircraft *aircraft);
void enableSpeechIfNeeded();
void speechNotification(Aircraft *aircraft, const QString &speech);
void commandNotification(Aircraft *aircraft, const QString &command);
QString subAircraftString(Aircraft *aircraft, const QString &string);
void resizeTable();
Aircraft *aircraftForViewRow(int viewRow) const;
void removeAircraft(QHash<int, Aircraft *>::iterator& i, Aircraft *aircraft);
void initCoverageDisplay();
Aircraft *findAircraft(quint32 icao) const { return m_aircraft.value((int) icao, nullptr); }
void flushMapUpdates();
QString getDataDir();
void update3DModels();
void updateAirports();
void updateAirspaces();
void updateNavAids();
void updateChannelList();
void removeAircraft(QHash<int, Aircraft *>::iterator& i, Aircraft *aircraft);
QAction *createCheckableItem(QString& text, int idx, bool checked);
Aircraft* findAircraftByFlight(const QString& flight);
QString dataTimeToShortString(QDateTime dt);
void initFlightInformation();
void initAviationWeather();
void setShowContainmentRadius(bool show);
void applyMapSettings();
void clearStaleTileCache(const QString& cachePath);
void updatePhotoText(Aircraft *aircraft);
void updatePhotoFlightInformation(Aircraft *aircraft);
void findOnChannelMap(Aircraft *aircraft);
int squawkDecode(int code) const;
int gillhamToFeet(int n) const;
int grayToBinary(int gray, int bits) const;
void redrawMap();
void applyImportSettings();
bool importCredentialsConfigured() const;
bool importAccessTokenValid() const;
void invalidateImportAuthentication();
void requestImportAccessToken();
void sendImportRequest();
void handleImportTokenReply(QNetworkReply *reply);
void sendAircraftReport();
void updatePosition(float latitude, float longitude, float altitude);
void clearOldHeading(Aircraft *aircraft, const QDateTime& dateTime, float newTrack);
void updateQNH(const Aircraft *aircraft, float qnh);
void setCallsign(Aircraft *aircraft, const QString& callsign);
void initCoverageMap();
void clearCoverageMap();
void updateCoverageMap(float azimuth, float elevation, float distance, float altitude);
void leaveEvent(QEvent*);
void enterEvent(EnterEventType*);
void updateDFStats(int df);
bool updateTCStats(int tc, int row, int low, int high);
void resetStats();
void plotChart();
int countActiveAircraft();
void averageSeries(QLineSeries *series, const QDateTime& startTime, const QDateTime& endTime);
void legendMarkerClicked();
@ -1480,8 +872,20 @@ private slots: @@ -1480,8 +872,20 @@ private slots:
void on_tapsPerPhase_valueChanged(int value);
void statsTable_customContextMenuRequested(QPoint pos);
void adsbData_customContextMenuRequested(QPoint point);
void on_adsbData_cellClicked(int row, int column);
void on_adsbData_cellDoubleClicked(int row, int column);
// Fed by the tracker, which does the decoding on the channel's worker thread
void aircraftUpdated(const QList<ADSBAircraftUpdate>& updates);
void aircraftRemoved(const QList<quint32>& icaos);
void statsUpdated(const QHash<int, QVariant>& stats);
void coverageUpdated(int band, const QVector<QPointF>& polygon);
void qnhEstimate(int qnh);
void speechRequest(const QString& speech);
void highlightRequest(quint32 icao);
void targetRequest(quint32 icao);
void photoRefresh(quint32 icao);
void rates(double adsbRate, double modesRate, int activeAircraft);
void adsbData_clicked(const QModelIndex& index);
void adsbData_doubleClicked(const QModelIndex& index);
void adsbData_sectionMoved(int logicalIndex, int oldVisualIndex, int newVisualIndex);
void adsbData_sectionResized(int logicalIndex, int oldSize, int newSize);
void columnSelectMenu(QPoint pos);
@ -1525,16 +929,12 @@ private slots: @@ -1525,16 +929,12 @@ private slots:
void photoClicked();
virtual void showEvent(QShowEvent *event) override;
virtual bool eventFilter(QObject *obj, QEvent *event) override;
void import();
void handleImportNetworkReply(QNetworkReply *reply);
void handleImportReply(QNetworkReply* reply);
void preferenceChanged(int elementType);
void devicePositionChanged(float latitude, float longitude, float altitude);
void requestMetar(const QString& icao);
void weatherUpdated(const AviationWeather::METAR &metar);
void on_manualQNH_clicked(bool checked);
void on_qnh_valueChanged(int value);
void clearCoverage(const QPoint& p);
void clearStats(const QPoint& p);
void clearChart(const QPoint& p);
void resetChartAxes();

620
plugins/channelrx/demodadsb/adsbdemodgui.ui

@ -1082,7 +1082,7 @@ @@ -1082,7 +1082,7 @@
<number>0</number>
</property>
<item>
<widget class="QTableWidget" name="adsbData">
<widget class="QTableView" name="adsbData">
<property name="sizePolicy">
<sizepolicy hsizetype="Expanding" vsizetype="Expanding">
<horstretch>1</horstretch>
@ -1104,624 +1104,6 @@ @@ -1104,624 +1104,6 @@
<property name="selectionBehavior">
<enum>QAbstractItemView::SelectionBehavior::SelectRows</enum>
</property>
<column>
<property name="text">
<string>ICAO ID</string>
</property>
<property name="toolTip">
<string extracomment="Double click to search for the aircraft on www.planespotters.net">Aircraft International Civil Aviation Organization identifier. Links to www.planespotters.net</string>
</property>
</column>
<column>
<property name="text">
<string>Callsign</string>
</property>
<property name="toolTip">
<string>Callsign. Links to www.flightradar24.com</string>
</property>
</column>
<column>
<property name="text">
<string>ATC Callsign</string>
</property>
<property name="toolTip">
<string>Airline callsign used by ATC</string>
</property>
</column>
<column>
<property name="text">
<string>Aircraft</string>
</property>
<property name="toolTip">
<string>Aircraft model</string>
</property>
</column>
<column>
<property name="text">
<string>Type</string>
</property>
<property name="toolTip">
<string>ICAO aircraft type designator</string>
</property>
</column>
<column>
<property name="text">
<string>Sideview</string>
</property>
</column>
<column>
<property name="text">
<string>Airline</string>
</property>
<property name="toolTip">
<string>Airline logo</string>
</property>
</column>
<column>
<property name="text">
<string>Country</string>
</property>
<property name="toolTip">
<string>Country of registration</string>
</property>
</column>
<column>
<property name="text">
<string>GS (kn)</string>
</property>
<property name="toolTip">
<string>Groundspeed in knots or kilometers per hour</string>
</property>
</column>
<column>
<property name="text">
<string>TAS (kn)</string>
</property>
<property name="toolTip">
<string>True airpeed in knots or kilometers per hour</string>
</property>
</column>
<column>
<property name="text">
<string>IAS (kn)</string>
</property>
<property name="toolTip">
<string>Indicated airspeed in knots or kilometers per hour</string>
</property>
</column>
<column>
<property name="text">
<string>Mach</string>
</property>
<property name="toolTip">
<string>Mach number</string>
</property>
</column>
<column>
<property name="text">
<string>Sel Alt (ft)</string>
</property>
<property name="toolTip">
<string>Selected altitude in feet or metres (As set on MCP/FCU or by FMS)</string>
</property>
</column>
<column>
<property name="text">
<string>Alt (ft)</string>
</property>
<property name="toolTip">
<string>Altitude in feet or metres</string>
</property>
</column>
<column>
<property name="text">
<string>VR (ft/m)</string>
</property>
<property name="toolTip">
<string>Vertical climb rate in feet per minute or metres per second</string>
</property>
</column>
<column>
<property name="text">
<string>Sel Hd (°)</string>
</property>
<property name="toolTip">
<string>Selected heading in degrees (As set on MCP/FCU or by FMS)</string>
</property>
</column>
<column>
<property name="text">
<string>Hd (°)</string>
</property>
<property name="toolTip">
<string>Aircraft heading in degrees</string>
</property>
</column>
<column>
<property name="text">
<string>Trk (°)</string>
</property>
<property name="toolTip">
<string>Aircraft track in degrees</string>
</property>
</column>
<column>
<property name="text">
<string>TR (°/s)</string>
</property>
<property name="toolTip">
<string>Turn rate in degrees per second</string>
</property>
</column>
<column>
<property name="text">
<string>Roll (°)</string>
</property>
<property name="toolTip">
<string>Roll angle in degrees</string>
</property>
</column>
<column>
<property name="text">
<string>D (km)</string>
</property>
<property name="toolTip">
<string>Range or distance of aircraft from home location</string>
</property>
</column>
<column>
<property name="text">
<string>Az/El (°)</string>
</property>
<property name="toolTip">
<string>Azimuth and elevation to aircraft from My Position. Double click to set as target.</string>
</property>
</column>
<column>
<property name="text">
<string>Cat</string>
</property>
<property name="toolTip">
<string>Aircraft standard category</string>
</property>
</column>
<column>
<property name="text">
<string>Status</string>
</property>
<property name="toolTip">
<string>Aircraft emergency status</string>
</property>
</column>
<column>
<property name="text">
<string>Squawk</string>
</property>
<property name="toolTip">
<string>Mode-A transponder code</string>
</property>
</column>
<column>
<property name="text">
<string>Ident</string>
</property>
<property name="toolTip">
<string>Ident switch active</string>
</property>
</column>
<column>
<property name="text">
<string>Reg</string>
</property>
<property name="toolTip">
<string>Aircraft registration</string>
</property>
</column>
<column>
<property name="text">
<string>Registered</string>
</property>
<property name="toolTip">
<string>Date aircraft was registered</string>
</property>
</column>
<column>
<property name="text">
<string>Manufacturer</string>
</property>
<property name="toolTip">
<string>Aircraft manufacturer</string>
</property>
</column>
<column>
<property name="text">
<string>Owner</string>
</property>
<property name="toolTip">
<string>Owner of the aircraft</string>
</property>
</column>
<column>
<property name="text">
<string>Operator</string>
</property>
<property name="toolTip">
<string>Aircraft operator ICAO code</string>
</property>
</column>
<column>
<property name="text">
<string>AP</string>
</property>
<property name="toolTip">
<string>Autopilot enabled</string>
</property>
</column>
<column>
<property name="text">
<string>V Mode</string>
</property>
<property name="toolTip">
<string>MCP/FCU vertical mode</string>
</property>
</column>
<column>
<property name="text">
<string>L Mode</string>
</property>
<property name="toolTip">
<string>MCP/FCU lateral mode</string>
</property>
</column>
<column>
<property name="text">
<string>TCAS</string>
</property>
<property name="toolTip">
<string>TCAS operational. RA in red if active</string>
</property>
</column>
<column>
<property name="text">
<string>ACAS</string>
</property>
<property name="toolTip">
<string>Airborne collision avoidance system capability</string>
</property>
</column>
<column>
<property name="text">
<string>RA</string>
</property>
<property name="toolTip">
<string>ACAS active resolition advisory</string>
</property>
</column>
<column>
<property name="text">
<string>Max AS (kn)</string>
</property>
<property name="toolTip">
<string>Maximum speed in knots</string>
</property>
</column>
<column>
<property name="text">
<string>Version</string>
</property>
<property name="toolTip">
<string>ADS-B version</string>
</property>
</column>
<column>
<property name="text">
<string>L (m)</string>
</property>
<property name="toolTip">
<string>Aircraft length in metres</string>
</property>
</column>
<column>
<property name="text">
<string>W (m)</string>
</property>
<property name="toolTip">
<string>Aircraft width in metres</string>
</property>
</column>
<column>
<property name="text">
<string>QNH (mb)</string>
</property>
<property name="toolTip">
<string>Barometer setting in millibars</string>
</property>
</column>
<column>
<property name="text">
<string>H Wnd (kn)</string>
</property>
<property name="toolTip">
<string>Headwind in knots or kilometers per hour</string>
</property>
</column>
<column>
<property name="text">
<string>OAT (C)</string>
</property>
<property name="toolTip">
<string>Outside air temperature in degrees Celsius estimated from Mach and TAS</string>
</property>
</column>
<column>
<property name="text">
<string>Wnd (kn)</string>
</property>
<property name="toolTip">
<string>Wind speed in knots</string>
</property>
</column>
<column>
<property name="text">
<string>Wnd (°)</string>
</property>
<property name="toolTip">
<string>Wind direction in degrees</string>
</property>
</column>
<column>
<property name="text">
<string>P (hPa)</string>
</property>
<property name="toolTip">
<string>Static air pressure in hectopascals</string>
</property>
</column>
<column>
<property name="text">
<string>T (C)</string>
</property>
<property name="toolTip">
<string>Static air temperature in degrees Celsius</string>
</property>
</column>
<column>
<property name="text">
<string>U (%)</string>
</property>
<property name="toolTip">
<string>Humidity in percent</string>
</property>
</column>
<column>
<property name="text">
<string>Lat (°)</string>
</property>
<property name="toolTip">
<string extracomment="Double click to centre the map on this aircraft">Latitude in degrees positive towards the North</string>
</property>
</column>
<column>
<property name="text">
<string>Lon (°)</string>
</property>
<property name="toolTip">
<string extracomment="Double click to centre the map on this aircraft">Longitude in degrees. Positive towards the East</string>
</property>
</column>
<column>
<property name="text">
<string>IC</string>
</property>
<property name="toolTip">
<string>Interrogator code (II/SI)</string>
</property>
</column>
<column>
<property name="text">
<string>Updated</string>
</property>
<property name="toolTip">
<string>Time when the last ADS-B message from this aircraft was received.</string>
</property>
</column>
<column>
<property name="text">
<string>Frames</string>
</property>
<property name="toolTip">
<string>Number of ADS-B and Mode S frames received from this aircraft</string>
</property>
</column>
<column>
<property name="text">
<string>ADS-B FC</string>
</property>
<property name="toolTip">
<string>Number of ADS-B frames received from this aircraft</string>
</property>
</column>
<column>
<property name="text">
<string>Mode S FC</string>
</property>
<property name="toolTip">
<string>Number of Mode S frames received from this aircraft</string>
</property>
</column>
<column>
<property name="text">
<string>Non-transponder</string>
</property>
<property name="toolTip">
<string>Non transponder device frame count</string>
</property>
</column>
<column>
<property name="text">
<string>TIS-B FC</string>
</property>
<property name="toolTip">
<string>Number of TIS-B frames received with this aircraft's ICAO</string>
</property>
</column>
<column>
<property name="text">
<string>ADS-R FC</string>
</property>
<property name="toolTip">
<string>Number of ADS-R frames received with this aircraft's ICAO</string>
</property>
</column>
<column>
<property name="text">
<string>Rc</string>
</property>
<property name="toolTip">
<string>Horizontal containment radius limit</string>
</property>
</column>
<column>
<property name="text">
<string>NACp</string>
</property>
<property name="toolTip">
<string>Navigation accuracy category - 95% horizontal position</string>
</property>
</column>
<column>
<property name="text">
<string>NACv</string>
</property>
<property name="toolTip">
<string>Navigation accuracy category - velocity</string>
</property>
</column>
<column>
<property name="text">
<string>GVA</string>
</property>
<property name="toolTip">
<string>Geometric vertical accuracy</string>
</property>
</column>
<column>
<property name="text">
<string>NIC</string>
</property>
<property name="toolTip">
<string>Navigation integrity category</string>
</property>
</column>
<column>
<property name="text">
<string>NICbaro</string>
</property>
<property name="toolTip">
<string>Barometric altitude integrity code</string>
</property>
</column>
<column>
<property name="text">
<string>SIL</string>
</property>
<property name="toolTip">
<string>Surveillance integrity level</string>
</property>
</column>
<column>
<property name="text">
<string>Correlation</string>
</property>
<property name="toolTip">
<string>Correlation values for received frames. min/avg/max</string>
</property>
</column>
<column>
<property name="text">
<string>RSSI</string>
</property>
<property name="toolTip">
<string>Received Signal Strength Indicator (dBFS)</string>
</property>
</column>
<column>
<property name="text">
<string>Flight Status</string>
</property>
<property name="toolTip">
<string>Status of flight</string>
</property>
</column>
<column>
<property name="text">
<string>Dep</string>
</property>
<property name="toolTip">
<string>Departure airport</string>
</property>
</column>
<column>
<property name="text">
<string>Arr</string>
</property>
<property name="toolTip">
<string>Arrival airport</string>
</property>
</column>
<column>
<property name="text">
<string>Stops</string>
</property>
</column>
<column>
<property name="text">
<string>STD</string>
</property>
<property name="toolTip">
<string>Scheduled time of departure</string>
</property>
</column>
<column>
<property name="text">
<string>ETD</string>
</property>
<property name="toolTip">
<string>Estimated time of departure</string>
</property>
</column>
<column>
<property name="text">
<string>ATD</string>
</property>
<property name="toolTip">
<string>Actual time of departure</string>
</property>
</column>
<column>
<property name="text">
<string>STA</string>
</property>
<property name="toolTip">
<string>Scheduled time of arrival</string>
</property>
</column>
<column>
<property name="text">
<string>ETA</string>
</property>
<property name="toolTip">
<string>Estimated time of arrival</string>
</property>
</column>
<column>
<property name="text">
<string>ATA</string>
</property>
<property name="toolTip">
<string>Actual time of arrival</string>
</property>
</column>
</widget>
</item>
<item>

3932
plugins/channelrx/demodadsb/adsbdemodmapliveries.qrc

File diff suppressed because it is too large Load Diff

3
plugins/channelrx/demodadsb/adsbdemodnotificationdialog.cpp

@ -21,6 +21,7 @@ @@ -21,6 +21,7 @@
#include <QCheckBox>
#include "adsbdemodnotificationdialog.h"
#include "gui/fastitemdelegate.h"
// Map main ADS-B table column numbers to combo box indices
std::vector<int> ADSBDemodNotificationDialog::m_columnMap = {
@ -39,6 +40,8 @@ ADSBDemodNotificationDialog::ADSBDemodNotificationDialog(ADSBDemodSettings *sett @@ -39,6 +40,8 @@ ADSBDemodNotificationDialog::ADSBDemodNotificationDialog(ADSBDemodSettings *sett
{
ui->setupUi(this);
ui->table->setItemDelegate(new FastItemDelegate(ui->table));
resizeTable();
for (int i = 0; i < m_settings->m_notificationSettings.size(); i++) {

101
plugins/channelrx/demodadsb/adsbdemodsettings.cpp

@ -23,6 +23,8 @@ @@ -23,6 +23,8 @@
#include "util/simpleserializer.h"
#include "settings/serializable.h"
#include "util/flightpathpalette.h"
#include "adsbdemodsettings.h"
ADSBDemodSettings::ADSBDemodSettings() :
@ -81,6 +83,7 @@ void ADSBDemodSettings::resetToDefaults() @@ -81,6 +83,7 @@ void ADSBDemodSettings::resetToDefaults()
m_aviationstackAPIKey = "";
m_checkWXAPIKey = "";
m_maptilerAPIKey = "";
m_cartoDBAPIKey = "";
for (int i = 0; i < ADSBDEMOD_COLUMNS; i++)
{
m_columnIndexes[i] = i;
@ -117,6 +120,7 @@ void ADSBDemodSettings::resetToDefaults() @@ -117,6 +120,7 @@ void ADSBDemodSettings::resetToDefaults()
m_flightPathPaletteName = "Spectral";
applyPalette();
m_favourLivery = true;
m_useLiveryIcons = true;
}
QByteArray ADSBDemodSettings::serialize() const
@ -214,6 +218,8 @@ QByteArray ADSBDemodSettings::serialize() const @@ -214,6 +218,8 @@ QByteArray ADSBDemodSettings::serialize() const
s.writeBool(77, m_favourLivery);
s.writeString(78, m_maptilerAPIKey);
s.writeString(80, m_cartoDBAPIKey);
s.writeBool(79, m_useLiveryIcons);
for (int i = 0; i < ADSBDEMOD_COLUMNS; i++) {
s.writeS32(100 + i, m_columnIndexes[i]);
@ -361,6 +367,8 @@ bool ADSBDemodSettings::deserialize(const QByteArray& data) @@ -361,6 +367,8 @@ bool ADSBDemodSettings::deserialize(const QByteArray& data)
d.readBool(77, &m_favourLivery, true);
d.readString(78, &m_maptilerAPIKey, "");
d.readString(80, &m_cartoDBAPIKey, "");
d.readBool(79, &m_useLiveryIcons, true);
applyPalette();
@ -591,6 +599,9 @@ void ADSBDemodSettings::applySettings(const QStringList& settingsKeys, const ADS @@ -591,6 +599,9 @@ void ADSBDemodSettings::applySettings(const QStringList& settingsKeys, const ADS
if (settingsKeys.contains("maptilerAPIKey")) {
m_maptilerAPIKey = settings.m_maptilerAPIKey;
}
if (settingsKeys.contains("cartoDBAPIKey")) {
m_cartoDBAPIKey = settings.m_cartoDBAPIKey;
}
if (settingsKeys.contains("logFilename")) {
m_logFilename = settings.m_logFilename;
}
@ -656,6 +667,9 @@ void ADSBDemodSettings::applySettings(const QStringList& settingsKeys, const ADS @@ -656,6 +667,9 @@ void ADSBDemodSettings::applySettings(const QStringList& settingsKeys, const ADS
if (settingsKeys.contains("favourLivery")) {
m_favourLivery = settings.m_favourLivery;
}
if (settingsKeys.contains("useLiveryIcons")) {
m_useLiveryIcons = settings.m_useLiveryIcons;
}
}
QString ADSBDemodSettings::getDebugString(const QStringList& settingsKeys, bool force) const
@ -797,6 +811,9 @@ QString ADSBDemodSettings::getDebugString(const QStringList& settingsKeys, bool @@ -797,6 +811,9 @@ QString ADSBDemodSettings::getDebugString(const QStringList& settingsKeys, bool
if (settingsKeys.contains("maptilerAPIKey") || force) {
ostr << " m_maptilerAPIKey: " << m_maptilerAPIKey.toStdString();
}
if (settingsKeys.contains("cartoDBAPIKey") || force) {
ostr << " m_cartoDBAPIKey: " << m_cartoDBAPIKey.toStdString();
}
if (settingsKeys.contains("logFilename") || force) {
ostr << " m_logFilename: " << m_logFilename.toStdString();
}
@ -860,90 +877,14 @@ QString ADSBDemodSettings::getDebugString(const QStringList& settingsKeys, bool @@ -860,90 +877,14 @@ QString ADSBDemodSettings::getDebugString(const QStringList& settingsKeys, bool
if (settingsKeys.contains("favourLivery") || force) {
ostr << " m_favourLivery: " << m_favourLivery;
}
if (settingsKeys.contains("useLiveryIcons") || force) {
ostr << " m_useLiveryIcons: " << m_useLiveryIcons;
}
return QString(ostr.str().c_str());
}
void ADSBDemodSettings::applyPalette()
{
if (m_palettes.contains(m_flightPathPaletteName)) {
m_flightPathPalette = m_palettes.value(m_flightPathPaletteName);
} else {
m_flightPathPalette = m_rainbowPalette;
}
m_flightPathPalette = FlightPathPalette::getPalette(m_flightPathPaletteName);
}
const QVariant ADSBDemodSettings::m_rainbowPalette[8] = {
QVariant(QColor(0xff, 0x00, 0x00)),
QVariant(QColor(0xff, 0x7f, 0x00)),
QVariant(QColor(0xff, 0xff, 0x00)),
QVariant(QColor(0xf7, 0xff, 0x00)),
QVariant(QColor(0x00, 0xff, 0x00)),
QVariant(QColor(0x00, 0xff, 0x7f)),
QVariant(QColor(0x00, 0xff, 0xff)),
QVariant(QColor(0x00, 0x7f, 0xff)),
};
const QVariant ADSBDemodSettings::m_pastelPalette[8] = {
QVariant(QColor(0xff, 0xad, 0xad)),
QVariant(QColor(0xff, 0xd6, 0xa5)),
QVariant(QColor(0xfd, 0xff, 0xb6)),
QVariant(QColor(0xca, 0xff, 0xbf)),
QVariant(QColor(0x9b, 0xf6, 0xff)),
QVariant(QColor(0xa0, 0xc4, 0xff)),
QVariant(QColor(0xbd, 0xb2, 0xff)),
QVariant(QColor(0xff, 0xc6, 0xff)),
};
const QVariant ADSBDemodSettings::m_spectralPalette[8] = {
QVariant(QColor(0xd5, 0x3e, 0x4f)),
QVariant(QColor(0xf4, 0x6d, 0x43)),
QVariant(QColor(0xfd, 0xae, 0x61)),
QVariant(QColor(0xfe, 0xe0, 0x8b)),
QVariant(QColor(0xe6, 0xf5, 0x98)),
QVariant(QColor(0xab, 0xdd, 0xa4)),
QVariant(QColor(0x66, 0xc2, 0xa5)),
QVariant(QColor(0x32, 0x88, 0xbd)),
};
const QVariant ADSBDemodSettings::m_bluePalette[8] = {
QVariant(QColor(0xde, 0xeb, 0xf7)),
QVariant(QColor(0xc6, 0xdb, 0xef)),
QVariant(QColor(0x9e, 0xca, 0xe1)),
QVariant(QColor(0x6b, 0xae, 0xd6)),
QVariant(QColor(0x42, 0x92, 0xc6)),
QVariant(QColor(0x21, 0x71, 0xb5)),
QVariant(QColor(0x08, 0x51, 0x9c)),
QVariant(QColor(0x08, 0x30, 0x6b)),
};
const QVariant ADSBDemodSettings::m_purplePalette[8] = {
QVariant(QColor(0xcc, 0xaf, 0xf2)),
QVariant(QColor(0xb6, 0x99, 0xe0)),
QVariant(QColor(0xa0, 0x84, 0xcf)),
QVariant(QColor(0x8a, 0x6f, 0xbd)),
QVariant(QColor(0x76, 0x5a, 0xac)),
QVariant(QColor(0x62, 0x45, 0x9a)),
QVariant(QColor(0x4f, 0x30, 0x89)),
QVariant(QColor(0x3e, 0x18, 0x78)),
};
const QVariant ADSBDemodSettings::m_greyPalette[8] = {
QVariant(QColor(0x80, 0x80, 0x80)),
QVariant(QColor(0x80, 0x80, 0x80)),
QVariant(QColor(0x80, 0x80, 0x80)),
QVariant(QColor(0x80, 0x80, 0x80)),
QVariant(QColor(0x80, 0x80, 0x80)),
QVariant(QColor(0x80, 0x80, 0x80)),
QVariant(QColor(0x80, 0x80, 0x80)),
QVariant(QColor(0x80, 0x80, 0x80)),
};
const QHash<QString, const QVariant *> ADSBDemodSettings::m_palettes = {
{"Rainbow", &ADSBDemodSettings::m_rainbowPalette[0]},
{"Pastel", &ADSBDemodSettings::m_pastelPalette[0]},
{"Spectral", &ADSBDemodSettings::m_spectralPalette[0]},
{"Blues", &ADSBDemodSettings::m_bluePalette[0]},
{"Purples", &ADSBDemodSettings::m_purplePalette[0]},
{"Grey", &ADSBDemodSettings::m_greyPalette[0]},
};

10
plugins/channelrx/demodadsb/adsbdemodsettings.h

@ -197,6 +197,7 @@ struct ADSBDemodSettings @@ -197,6 +197,7 @@ struct ADSBDemodSettings
QString m_aviationstackAPIKey; //!< aviationstack.com API key
QString m_checkWXAPIKey; //!< checkwxapi.com API key
QString m_maptilerAPIKey; //!< maptiler.com API key (for osm/satellite map)
QString m_cartoDBAPIKey; //!< carto.com API key (for the aviation maps, which use CartoDB tiles without labels)
QString m_logFilename;
bool m_logEnabled;
@ -229,6 +230,7 @@ struct ADSBDemodSettings @@ -229,6 +230,7 @@ struct ADSBDemodSettings
bool m_displayIC[ADSB_IC_MAX];
QString m_flightPathPaletteName;
bool m_favourLivery; //!< Favour airline livery over aircraft type when exact 3D model isn't available
bool m_useLiveryIcons; //!< Use aircraft icons with airline liveries on 2D map, instead of black icons
const QVariant *m_flightPathPalette;
@ -244,14 +246,6 @@ struct ADSBDemodSettings @@ -244,14 +246,6 @@ struct ADSBDemodSettings
QString getDebugString(const QStringList& settingsKeys, bool force = false) const;
void applyPalette();
static const QVariant m_rainbowPalette[8];
static const QVariant m_pastelPalette[8];
static const QVariant m_spectralPalette[8];
static const QVariant m_bluePalette[8];
static const QVariant m_purplePalette[8];
static const QVariant m_greyPalette[8];
static const QHash<QString, const QVariant *> m_palettes;
};
#endif /* PLUGINS_CHANNELRX_DEMODADSB_ADSBDEMODSETTINGS_H_ */

14
plugins/channelrx/demodadsb/adsbdemodsinkworker.cpp

@ -261,18 +261,8 @@ bool ADSBDemodSinkWorker::icaoHeardRecently(unsigned icao, const QDateTime &date @@ -261,18 +261,8 @@ bool ADSBDemodSinkWorker::icaoHeardRecently(unsigned icao, const QDateTime &date
void ADSBDemodSinkWorker::forwardFrame(const unsigned char *data, int size, float preambleCorrelation, float correlationOnes, const QDateTime& dateTime, unsigned crc)
{
// Pass to GUI
if (m_sink->getMessageQueueToGUI())
{
ADSBDemodReport::MsgReportADSB *msg = ADSBDemodReport::MsgReportADSB::create(
QByteArray((char*)data, size),
preambleCorrelation,
correlationOnes,
dateTime,
crc);
m_sink->getMessageQueueToGUI()->push(msg);
}
// Pass to worker to feed to other servers
// Pass to the tracker, which decodes the frame, and passes it on to be exported
// to other servers and to the GUI
if (m_sink->getMessageQueueToWorker())
{
ADSBDemodReport::MsgReportADSB *msg = ADSBDemodReport::MsgReportADSB::create(

387
plugins/channelrx/demodadsb/adsbdemodtracker.cpp

@ -0,0 +1,387 @@ @@ -0,0 +1,387 @@
///////////////////////////////////////////////////////////////////////////////////
// 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 <QDebug>
#include <QStandardPaths>
#include <QNetworkAccessManager>
#include "dsp/dspcommands.h"
#include "maincore.h"
#include "util/osndb.h"
#include "adsbdemod.h"
#include "adsbdemodreport.h"
#include "adsbdemodtracker.h"
#include "adsbdemodworker.h"
MESSAGE_CLASS_DEFINITION(ADSBDemodTracker::MsgConfigureADSBDemodTracker, Message)
ADSBDemodTracker::ADSBDemodTracker(ADSBDemod *adsbDemod) :
m_adsbDemod(adsbDemod),
m_exportWorker(nullptr),
m_messageQueueToGUI(nullptr),
m_centerFrequency(0),
m_deviceCenterFrequency(0),
m_basebandSampleRate(0),
m_flushTimer(nullptr),
m_tickTimer(nullptr),
m_importNetworkManager(nullptr),
m_importTimer(nullptr),
m_flightInformation(nullptr),
m_importRequestGeneration(0),
m_importAuthenticationRetry(false),
m_statsChanged(false),
m_trackAircraft(nullptr),
m_qnhReported(0),
m_rangeFails(0),
m_altFails(0),
m_adsbFrameRateCount(0),
m_modesFrameRateCount(0),
m_totalBytes(0),
m_maxRangeStat(0.0f),
m_maxAltitudeStat(0.0f),
m_maxRateState(0.0f),
m_loadingData(false)
{
qRegisterMetaType<ADSBAircraftUpdate>("ADSBAircraftUpdate");
qRegisterMetaType<QList<ADSBAircraftUpdate>>("QList<ADSBAircraftUpdate>");
qRegisterMetaType<QHash<int, QVariant>>("QHash<int,QVariant>");
qRegisterMetaType<QList<quint32>>("QList<quint32>");
qRegisterMetaType<QVector<QPointF>>("QVector<QPointF>");
for (int i = 0; i < 32; i++)
{
m_dfStats[i] = 0;
m_tcStats[i] = 0;
}
m_frameRateTime = QDateTime::currentDateTime();
m_statsTime = m_frameRateTime;
initCoverageMap();
}
ADSBDemodTracker::~ADSBDemodTracker()
{
// Anything still on the map belongs to aircraft that are about to go
for (ADSBAircraft *aircraft : m_aircraft) {
clearFromMap(aircraft->m_icaoHex);
}
delete m_flushTimer;
delete m_tickTimer;
delete m_importTimer;
delete m_importNetworkManager;
delete m_flightInformation;
for (auto animations : m_pendingMapUpdates)
{
if (animations)
{
qDeleteAll(*animations);
delete animations;
}
}
m_pendingMapUpdates.clear();
qDeleteAll(m_aircraft);
m_aircraft.clear();
m_inputMessageQueue.clear();
}
QString ADSBDemodTracker::getDataDir()
{
// Where the aircraft and airport databases and the 3D models live
QStringList locations = QStandardPaths::standardLocations(QStandardPaths::AppDataLocation);
return locations[0];
}
void ADSBDemodTracker::startWork()
{
// Build the shared 3D model tables now rather than letting the first aircraft report
// pay for it. Cheap when another plugin has already done it.
Aircraft3DModels::instance();
// Created here so they belong to the thread that will use them
m_flushTimer = new QTimer();
m_tickTimer = new QTimer();
m_importTimer = new QTimer();
m_importNetworkManager = new QNetworkAccessManager();
connect(m_importTimer, &QTimer::timeout, this, &ADSBDemodTracker::import);
connect(m_importNetworkManager, &QNetworkAccessManager::finished,
this, &ADSBDemodTracker::handleImportNetworkReply);
connect(m_flushTimer, &QTimer::timeout, this, &ADSBDemodTracker::flush);
connect(m_tickTimer, &QTimer::timeout, this, &ADSBDemodTracker::tick);
// Four times a second is well above the rate at which aircraft move on screen,
// and far below the rate at which frames arrive
m_flushTimer->start(250);
m_tickTimer->start(1000);
applyImportSettings();
initFlightInformation();
connect(&m_inputMessageQueue, &MessageQueue::messageEnqueued, this, &ADSBDemodTracker::handleInputMessages);
// Settings and frames can arrive before the thread has started running
handleInputMessages();
}
// Send everything that has changed since the last time to the GUI
void ADSBDemodTracker::flush()
{
if (!m_removedAircraft.isEmpty())
{
emit aircraftRemoved(m_removedAircraft);
m_removedAircraft.clear();
}
if (!m_dirtyAircraft.isEmpty())
{
QList<ADSBAircraftUpdate> updates;
updates.reserve(m_dirtyAircraft.size());
for (ADSBAircraft *aircraft : m_dirtyAircraft)
{
ADSBAircraftUpdate update;
update.m_state = *aircraft;
update.m_isNew = aircraft->m_isNew;
updates.append(update);
// The copy carries the flags; ours start again
aircraft->clearDirtyCells();
aircraft->m_isNew = false;
aircraft->m_positionChanged = false;
aircraft->m_trailCleared = false;
aircraft->m_positionUpdates.clear();
}
m_dirtyAircraft.clear();
emit aircraftUpdated(updates);
}
if (!m_pendingMapUpdates.isEmpty())
{
for (auto it = m_pendingMapUpdates.cbegin(); it != m_pendingMapUpdates.cend(); ++it) {
sendToMap(it.key(), it.value());
}
m_pendingMapUpdates.clear();
}
if (m_statsChanged)
{
emit statsUpdated(m_stats);
m_statsChanged = false;
}
}
void ADSBDemodTracker::setStat(int row, const QVariant& value)
{
if (m_stats.value(row) != value)
{
m_stats[row] = value;
m_statsChanged = true;
}
}
// Once a second: age out aircraft we have stopped hearing, work out frame rates and
// report the current picture for the web API
void ADSBDemodTracker::tick()
{
QDateTime now = QDateTime::currentDateTime();
qint64 nowSecs = now.toSecsSinceEpoch();
QHash<int, ADSBAircraft *>::iterator i = m_aircraft.begin();
while (i != m_aircraft.end())
{
ADSBAircraft *aircraft = i.value();
if (nowSecs - aircraft->m_updateTime.toSecsSinceEpoch() >= m_settings.m_removeTimeout) {
removeAircraft(i, aircraft);
} else {
// A resolution advisory is re-broadcast every second or so while it is
// active, so one that stops arriving is over - and the clear-of-conflict
// indication only lingers briefly after it was raised. Queued to the map
// on the transition: no frame will arrive to carry the change otherwise
if ( (aircraft->m_raActive || aircraft->m_raTerminated)
&& aircraft->m_raDateTime.isValid()
&& (aircraft->m_raDateTime.secsTo(now) >= 10))
{
aircraft->m_raActive = false;
aircraft->m_raTerminated = false;
aircraft->m_tcasAlert = false;
queueMapUpdate(aircraft, nullptr);
}
++i;
}
}
sendAircraftReport();
qint64 ms = m_frameRateTime.msecsTo(now);
if (ms > 0)
{
double s = ms / 1000.0;
double adsbRate = m_adsbFrameRateCount / s;
double modesRate = m_modesFrameRateCount / s;
double totalRate = adsbRate + modesRate;
setStat(ADSB_RATE, adsbRate);
setStat(MODE_S_RATE, modesRate);
setStat(TOTAL_RATE, totalRate);
if (totalRate > m_maxRateState)
{
m_maxRateState = (float) totalRate;
setStat(MAX_RATE, m_maxRateState);
}
setStat(DATA_RATE, (m_totalBytes * 8 / 1000) / s);
m_frameRateTime = now;
m_adsbFrameRateCount = 0;
m_modesFrameRateCount = 0;
m_totalBytes = 0;
emit rates(adsbRate, modesRate, countActiveAircraft());
}
}
// The databases are loaded by the GUI and shared read-only
void ADSBDemodTracker::reloadDatabases()
{
m_aircraftInfo = OsnDB::getAircraftInformation();
m_routeInfo = OsnDB::getAircraftRouteInformation();
qDebug() << "ADSBDemodTracker::reloadDatabases:" << (m_aircraftInfo ? m_aircraftInfo->size() : 0) << "aircraft";
// Aircraft already being tracked may now have details, so look them up again
for (ADSBAircraft *aircraft : m_aircraft)
{
if (m_aircraftInfo->contains(aircraft->m_icao))
{
aircraft->m_aircraftInfo = m_aircraftInfo->value(aircraft->m_icao);
markDirty(aircraft);
}
}
}
void ADSBDemodTracker::requestFlightInformation(const QString& flight)
{
if (m_flightInformation) {
m_flightInformation->getFlightInformation(flight);
} else {
qDebug() << "ADSBDemodTracker::requestFlightInformation: no flight information service - is the API key set?";
}
}
void ADSBDemodTracker::setPosition(float latitude, float longitude, float altitude)
{
const bool moved = (m_azEl.getLocationSpherical().m_latitude != latitude)
|| (m_azEl.getLocationSpherical().m_longitude != longitude);
m_azEl.setLocation(latitude, longitude, altitude);
if (moved)
{
// The coverage outline is centred on the station, so start it again from here
initCoverageMap();
for (int i = 0; i < 2; i++) {
emit coverageUpdated(i, m_coverageAirspace[i].m_polygon);
}
}
}
void ADSBDemodTracker::setTrackAircraft(quint32 icao)
{
m_trackAircraft = m_aircraft.value((int) icao, nullptr);
}
void ADSBDemodTracker::deleteAllAircraft()
{
qDebug() << "ADSBDemodTracker::deleteAllAircraft:" << m_aircraft.size() << "aircraft";
QHash<int, ADSBAircraft *>::iterator i = m_aircraft.begin();
while (i != m_aircraft.end())
{
ADSBAircraft *aircraft = i.value();
removeAircraft(i, aircraft);
}
// Tell the GUI now rather than waiting for the next flush
flush();
}
void ADSBDemodTracker::handleInputMessages()
{
Message* message;
while ((message = m_inputMessageQueue.pop()) != nullptr)
{
if (handleMessage(*message)) {
delete message;
}
}
}
bool ADSBDemodTracker::handleMessage(const Message& message)
{
if (MsgConfigureADSBDemodTracker::match(message))
{
MsgConfigureADSBDemodTracker& cfg = (MsgConfigureADSBDemodTracker&) message;
applySettings(cfg.getSettings(), cfg.getSettingsKeys(), cfg.getForce());
return true;
}
else if (ADSBDemodReport::MsgReportADSB::match(message))
{
ADSBDemodReport::MsgReportADSB& report = (ADSBDemodReport::MsgReportADSB&) message;
// Beast export and .csv logging
if (m_exportWorker) {
m_exportWorker->getInputMessageQueue()->push(new ADSBDemodReport::MsgReportADSB(report));
}
handleADSB(report.getData(), report.getDateTime(), report.getPreambleCorrelation(),
report.getCorrelationOnes(), report.getCRC(), true);
return true;
}
else if (DSPSignalNotification::match(message))
{
DSPSignalNotification& notif = (DSPSignalNotification&) message;
m_basebandSampleRate = notif.getSampleRate();
m_centerFrequency = notif.getCenterFrequency();
m_deviceCenterFrequency = notif.getCenterFrequency();
return true;
}
else
{
return false;
}
}
void ADSBDemodTracker::applySettings(const ADSBDemodSettings& settings, const QStringList& settingsKeys, bool force)
{
const bool wasManualQNH = m_settings.m_manualQNH;
if (force) {
m_settings = settings;
} else {
m_settings.applySettings(settingsKeys, settings);
}
// Coming off manual QNH, the spin box holds whatever was typed, so the next estimate
// has to be reported even if it is within the hysteresis of the last one we sent
if (wasManualQNH && !m_settings.m_manualQNH) {
m_qnhReported = 0;
}
if (m_importTimer) {
applyImportSettings();
}
}

374
plugins/channelrx/demodadsb/adsbdemodtracker.h

@ -0,0 +1,374 @@ @@ -0,0 +1,374 @@
///////////////////////////////////////////////////////////////////////////////////
// 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_ADSBDEMODTRACKER_H
#define INCLUDE_ADSBDEMODTRACKER_H
#include <QObject>
#include <QHash>
#include <QSet>
#include <QList>
#include <QTimer>
#include <QRandomGenerator>
#include <QDateTime>
#include <QPointF>
#include <QRegularExpression>
#include <QPointer>
#include "util/message.h"
#include "util/messagequeue.h"
#include "util/azel.h"
#include "util/movingaverage.h"
#include "util/openaip.h"
#include "util/osndb.h"
#include "util/aircraft3dmodels.h"
#include "util/ourairportsdb.h"
#include "util/flightinformation.h"
#include "adsbaircraft.h"
#include "adsbdemodsettings.h"
namespace SWGSDRangel {
class SWGMapAnimation;
}
class ADSBDemod;
class ADSBDemodWorker;
class QNetworkAccessManager;
class QNetworkReply;
// Rows of the statistics table, which the tracker fills in and the GUI displays
enum StatsRow {
ADSB_FRAMES,
MODE_S_FRAMES,
TOTAL_FRAMES,
ADSB_RATE,
MODE_S_RATE,
TOTAL_RATE,
DATA_RATE,
CORRELATOR_MATCHES,
PERCENT_VALID,
PREAMBLE_FAILS,
CRC_FAILS,
TYPE_FAILS,
INVALID_FAILS,
ICAO_FAILS,
RANGE_FAILS,
ALT_FAILS,
AVERAGE_CORRELATION,
TC_0,
TC_1_4,
TC_5_8,
TC_9_18,
TC_19,
TC_20_22,
TC_24,
TC_28,
TC_29,
TC_31,
TC_UNUSED,
DF0,
DF4,
DF5,
DF11,
DF16,
DF17,
DF18,
DF19,
DF20_21,
DF22,
DF24,
MAX_RANGE,
MAX_ALTITUDE,
MAX_RATE
};
// One aircraft's decoded state, on its way to the GUI. The state carries its own
// record of which table cells changed, so the GUI repaints only those
struct ADSBAircraftUpdate {
ADSBAircraft m_state;
bool m_isNew = false;
};
Q_DECLARE_METATYPE(ADSBAircraftUpdate)
// Decodes ADS-B and Mode-S frames and tracks the aircraft they come from.
//
// This runs on the channel's worker thread rather than in the GUI, so that a busy
// sky doesn't compete with drawing the user interface, and so that the channel still
// decodes, reports and feeds aggregators when SDRangel is run headless as a server.
//
// Frames arrive here directly from the demodulator; those that are to be exported in
// Beast format or logged are passed on to ADSBDemodWorker, which shares this thread.
class ADSBDemodTracker : public QObject {
Q_OBJECT
public:
class MsgConfigureADSBDemodTracker : public Message {
MESSAGE_CLASS_DECLARATION
public:
const ADSBDemodSettings& getSettings() const { return m_settings; }
const QStringList& getSettingsKeys() const { return m_settingsKeys; }
bool getForce() const { return m_force; }
static MsgConfigureADSBDemodTracker* create(const ADSBDemodSettings& settings, const QStringList& settingsKeys, bool force)
{
return new MsgConfigureADSBDemodTracker(settings, settingsKeys, force);
}
private:
ADSBDemodSettings m_settings;
QStringList m_settingsKeys;
bool m_force;
MsgConfigureADSBDemodTracker(const ADSBDemodSettings& settings, const QStringList& settingsKeys, bool force) :
Message(),
m_settings(settings),
m_settingsKeys(settingsKeys),
m_force(force)
{ }
};
explicit ADSBDemodTracker(ADSBDemod *adsbDemod);
~ADSBDemodTracker();
MessageQueue *getInputMessageQueue() { return &m_inputMessageQueue; }
// The worker that exports frames in Beast format and writes the .csv log. It
// shares this thread, so frames can be handed to it directly
void setExportWorker(ADSBDemodWorker *worker) { m_exportWorker = worker; }
void setMessageQueueToGUI(MessageQueue *queue) { m_messageQueueToGUI = queue; }
static QString getDataDir();
public slots:
// Called from the GUI thread, so these are invoked through the event loop
void setPosition(float latitude, float longitude, float altitude);
void setTrackAircraft(quint32 icao);
void setLoadingData(bool loading)
{
if (loading && !m_loadingData) {
m_replayAircraftReported.clear();
}
m_loadingData = loading;
}
void deleteAllAircraft();
void clearCoverage();
void resetStats();
void reloadDatabases();
void requestFlightInformation(const QString& flight);
public:
signals:
// Everything that changed since the last flush, about four times a second
void aircraftUpdated(const QList<ADSBAircraftUpdate>& updates);
void aircraftRemoved(const QList<quint32>& icaos);
void statsUpdated(const QHash<int, QVariant>& stats);
void coverageUpdated(int band, const QVector<QPointF>& polygon);
void qnhEstimate(int qnh);
// For the frames-per-second chart
void rates(double adsbRate, double modesRate, int activeAircraft);
// The GUI owns the voice, the selection and the photo panel
void speechRequest(const QString& speech);
void highlightRequest(quint32 icao);
void targetRequest(quint32 icao);
void photoRefresh(quint32 icao);
public slots:
// Called when the worker thread starts. Anything with thread affinity - timers,
// sockets, network access - must be created here rather than in the constructor
void startWork();
private slots:
void handleInputMessages();
void flightInformationUpdated(const FlightInformation::Flight& flight);
// Sends everything that changed to the GUI in one go
void flush();
// Ages out aircraft that have not been heard from, and reports to the web API
void tick();
private:
ADSBDemod *m_adsbDemod;
ADSBDemodWorker *m_exportWorker;
MessageQueue *m_messageQueueToGUI;
MessageQueue m_inputMessageQueue;
ADSBDemodSettings m_settings;
qint64 m_centerFrequency;
qint64 m_deviceCenterFrequency;
int m_basebandSampleRate;
QTimer *m_flushTimer;
QTimer *m_tickTimer;
QSet<ADSBAircraft *> m_dirtyAircraft;
// Aircraft waiting to be sent to the Map, with any animations that have built up for
// them. We hear several frames a second per aircraft but only its position moves, so
// sending on every one just makes the Map redraw the same thing repeatedly
QHash<ADSBAircraft *, QList<SWGSDRangel::SWGMapAnimation *> *> m_pendingMapUpdates;
QList<quint32> m_removedAircraft;
QHash<int, QVariant> m_stats;
bool m_statsChanged;
QDateTime m_statsTime;
void get3DModel(ADSBAircraft *aircraft);
void get3DModelBasedOnCategory(ADSBAircraft *aircraft);
QHash<int, ADSBAircraft *> m_aircraft; // Hashed on ICAO
QSharedPointer<const QHash<int, AircraftInformation *>> m_aircraftInfo;
QSharedPointer<const QHash<QString, AircraftRouteInformation *>> m_routeInfo; // Hashed on callsign
AzEl m_azEl; // Position of station
ADSBAircraft *m_trackAircraft; // Aircraft we want to track in Channel Report
MovingAverageUtil<float, double, 10> m_correlationAvg;
MovingAverageUtil<float, double, 10> m_correlationOnesAvg;
MovingAverageUtil<float, double, 100> m_qnhAvg;
//!< The QNH last reported to the GUI, and 0 when none has been. Rounding a moving
//!< average flickers across the boundary between two whole hectopascals, and every
//!< flicker used to run a settings update through the GUI, the channel, the
//!< baseband, the sink, the worker and back into this tracker - so only a change
//!< that has moved clear of the last reported value is sent.
int m_qnhReported;
static const int m_maxRangeDeg = 5;
QList<float> m_maxRange[2];
Airspace m_coverageAirspace[2];
qint64 m_rangeFails;
qint64 m_altFails;
QDateTime m_frameRateTime;
qint64 m_adsbFrameRateCount;
qint64 m_modesFrameRateCount;
qint64 m_totalBytes;
float m_maxRangeStat;
float m_maxAltitudeStat;
float m_maxRateState;
qint64 m_dfStats[32];
qint64 m_tcStats[32];
QRandomGenerator m_random;
// The model tables live in sdrbase now, shared with the Aircraft feature - see
// Aircraft3DModels. Only the emitter category fallback below is still ours, because
// no other protocol transmits a category.
bool m_loadingData;
// Aircraft for which this CSV replay has already emitted its downstream track
// boundary (an Aircraft report marker or a direct Map item reset). Cleared at the
// start of every file, and deliberately independent of m_aircraft: the demodulator
// can retain live state while a replay starts a new downstream track.
QSet<quint32> m_replayAircraftReported;
static const char m_idMap[];
static const QString m_categorySetA[];
static const QString m_categorySetB[];
static const QString m_categorySetC[];
static const QString m_emergencyStatus[];
static const QString m_flightStatuses[];
static const QString m_hazardSeverity[];
static const QString m_fomSources[];
static const QString m_nacvStrings[];
void clearFromMap(const QString& name);
void sendToMap(ADSBAircraft *aircraft,
QList<SWGSDRangel::SWGMapAnimation *> *animations,
const QDateTime& aircraftStateDateTime = QDateTime());
static QList<SWGSDRangel::SWGMapAnimation *> *copyAnimations(QList<SWGSDRangel::SWGMapAnimation *> *animations);
void queueMapUpdate(ADSBAircraft *aircraft, QList<SWGSDRangel::SWGMapAnimation *> *animations);
void discardMapUpdate(ADSBAircraft *aircraft);
ADSBAircraft *getAircraft(int icao, bool &newAircraft);
void atcCallsign(ADSBAircraft *aircraft);
void callsignToFlight(ADSBAircraft *aircraft);
bool calcAirTemp(ADSBAircraft *aircraft);
void handleADSB(
const QByteArray data,
const QDateTime dateTime,
float correlation,
float correlationOnes,
unsigned crc,
bool updateModel);
void decodeID(const QByteArray& data, QString& emitterCategory, QString& callsign);
bool decodeGroundspeed(const QByteArray& data, float& v, float& h);
bool decodeAirspeed(const QByteArray& data, bool& tas, int& as, bool& hdgValid, float& hdg);
bool decodeVerticalRate(const QByteArray& data, int& verticalRate);
void updateAircraftPosition(ADSBAircraft *aircraft, double latitude, double longitude, const QDateTime& dateTime);
bool validateGlobalPosition(double latitude, double longitude, bool countFailure);
bool validateLocalPosition(double latitude, double longitude, bool surfacePosition, bool countFailure);
bool decodeGlobalPosition(int f, const double cprLat[2], const double cprLong[2], const QDateTime cprTime[2], double& latitude, double& longitude, bool countFailure);
bool decodeLocalPosition(int f, double cprLat, double cprLong, bool onSurface, const QDateTime& dateTime, const ADSBAircraft *aircraft, double& latitude, double& longitude, bool countFailure);
void decodeCpr(const QByteArray& data, int& f, double& latCpr, double& lonCpr) const;
bool decodeAltitude(const QByteArray& data, int& altFt) const;
void decodeModeSAltitude(const QByteArray& data, const QDateTime dateTime, ADSBAircraft *aircraft);
void decodeModeS(const QByteArray data, const QDateTime dateTime, int df, ADSBAircraft *aircraft);
void decodeCommB(const QByteArray data, const QDateTime dateTime, int df, ADSBAircraft *aircraft, bool &updatedCallsign);
void decodeRABroadcast(const QByteArray data, const QDateTime dateTime, ADSBAircraft *aircraft);
QList<SWGSDRangel::SWGMapAnimation *> *animate(QDateTime dateTime, ADSBAircraft *aircraft);
SWGSDRangel::SWGMapAnimation *gearAnimation(QDateTime startDateTime, bool up);
SWGSDRangel::SWGMapAnimation *gearAngle(QDateTime startDateTime, bool flat);
SWGSDRangel::SWGMapAnimation *flapsAnimation(QDateTime startDateTime, float currentFlaps, float flaps);
SWGSDRangel::SWGMapAnimation *slatsAnimation(QDateTime startDateTime, bool retract);
SWGSDRangel::SWGMapAnimation *rotorAnimation(QDateTime startDateTime, bool stop);
SWGSDRangel::SWGMapAnimation *engineAnimation(QDateTime startDateTime, int engine, bool stop);
// Whether the model the map draws for this aircraft has a named animation, so it is
// only asked to play what it can - see Aircraft3DModels::hasAnimation()
bool modelHasAnimation(const ADSBAircraft *aircraft, const QString &animation) const;
void checkStaticNotification(ADSBAircraft *aircraft);
void checkDynamicNotification(ADSBAircraft *aircraft);
void commandNotification(ADSBAircraft *aircraft, const QString &command);
QString subAircraftString(ADSBAircraft *aircraft, const QString &string);
void removeAircraft(QHash<int, ADSBAircraft *>::iterator& i, ADSBAircraft *aircraft);
ADSBAircraft *findAircraftByFlight(const QString& flight);
int roundTo50Feet(int alt);
int squawkDecode(int code) const;
int gillhamToFeet(int n) const;
int grayToBinary(int gray, int bits) const;
void sendAircraftReport();
void clearOldHeading(ADSBAircraft *aircraft, const QDateTime& dateTime, float newTrack);
void updateQNH(const ADSBAircraft *aircraft, float qnh);
void setCallsign(ADSBAircraft *aircraft, const QString& callsign);
void initCoverageMap();
void clearCoverageMap();
void updateCoverageMap(float azimuth, float elevation, float distance, float altitude);
void updateDFStats(int df);
bool updateTCStats(int tc, int row, int low, int high);
int countActiveAircraft();
// Aircraft imported from the OpenSky Network, rather than heard directly
QNetworkAccessManager *m_importNetworkManager;
QTimer *m_importTimer;
QPointer<QNetworkReply> m_importTokenReply;
QPointer<QNetworkReply> m_importStatesReply;
QString m_importAccessToken;
QDateTime m_importAccessTokenExpiry;
int m_importRequestGeneration;
bool m_importAuthenticationRetry;
FlightInformation *m_flightInformation;
void initFlightInformation();
static QString dataTimeToShortString(QDateTime dt);
void applyImportSettings();
bool importCredentialsConfigured() const;
bool importAccessTokenValid() const;
void invalidateImportAuthentication();
void requestImportAccessToken();
void sendImportRequest();
void handleImportTokenReply(QNetworkReply *reply);
void handleImportNetworkReply(QNetworkReply *reply);
void handleImportReply(QNetworkReply *reply);
void import();
bool handleMessage(const Message& message);
void applySettings(const ADSBDemodSettings& settings, const QStringList& settingsKeys, bool force = false);
void markDirty(ADSBAircraft *aircraft) { m_dirtyAircraft.insert(aircraft); }
void setStat(int row, const QVariant& value);
};
#endif // INCLUDE_ADSBDEMODTRACKER_H

5466
plugins/channelrx/demodadsb/adsbdemodtrackerdecode.cpp

File diff suppressed because it is too large Load Diff

118
plugins/channelrx/demodadsb/adsbdemodworker.cpp

@ -88,63 +88,51 @@ void ADSBBeastServer::discardClient() @@ -88,63 +88,51 @@ void ADSBBeastServer::discardClient()
}
ADSBDemodWorker::ADSBDemodWorker() :
m_running(false)
m_heartbeatTimer(nullptr),
m_socket(nullptr),
m_beastServer(nullptr)
{
connect(&m_heartbeatTimer, SIGNAL(timeout()), this, SLOT(heartbeat()));
connect(&m_socket, SIGNAL(readyRead()),this, SLOT(recv()));
connect(&m_socket, SIGNAL(connected()), this, SLOT(connected()));
connect(&m_socket, SIGNAL(disconnected()), this, SLOT(disconnected()));
#if QT_VERSION < QT_VERSION_CHECK(5, 15, 0)
connect(&m_socket, QOverload<QAbstractSocket::SocketError>::of(&QAbstractSocket::error), this, &ADSBDemodWorker::errorOccurred);
#else
connect(&m_socket, &QAbstractSocket::errorOccurred, this, &ADSBDemodWorker::errorOccurred);
#endif
m_startTime = QDateTime::currentDateTime().toMSecsSinceEpoch();
m_heartbeatTimer.start(60*1000);
}
ADSBDemodWorker::~ADSBDemodWorker()
{
m_heartbeatTimer.stop();
m_beastServer.close();
if (m_socket.state() != QAbstractSocket::UnconnectedState) {
m_socket.close();
if (m_socket && m_socket->isOpen()) {
m_socket->close();
}
m_inputMessageQueue.clear();
}
void ADSBDemodWorker::reset()
{
QMutexLocker mutexLocker(&m_mutex);
m_inputMessageQueue.clear();
}
bool ADSBDemodWorker::startWork()
{
QMutexLocker mutexLocker(&m_mutex);
if (m_running) {
return m_running;
if (m_beastServer) {
m_beastServer->close();
}
connect(&m_inputMessageQueue, SIGNAL(messageEnqueued()), this, SLOT(handleInputMessages()));
m_running = true;
return m_running;
if (m_logFile.isOpen()) {
m_logFile.close();
}
delete m_heartbeatTimer;
delete m_socket;
delete m_beastServer;
m_inputMessageQueue.clear();
}
void ADSBDemodWorker::stopWork()
void ADSBDemodWorker::startWork()
{
QMutexLocker mutexLocker(&m_mutex);
if (!m_running) {
return;
}
// Created here so they belong to the thread that will use them
m_socket = new QTcpSocket();
m_beastServer = new ADSBBeastServer();
m_heartbeatTimer = new QTimer();
connect(m_heartbeatTimer, &QTimer::timeout, this, &ADSBDemodWorker::heartbeat);
connect(m_socket, &QTcpSocket::readyRead, this, &ADSBDemodWorker::recv);
connect(m_socket, &QTcpSocket::connected, this, &ADSBDemodWorker::connected);
connect(m_socket, &QTcpSocket::disconnected, this, &ADSBDemodWorker::disconnected);
#if QT_VERSION < QT_VERSION_CHECK(5, 15, 0)
connect(m_socket, QOverload<QAbstractSocket::SocketError>::of(&QAbstractSocket::error), this, &ADSBDemodWorker::errorOccurred);
#else
connect(m_socket, &QAbstractSocket::errorOccurred, this, &ADSBDemodWorker::errorOccurred);
#endif
m_heartbeatTimer->start(60*1000);
disconnect(&m_inputMessageQueue, SIGNAL(messageEnqueued()), this, SLOT(handleInputMessages()));
m_running = false;
connect(&m_inputMessageQueue, &MessageQueue::messageEnqueued, this, &ADSBDemodWorker::handleInputMessages);
// Settings can arrive before the thread has started running
handleInputMessages();
}
void ADSBDemodWorker::handleInputMessages()
@ -164,7 +152,6 @@ bool ADSBDemodWorker::handleMessage(const Message& message) @@ -164,7 +152,6 @@ bool ADSBDemodWorker::handleMessage(const Message& message)
{
if (MsgConfigureADSBDemodWorker::match(message))
{
QMutexLocker mutexLocker(&m_mutex);
MsgConfigureADSBDemodWorker& cfg = (MsgConfigureADSBDemodWorker&) message;
applySettings(cfg.getSettings(), cfg.getSettingsKeys(), cfg.getForce());
@ -203,12 +190,12 @@ void ADSBDemodWorker::applySettings(const ADSBDemodSettings& settings, const QSt @@ -203,12 +190,12 @@ void ADSBDemodWorker::applySettings(const ADSBDemodSettings& settings, const QSt
|| force)
{
// Close any existing connection
if (m_socket.isOpen()) {
m_socket.close();
if (m_socket->isOpen()) {
m_socket->close();
}
// Open connection
if (settings.m_feedEnabled && settings.m_exportClientEnabled) {
m_socket.connectToHost(settings.m_exportClientHost, settings.m_exportClientPort);
m_socket->connectToHost(settings.m_exportClientHost, settings.m_exportClientPort);
}
}
@ -217,11 +204,11 @@ void ADSBDemodWorker::applySettings(const ADSBDemodSettings& settings, const QSt @@ -217,11 +204,11 @@ void ADSBDemodWorker::applySettings(const ADSBDemodSettings& settings, const QSt
|| (settingsKeys.contains("exportServerPort") && (settings.m_exportServerPort != m_settings.m_exportServerPort))
|| force)
{
if (m_beastServer.isListening()) {
m_beastServer.close();
if (m_beastServer->isListening()) {
m_beastServer->close();
}
if (settings.m_feedEnabled && settings.m_exportServerEnabled) {
m_beastServer.listen(settings.m_exportServerPort);
m_beastServer->listen(settings.m_exportServerPort);
}
}
@ -281,7 +268,7 @@ void ADSBDemodWorker::recv() @@ -281,7 +268,7 @@ void ADSBDemodWorker::recv()
{
// Not expecting to receiving anything from server
qDebug() << "ADSBDemodWorker::recv";
qDebug() << m_socket.readAll();
qDebug() << m_socket->readAll();
}
void ADSBDemodWorker::send(const char *data, int length)
@ -289,11 +276,11 @@ void ADSBDemodWorker::send(const char *data, int length) @@ -289,11 +276,11 @@ void ADSBDemodWorker::send(const char *data, int length)
if (m_settings.m_feedEnabled && m_settings.m_exportClientEnabled)
{
// Reopen connection if it was lost
if (!m_socket.isOpen()) {
m_socket.connectToHost(m_settings.m_exportClientHost, m_settings.m_exportClientPort);
if (!m_socket->isOpen()) {
m_socket->connectToHost(m_settings.m_exportClientHost, m_settings.m_exportClientPort);
}
// Send data
m_socket.write(data, length);
m_socket->write(data, length);
}
}
@ -314,7 +301,7 @@ char *ADSBDemodWorker::escape(char *p, char c) @@ -314,7 +301,7 @@ char *ADSBDemodWorker::escape(char *p, char c)
void ADSBDemodWorker::handleADSB(QByteArray data, const QDateTime dateTime, float correlation)
{
if (m_logFile.isOpen()) {
m_logStream << dateTime.date().toString() << "," << dateTime.time().toString() << "," << data.toHex() << "," << correlation << "\n";
m_logStream << dateTime.date().toString() << "," << dateTime.time().toString(QStringLiteral("hh:mm:ss.zzz")) << "," << data.toHex() << "," << correlation << "\n";
}
if (m_settings.m_feedEnabled && (m_settings.m_exportClientEnabled || m_settings.m_exportServerEnabled))
@ -365,7 +352,7 @@ void ADSBDemodWorker::handleADSB(QByteArray data, const QDateTime dateTime, floa @@ -365,7 +352,7 @@ void ADSBDemodWorker::handleADSB(QByteArray data, const QDateTime dateTime, floa
send(beastBinary, length);
}
if (m_settings.m_exportServerEnabled) {
m_beastServer.send(beastBinary, length);
m_beastServer->send(beastBinary, length);
}
}
if (m_settings.m_exportClientEnabled && (m_settings.m_exportClientFormat == ADSBDemodSettings::BeastHex))
@ -379,14 +366,11 @@ void ADSBDemodWorker::handleADSB(QByteArray data, const QDateTime dateTime, floa @@ -379,14 +366,11 @@ void ADSBDemodWorker::handleADSB(QByteArray data, const QDateTime dateTime, floa
// Periodically send heartbeat to keep connection alive
void ADSBDemodWorker::heartbeat()
{
if (m_running)
{
const char heartbeat[] = {BEAST_ESC, '1', 0, 0, 0, 0, 0, 0, 0, 0, 0}; // Mode AC packet
if (m_settings.m_exportClientEnabled) {
send(heartbeat, sizeof(heartbeat));
}
if (m_settings.m_exportServerEnabled) {
m_beastServer.send(heartbeat, sizeof(heartbeat));
}
const char heartbeat[] = {BEAST_ESC, '1', 0, 0, 0, 0, 0, 0, 0, 0, 0}; // Mode AC packet
if (m_settings.m_feedEnabled && m_settings.m_exportClientEnabled) {
send(heartbeat, sizeof(heartbeat));
}
if (m_settings.m_feedEnabled && m_settings.m_exportServerEnabled) {
m_beastServer->send(heartbeat, sizeof(heartbeat));
}
}

19
plugins/channelrx/demodadsb/adsbdemodworker.h

@ -84,24 +84,25 @@ public: @@ -84,24 +84,25 @@ public:
ADSBDemodWorker();
~ADSBDemodWorker();
void reset();
bool startWork();
void stopWork();
bool isRunning() const { return m_running; }
MessageQueue *getInputMessageQueue() { return &m_inputMessageQueue; }
public slots:
// Called when the worker thread starts; everything with thread affinity is
// created here rather than in the constructor
void startWork();
public:
private:
MessageQueue m_inputMessageQueue;
ADSBDemodSettings m_settings;
bool m_running;
QRecursiveMutex m_mutex;
QTimer m_heartbeatTimer;
QTcpSocket m_socket;
QTimer *m_heartbeatTimer;
QTcpSocket *m_socket;
QFile m_logFile;
QTextStream m_logStream;
qint64 m_startTime;
ADSBBeastServer m_beastServer;
ADSBBeastServer *m_beastServer;
bool handleMessage(const Message& cmd);
void applySettings(const ADSBDemodSettings& settings, const QStringList& settingsKeys, bool force = false);

11
plugins/channelrx/demodadsb/adsbosmtemplateserver.h

@ -28,14 +28,15 @@ class ADSBOSMTemplateServer : public QTcpServer @@ -28,14 +28,15 @@ class ADSBOSMTemplateServer : public QTcpServer
{
Q_OBJECT
private:
QString m_thunderforestAPIKey;
QString m_maptilerAPIKey;
QString m_cartoDBAPIKey;
public:
// port - port to listen on / is listening on. Use 0 for any free port.
ADSBOSMTemplateServer(const QString &maptilerAPIKey, quint16 &port, QObject* parent = 0) :
ADSBOSMTemplateServer(const QString &maptilerAPIKey, const QString &cartoDBAPIKey, quint16 &port, QObject* parent = 0) :
QTcpServer(parent),
m_maptilerAPIKey(maptilerAPIKey)
m_maptilerAPIKey(maptilerAPIKey),
m_cartoDBAPIKey(cartoDBAPIKey)
{
listen(QHostAddress::Any, port);
port = serverPort();
@ -100,14 +101,14 @@ private slots: @@ -100,14 +101,14 @@ private slots:
int idx = map.indexOf(tokens[1]);
xml = QString("\
{\
\"UrlTemplate\" : \"http://1.basemaps.cartocdn.com/%2/%z/%x/%y.png%1\",\
\"UrlTemplate\" : \"http://1.basemaps.cartocdn.com/%2/%z/%x/%y.png%1?key=%4\",\
\"ImageFormat\" : \"png\",\
\"QImageFormat\" : \"Indexed8\",\
\"ID\" : \"%3\",\
\"MaximumZoomLevel\" : 20,\
\"MapCopyRight\" : \"<a href='https://carto.com'>CartoDB</a>\",\
\"DataCopyRight\" : \"<a href='https://carto.com'>CartoDB</a>\"\
}").arg(hiresURL).arg(mapUrl[idx]).arg(mapId[idx]);
}").arg(hiresURL).arg(mapUrl[idx]).arg(mapId[idx]).arg(m_cartoDBAPIKey);
}
else
{

BIN
plugins/channelrx/demodadsb/map/liveries/A20N.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.8 KiB

BIN
plugins/channelrx/demodadsb/map/liveries/A20N_AAN.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.9 KiB

BIN
plugins/channelrx/demodadsb/map/liveries/A20N_ACI.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.3 KiB

BIN
plugins/channelrx/demodadsb/map/liveries/A20N_ADH.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.3 KiB

BIN
plugins/channelrx/demodadsb/map/liveries/A20N_AEE.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.0 KiB

BIN
plugins/channelrx/demodadsb/map/liveries/A20N_AFL.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.0 KiB

BIN
plugins/channelrx/demodadsb/map/liveries/A20N_AFX.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.0 KiB

BIN
plugins/channelrx/demodadsb/map/liveries/A20N_AHY.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.0 KiB

BIN
plugins/channelrx/demodadsb/map/liveries/A20N_AIC.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.0 KiB

BIN
plugins/channelrx/demodadsb/map/liveries/A20N_AIC_VTI.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.9 KiB

BIN
plugins/channelrx/demodadsb/map/liveries/A20N_AIQ.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.3 KiB

BIN
plugins/channelrx/demodadsb/map/liveries/A20N_ALK.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.0 KiB

BIN
plugins/channelrx/demodadsb/map/liveries/A20N_AMC.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.2 KiB

BIN
plugins/channelrx/demodadsb/map/liveries/A20N_AMU.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.0 KiB

BIN
plugins/channelrx/demodadsb/map/liveries/A20N_AMV.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.0 KiB

BIN
plugins/channelrx/demodadsb/map/liveries/A20N_ANA.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.1 KiB

BIN
plugins/channelrx/demodadsb/map/liveries/A20N_ANZ.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.2 KiB

BIN
plugins/channelrx/demodadsb/map/liveries/A20N_APJ.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.1 KiB

BIN
plugins/channelrx/demodadsb/map/liveries/A20N_AUA.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.0 KiB

BIN
plugins/channelrx/demodadsb/map/liveries/A20N_AUL.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.1 KiB

BIN
plugins/channelrx/demodadsb/map/liveries/A20N_AVA.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.0 KiB

BIN
plugins/channelrx/demodadsb/map/liveries/A20N_AXM.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.3 KiB

BIN
plugins/channelrx/demodadsb/map/liveries/A20N_AZU.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.9 KiB

BIN
plugins/channelrx/demodadsb/map/liveries/A20N_BAV.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.0 KiB

BIN
plugins/channelrx/demodadsb/map/liveries/A20N_BAW.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.8 KiB

BIN
plugins/channelrx/demodadsb/map/liveries/A20N_BEL.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.0 KiB

BIN
plugins/channelrx/demodadsb/map/liveries/A20N_BHE.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.0 KiB

BIN
plugins/channelrx/demodadsb/map/liveries/A20N_BTK.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.0 KiB

BIN
plugins/channelrx/demodadsb/map/liveries/A20N_BVX.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.9 KiB

BIN
plugins/channelrx/demodadsb/map/liveries/A20N_CBJ.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.0 KiB

BIN
plugins/channelrx/demodadsb/map/liveries/A20N_CCA.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.0 KiB

BIN
plugins/channelrx/demodadsb/map/liveries/A20N_CCM.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.1 KiB

BIN
plugins/channelrx/demodadsb/map/liveries/A20N_CDC.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.2 KiB

BIN
plugins/channelrx/demodadsb/map/liveries/A20N_CEB.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.1 KiB

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save