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
|
After Width: | Height: | Size: 31 KiB |
|
After Width: | Height: | Size: 115 KiB |
|
After Width: | Height: | Size: 21 KiB |
|
After Width: | Height: | Size: 87 KiB |
|
After Width: | Height: | Size: 68 KiB |
|
After Width: | Height: | Size: 242 KiB |
|
After Width: | Height: | Size: 28 KiB |
|
After Width: | Height: | Size: 233 KiB |
|
After Width: | Height: | Size: 26 KiB |
|
After Width: | Height: | Size: 76 KiB |
|
After Width: | Height: | Size: 30 KiB |
|
After Width: | Height: | Size: 70 KiB |
@ -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 */ |
||||
|
||||
@ -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; |
||||
} |
||||
|
||||
@ -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
|
||||
@ -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
|
||||
@ -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
|
||||
@ -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
|
||||
|
After Width: | Height: | Size: 337 B |
@ -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; |
||||
} |
||||
|
||||
@ -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
|
||||
@ -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(); |
||||
} |
||||
@ -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
|
||||
@ -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(); |
||||
} |
||||
} |
||||
@ -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
|
||||
|
After Width: | Height: | Size: 3.8 KiB |
|
After Width: | Height: | Size: 3.9 KiB |
|
After Width: | Height: | Size: 4.3 KiB |
|
After Width: | Height: | Size: 4.3 KiB |
|
After Width: | Height: | Size: 4.0 KiB |
|
After Width: | Height: | Size: 4.0 KiB |
|
After Width: | Height: | Size: 4.0 KiB |
|
After Width: | Height: | Size: 4.0 KiB |
|
After Width: | Height: | Size: 4.0 KiB |
|
After Width: | Height: | Size: 3.9 KiB |
|
After Width: | Height: | Size: 4.3 KiB |
|
After Width: | Height: | Size: 4.0 KiB |
|
After Width: | Height: | Size: 4.2 KiB |
|
After Width: | Height: | Size: 4.0 KiB |
|
After Width: | Height: | Size: 4.0 KiB |
|
After Width: | Height: | Size: 4.1 KiB |
|
After Width: | Height: | Size: 4.2 KiB |
|
After Width: | Height: | Size: 4.1 KiB |
|
After Width: | Height: | Size: 4.0 KiB |
|
After Width: | Height: | Size: 4.1 KiB |
|
After Width: | Height: | Size: 4.0 KiB |
|
After Width: | Height: | Size: 4.3 KiB |
|
After Width: | Height: | Size: 3.9 KiB |
|
After Width: | Height: | Size: 4.0 KiB |
|
After Width: | Height: | Size: 3.8 KiB |
|
After Width: | Height: | Size: 4.0 KiB |
|
After Width: | Height: | Size: 4.0 KiB |
|
After Width: | Height: | Size: 4.0 KiB |
|
After Width: | Height: | Size: 3.9 KiB |
|
After Width: | Height: | Size: 4.0 KiB |
|
After Width: | Height: | Size: 4.0 KiB |
|
After Width: | Height: | Size: 4.1 KiB |
|
After Width: | Height: | Size: 4.2 KiB |
|
After Width: | Height: | Size: 4.1 KiB |