diff --git a/CMakeLists.txt b/CMakeLists.txt index dd82ccf9b..5e0f9acc1 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -141,6 +141,7 @@ option(ENABLE_CHANNELRX_DEMODDVB "Enable channelrx demoddvb plugin" ON) option(ENABLE_CHANNELRX_RADIOCLOCK "Enable channelrx radioclock plugin" ON) option(ENABLE_CHANNELRX_RADIOASTRONOMY "Enable channelrx radioastronomy plugin" ON) option(ENABLE_CHANNELRX_DEMODRADIOSONDE "Enable channelrx demodradiosonde plugin" ON) +option(ENABLE_CHANNELRX_DEMODDRONEID "Enable channelrx demoddroneid plugin" ON) option(ENABLE_CHANNELRX_FREQTRACKER "Enable channelrx freqtracker plugin" ON) option(ENABLE_CHANNELRX_DEMODATV "Enable channelrx demodatv plugin" ON) option(ENABLE_CHANNELRX_DEMODPAGER "Enable channelrx demodpager plugin" ON) diff --git a/doc/img/DroneIDDemod_plugin.png b/doc/img/DroneIDDemod_plugin.png new file mode 100644 index 000000000..07f729b22 Binary files /dev/null and b/doc/img/DroneIDDemod_plugin.png differ diff --git a/plugins/channelrx/CMakeLists.txt b/plugins/channelrx/CMakeLists.txt index 5e0402268..b703fa322 100644 --- a/plugins/channelrx/CMakeLists.txt +++ b/plugins/channelrx/CMakeLists.txt @@ -139,6 +139,12 @@ else() message(STATUS "Not building demodradiosonde (ENABLE_CHANNELRX_DEMODRADIOSONDE=${ENABLE_CHANNELRX_DEMODRADIOSONDE})") endif() +if (ENABLE_CHANNELRX_DEMODDRONEID) + add_subdirectory(demoddroneid) +else() + message(STATUS "Not building demoddroneid (ENABLE_CHANNELRX_DEMODDRONEID=${ENABLE_CHANNELRX_DEMODDRONEID})") +endif() + if(ENABLE_CHANNELRX_DEMODDAB AND DAB_FOUND AND ZLIB_FOUND AND FAAD_FOUND) add_subdirectory(demoddab) else() diff --git a/plugins/channelrx/demoddroneid/CMakeLists.txt b/plugins/channelrx/demoddroneid/CMakeLists.txt new file mode 100644 index 000000000..7cd485f14 --- /dev/null +++ b/plugins/channelrx/demoddroneid/CMakeLists.txt @@ -0,0 +1,78 @@ +project(demoddroneid) + +set(demoddroneid_SOURCES + droneiddemod.cpp + droneiddemodsettings.cpp + droneiddemodbaseband.cpp + droneiddemodsink.cpp + droneiddemodworker.cpp + droneiddemodplugin.cpp + droneiddemodwebapiadapter.cpp + droneiddecoder.cpp + droneiddetector.cpp + droneiddemod.qrc +) + +set(demoddroneid_HEADERS + droneiddemod.h + droneiddemodsettings.h + droneiddemodbaseband.h + droneiddemodsink.h + droneiddemodworker.h + droneiddemodplugin.h + droneiddemodwebapiadapter.h + droneiddecoder.h + droneiddetector.h +) + +include_directories( + ${CMAKE_SOURCE_DIR}/swagger/sdrangel/code/qt5/client +) + +if(NOT SERVER_MODE) + set(demoddroneid_SOURCES + ${demoddroneid_SOURCES} + droneiddemodgui.cpp + droneiddemodgui.ui + ) + set(demoddroneid_HEADERS + ${demoddroneid_HEADERS} + droneiddemodgui.h + ) + + set(TARGET_NAME ${PLUGINS_PREFIX}demoddroneid) + set(TARGET_LIB "Qt::Widgets") + set(TARGET_LIB_GUI "sdrgui") + set(INSTALL_FOLDER ${INSTALL_PLUGINS_DIR}) +else() + set(TARGET_NAME ${PLUGINSSRV_PREFIX}demoddroneidsrv) + set(TARGET_LIB "") + set(TARGET_LIB_GUI "") + set(INSTALL_FOLDER ${INSTALL_PLUGINSSRV_DIR}) +endif() + +if(NOT Qt6_FOUND) + add_library(${TARGET_NAME} ${demoddroneid_SOURCES}) +else() + qt_add_plugin(${TARGET_NAME} CLASS_NAME DroneIDDemodPlugin) + target_sources(${TARGET_NAME} PRIVATE ${demoddroneid_SOURCES}) +endif() + +if(NOT BUILD_SHARED_LIBS) + set_property(GLOBAL APPEND PROPERTY STATIC_PLUGINS_PROPERTY ${TARGET_NAME}) +endif() + +target_link_libraries(${TARGET_NAME} PRIVATE + Qt::Core + ${TARGET_LIB} + sdrbase + ${TARGET_LIB_GUI} +) + +install(TARGETS ${TARGET_NAME} DESTINATION ${INSTALL_FOLDER}) + +# Install debug symbols +if (WIN32) + install(FILES $/${TARGET_NAME}stripped.pdb CONFIGURATIONS Release DESTINATION ${INSTALL_FOLDER} RENAME ${TARGET_NAME}.pdb ) + install(FILES $ CONFIGURATIONS Debug RelWithDebInfo DESTINATION ${INSTALL_FOLDER} ) +endif() diff --git a/plugins/channelrx/demoddroneid/droneiddecoder.cpp b/plugins/channelrx/demoddroneid/droneiddecoder.cpp new file mode 100644 index 000000000..ed3f565ff --- /dev/null +++ b/plugins/channelrx/demoddroneid/droneiddecoder.cpp @@ -0,0 +1,473 @@ +/////////////////////////////////////////////////////////////////////////////////// +// Copyright (C) 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 . // +/////////////////////////////////////////////////////////////////////////////////// + +#include +#include + +#include "dsp/fftengine.h" +#include "dsp/fftfactory.h" +#include "util/ltegold.h" + +#include "droneiddecoder.h" + +const int DroneIDDecoder::m_cpLengths[DroneIDDecoder::m_nbSymbols] = {80, 72, 72, 72, 72, 72, 72, 72, 80}; +const int DroneIDDecoder::m_zcSymbols[2] = {3, 5}; +const int DroneIDDecoder::m_zcRoots[2] = {600, 147}; +const int DroneIDDecoder::m_dataSymbols[6] = {1, 2, 4, 6, 7, 8}; + +DroneIDDecoder::DroneIDDecoder(FFTFactory *fftFactory) : + m_maxIterations(8), + m_maxIntegerCFO(8), + m_fftFactory(fftFactory), + m_fftEngine(nullptr), + m_fftSequence(0), + m_kissFFT(m_fftSize, false) +{ + if (m_fftFactory) { + m_fftSequence = m_fftFactory->getEngine(m_fftSize, false, &m_fftEngine); + } + + carrierBins(m_bins); + zadoffChu(m_zcRoots[0], m_zc[0]); + zadoffChu(m_zcRoots[1], m_zc[1]); + m_zcRef.resize(m_nbCarriers); + for (int c = 0; c < m_nbCarriers; c++) { + m_zcRef[c] = std::conj(m_zc[0][c]) * m_zc[1][c]; + } + m_zcDiff.resize(m_fftSize); + symbolStarts(m_symbolStarts); + LTEGold::generate(m_scramblerInit, m_codedBits, m_scrambler); + m_turbo.setBlockSize(m_blockBits); + m_fftIn.resize(m_fftSize); + m_symbols.resize(m_nbSymbols); + for (auto& s : m_symbols) { + s.resize(m_fftSize); + } +} + +void DroneIDDecoder::carrierBins(std::vector& bins) +{ + bins.resize(m_nbCarriers); + for (int i = 0; i < m_nbCarriers; i++) + { + int k = i < m_nbCarriers / 2 ? i - m_nbCarriers / 2 : i - m_nbCarriers / 2 + 1; // -300..-1, 1..300 + bins[i] = (k + m_fftSize) % m_fftSize; + } +} + +void DroneIDDecoder::zadoffChu(int root, std::vector& seq) +{ + const int Nzc = m_nbCarriers + 1; + + // Element on DC (n=300) isn't transmitted + seq.clear(); + for (int n = 0; n < Nzc; n++) + { + if (n != Nzc / 2) + { + double phase = -M_PI * root * (double) n * (double) (n + 1) / Nzc; + seq.push_back(cf((float) std::cos(phase), (float) std::sin(phase))); + } + } +} + +void DroneIDDecoder::symbolStarts(std::vector& starts) +{ + starts.resize(m_nbSymbols); + int p = 0; + for (int i = 0; i < m_nbSymbols; i++) + { + starts[i] = p; + p += m_cpLengths[i] + m_fftSize; + } +} + +// Find candidate frame starts by correlating each symbol's cyclic prefix with the end of the symbol. +// As symbols are similar lengths, the metric is also high when offset by a whole number of symbols, +// particularly at low SNR, so we return the best start along with the best starts nearby offset by +// whole symbols, to be checked with the ZC sequences. +void DroneIDDecoder::findTiming(const cf *samples, int length, std::vector& candidates) +{ + const int N = m_fftSize; + const int symbolLength = m_cpLengths[1] + N; + const int search = 24; + std::vector> q(length + 1); + std::vector e(length + 1); + const int nbStarts = length - m_frameLength + 1; + + candidates.clear(); + if (nbStarts <= 0) { + return; + } + + q[0] = 0.0; + e[0] = 0.0; + for (int i = 0; i < length; i++) + { + std::complex x = samples[i]; + q[i + 1] = q[i] + ((i + N < length) ? x * std::conj((std::complex) samples[i + N]) : 0.0); + e[i + 1] = e[i] + std::norm(x); + } + + std::vector metrics(nbStarts); + std::vector corrs(nbStarts); + int best = 0; + + for (int s = 0; s < nbStarts; s++) + { + std::complex acc = 0.0; + double energy = 0.0; + + for (int k = 0; k < m_nbSymbols; k++) + { + int a = s + m_symbolStarts[k]; + int cp = m_cpLengths[k]; + acc += q[a + cp] - q[a]; + energy += 0.5 * ((e[a + cp] - e[a]) + (e[a + N + cp] - e[a + N])); + } + metrics[s] = energy > 0.0 ? (float) (std::abs(acc) / energy) : 0.0f; + corrs[s] = cf((float) acc.real(), (float) acc.imag()); + if (metrics[s] > metrics[best]) { + best = s; + } + } + + for (int j = -m_maxSymbolOffset; j <= m_maxSymbolOffset; j++) + { + int centre = best + j * symbolLength; + int lo = std::max(0, centre - (j == 0 ? 0 : search)); + int hi = std::min(nbStarts - 1, centre + (j == 0 ? 0 : search)); + if (lo > hi) { + continue; + } + int s = lo; + for (int i = lo + 1; i <= hi; i++) + { + if (metrics[i] > metrics[s]) { + s = i; + } + } + Candidate c; + c.m_start = s; + c.m_correlation = corrs[s]; + c.m_metric = metrics[s]; + candidates.push_back(c); + } +} + +DroneIDDecoder::~DroneIDDecoder() +{ + if (m_fftFactory && m_fftEngine) { + m_fftFactory->releaseEngine(m_fftSize, false, m_fftSequence); + } +} + +// FFT a symbol after correcting frequency offset +void DroneIDDecoder::fftSymbol(const cf *samples, int length, int frameStart, double cyclesPerSample, int symbol) +{ + const int start = frameStart + m_symbolStarts[symbol] + m_cpLengths[symbol] - m_fftBackoff; + cf *in = m_fftEngine ? m_fftEngine->in() : m_fftIn.data(); + + // Use absolute sample index for phase, so symbols are phase coherent + std::complex rotation = std::polar(1.0, -2.0 * M_PI * std::fmod(cyclesPerSample * start, 1.0)); + const std::complex step = std::polar(1.0, -2.0 * M_PI * cyclesPerSample); + + for (int i = 0; i < m_fftSize; i++) + { + int idx = start + i; + if ((idx >= 0) && (idx < length)) { + in[i] = samples[idx] * cf((float) rotation.real(), (float) rotation.imag()); + } else { + in[i] = 0.0f; + } + rotation *= step; + } + + if (m_fftEngine) + { + m_fftEngine->transform(); + std::copy(m_fftEngine->out(), m_fftEngine->out() + m_fftSize, m_symbols[symbol].begin()); + } + else + { + m_kissFFT.transform(m_fftIn.data(), m_symbols[symbol].data()); + } +} + +// FFT each symbol after correcting frequency offset +void DroneIDDecoder::fftSymbols(const cf *samples, int length, int frameStart, double cyclesPerSample) +{ + for (int k = 0; k < m_nbSymbols; k++) { + fftSymbol(samples, length, frameStart, cyclesPerSample, k); + } +} + +// Phase difference between the ZC symbols in each FFT bin, for zcConsistency +void DroneIDDecoder::zcPhaseDifference() +{ + const std::vector& y4 = m_symbols[m_zcSymbols[0]]; + const std::vector& y6 = m_symbols[m_zcSymbols[1]]; + + // Only phase is used, so a strong narrowband interferer on one carrier doesn't dominate + for (int i = 0; i < m_fftSize; i++) + { + cf p = y4[i] * std::conj(y6[i]); + float mag = std::abs(p); + m_zcDiff[i] = mag > 0.0f ? p / mag : 0.0f; + } +} + +// Estimate channel from both ZC symbols, assuming a frequency offset of shift bins. +// With the correct shift, both estimates are the same apart from a common phase rotation. +// As the ZC sequences have unit magnitude, h4*conj(h6) = y4*conj(y6) * conj(zc4)*zc6. +float DroneIDDecoder::zcConsistency(int shift) +{ + cf corr = 0.0f; + + for (int c = 0; c < m_nbCarriers; c++) + { + int bin = (m_bins[c] + shift + m_fftSize) % m_fftSize; + corr += m_zcDiff[bin] * m_zcRef[c]; + } + + return std::abs(corr) / m_nbCarriers; +} + +bool DroneIDDecoder::checkCRC(const std::vector& bits) +{ + uint8_t bytes[m_blockBytes]; + + for (int i = 0; i < m_blockBytes; i++) + { + uint8_t b = 0; + for (int j = 0; j < 8; j++) { + b = (b << 1) | bits[i * 8 + j]; + } + bytes[i] = b; + } + m_crc.init(); + m_crc.calculate(bytes, m_blockBytes); + return m_crc.get() == 0; +} + +bool DroneIDDecoder::decode(const cf *samples, int length, Result& result) +{ + // Pad so a frame without the first symbol can start at the beginning of the buffer + const int pad = m_cpLengths[0] + m_fftSize; + const int paddedLength = length + 2 * pad; + + result = Result(); + m_derotated.assign(paddedLength, 0.0f); + std::copy(samples, samples + length, m_derotated.begin() + pad); + + // Candidate timings and fractional frequency offsets from cyclic prefix + std::vector candidates; + findTiming(m_derotated.data(), paddedLength, candidates); + for (const auto& candidate : candidates) { + result.m_cpMetric = std::max(result.m_cpMetric, candidate.m_metric); + } + + // For each candidate, find integer frequency offset where both ZC symbols give consistent + // channel estimates. Choose candidate with best consistency. + int frameStart = -1; + double cyclesPerSample = 0.0; + int bestShift = 0; + float bestMetric = -1.0f; + + for (const auto& candidate : candidates) + { + if (candidate.m_metric < m_minCPMetric) { + continue; + } + double cycles = -std::arg(candidate.m_correlation) / (2.0 * M_PI * m_fftSize); + // Only the ZC symbols are needed to evaluate the candidate + fftSymbol(m_derotated.data(), paddedLength, candidate.m_start, cycles, m_zcSymbols[0]); + fftSymbol(m_derotated.data(), paddedLength, candidate.m_start, cycles, m_zcSymbols[1]); + zcPhaseDifference(); + + for (int shift = -m_maxIntegerCFO; shift <= m_maxIntegerCFO; shift++) + { + float m = zcConsistency(shift); + if (m > bestMetric) + { + bestMetric = m; + bestShift = shift; + frameStart = candidate.m_start; + cyclesPerSample = cycles; + result.m_cpMetric = candidate.m_metric; + } + } + } + + result.m_zcMetric = std::max(bestMetric, 0.0f); + if ((frameStart < 0) || (bestMetric < m_minZCMetric)) { + return false; + } + result.m_frameStart = frameStart - pad; + cyclesPerSample += bestShift / (double) m_fftSize; + fftSymbols(m_derotated.data(), paddedLength, frameStart, cyclesPerSample); + result.m_cfo = (float) (cyclesPerSample * m_sampleRate); + + // Channel estimate from ZC symbols + std::vector h4(m_nbCarriers), h6(m_nbCarriers), h(m_nbCarriers); + cf drift = 0.0f; + + for (int c = 0; c < m_nbCarriers; c++) + { + h4[c] = m_symbols[m_zcSymbols[0]][m_bins[c]] * std::conj(m_zc[0][c]); + h6[c] = m_symbols[m_zcSymbols[1]][m_bins[c]] * std::conj(m_zc[1][c]); + cf p = h6[c] * std::conj(h4[c]); + float mag = std::abs(p); + if (mag > 0.0f) { + drift += p / mag; + } + } + + // Residual phase rotation between the ZC symbols + float phi = std::arg(drift); + cf derot = std::polar(1.0f, -phi); + std::vector noise(m_nbCarriers); + std::vector havg(m_nbCarriers); + + for (int c = 0; c < m_nbCarriers; c++) + { + cf h6r = h6[c] * derot; + havg[c] = 0.5f * (h4[c] + h6r); + // Each estimate has the noise variance of the received signal, the difference has twice that + noise[c] = 0.5f * std::norm(h4[c] - h6r); + } + + // Smooth channel estimate across adjacent carriers, and noise estimate over a wider range. + // Noise is estimated per carrier, so carriers with narrowband interference have low confidence. + std::vector sigma2(m_nbCarriers); + float signal = 0.0f; + float noiseTotal = 0.0f; + for (int c = 0; c < m_nbCarriers; c++) + { + cf sum = 0.0f; + int n = 0; + for (int d = -m_channelSmoothing; d <= m_channelSmoothing; d++) + { + int i = c + d; + if ((i >= 0) && (i < m_nbCarriers)) + { + sum += havg[i]; + n++; + } + } + h[c] = sum / (float) n; + signal += std::norm(h[c]); + + float nsum = 0.0f; + n = 0; + for (int d = -m_noiseSmoothing; d <= m_noiseSmoothing; d++) + { + int i = c + d; + if ((i >= 0) && (i < m_nbCarriers)) + { + nsum += noise[i]; + n++; + } + } + sigma2[c] = nsum / n; + noiseTotal += noise[c]; + } + signal /= m_nbCarriers; + noiseTotal = std::max(noiseTotal / m_nbCarriers, signal * 1e-6f); + for (int c = 0; c < m_nbCarriers; c++) { + sigma2[c] = std::max(sigma2[c], signal * 1e-6f); + } + result.m_snr = 10.0f * std::log10(signal / noiseTotal); + + // Channel for each symbol, interpolating phase drift linearly in time + const float t4 = (float) (m_symbolStarts[m_zcSymbols[0]] + m_cpLengths[m_zcSymbols[0]]); + const float t6 = (float) (m_symbolStarts[m_zcSymbols[1]] + m_cpLengths[m_zcSymbols[1]]); + auto symbolRotation = [&](int k) { + float t = (float) (m_symbolStarts[k] + m_cpLengths[k]); + return std::polar(1.0f, phi * (t - t4) / (t6 - t4)); + }; + + // Check first symbol, which is scrambled zeros, to see if it was transmitted + { + cf rot = symbolRotation(0); + int zeros = 0; + for (int c = 0; c < m_nbCarriers; c++) + { + cf r = m_symbols[0][m_bins[c]] * std::conj(h[c] * rot); + zeros += ((r.real() < 0.0f ? 1 : 0) == m_scrambler[2 * c]); + zeros += ((r.imag() < 0.0f ? 1 : 0) == m_scrambler[2 * c + 1]); + } + result.m_legacy = zeros < (int) (0.75f * 2 * m_nbCarriers); + } + + // Soft demap QPSK, descramble + std::vector llrs(m_codedBits); + const float scale = 2.0f * (float) M_SQRT2; + float evm = 0.0f; + + for (int d = 0; d < 6; d++) + { + int k = m_dataSymbols[d]; + cf rot = symbolRotation(k); + + for (int c = 0; c < m_nbCarriers; c++) + { + cf hk = h[c] * rot; + cf y = m_symbols[k][m_bins[c]]; + cf r = y * std::conj(hk); + int idx = 2 * (d * m_nbCarriers + c); + + llrs[idx] = scale * r.real() / sigma2[c] * (m_scrambler[idx] ? -1.0f : 1.0f); + llrs[idx + 1] = scale * r.imag() / sigma2[c] * (m_scrambler[idx + 1] ? -1.0f : 1.0f); + + float hn = std::norm(hk); + if (hn > 0.0f) + { + cf eq = r / hn; + cf ref((eq.real() < 0.0f ? -1.0f : 1.0f) / (float) M_SQRT2, (eq.imag() < 0.0f ? -1.0f : 1.0f) / (float) M_SQRT2); + evm += std::norm(eq - ref); + } + } + } + result.m_evm = std::sqrt(evm / (6 * m_nbCarriers)); + + // Rate dematching and turbo decoding + std::vector d0, d1, d2; + std::vector bits; + + LTERateMatcher::dematch(llrs, m_blockBits + 4, 0, d0, d1, d2); + int iterations = m_turbo.decode(d0, d1, d2, bits, m_maxIterations, + [this](const std::vector& b) { return checkCRC(b); }); + + result.m_iterations = std::abs(iterations); + result.m_crcValid = iterations > 0; + if (result.m_crcValid) + { + result.m_payload.resize(m_dataBytes); + for (int i = 0; i < m_dataBytes; i++) + { + uint8_t b = 0; + for (int j = 0; j < 8; j++) { + b = (b << 1) | bits[i * 8 + j]; + } + result.m_payload[i] = b; + } + } + + return true; +} diff --git a/plugins/channelrx/demoddroneid/droneiddecoder.h b/plugins/channelrx/demoddroneid/droneiddecoder.h new file mode 100644 index 000000000..e50d3fbc7 --- /dev/null +++ b/plugins/channelrx/demoddroneid/droneiddecoder.h @@ -0,0 +1,146 @@ +/////////////////////////////////////////////////////////////////////////////////// +// Copyright (C) 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 . // +/////////////////////////////////////////////////////////////////////////////////// + +#ifndef INCLUDE_DRONEIDDECODER_H +#define INCLUDE_DRONEIDDECODER_H + +#include +#include +#include +#include + +#include "dsp/kissfft.h" +#include "dsp/lteturbo.h" +#include "util/crc.h" + +class FFTEngine; +class FFTFactory; + +// Physical layer decoder for DJI DroneID bursts. +// +// A burst is 9 OFDM symbols at 15.36 MS/s (1024 point FFT, 15 kHz subcarrier spacing, +// 600 used subcarriers plus DC). Symbols 4 and 6 are Zadoff-Chu sequences used for +// synchronisation and channel estimation. Symbol 1 is a known (scrambled zero) symbol and +// is not sent by older drones. The remaining 6 symbols carry 7200 QPSK bits, which are +// a Gold sequence scrambled, rate matched, LTE turbo coded 1408 bit block with CRC24A. +class DroneIDDecoder +{ +public: + typedef std::complex cf; + + static constexpr int m_sampleRate = 15360000; + static constexpr int m_fftSize = 1024; + static constexpr int m_nbCarriers = 600; + static constexpr int m_nbSymbols = 9; + static constexpr int m_frameLength = 2 * (80 + 1024) + 7 * (72 + 1024); // 9880 samples + static const int m_cpLengths[m_nbSymbols]; + static const int m_zcSymbols[2]; // Symbol indices (0-based) holding ZC sequences + static const int m_zcRoots[2]; + static const int m_dataSymbols[6]; // Symbol indices holding data + static constexpr int m_codedBits = 6 * m_nbCarriers * 2; // 7200 + static constexpr int m_blockBits = 1408; // Turbo code block size K + static constexpr int m_blockBytes = m_blockBits / 8; + static constexpr int m_payloadBytes = 91; // Length of flight information message + static constexpr int m_dataBytes = m_blockBytes - 3; // Bytes available for messages (excluding CRC24) + static constexpr uint32_t m_scramblerInit = 0x12345678; + + struct Result { + int m_frameStart; // Index of start of frame (first CP) in buffer + bool m_legacy; // True if first symbol wasn't transmitted + float m_cpMetric; // Normalised cyclic prefix correlation 0..1 + float m_zcMetric; // Normalised Zadoff-Chu channel estimate consistency 0..1 + float m_cfo; // Carrier frequency offset in Hz + float m_snr; // SNR in dB, estimated from ZC symbols + float m_evm; // RMS error vector magnitude of data symbols + int m_iterations; // Number of turbo iterations used + bool m_crcValid; // Whether CRC24A of turbo decoded block was valid + std::vector m_payload; // m_dataBytes, if CRC valid. Message is at start, followed by zero padding. + + Result() : + m_frameStart(-1), + m_legacy(false), + m_cpMetric(0.0f), + m_zcMetric(0.0f), + m_cfo(0.0f), + m_snr(0.0f), + m_evm(0.0f), + m_iterations(0), + m_crcValid(false) + {} + }; + + // If fftFactory is null, a built-in FFT is used (E.g. for tests that run without DSPEngine) + DroneIDDecoder(FFTFactory *fftFactory = nullptr); + ~DroneIDDecoder(); + + void setMaxIterations(int iterations) { m_maxIterations = std::max(1, iterations); } + void setMaxIntegerCFO(int bins) { m_maxIntegerCFO = bins; } + + // Search samples (at m_sampleRate) for a frame and decode it. + // Returns true if a frame was detected (CP and ZC correlation), with result.m_crcValid + // indicating whether it was successfully decoded. + bool decode(const cf *samples, int length, Result& result); + + // Shared with modulator for tests + static void carrierBins(std::vector& bins); // FFT bin for each of the 600 carriers, lowest frequency first + static void zadoffChu(int root, std::vector& seq); // Frequency domain ZC for the 600 carriers + static void symbolStarts(std::vector& starts); // Start of each symbol's CP relative to frame start + +private: + static constexpr int m_maxSymbolOffset = 2; // Timing candidates checked either side of best CP correlation, in symbols + static constexpr int m_fftBackoff = 4; // Samples before the end of the CP that the FFT window starts, to allow for timing error + static constexpr int m_channelSmoothing = 4; // Carriers either side used for smoothing channel estimate + static constexpr int m_noiseSmoothing = 8; // Carriers either side used for smoothing noise estimate + static constexpr float m_minCPMetric = 0.1f; // Minimum metrics for a frame to be considered detected + static constexpr float m_minZCMetric = 0.3f; + + int m_maxIterations; + int m_maxIntegerCFO; + std::vector m_bins; + std::vector m_zc[2]; + std::vector m_zcRef; // conj(m_zc[0]) * m_zc[1] + std::vector m_symbolStarts; + std::vector m_scrambler; + FFTFactory *m_fftFactory; + FFTEngine *m_fftEngine; + unsigned int m_fftSequence; + kissfft m_kissFFT; + LTETurboDecoder m_turbo; + crc24a m_crc; + + // Working buffers + std::vector m_derotated; + std::vector m_fftIn; + std::vector> m_symbols; // FFT output per symbol, length m_fftSize + std::vector m_zcDiff; // Normalised y4*conj(y6) per FFT bin + + struct Candidate { + int m_start; + cf m_correlation; + float m_metric; + }; + + void findTiming(const cf *samples, int length, std::vector& candidates); + void fftSymbol(const cf *samples, int length, int frameStart, double cyclesPerSample, int symbol); + void fftSymbols(const cf *samples, int length, int frameStart, double cyclesPerSample); + void zcPhaseDifference(); + float zcConsistency(int shift); + bool checkCRC(const std::vector& bits); +}; + +#endif // INCLUDE_DRONEIDDECODER_H diff --git a/plugins/channelrx/demoddroneid/droneiddemod.cpp b/plugins/channelrx/demoddroneid/droneiddemod.cpp new file mode 100644 index 000000000..2c6cd5c55 --- /dev/null +++ b/plugins/channelrx/demoddroneid/droneiddemod.cpp @@ -0,0 +1,1133 @@ +/////////////////////////////////////////////////////////////////////////////////// +// Copyright (C) 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 . // +/////////////////////////////////////////////////////////////////////////////////// + +#include "droneiddemod.h" + +#include +#include + +#include +#include +#include +#include +#include + +#include "SWGChannelSettings.h" +#include "SWGChannelReport.h" +#include "SWGWorkspaceInfo.h" +#include "SWGMapItem.h" +#include "SWGMapAnimation.h" + +#include "dsp/dspcommands.h" +#include "util/db.h" +#include "util/droneid.h" +#include "settings/serializable.h" +#include "device/deviceapi.h" +#include "channel/channelwebapiutils.h" +#include "maincore.h" + +MESSAGE_CLASS_DEFINITION(DroneIDDemod::MsgConfigureDroneIDDemod, Message) +MESSAGE_CLASS_DEFINITION(DroneIDDemod::MsgBurstResult, Message) + +const char * const DroneIDDemod::m_channelIdURI = "sdrangel.channel.droneiddemod"; +const char * const DroneIDDemod::m_channelId = "DroneIDDemod"; + + +DroneIDDemod::DroneIDDemod(DeviceAPI *deviceAPI) : + ChannelAPI(m_channelIdURI, ChannelAPI::StreamSingleSink), + m_deviceAPI(deviceAPI), + m_basebandSampleRate(0), + m_centerFrequency(0), + m_burstsDecoded(0), + m_dronesTracked(0), + m_scanPosition(0), + m_scanFrequency(0), + m_scanTuneTime(0), + m_scanBurstTime(-1), + m_scanLocked(false) +{ + setObjectName(m_channelId); + m_thread.setObjectName("DroneIDDeBB"); + + m_basebandSink = new DroneIDDemodBaseband(this); + m_basebandSink->setMessageQueueToChannel(getInputMessageQueue()); + m_basebandSink->setChannel(this); + m_basebandSink->moveToThread(&m_thread); + + applySettings(QStringList(), m_settings, true); + + m_deviceAPI->addChannelSink(this); + m_deviceAPI->addChannelSinkAPI(this); + + m_networkManager = new QNetworkAccessManager(); + QObject::connect( + m_networkManager, + &QNetworkAccessManager::finished, + this, + &DroneIDDemod::networkManagerFinished + ); + QObject::connect( + this, + &ChannelAPI::indexInDeviceSetChanged, + this, + &DroneIDDemod::handleIndexInDeviceSetChanged + ); + + connect(&m_mapTimer, &QTimer::timeout, this, &DroneIDDemod::removeOldDrones); + m_mapTimer.start(10 * 1000); + connect(&m_scanTimer, &QTimer::timeout, this, &DroneIDDemod::scanTimeout); +} + +DroneIDDemod::~DroneIDDemod() +{ + qDebug("DroneIDDemod::~DroneIDDemod"); + m_mapTimer.stop(); + m_scanTimer.stop(); + for (auto it = m_drones.begin(); it != m_drones.end(); ++it) + { + if (it->m_onMap) { + clearFromMap(it.key()); + } + } + QObject::disconnect( + m_networkManager, + &QNetworkAccessManager::finished, + this, + &DroneIDDemod::networkManagerFinished + ); + delete m_networkManager; + m_deviceAPI->removeChannelSinkAPI(this); + m_deviceAPI->removeChannelSink(this, true); + + if (m_basebandSink->isRunning()) { + stop(); + } + + delete m_basebandSink; +} + +void DroneIDDemod::setDeviceAPI(DeviceAPI *deviceAPI) +{ + if (deviceAPI != m_deviceAPI) + { + m_deviceAPI->removeChannelSinkAPI(this); + m_deviceAPI->removeChannelSink(this, false); + m_deviceAPI = deviceAPI; + m_deviceAPI->addChannelSink(this); + m_deviceAPI->addChannelSinkAPI(this); + } +} + +uint32_t DroneIDDemod::getNumberOfDeviceStreams() const +{ + return m_deviceAPI->getNbSourceStreams(); +} + +void DroneIDDemod::feed(const SampleVector::const_iterator& begin, const SampleVector::const_iterator& end, bool firstOfBurst) +{ + (void) firstOfBurst; + m_basebandSink->feed(begin, end); +} + +void DroneIDDemod::start() +{ + qDebug("DroneIDDemod::start"); + + m_basebandSink->reset(); + m_basebandSink->startWork(); + m_thread.start(); + + DSPSignalNotification *dspMsg = new DSPSignalNotification(m_basebandSampleRate, m_centerFrequency); + m_basebandSink->getInputMessageQueue()->push(dspMsg); + + DroneIDDemodBaseband::MsgConfigureDroneIDDemodBaseband *msg = DroneIDDemodBaseband::MsgConfigureDroneIDDemodBaseband::create(QStringList(), m_settings, true); + m_basebandSink->getInputMessageQueue()->push(msg); +} + +void DroneIDDemod::stop() +{ + qDebug("DroneIDDemod::stop"); + m_basebandSink->stopWork(); + m_thread.quit(); + m_thread.wait(); +} + +bool DroneIDDemod::handleMessage(const Message& cmd) +{ + if (MsgConfigureDroneIDDemod::match(cmd)) + { + MsgConfigureDroneIDDemod& cfg = (MsgConfigureDroneIDDemod&) cmd; + qDebug() << "DroneIDDemod::handleMessage: MsgConfigureDroneIDDemod"; + applySettings(cfg.getSettingsKeys(), cfg.getSettings(), cfg.getForce()); + + return true; + } + else if (DSPSignalNotification::match(cmd)) + { + DSPSignalNotification& notif = (DSPSignalNotification&) cmd; + m_basebandSampleRate = notif.getSampleRate(); + m_centerFrequency = notif.getCenterFrequency(); + // Forward to the sink + DSPSignalNotification* rep = new DSPSignalNotification(notif); // make a copy + qDebug() << "DroneIDDemod::handleMessage: DSPSignalNotification"; + m_basebandSink->getInputMessageQueue()->push(rep); + // Forward to GUI if any + if (getMessageQueueToGUI()) { + getMessageQueueToGUI()->push(new DSPSignalNotification(notif)); + } + + return true; + } + else if (MsgBurstResult::match(cmd)) + { + handleBurstResult((const MsgBurstResult&) cmd); + + return true; + } + else if (MainCore::MsgChannelDemodQuery::match(cmd)) + { + qDebug() << "DroneIDDemod::handleMessage: MsgChannelDemodQuery"; + sendSampleRateToDemodAnalyzer(); + + return true; + } + else + { + return false; + } +} + +void DroneIDDemod::handleBurstResult(const MsgBurstResult& result) +{ + if (result.getDetected() && m_scanTimer.isActive()) + { + qint64 now = m_scanClock.elapsed(); + + if (now - m_scanTuneTime >= m_scanSettleTime) + { + m_scanBurstTime = now; + + // Remember frequency, so it's searched first in future + qint64 frequency = scanFrequencyMatch(result.getFrequency()); + + if (frequency != 0) + { + m_scanHistory.removeAll(frequency); + m_scanHistory.prepend(frequency); + } + } + } + + // Forward bursts with DroneID sync to GUI, so it can display SNR even if not decoded. + // Other detections (E.g. from video link) aren't forwarded, as they can occur at a high rate. + if (result.getDetected() && getMessageQueueToGUI()) { + getMessageQueueToGUI()->push(new MsgBurstResult(result)); + } + + if (!result.getDecoded() || result.getMessage().isEmpty()) { + return; + } + + m_burstsDecoded++; + + const QByteArray& bytes = result.getMessage(); + DroneIDMessage *msg = DroneIDMessage::decode(bytes); + + // Forward to packet consumers (E.g. MCP) + QList packetPipes; + MainCore::instance()->getMessagePipes().getMessagePipes(this, "packets", packetPipes); + + for (const auto& pipe : packetPipes) + { + MessageQueue *messageQueue = qobject_cast(pipe->m_element); + messageQueue->push(MainCore::MsgPacket::create(this, bytes, result.getDateTime())); + } + + // Forward via UDP + if (m_settings.m_udpEnabled) { + m_udpSocket.writeDatagram(bytes.data(), bytes.size(), QHostAddress(m_settings.m_udpAddress), m_settings.m_udpPort); + } + + logMessage(result, msg); + + if (msg) + { + if (!msg->m_serial.isEmpty()) + { + Drone& drone = m_drones[msg->m_serial]; + m_dronesTracked = m_drones.size(); + drone.m_lastUpdate = QDateTime::currentDateTime(); + drone.m_lastSeen = result.getDateTime().isValid() ? result.getDateTime() : drone.m_lastUpdate; + if (msg->isFlightInformation()) + { + sendToMap(msg, result.getDateTime(), drone); + drone.m_onMap = true; + } + } + delete msg; + } +} + +void DroneIDDemod::logMessage(const MsgBurstResult& result, const DroneIDMessage *msg) +{ + if (!m_logFile.isOpen()) { + return; + } + + m_logStream << result.getDateTime().date().toString() << "," + << result.getDateTime().time().toString() << "," + << result.getMessage().toHex() << ","; + + if (msg && msg->isFlightInformation()) + { + m_logStream << msg->m_serial << "," + << msg->getProductTypeName() << "," + << msg->m_sequence << "," + << QString::number(msg->m_latitude, 'f', 7) << "," + << QString::number(msg->m_longitude, 'f', 7) << "," + << msg->m_altitude << "," + << msg->m_height << "," + << msg->getSpeed() << "," + << msg->m_vUp << "," + << msg->m_yaw << "," + << QString::number(msg->m_pilotLatitude, 'f', 7) << "," + << QString::number(msg->m_pilotLongitude, 'f', 7) << "," + << QString::number(msg->m_homeLatitude, 'f', 7) << "," + << QString::number(msg->m_homeLongitude, 'f', 7) << "," + << msg->m_uuid << "," + << (msg->m_crcValid ? "OK" : "Bad") << ","; + } + else if (msg) + { + m_logStream << msg->m_serial << ",,,,,,,,,,,,,,," << (msg->m_crcValid ? "OK" : "Bad") << ","; + } + else + { + m_logStream << ",,,,,,,,,,,,,,,,"; + } + m_logStream << result.getSNR() << "," << result.getCFO() << "," + << QString::number(result.getFrequency() / 1e6, 'f', 3) << "\n"; +} + +// If model is specified, it is displayed on the 3D map, oriented by imageRotation. +// If animation is specified, that animation in the model is started (or stopped if stopAnimation is true). +// altitudeReference is 0 for altitude above WGS84 ellipsoid, 1 to clamp to ground, 2 for height above ground +// or 3 for altitude above WGS84 ellipsoid, but not below ground. +void DroneIDDemod::sendMapItem(const QString& name, double latitude, double longitude, float altitude, int altitudeReference, + const QString& image, float imageRotation, const QString& label, const QString& text, const QDateTime& dateTime, + const QString& model, const QString& animation, bool stopAnimation) +{ + QList mapPipes; + MainCore::instance()->getMessagePipes().getMessagePipes(this, "mapitems", mapPipes); + + for (const auto& pipe : mapPipes) + { + MessageQueue *messageQueue = qobject_cast(pipe->m_element); + SWGSDRangel::SWGMapItem *swgMapItem = new SWGSDRangel::SWGMapItem(); + swgMapItem->setName(new QString(name)); + swgMapItem->setLatitude(latitude); + swgMapItem->setLongitude(longitude); + swgMapItem->setAltitude(altitude); + swgMapItem->setAltitudeReference(altitudeReference); + swgMapItem->setPositionDateTime(new QString(dateTime.toString(Qt::ISODateWithMs))); + swgMapItem->setFixedPosition(false); + swgMapItem->setImage(new QString(image)); + swgMapItem->setImageRotation(imageRotation); + swgMapItem->setLabel(new QString(label)); + swgMapItem->setText(new QString(text)); + if (!model.isEmpty()) + { + swgMapItem->setModel(new QString(model)); + swgMapItem->setOrientation(1); // Use heading, rather than velocity calculated from positions + swgMapItem->setHeading(imageRotation); + swgMapItem->setPitch(0.0f); + swgMapItem->setRoll(0.0f); + swgMapItem->setOrientationDateTime(new QString(dateTime.toString(Qt::ISODateWithMs))); + swgMapItem->setLabelAltitudeOffset(1.0f); + + if (!animation.isEmpty()) + { + // Each map item owns and deletes its animations, so create for each pipe + SWGSDRangel::SWGMapAnimation *swgAnimation = new SWGSDRangel::SWGMapAnimation(); + swgAnimation->setName(new QString(animation)); + swgAnimation->setStartDateTime(new QString(dateTime.toString(Qt::ISODateWithMs))); + swgAnimation->setReverse(0); + swgAnimation->setLoop(1); + swgAnimation->setMultiplier(1.0f); + swgAnimation->setStop(stopAnimation ? 1 : 0); + QList *animations = new QList(); + animations->append(swgAnimation); + swgMapItem->setAnimations(animations); + } + } + MainCore::MsgMapItem *msg = MainCore::MsgMapItem::create(this, swgMapItem); + messageQueue->push(msg); + } +} + +void DroneIDDemod::sendToMap(const DroneIDMessage *msg, const QDateTime& dateTime, Drone& drone) +{ + const QString model = msg->getProductTypeName(); + + if (msg->hasPosition()) + { + QString text = QString("DroneID\nSerial: %1\nModel: %2\nAltitude: %3 m (WGS84)\nHeight: %4 m (above take-off)\nSpeed: %5 m/s\nVertical speed: %6 m/s\nYaw: %7%8") + .arg(msg->m_serial) + .arg(model) + .arg(msg->m_altitude) + .arg(msg->m_height) + .arg(msg->getSpeed(), 0, 'f', 1) + .arg(msg->m_vUp, 0, 'f', 1) + .arg(msg->m_yaw, 0, 'f', 0) + .arg(QChar(0xb0)); + // Yaw is -180 to 180 + float heading = msg->m_yaw < 0.0f ? msg->m_yaw + 360.0f : msg->m_yaw; + float altitude; + int altitudeReference; + + if (m_settings.m_mapAltitude == DroneIDDemodSettings::MAP_ALTITUDE) + { + // Altitude appears to be GPS height above the WGS84 ellipsoid (not MSL), as used by the 3D map. + // GPS error can put it slightly below ground on take-off and landing, so clip to ground. + altitude = msg->m_altitude; + altitudeReference = 3; + } + else + { + // Height above take-off point, displayed relative to the ground at the drone's position. + // This is never below ground, but is offset by any difference in ground height from the take-off point. + altitude = std::max(msg->m_height, 0.0f); + altitudeReference = 2; + } + + // Spin propellers in 3D model while motors are on. Animations are only sent when this changes. + bool motorsOn = (msg->m_stateInfo & DroneIDMessage::MotorsOn) != 0; + QString animation; + + if (motorsOn != drone.m_propellersSpinning) + { + animation = "Take 01"; + drone.m_propellersSpinning = motorsOn; + } + + sendMapItem(msg->m_serial, msg->m_latitude, msg->m_longitude, altitude, altitudeReference, + "qrc:///droneiddemod/map/drone.png", heading, model, text, dateTime, "drone.glb", animation, !motorsOn); + } + if (msg->hasPilotPosition()) + { + QString text = QString("DroneID Pilot\nSerial: %1\nModel: %2").arg(msg->m_serial).arg(model); + sendMapItem(msg->m_serial + " Pilot", msg->m_pilotLatitude, msg->m_pilotLongitude, 0.0f, 1, + "qrc:///droneiddemod/map/pilot.png", 0.0f, QString("%1 Pilot").arg(model), text, dateTime); + } + if (msg->hasHomePosition()) + { + QString text = QString("DroneID Home\nSerial: %1\nModel: %2").arg(msg->m_serial).arg(model); + sendMapItem(msg->m_serial + " Home", msg->m_homeLatitude, msg->m_homeLongitude, 0.0f, 1, + "qrc:///droneiddemod/map/home.png", 0.0f, QString("%1 Home").arg(model), text, dateTime); + } +} + +void DroneIDDemod::clearFromMap(const QString& serial) +{ + QList mapPipes; + MainCore::instance()->getMessagePipes().getMessagePipes(this, "mapitems", mapPipes); + + for (const auto& pipe : mapPipes) + { + MessageQueue *messageQueue = qobject_cast(pipe->m_element); + for (const auto& name : {serial, serial + " Pilot", serial + " Home"}) + { + SWGSDRangel::SWGMapItem *swgMapItem = new SWGSDRangel::SWGMapItem(); + swgMapItem->setName(new QString(name)); + swgMapItem->setImage(new QString("")); + MainCore::MsgMapItem *msg = MainCore::MsgMapItem::create(this, swgMapItem); + messageQueue->push(msg); + } + } +} + +void DroneIDDemod::removeOldDrones() +{ + if (m_settings.m_mapTimeout <= 0) { + return; + } + + // When playing a recording faster or slower than real time, the message times from the file + // determine whether a drone has stopped transmitting. Wall clock time is always also checked, + // so drones are removed when the recording or transmissions stop + QDateTime latest; + for (const auto& drone : m_drones) + { + if (!latest.isValid() || (drone.m_lastSeen > latest)) { + latest = drone.m_lastSeen; + } + } + QDateTime now = QDateTime::currentDateTime(); + + for (auto it = m_drones.begin(); it != m_drones.end(); ) + { + bool expired = it->m_lastUpdate.secsTo(now) > m_settings.m_mapTimeout; + + if (m_settings.m_useFileTime) { + expired = expired || (it->m_lastSeen.secsTo(latest) > m_settings.m_mapTimeout); + } + + if (expired) + { + if (it->m_onMap) { + clearFromMap(it.key()); + } + it = m_drones.erase(it); + } + else + { + ++it; + } + } + m_dronesTracked = m_drones.size(); +} + +void DroneIDDemod::setCenterFrequency(qint64 frequency) +{ + DroneIDDemodSettings settings = m_settings; + settings.m_inputFrequencyOffset = frequency; + applySettings(QStringList("inputFrequencyOffset"), settings, false); + + if (m_guiMessageQueue) // forward to GUI if any + { + MsgConfigureDroneIDDemod *msgToGUI = MsgConfigureDroneIDDemod::create(QStringList("inputFrequencyOffset"), settings, false); + m_guiMessageQueue->push(msgToGUI); + } +} + +void DroneIDDemod::applySettings(const QStringList& settingsKeys, const DroneIDDemodSettings& settings, bool force) +{ + qDebug() << "DroneIDDemod::applySettings:" << settings.getDebugString(settingsKeys, force); + + if (settingsKeys.contains("streamIndex") && (m_settings.m_streamIndex != settings.m_streamIndex)) + { + if (m_deviceAPI->getSampleMIMO()) // change of stream is possible for MIMO devices only + { + m_deviceAPI->removeChannelSinkAPI(this); + m_deviceAPI->removeChannelSink(this, m_settings.m_streamIndex); + m_deviceAPI->addChannelSink(this, settings.m_streamIndex); + m_deviceAPI->addChannelSinkAPI(this); + m_settings.m_streamIndex = settings.m_streamIndex; // make sure ChannelAPI::getStreamIndex() is consistent + emit streamIndexChanged(settings.m_streamIndex); + } + } + + DroneIDDemodBaseband::MsgConfigureDroneIDDemodBaseband *msg = DroneIDDemodBaseband::MsgConfigureDroneIDDemodBaseband::create(settingsKeys, settings, force); + m_basebandSink->getInputMessageQueue()->push(msg); + + if (settings.m_useReverseAPI) + { + bool fullUpdate = ((settingsKeys.contains("useReverseAPI") && (m_settings.m_useReverseAPI != settings.m_useReverseAPI)) && settings.m_useReverseAPI) || + (settingsKeys.contains("reverseAPIAddress") && (m_settings.m_reverseAPIAddress != settings.m_reverseAPIAddress)) || + (settingsKeys.contains("reverseAPIPort") && (m_settings.m_reverseAPIPort != settings.m_reverseAPIPort)) || + (settingsKeys.contains("reverseAPIDeviceIndex") && (m_settings.m_reverseAPIDeviceIndex != settings.m_reverseAPIDeviceIndex)) || + (settingsKeys.contains("reverseAPIChannelIndex") && (m_settings.m_reverseAPIChannelIndex != settings.m_reverseAPIChannelIndex)); + webapiReverseSendSettings(settingsKeys, settings, fullUpdate || force); + } + + if ((settingsKeys.contains("logEnabled") && (settings.m_logEnabled != m_settings.m_logEnabled)) + || (settingsKeys.contains("logFilename") && (settings.m_logFilename != m_settings.m_logFilename)) + || force) + { + if (m_logFile.isOpen()) + { + m_logStream.flush(); + m_logFile.close(); + } + if (settings.m_logEnabled && !settings.m_logFilename.isEmpty()) + { + m_logFile.setFileName(settings.m_logFilename); + if (m_logFile.open(QIODevice::WriteOnly | QIODevice::Append | QIODevice::Text)) + { + qDebug() << "DroneIDDemod::applySettings - Logging to: " << settings.m_logFilename; + bool newFile = m_logFile.size() == 0; + m_logStream.setDevice(&m_logFile); + if (newFile) + { + // Write header + m_logStream << "Date,Time,Data,Serial,Model,Seq,Lat,Lon,Alt (m),Height (m),Speed (m/s),V/S (m/s),Yaw,Pilot Lat,Pilot Lon,Home Lat,Home Lon,UUID,CRC,SNR (dB),CFO (Hz),Frequency (MHz)\n"; + } + } + else + { + qDebug() << "DroneIDDemod::applySettings - Unable to open log file: " << settings.m_logFilename; + } + } + } + + bool scanChanged = (settingsKeys.contains("scan") && (settings.m_scan != m_settings.m_scan)) + || (settingsKeys.contains("scanBand") && (settings.m_scanBand != m_settings.m_scanBand)) + || force; + + if (force) { + m_settings = settings; + } else { + m_settings.applySettings(settingsKeys, settings); + } + + if (scanChanged) + { + if (m_settings.m_scan) { + startScan(); + } else { + stopScan(); + } + } +} + +// Scanning steps the device center frequency through the DroneID channels, so that the channel +// is on each of them for m_scanDwell seconds. When a burst with DroneID sync is detected, the scan +// pauses until no bursts have been detected for m_scanHold seconds. +// Each pass through the channels starts with those that bursts have previously been detected on, +// most recent first, as drones often reuse channels, followed by the remainder in frequency order. +void DroneIDDemod::startScan() +{ + m_scanFrequencies = DroneIDDemodSettings::getScanFrequencies(m_settings.m_scanBand); + m_scanClock.start(); + m_scanBurstTime = -1; + m_scanLocked = false; + + // Start on the current channel, if it's one of those being scanned + m_scanFrequency = scanFrequencyMatch(m_centerFrequency + m_settings.m_inputFrequencyOffset); + scanNewPass(); + + if (m_scanFrequency != 0) { + m_scanTuneTime = m_scanClock.elapsed() - m_scanSettleTime; + } else { + m_scanTuneTime = std::numeric_limits::min() / 2; // Tune on first timeout when device is running + } + + m_scanTimer.start(m_scanTimerInterval); +} + +void DroneIDDemod::stopScan() +{ + m_scanTimer.stop(); + m_scanLocked = false; +} + +// Returns the scanned frequency that matches the given frequency, or 0 if none +qint64 DroneIDDemod::scanFrequencyMatch(qint64 frequency) const +{ + for (const auto f : m_scanFrequencies) + { + // Allow for small differences due to LO correction or tuning resolution + if (std::abs(f - frequency) <= 1000) { + return f; + } + } + + return 0; +} + +// Create order of frequencies to visit: previously used frequencies first, then the rest. +// The current frequency is visited last, as we've just been listening to it. +void DroneIDDemod::scanNewPass() +{ + m_scanOrder.clear(); + + for (const auto f : m_scanHistory) + { + if (m_scanFrequencies.contains(f) && (f != m_scanFrequency)) { + m_scanOrder.append(f); + } + } + for (const auto f : m_scanFrequencies) + { + if (!m_scanOrder.contains(f) && (f != m_scanFrequency)) { + m_scanOrder.append(f); + } + } + if (m_scanFrequency != 0) { + m_scanOrder.append(m_scanFrequency); + } + + m_scanPosition = 0; +} + +void DroneIDDemod::scanTune(qint64 frequency) +{ + qint64 centerFrequency = frequency - m_settings.m_inputFrequencyOffset; + + m_scanFrequency = frequency; + m_scanTuneTime = m_scanClock.elapsed(); + + if (!ChannelWebAPIUtils::setCenterFrequency(getDeviceSetIndex(), centerFrequency)) { + qWarning() << "DroneIDDemod::scanTune: Failed to set device center frequency to" << centerFrequency; + } +} + +void DroneIDDemod::scanTimeout() +{ + if (m_scanOrder.isEmpty()) { + return; + } + + qint64 now = m_scanClock.elapsed(); + bool locked = (m_scanBurstTime >= 0) && (now - m_scanBurstTime < (qint64) (m_settings.m_scanHold * 1000.0f)); + + m_scanLocked = locked; + + // Don't retune while device isn't running, as no bursts can be received + if (locked || !m_basebandSink->isRunning()) { + return; + } + + if (m_scanBurstTime >= 0) + { + // Bursts have stopped on this channel. Start a new pass, so other previously used channels are searched first + m_scanBurstTime = -1; + scanNewPass(); + } + else if (now - m_scanTuneTime < (qint64) (m_settings.m_scanDwell * 1000.0f)) + { + return; + } + + if (m_scanPosition >= m_scanOrder.size()) { + scanNewPass(); + } + + scanTune(m_scanOrder[m_scanPosition++]); +} + +QByteArray DroneIDDemod::serialize() const +{ + return m_settings.serialize(); +} + +bool DroneIDDemod::deserialize(const QByteArray& data) +{ + if (m_settings.deserialize(data)) + { + MsgConfigureDroneIDDemod *msg = MsgConfigureDroneIDDemod::create(QStringList(), m_settings, true); + m_inputMessageQueue.push(msg); + return true; + } + else + { + m_settings.resetToDefaults(); + MsgConfigureDroneIDDemod *msg = MsgConfigureDroneIDDemod::create(QStringList(), m_settings, true); + m_inputMessageQueue.push(msg); + return false; + } +} + +void DroneIDDemod::sendSampleRateToDemodAnalyzer() +{ + QList reportPipes; + MainCore::instance()->getMessagePipes().getMessagePipes(this, "reportdemod", reportPipes); + + for (const auto& pipe : reportPipes) + { + MessageQueue *messageQueue = qobject_cast(pipe->m_element); + MainCore::MsgChannelDemodReport *msg = MainCore::MsgChannelDemodReport::create( + this, + DroneIDDemodSettings::DRONEIDDEMOD_CHANNEL_SAMPLE_RATE + ); + messageQueue->push(msg); + } +} + +int DroneIDDemod::webapiSettingsGet( + SWGSDRangel::SWGChannelSettings& response, + QString& errorMessage) +{ + (void) errorMessage; + response.setDroneIdDemodSettings(new SWGSDRangel::SWGDroneIDDemodSettings()); + response.getDroneIdDemodSettings()->init(); + webapiFormatChannelSettings(response, m_settings); + return 200; +} + +int DroneIDDemod::webapiWorkspaceGet( + SWGSDRangel::SWGWorkspaceInfo& response, + QString& errorMessage) +{ + (void) errorMessage; + response.setIndex(m_settings.m_workspaceIndex); + return 200; +} + +int DroneIDDemod::webapiReportGet( + SWGSDRangel::SWGChannelReport& response, + QString& errorMessage) +{ + (void) errorMessage; + response.setDroneIdDemodReport(new SWGSDRangel::SWGDroneIDDemodReport()); + response.getDroneIdDemodReport()->init(); + webapiFormatChannelReport(response); + return 200; +} + +void DroneIDDemod::webapiFormatChannelReport(SWGSDRangel::SWGChannelReport& response) +{ + double magsqAvg, magsqPeak; + int nbMagsqSamples; + getMagSqLevels(magsqAvg, magsqPeak, nbMagsqSamples); + + response.getDroneIdDemodReport()->setChannelPowerDb(CalcDb::dbPower(magsqAvg)); + response.getDroneIdDemodReport()->setChannelSampleRate(m_basebandSink->getChannelSampleRate()); + response.getDroneIdDemodReport()->setBurstsDetected(getBurstsDetected()); + response.getDroneIdDemodReport()->setBurstsDecoded(getBurstsDecoded()); + response.getDroneIdDemodReport()->setBurstsDropped(getBurstsDropped()); + response.getDroneIdDemodReport()->setDronesTracked(getDronesTracked()); + response.getDroneIdDemodReport()->setScanLocked(isScanLocked() ? 1 : 0); +} + +int DroneIDDemod::webapiSettingsPutPatch( + bool force, + const QStringList& channelSettingsKeys, + SWGSDRangel::SWGChannelSettings& response, + QString& errorMessage) +{ + (void) errorMessage; + DroneIDDemodSettings settings = m_settings; + webapiUpdateChannelSettings(settings, channelSettingsKeys, response); + + MsgConfigureDroneIDDemod *msg = MsgConfigureDroneIDDemod::create(channelSettingsKeys, settings, force); + m_inputMessageQueue.push(msg); + + qDebug("DroneIDDemod::webapiSettingsPutPatch: forward to GUI: %p", m_guiMessageQueue); + if (m_guiMessageQueue) // forward to GUI if any + { + MsgConfigureDroneIDDemod *msgToGUI = MsgConfigureDroneIDDemod::create(channelSettingsKeys, settings, force); + m_guiMessageQueue->push(msgToGUI); + } + + webapiFormatChannelSettings(response, settings); + + return 200; +} + +void DroneIDDemod::webapiUpdateChannelSettings( + DroneIDDemodSettings& settings, + const QStringList& channelSettingsKeys, + SWGSDRangel::SWGChannelSettings& response) +{ + if (channelSettingsKeys.contains("inputFrequencyOffset")) { + settings.m_inputFrequencyOffset = response.getDroneIdDemodSettings()->getInputFrequencyOffset(); + } + if (channelSettingsKeys.contains("detectionThreshold")) { + settings.m_detectionThreshold = std::clamp(response.getDroneIdDemodSettings()->getDetectionThreshold(), 0.05f, 0.95f); + } + if (channelSettingsKeys.contains("turboIterations")) { + settings.m_turboIterations = std::clamp(response.getDroneIdDemodSettings()->getTurboIterations(), 1, 16); + } + if (channelSettingsKeys.contains("filterSerial")) { + settings.m_filterSerial = *response.getDroneIdDemodSettings()->getFilterSerial(); + } + if (channelSettingsKeys.contains("mapTimeout")) { + settings.m_mapTimeout = std::clamp(response.getDroneIdDemodSettings()->getMapTimeout(), 0, 3600); + } + if (channelSettingsKeys.contains("mapAltitude")) { + settings.m_mapAltitude = (DroneIDDemodSettings::MapAltitude) std::clamp(response.getDroneIdDemodSettings()->getMapAltitude(), + (int) DroneIDDemodSettings::MAP_ALTITUDE, (int) DroneIDDemodSettings::MAP_HEIGHT); + } + if (channelSettingsKeys.contains("scan")) { + settings.m_scan = response.getDroneIdDemodSettings()->getScan() != 0; + } + if (channelSettingsKeys.contains("scanBand")) { + settings.m_scanBand = (DroneIDDemodSettings::ScanBand) std::clamp(response.getDroneIdDemodSettings()->getScanBand(), + (int) DroneIDDemodSettings::BAND_2_4_GHZ, (int) DroneIDDemodSettings::BAND_2_4_AND_5_8_GHZ); + } + if (channelSettingsKeys.contains("scanDwell")) { + settings.m_scanDwell = std::clamp(response.getDroneIdDemodSettings()->getScanDwell(), 0.5f, 60.0f); + } + if (channelSettingsKeys.contains("scanHold")) { + settings.m_scanHold = std::clamp(response.getDroneIdDemodSettings()->getScanHold(), 0.5f, 600.0f); + } + if (channelSettingsKeys.contains("udpEnabled")) { + settings.m_udpEnabled = response.getDroneIdDemodSettings()->getUdpEnabled(); + } + if (channelSettingsKeys.contains("udpAddress")) { + settings.m_udpAddress = *response.getDroneIdDemodSettings()->getUdpAddress(); + } + if (channelSettingsKeys.contains("udpPort")) { + settings.m_udpPort = response.getDroneIdDemodSettings()->getUdpPort(); + } + if (channelSettingsKeys.contains("logFilename")) { + settings.m_logFilename = *response.getDroneIdDemodSettings()->getLogFilename(); + } + if (channelSettingsKeys.contains("logEnabled")) { + settings.m_logEnabled = response.getDroneIdDemodSettings()->getLogEnabled(); + } + if (channelSettingsKeys.contains("useFileTime")) { + settings.m_useFileTime = response.getDroneIdDemodSettings()->getUseFileTime(); + } + if (channelSettingsKeys.contains("rgbColor")) { + settings.m_rgbColor = response.getDroneIdDemodSettings()->getRgbColor(); + } + if (channelSettingsKeys.contains("title")) { + settings.m_title = *response.getDroneIdDemodSettings()->getTitle(); + } + if (channelSettingsKeys.contains("streamIndex")) { + settings.m_streamIndex = response.getDroneIdDemodSettings()->getStreamIndex(); + } + if (channelSettingsKeys.contains("useReverseAPI")) { + settings.m_useReverseAPI = response.getDroneIdDemodSettings()->getUseReverseApi() != 0; + } + if (channelSettingsKeys.contains("reverseAPIAddress")) { + settings.m_reverseAPIAddress = *response.getDroneIdDemodSettings()->getReverseApiAddress(); + } + if (channelSettingsKeys.contains("reverseAPIPort")) { + settings.m_reverseAPIPort = response.getDroneIdDemodSettings()->getReverseApiPort(); + } + if (channelSettingsKeys.contains("reverseAPIDeviceIndex")) { + settings.m_reverseAPIDeviceIndex = response.getDroneIdDemodSettings()->getReverseApiDeviceIndex(); + } + if (channelSettingsKeys.contains("reverseAPIChannelIndex")) { + settings.m_reverseAPIChannelIndex = response.getDroneIdDemodSettings()->getReverseApiChannelIndex(); + } + if (settings.m_channelMarker && channelSettingsKeys.contains("channelMarker")) { + settings.m_channelMarker->updateFrom(channelSettingsKeys, response.getDroneIdDemodSettings()->getChannelMarker()); + } + if (settings.m_rollupState && channelSettingsKeys.contains("rollupState")) { + settings.m_rollupState->updateFrom(channelSettingsKeys, response.getDroneIdDemodSettings()->getRollupState()); + } +} + +void DroneIDDemod::setString(QString *(SWGSDRangel::SWGDroneIDDemodSettings::*get)(), void (SWGSDRangel::SWGDroneIDDemodSettings::*set)(QString*), + SWGSDRangel::SWGDroneIDDemodSettings *swg, const QString& value) +{ + if ((swg->*get)()) { + *(swg->*get)() = value; + } else { + (swg->*set)(new QString(value)); + } +} + +void DroneIDDemod::webapiFormatChannelSettings(SWGSDRangel::SWGChannelSettings& response, const DroneIDDemodSettings& settings) +{ + SWGSDRangel::SWGDroneIDDemodSettings *swg = response.getDroneIdDemodSettings(); + + swg->setInputFrequencyOffset(settings.m_inputFrequencyOffset); + swg->setDetectionThreshold(settings.m_detectionThreshold); + swg->setTurboIterations(settings.m_turboIterations); + setString(&SWGSDRangel::SWGDroneIDDemodSettings::getFilterSerial, &SWGSDRangel::SWGDroneIDDemodSettings::setFilterSerial, swg, settings.m_filterSerial); + swg->setMapTimeout(settings.m_mapTimeout); + swg->setMapAltitude((int) settings.m_mapAltitude); + swg->setScan(settings.m_scan ? 1 : 0); + swg->setScanBand((int) settings.m_scanBand); + swg->setScanDwell(settings.m_scanDwell); + swg->setScanHold(settings.m_scanHold); + swg->setUdpEnabled(settings.m_udpEnabled); + setString(&SWGSDRangel::SWGDroneIDDemodSettings::getUdpAddress, &SWGSDRangel::SWGDroneIDDemodSettings::setUdpAddress, swg, settings.m_udpAddress); + swg->setUdpPort(settings.m_udpPort); + setString(&SWGSDRangel::SWGDroneIDDemodSettings::getLogFilename, &SWGSDRangel::SWGDroneIDDemodSettings::setLogFilename, swg, settings.m_logFilename); + swg->setLogEnabled(settings.m_logEnabled); + swg->setUseFileTime(settings.m_useFileTime); + swg->setRgbColor(settings.m_rgbColor); + setString(&SWGSDRangel::SWGDroneIDDemodSettings::getTitle, &SWGSDRangel::SWGDroneIDDemodSettings::setTitle, swg, settings.m_title); + swg->setStreamIndex(settings.m_streamIndex); + swg->setUseReverseApi(settings.m_useReverseAPI ? 1 : 0); + setString(&SWGSDRangel::SWGDroneIDDemodSettings::getReverseApiAddress, &SWGSDRangel::SWGDroneIDDemodSettings::setReverseApiAddress, swg, settings.m_reverseAPIAddress); + swg->setReverseApiPort(settings.m_reverseAPIPort); + swg->setReverseApiDeviceIndex(settings.m_reverseAPIDeviceIndex); + swg->setReverseApiChannelIndex(settings.m_reverseAPIChannelIndex); + + if (settings.m_channelMarker) + { + if (swg->getChannelMarker()) + { + settings.m_channelMarker->formatTo(swg->getChannelMarker()); + } + else + { + SWGSDRangel::SWGChannelMarker *swgChannelMarker = new SWGSDRangel::SWGChannelMarker(); + settings.m_channelMarker->formatTo(swgChannelMarker); + swg->setChannelMarker(swgChannelMarker); + } + } + + if (settings.m_rollupState) + { + if (swg->getRollupState()) + { + settings.m_rollupState->formatTo(swg->getRollupState()); + } + else + { + SWGSDRangel::SWGRollupState *swgRollupState = new SWGSDRangel::SWGRollupState(); + settings.m_rollupState->formatTo(swgRollupState); + swg->setRollupState(swgRollupState); + } + } +} + +void DroneIDDemod::webapiReverseSendSettings(const QStringList& channelSettingsKeys, const DroneIDDemodSettings& settings, bool force) +{ + SWGSDRangel::SWGChannelSettings *swgChannelSettings = new SWGSDRangel::SWGChannelSettings(); + webapiFormatChannelSettings(channelSettingsKeys, swgChannelSettings, settings, force); + + QString channelSettingsURL = QString("http://%1:%2/sdrangel/deviceset/%3/channel/%4/settings") + .arg(settings.m_reverseAPIAddress) + .arg(settings.m_reverseAPIPort) + .arg(settings.m_reverseAPIDeviceIndex) + .arg(settings.m_reverseAPIChannelIndex); + m_networkRequest.setUrl(QUrl(channelSettingsURL)); + m_networkRequest.setHeader(QNetworkRequest::ContentTypeHeader, "application/json"); + + QBuffer *buffer = new QBuffer(); + buffer->open((QBuffer::ReadWrite)); + buffer->write(swgChannelSettings->asJson().toUtf8()); + buffer->seek(0); + + // Always use PATCH to avoid passing reverse API settings + QNetworkReply *reply = m_networkManager->sendCustomRequest(m_networkRequest, "PATCH", buffer); + buffer->setParent(reply); + + delete swgChannelSettings; +} + +void DroneIDDemod::webapiFormatChannelSettings( + const QStringList& channelSettingsKeys, + SWGSDRangel::SWGChannelSettings *swgChannelSettings, + const DroneIDDemodSettings& settings, + bool force +) +{ + swgChannelSettings->setDirection(0); // Single sink (Rx) + swgChannelSettings->setOriginatorChannelIndex(getIndexInDeviceSet()); + swgChannelSettings->setOriginatorDeviceSetIndex(getDeviceSetIndex()); + if (swgChannelSettings->getChannelType()) { + *swgChannelSettings->getChannelType() = m_channelId; + } else { + swgChannelSettings->setChannelType(new QString(m_channelId)); + } + swgChannelSettings->setDroneIdDemodSettings(new SWGSDRangel::SWGDroneIDDemodSettings()); + SWGSDRangel::SWGDroneIDDemodSettings *swg = swgChannelSettings->getDroneIdDemodSettings(); + + // transfer data that has been modified. When force is on transfer all data except reverse API data + + if (channelSettingsKeys.contains("inputFrequencyOffset") || force) { + swg->setInputFrequencyOffset(settings.m_inputFrequencyOffset); + } + if (channelSettingsKeys.contains("detectionThreshold") || force) { + swg->setDetectionThreshold(settings.m_detectionThreshold); + } + if (channelSettingsKeys.contains("turboIterations") || force) { + swg->setTurboIterations(settings.m_turboIterations); + } + if (channelSettingsKeys.contains("filterSerial") || force) { + swg->setFilterSerial(new QString(settings.m_filterSerial)); + } + if (channelSettingsKeys.contains("mapTimeout") || force) { + swg->setMapTimeout(settings.m_mapTimeout); + } + if (channelSettingsKeys.contains("mapAltitude") || force) { + swg->setMapAltitude((int) settings.m_mapAltitude); + } + if (channelSettingsKeys.contains("scan") || force) { + swg->setScan(settings.m_scan ? 1 : 0); + } + if (channelSettingsKeys.contains("scanBand") || force) { + swg->setScanBand((int) settings.m_scanBand); + } + if (channelSettingsKeys.contains("scanDwell") || force) { + swg->setScanDwell(settings.m_scanDwell); + } + if (channelSettingsKeys.contains("scanHold") || force) { + swg->setScanHold(settings.m_scanHold); + } + if (channelSettingsKeys.contains("udpEnabled") || force) { + swg->setUdpEnabled(settings.m_udpEnabled); + } + if (channelSettingsKeys.contains("udpAddress") || force) { + swg->setUdpAddress(new QString(settings.m_udpAddress)); + } + if (channelSettingsKeys.contains("udpPort") || force) { + swg->setUdpPort(settings.m_udpPort); + } + if (channelSettingsKeys.contains("logFilename") || force) { + swg->setLogFilename(new QString(settings.m_logFilename)); + } + if (channelSettingsKeys.contains("logEnabled") || force) { + swg->setLogEnabled(settings.m_logEnabled); + } + if (channelSettingsKeys.contains("useFileTime") || force) { + swg->setUseFileTime(settings.m_useFileTime); + } + if (channelSettingsKeys.contains("rgbColor") || force) { + swg->setRgbColor(settings.m_rgbColor); + } + if (channelSettingsKeys.contains("title") || force) { + swg->setTitle(new QString(settings.m_title)); + } + if (channelSettingsKeys.contains("streamIndex") || force) { + swg->setStreamIndex(settings.m_streamIndex); + } + + if (settings.m_channelMarker && (channelSettingsKeys.contains("channelMarker") || force)) + { + SWGSDRangel::SWGChannelMarker *swgChannelMarker = new SWGSDRangel::SWGChannelMarker(); + settings.m_channelMarker->formatTo(swgChannelMarker); + swg->setChannelMarker(swgChannelMarker); + } + + if (settings.m_rollupState && (channelSettingsKeys.contains("rollupState") || force)) + { + SWGSDRangel::SWGRollupState *swgRollupState = new SWGSDRangel::SWGRollupState(); + settings.m_rollupState->formatTo(swgRollupState); + swg->setRollupState(swgRollupState); + } +} + +void DroneIDDemod::networkManagerFinished(QNetworkReply *reply) +{ + QNetworkReply::NetworkError replyError = reply->error(); + + if (replyError) + { + qWarning() << "DroneIDDemod::networkManagerFinished:" + << " error(" << (int) replyError + << "): " << replyError + << ": " << reply->errorString(); + } + else + { + QString answer = reply->readAll(); + answer.chop(1); // remove last \n + qDebug("DroneIDDemod::networkManagerFinished: reply:\n%s", answer.toStdString().c_str()); + } + + reply->deleteLater(); +} + +void DroneIDDemod::handleIndexInDeviceSetChanged(int index) +{ + if (index < 0) { + return; + } + + QString fifoLabel = QString("%1 [%2:%3]") + .arg(m_channelId) + .arg(m_deviceAPI->getDeviceSetIndex()) + .arg(index); + m_basebandSink->setFifoLabel(fifoLabel); +} + +int DroneIDDemod::getChannelSampleRate() const +{ + return m_basebandSink ? m_basebandSink->getChannelSampleRate() : 0; +} diff --git a/plugins/channelrx/demoddroneid/droneiddemod.h b/plugins/channelrx/demoddroneid/droneiddemod.h new file mode 100644 index 000000000..43b490b28 --- /dev/null +++ b/plugins/channelrx/demoddroneid/droneiddemod.h @@ -0,0 +1,287 @@ +/////////////////////////////////////////////////////////////////////////////////// +// Copyright (C) 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 . // +/////////////////////////////////////////////////////////////////////////////////// + +#ifndef INCLUDE_DRONEIDDEMOD_H +#define INCLUDE_DRONEIDDEMOD_H + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#include "dsp/basebandsamplesink.h" +#include "channel/channelapi.h" +#include "util/message.h" + +#include "droneiddemodbaseband.h" +#include "droneiddemodsettings.h" + +namespace SWGSDRangel { + class SWGDroneIDDemodSettings; +} + +class QNetworkAccessManager; +class QNetworkReply; +class DeviceAPI; +class DroneIDMessage; + +class DroneIDDemod : public BasebandSampleSink, public ChannelAPI { + +public: + class MsgConfigureDroneIDDemod : public Message { + MESSAGE_CLASS_DECLARATION + + public: + const DroneIDDemodSettings& getSettings() const { return m_settings; } + bool getForce() const { return m_force; } + const QStringList& getSettingsKeys() const { return m_settingsKeys; } + + static MsgConfigureDroneIDDemod* create(const QStringList& settingsKeys, const DroneIDDemodSettings& settings, bool force) + { + return new MsgConfigureDroneIDDemod(settingsKeys, settings, force); + } + + private: + DroneIDDemodSettings m_settings; + QStringList m_settingsKeys; + bool m_force; + + MsgConfigureDroneIDDemod(const QStringList& settingsKeys, const DroneIDDemodSettings& settings, bool force) : + Message(), + m_settings(settings), + m_settingsKeys(settingsKeys), + m_force(force) + { } + }; + + // Result of attempting to decode a burst + class MsgBurstResult : public Message { + MESSAGE_CLASS_DECLARATION + + public: + bool getDetected() const { return m_detected; } //!< Whether DroneID sync sequences were found + bool getDecoded() const { return m_decoded; } //!< Whether turbo decoded data passed CRC + QByteArray getMessage() const { return m_message; } //!< Decoded message + QDateTime getDateTime() const { return m_dateTime; } + float getSNR() const { return m_snr; } + float getCFO() const { return m_cfo; } + float getEVM() const { return m_evm; } + float getZCMetric() const { return m_zcMetric; } + int getIterations() const { return m_iterations; } + bool getLegacy() const { return m_legacy; } + qint64 getFrequency() const { return m_frequency; } //!< Channel frequency in Hz the burst was received on + + static MsgBurstResult* create(bool detected, bool decoded, const QByteArray& message, QDateTime dateTime, + float snr, float cfo, float evm, float zcMetric, int iterations, bool legacy, qint64 frequency) + { + return new MsgBurstResult(detected, decoded, message, dateTime, snr, cfo, evm, zcMetric, iterations, legacy, frequency); + } + + private: + bool m_detected; + bool m_decoded; + QByteArray m_message; + QDateTime m_dateTime; + float m_snr; + float m_cfo; + float m_evm; + float m_zcMetric; + int m_iterations; + bool m_legacy; + qint64 m_frequency; + + MsgBurstResult(bool detected, bool decoded, const QByteArray& message, QDateTime dateTime, + float snr, float cfo, float evm, float zcMetric, int iterations, bool legacy, qint64 frequency) : + Message(), + m_detected(detected), + m_decoded(decoded), + m_message(message), + m_dateTime(dateTime), + m_snr(snr), + m_cfo(cfo), + m_evm(evm), + m_zcMetric(zcMetric), + m_iterations(iterations), + m_legacy(legacy), + m_frequency(frequency) + { } + }; + + DroneIDDemod(DeviceAPI *deviceAPI); + virtual ~DroneIDDemod(); + virtual void destroy() { delete this; } + virtual void setDeviceAPI(DeviceAPI *deviceAPI); + virtual DeviceAPI *getDeviceAPI() { return m_deviceAPI; } + + using BasebandSampleSink::feed; + virtual void feed(const SampleVector::const_iterator& begin, const SampleVector::const_iterator& end, bool po); + virtual void start(); + virtual void stop(); + virtual void pushMessage(Message *msg) { m_inputMessageQueue.push(msg); } + virtual QString getSinkName() { return objectName(); } + + virtual void getIdentifier(QString& id) { id = objectName(); } + virtual QString getIdentifier() const { return objectName(); } + virtual const QString& getURI() const { return getName(); } + virtual void getTitle(QString& title) { title = m_settings.m_title; } + virtual qint64 getCenterFrequency() const { return m_settings.m_inputFrequencyOffset; } + int getChannelSampleRate() const override; + virtual void setCenterFrequency(qint64 frequency); + + virtual QByteArray serialize() const; + virtual bool deserialize(const QByteArray& data); + + virtual int getNbSinkStreams() const { return 1; } + virtual int getNbSourceStreams() const { return 0; } + virtual int getStreamIndex() const { return m_settings.m_streamIndex; } + + virtual qint64 getStreamCenterFrequency(int streamIndex, bool sinkElseSource) const + { + (void) streamIndex; + (void) sinkElseSource; + return 0; + } + + virtual int webapiSettingsGet( + SWGSDRangel::SWGChannelSettings& response, + QString& errorMessage); + + virtual int webapiWorkspaceGet( + SWGSDRangel::SWGWorkspaceInfo& response, + QString& errorMessage); + + virtual int webapiSettingsPutPatch( + bool force, + const QStringList& channelSettingsKeys, + SWGSDRangel::SWGChannelSettings& response, + QString& errorMessage); + + virtual int webapiReportGet( + SWGSDRangel::SWGChannelReport& response, + QString& errorMessage); + + static void webapiFormatChannelSettings( + SWGSDRangel::SWGChannelSettings& response, + const DroneIDDemodSettings& settings); + + static void webapiUpdateChannelSettings( + DroneIDDemodSettings& settings, + const QStringList& channelSettingsKeys, + SWGSDRangel::SWGChannelSettings& response); + + double getMagSq() const { return m_basebandSink->getMagSq(); } + + void getMagSqLevels(double& avg, double& peak, int& nbSamples) { + m_basebandSink->getMagSqLevels(avg, peak, nbSamples); + } + + int getBurstsDetected() const { return m_basebandSink->getBurstsDetected(); } + int getBurstsDropped() const { return m_basebandSink->getBurstsDropped(); } + int getBurstsDecoded() const { return m_burstsDecoded; } + int getDronesTracked() const { return m_dronesTracked; } + bool isScanLocked() const { return m_scanLocked; } //!< Whether scan is paused on a channel with DroneID bursts + + uint32_t getNumberOfDeviceStreams() const; + + static const char * const m_channelIdURI; + static const char * const m_channelId; + +private: + static constexpr int m_scanTimerInterval = 100; // How often scan state is checked, in ms + // Bursts detected shortly after retuning may be from samples received on the previous frequency, + // so are ignored when deciding whether to remain on a channel + static constexpr qint64 m_scanSettleTime = 250; // ms + + struct Drone { + QDateTime m_lastSeen; // Message time, which may be from a file + QDateTime m_lastUpdate; // Wall clock time message was received + bool m_onMap; + bool m_propellersSpinning; // Whether propeller animation has been started on 3D map + + Drone() : m_onMap(false), m_propellersSpinning(false) {} + }; + + DeviceAPI *m_deviceAPI; + QThread m_thread; + DroneIDDemodBaseband* m_basebandSink; + DroneIDDemodSettings m_settings; + int m_basebandSampleRate; //!< stored from device message used when starting baseband sink + qint64 m_centerFrequency; + QUdpSocket m_udpSocket; + QFile m_logFile; + QTextStream m_logStream; + std::atomic m_burstsDecoded; // Atomic, as read by web API thread + std::atomic m_dronesTracked; + QHash m_drones; // Indexed by serial number + QTimer m_mapTimer; + + QTimer m_scanTimer; + QElapsedTimer m_scanClock; + QList m_scanFrequencies; // Frequencies in band being scanned + QList m_scanHistory; // Frequencies bursts have been detected on, most recent first + QList m_scanOrder; // Order frequencies are visited in this pass + int m_scanPosition; // Index in to m_scanOrder of next frequency to tune to + qint64 m_scanFrequency; // Frequency currently tuned to, or 0 if not on a scanned frequency + qint64 m_scanTuneTime; // m_scanClock time of last retune + qint64 m_scanBurstTime; // m_scanClock time of last burst detected, or -1 if none + std::atomic m_scanLocked; + + QNetworkAccessManager *m_networkManager; + QNetworkRequest m_networkRequest; + + virtual bool handleMessage(const Message& cmd); + void applySettings(const QStringList& settingsKeys, const DroneIDDemodSettings& settings, bool force = false); + void sendSampleRateToDemodAnalyzer(); + void handleBurstResult(const MsgBurstResult& result); + void logMessage(const MsgBurstResult& result, const DroneIDMessage *msg); + void sendToMap(const DroneIDMessage *msg, const QDateTime& dateTime, Drone& drone); + void sendMapItem(const QString& name, double latitude, double longitude, float altitude, int altitudeReference, + const QString& image, float imageRotation, const QString& label, const QString& text, const QDateTime& dateTime, + const QString& model = QString(), const QString& animation = QString(), bool stopAnimation = false); + void clearFromMap(const QString& serial); + static void setString(QString *(SWGSDRangel::SWGDroneIDDemodSettings::*get)(), void (SWGSDRangel::SWGDroneIDDemodSettings::*set)(QString*), + SWGSDRangel::SWGDroneIDDemodSettings *swg, const QString& value); + void startScan(); + void stopScan(); + void scanNewPass(); + void scanTune(qint64 frequency); + qint64 scanFrequencyMatch(qint64 frequency) const; + void webapiFormatChannelReport(SWGSDRangel::SWGChannelReport& response); + void webapiReverseSendSettings(const QStringList& channelSettingsKeys, const DroneIDDemodSettings& settings, bool force); + void webapiFormatChannelSettings( + const QStringList& channelSettingsKeys, + SWGSDRangel::SWGChannelSettings *swgChannelSettings, + const DroneIDDemodSettings& settings, + bool force + ); + +private slots: + void networkManagerFinished(QNetworkReply *reply); + void handleIndexInDeviceSetChanged(int index); + void removeOldDrones(); + void scanTimeout(); +}; + +#endif // INCLUDE_DRONEIDDEMOD_H diff --git a/plugins/channelrx/demoddroneid/droneiddemod.qrc b/plugins/channelrx/demoddroneid/droneiddemod.qrc new file mode 100644 index 000000000..95ad34a04 --- /dev/null +++ b/plugins/channelrx/demoddroneid/droneiddemod.qrc @@ -0,0 +1,7 @@ + + + map/drone.png + map/pilot.png + map/home.png + + diff --git a/plugins/channelrx/demoddroneid/droneiddemodbaseband.cpp b/plugins/channelrx/demoddroneid/droneiddemodbaseband.cpp new file mode 100644 index 000000000..375ceb332 --- /dev/null +++ b/plugins/channelrx/demoddroneid/droneiddemodbaseband.cpp @@ -0,0 +1,210 @@ +/////////////////////////////////////////////////////////////////////////////////// +// Copyright (C) 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 . // +/////////////////////////////////////////////////////////////////////////////////// + +#include + +#include "dsp/dspcommands.h" +#include "dsp/downchannelizer.h" + +#include "droneiddemodbaseband.h" +#include "droneiddemodworker.h" + +MESSAGE_CLASS_DEFINITION(DroneIDDemodBaseband::MsgConfigureDroneIDDemodBaseband, Message) + +DroneIDDemodBaseband::DroneIDDemodBaseband(DroneIDDemod *droneIDDemod) : + m_sink(droneIDDemod), + m_running(false) +{ + qDebug("DroneIDDemodBaseband::DroneIDDemodBaseband"); + + m_sampleFifo.setSize(SampleSinkFifo::getSizePolicy(DroneIDDemodSettings::DRONEIDDEMOD_CHANNEL_SAMPLE_RATE)); + m_channelizer = new DownChannelizer(&m_sink); + + m_worker = new DroneIDDemodWorker(); + m_workerThread.setObjectName("DroneIDDecode"); + m_worker->moveToThread(&m_workerThread); + m_sink.setWorker(m_worker); +} + +DroneIDDemodBaseband::~DroneIDDemodBaseband() +{ + m_inputMessageQueue.clear(); + + if (m_workerThread.isRunning()) + { + m_workerThread.quit(); + m_workerThread.wait(); + } + + delete m_worker; + delete m_channelizer; +} + +void DroneIDDemodBaseband::reset() +{ + QMutexLocker mutexLocker(&m_mutex); + m_inputMessageQueue.clear(); + m_sampleFifo.reset(); + m_sink.reset(); +} + +void DroneIDDemodBaseband::startWork() +{ + QMutexLocker mutexLocker(&m_mutex); + QObject::connect( + &m_sampleFifo, + &SampleSinkFifo::dataReady, + this, + &DroneIDDemodBaseband::handleData, + Qt::QueuedConnection + ); + connect(&m_inputMessageQueue, SIGNAL(messageEnqueued()), this, SLOT(handleInputMessages())); + m_workerThread.start(); + m_running = true; +} + +void DroneIDDemodBaseband::stopWork() +{ + QMutexLocker mutexLocker(&m_mutex); + disconnect(&m_inputMessageQueue, SIGNAL(messageEnqueued()), this, SLOT(handleInputMessages())); + QObject::disconnect( + &m_sampleFifo, + &SampleSinkFifo::dataReady, + this, + &DroneIDDemodBaseband::handleData + ); + m_workerThread.quit(); + m_workerThread.wait(); + m_running = false; +} + +void DroneIDDemodBaseband::setChannel(ChannelAPI *channel) +{ + m_sink.setChannel(channel); +} + +void DroneIDDemodBaseband::setMessageQueueToChannel(MessageQueue *messageQueue) +{ + m_worker->setMessageQueueToChannel(messageQueue); +} + +void DroneIDDemodBaseband::feed(const SampleVector::const_iterator& begin, const SampleVector::const_iterator& end) +{ + m_sampleFifo.write(begin, end); +} + +void DroneIDDemodBaseband::handleData() +{ + QMutexLocker mutexLocker(&m_mutex); + + while ((m_sampleFifo.fill() > 0) && (m_inputMessageQueue.size() == 0)) + { + SampleVector::iterator part1begin; + SampleVector::iterator part1end; + SampleVector::iterator part2begin; + SampleVector::iterator part2end; + + std::size_t count = m_sampleFifo.readBegin(m_sampleFifo.fill(), &part1begin, &part1end, &part2begin, &part2end); + + // first part of FIFO data + if (part1begin != part1end) { + m_channelizer->feed(part1begin, part1end); + } + + // second part of FIFO data (used when block wraps around) + if(part2begin != part2end) { + m_channelizer->feed(part2begin, part2end); + } + + m_sampleFifo.readCommit((unsigned int) count); + } +} + +void DroneIDDemodBaseband::handleInputMessages() +{ + Message* message; + + while ((message = m_inputMessageQueue.pop()) != nullptr) + { + if (!handleMessage(*message)) { + qDebug("%s: unhandled message: %s", Q_FUNC_INFO, message->getIdentifier()); + } + delete message; + } +} + +bool DroneIDDemodBaseband::handleMessage(const Message& cmd) +{ + if (MsgConfigureDroneIDDemodBaseband::match(cmd)) + { + QMutexLocker mutexLocker(&m_mutex); + MsgConfigureDroneIDDemodBaseband& cfg = (MsgConfigureDroneIDDemodBaseband&) cmd; + qDebug() << "DroneIDDemodBaseband::handleMessage: MsgConfigureDroneIDDemodBaseband"; + + applySettings(cfg.getSettingsKeys(), cfg.getSettings(), cfg.getForce()); + + return true; + } + else if (DSPSignalNotification::match(cmd)) + { + QMutexLocker mutexLocker(&m_mutex); + DSPSignalNotification& notif = (DSPSignalNotification&) cmd; + qDebug() << "DroneIDDemodBaseband::handleMessage: DSPSignalNotification: basebandSampleRate: " << notif.getSampleRate(); + setBasebandSampleRate(notif.getSampleRate()); + m_sampleFifo.setSize(SampleSinkFifo::getSizePolicy(notif.getSampleRate())); + m_sink.setCenterFrequency(notif.getCenterFrequency()); + + return true; + } + else + { + return false; + } +} + +void DroneIDDemodBaseband::applySettings(const QStringList& settingsKeys, const DroneIDDemodSettings& settings, bool force) +{ + if ((settingsKeys.contains("inputFrequencyOffset") && (settings.m_inputFrequencyOffset != m_settings.m_inputFrequencyOffset)) || force) + { + m_channelizer->setChannelization(DroneIDDemodSettings::DRONEIDDEMOD_CHANNEL_SAMPLE_RATE, settings.m_inputFrequencyOffset); + m_sink.applyChannelSettings(m_channelizer->getChannelSampleRate(), m_channelizer->getChannelFrequencyOffset()); + } + + if (settingsKeys.contains("turboIterations") || force) { + m_worker->setMaxIterations(settings.m_turboIterations); + } + + m_sink.applySettings(settingsKeys, settings, force); + + if (force) { + m_settings = settings; + } else { + m_settings.applySettings(settingsKeys, settings); + } +} + +int DroneIDDemodBaseband::getChannelSampleRate() const +{ + return m_channelizer->getChannelSampleRate(); +} + +void DroneIDDemodBaseband::setBasebandSampleRate(int sampleRate) +{ + m_channelizer->setBasebandSampleRate(sampleRate); + m_sink.applyChannelSettings(m_channelizer->getChannelSampleRate(), m_channelizer->getChannelFrequencyOffset()); +} diff --git a/plugins/channelrx/demoddroneid/droneiddemodbaseband.h b/plugins/channelrx/demoddroneid/droneiddemodbaseband.h new file mode 100644 index 000000000..c6d0dfa5c --- /dev/null +++ b/plugins/channelrx/demoddroneid/droneiddemodbaseband.h @@ -0,0 +1,106 @@ +/////////////////////////////////////////////////////////////////////////////////// +// Copyright (C) 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 . // +/////////////////////////////////////////////////////////////////////////////////// + +#ifndef INCLUDE_DRONEIDDEMODBASEBAND_H +#define INCLUDE_DRONEIDDEMODBASEBAND_H + +#include +#include +#include + +#include "dsp/samplesinkfifo.h" +#include "util/message.h" +#include "util/messagequeue.h" + +#include "droneiddemodsink.h" + +class DownChannelizer; +class ChannelAPI; +class DroneIDDemod; +class DroneIDDemodWorker; + +class DroneIDDemodBaseband : public QObject +{ + Q_OBJECT +public: + class MsgConfigureDroneIDDemodBaseband : public Message { + MESSAGE_CLASS_DECLARATION + + public: + const DroneIDDemodSettings& getSettings() const { return m_settings; } + const QStringList& getSettingsKeys() const { return m_settingsKeys; } + bool getForce() const { return m_force; } + + static MsgConfigureDroneIDDemodBaseband* create(const QStringList& settingsKeys, const DroneIDDemodSettings& settings, bool force) + { + return new MsgConfigureDroneIDDemodBaseband(settingsKeys, settings, force); + } + + private: + DroneIDDemodSettings m_settings; + QStringList m_settingsKeys; + bool m_force; + + MsgConfigureDroneIDDemodBaseband(const QStringList& settingsKeys, const DroneIDDemodSettings& settings, bool force) : + Message(), + m_settings(settings), + m_settingsKeys(settingsKeys), + m_force(force) + { } + }; + + DroneIDDemodBaseband(DroneIDDemod *droneIDDemod); + ~DroneIDDemodBaseband(); + void reset(); + void startWork(); + void stopWork(); + void feed(const SampleVector::const_iterator& begin, const SampleVector::const_iterator& end); + MessageQueue *getInputMessageQueue() { return &m_inputMessageQueue; } //!< Get the queue for asynchronous inbound communication + void getMagSqLevels(double& avg, double& peak, int& nbSamples) { + m_sink.getMagSqLevels(avg, peak, nbSamples); + } + int getChannelSampleRate() const; + void setMessageQueueToChannel(MessageQueue *messageQueue); + void setBasebandSampleRate(int sampleRate); + void setChannel(ChannelAPI *channel); + double getMagSq() const { return m_sink.getMagSq(); } + int getBurstsDetected() const { return m_sink.getBurstsDetected(); } + int getBurstsDropped() const { return m_sink.getBurstsDropped(); } + bool isRunning() const { return m_running; } + void setFifoLabel(const QString& label) { m_sampleFifo.setLabel(label); } + +private: + SampleSinkFifo m_sampleFifo; + DownChannelizer *m_channelizer; + DroneIDDemodSink m_sink; + DroneIDDemodWorker *m_worker; + QThread m_workerThread; + MessageQueue m_inputMessageQueue; //!< Queue for asynchronous inbound communication + DroneIDDemodSettings m_settings; + bool m_running; + QRecursiveMutex m_mutex; + + bool handleMessage(const Message& cmd); + void applySettings(const QStringList& settingsKeys, const DroneIDDemodSettings& settings, bool force = false); + +private slots: + void handleInputMessages(); + void handleData(); //!< Handle data when samples have to be processed +}; + +#endif // INCLUDE_DRONEIDDEMODBASEBAND_H diff --git a/plugins/channelrx/demoddroneid/droneiddemodgui.cpp b/plugins/channelrx/demoddroneid/droneiddemodgui.cpp new file mode 100644 index 000000000..9981170f2 --- /dev/null +++ b/plugins/channelrx/demoddroneid/droneiddemodgui.cpp @@ -0,0 +1,1042 @@ +/////////////////////////////////////////////////////////////////////////////////// +// Copyright (C) 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 . // +/////////////////////////////////////////////////////////////////////////////////// + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "droneiddemodgui.h" + +#include "device/deviceuiset.h" +#include "dsp/dspcommands.h" +#include "ui_droneiddemodgui.h" +#include "plugin/pluginapi.h" +#include "util/csv.h" +#include "util/db.h" +#include "util/droneid.h" +#include "gui/messagedialog.h" +#include "gui/basicchannelsettingsdialog.h" +#include "gui/datetimedelegate.h" +#include "gui/decimaldelegate.h" +#include "gui/dialpopup.h" +#include "gui/dialogpositioner.h" +#include "gui/tabletapandhold.h" +#include "maincore.h" +#include "feature/featurewebapiutils.h" +#include "channel/channelwebapiutils.h" + +#include "droneiddemod.h" + +void DroneIDDemodGUI::resizeTable() +{ + // Fill table with a row of dummy data that will size the columns nicely + // Trailing chars are for sort arrow + int row = ui->messages->rowCount(); + ui->messages->setRowCount(row + 1); + ui->messages->setItem(row, COL_DATE_TIME, new QTableWidgetItem("2015/04/15 10:17:00-")); + ui->messages->setItem(row, COL_SERIAL, new QTableWidgetItem("1581F5FKD229400T")); + ui->messages->setItem(row, COL_MODEL, new QTableWidgetItem("Mavic 3 Enterprise")); + ui->messages->setItem(row, COL_TYPE, new QTableWidgetItem("Purpose-")); + ui->messages->setItem(row, COL_SEQUENCE, new QTableWidgetItem("65535-")); + ui->messages->setItem(row, COL_LATITUDE, new QTableWidgetItem("-90.000000-")); + ui->messages->setItem(row, COL_LONGITUDE, new QTableWidgetItem("-180.000000-")); + ui->messages->setItem(row, COL_ALTITUDE, new QTableWidgetItem("10000-")); + ui->messages->setItem(row, COL_HEIGHT, new QTableWidgetItem("1000.0-")); + ui->messages->setItem(row, COL_SPEED, new QTableWidgetItem("100.0-")); + ui->messages->setItem(row, COL_VERTICAL_SPEED, new QTableWidgetItem("-100.0-")); + ui->messages->setItem(row, COL_COURSE, new QTableWidgetItem("359-")); + ui->messages->setItem(row, COL_YAW, new QTableWidgetItem("-180.0-")); + ui->messages->setItem(row, COL_PILOT_LATITUDE, new QTableWidgetItem("-90.000000-")); + ui->messages->setItem(row, COL_PILOT_LONGITUDE, new QTableWidgetItem("-180.000000-")); + ui->messages->setItem(row, COL_HOME_LATITUDE, new QTableWidgetItem("-90.000000-")); + ui->messages->setItem(row, COL_HOME_LONGITUDE, new QTableWidgetItem("-180.000000-")); + ui->messages->setItem(row, COL_UUID, new QTableWidgetItem("0123456789012345678")); + ui->messages->setItem(row, COL_STATE, new QTableWidgetItem("Motors on, In air, GPS")); + ui->messages->setItem(row, COL_GPS_TIME, new QTableWidgetItem("2015/04/15 10:17:00")); + ui->messages->setItem(row, COL_SNR, new QTableWidgetItem("30.0-")); + ui->messages->setItem(row, COL_CFO, new QTableWidgetItem("-100000-")); + ui->messages->setItem(row, COL_FREQUENCY, new QTableWidgetItem("5831.5-")); + ui->messages->setItem(row, COL_CRC, new QTableWidgetItem("CRC-")); + ui->messages->resizeColumnsToContents(); + ui->messages->removeRow(row); +} + +// Columns in table reordered +void DroneIDDemodGUI::messages_sectionMoved(int logicalIndex, int oldVisualIndex, int newVisualIndex) +{ + (void) oldVisualIndex; + + m_settings.m_columnIndexes[logicalIndex] = newVisualIndex; +} + +// Column in table resized (when hidden size is 0) +void DroneIDDemodGUI::messages_sectionResized(int logicalIndex, int oldSize, int newSize) +{ + (void) oldSize; + + m_settings.m_columnSizes[logicalIndex] = newSize; +} + +// Right click in table header - show column select menu +void DroneIDDemodGUI::messagesColumnSelectMenu(QPoint pos) +{ + m_messagesMenu->popup(ui->messages->horizontalHeader()->viewport()->mapToGlobal(pos)); +} + +// Hide/show column when menu selected +void DroneIDDemodGUI::messagesColumnSelectMenuChecked(bool checked) +{ + (void) checked; + + QAction* action = qobject_cast(sender()); + if (action != nullptr) + { + int idx = action->data().toInt(nullptr); + ui->messages->setColumnHidden(idx, !action->isChecked()); + } +} + +// Create column select menu item +QAction *DroneIDDemodGUI::createCheckableItem(QString &text, int idx, bool checked, const char *slot) +{ + QAction *action = new QAction(text, this); + action->setCheckable(true); + action->setChecked(checked); + action->setData(QVariant(idx)); + connect(action, SIGNAL(triggered()), this, slot); + return action; +} + +DroneIDDemodGUI* DroneIDDemodGUI::create(PluginAPI* pluginAPI, DeviceUISet *deviceUISet, BasebandSampleSink *rxChannel) +{ + DroneIDDemodGUI* gui = new DroneIDDemodGUI(pluginAPI, deviceUISet, rxChannel); + return gui; +} + +void DroneIDDemodGUI::destroy() +{ + delete this; +} + +void DroneIDDemodGUI::resetToDefaults() +{ + m_settings.resetToDefaults(); + displaySettings(); + applySettings(QStringList(), true); +} + +QByteArray DroneIDDemodGUI::serialize() const +{ + return m_settings.serialize(); +} + +bool DroneIDDemodGUI::deserialize(const QByteArray& data) +{ + if (m_settings.deserialize(data)) + { + displaySettings(); + applySettings(QStringList(), true); + return true; + } + else + { + resetToDefaults(); + return false; + } +} + +// Add row to table +// frequency is channel frequency in Hz the message was received on, or 0 if unknown +void DroneIDDemodGUI::messageReceived(const QByteArray& message, const QDateTime& dateTime, float snr, float cfo, qint64 frequency, bool live) +{ + DroneIDMessage *msg = DroneIDMessage::decode(message); + + if (!msg) + { + qDebug() << "DroneIDDemodGUI::messageReceived: Unsupported message: " << message.toHex(); + return; + } + + // Is scroll bar at bottom + QScrollBar *sb = ui->messages->verticalScrollBar(); + bool scrollToBottom = sb->value() == sb->maximum(); + + // Add to messages table + ui->messages->setSortingEnabled(false); + + // Limit table size, by removing oldest message. Table may be sorted, so search for it. + if (ui->messages->rowCount() >= m_maxRows) + { + int oldestRow = 0; + QDateTime oldest; + for (int i = 0; i < ui->messages->rowCount(); i++) + { + QDateTime rowDateTime = ui->messages->item(i, COL_DATE_TIME)->data(Qt::DisplayRole).toDateTime(); + if (!oldest.isValid() || (rowDateTime < oldest)) + { + oldest = rowDateTime; + oldestRow = i; + } + } + ui->messages->removeRow(oldestRow); + } + + int row = ui->messages->rowCount(); + ui->messages->setRowCount(row + 1); + + QTableWidgetItem *items[DRONEIDDEMOD_COLUMNS]; + for (int i = 0; i < DRONEIDDEMOD_COLUMNS; i++) + { + items[i] = new QTableWidgetItem(); + ui->messages->setItem(row, i, items[i]); + } + + items[COL_DATE_TIME]->setData(Qt::DisplayRole, dateTime); + items[COL_SERIAL]->setText(msg->m_serial); + items[COL_CRC]->setText(msg->m_crcValid ? "OK" : "Bad"); + + if (msg->isFlightInformation()) + { + items[COL_MODEL]->setText(msg->getProductTypeName()); + items[COL_TYPE]->setText("Flight"); + items[COL_SEQUENCE]->setData(Qt::DisplayRole, msg->m_sequence); + if (msg->hasPosition()) + { + items[COL_LATITUDE]->setData(Qt::DisplayRole, msg->m_latitude); + items[COL_LONGITUDE]->setData(Qt::DisplayRole, msg->m_longitude); + } + items[COL_ALTITUDE]->setData(Qt::DisplayRole, msg->m_altitude); + items[COL_HEIGHT]->setData(Qt::DisplayRole, msg->m_height); + items[COL_SPEED]->setData(Qt::DisplayRole, msg->getSpeed()); + items[COL_VERTICAL_SPEED]->setData(Qt::DisplayRole, msg->m_vUp); + if (msg->getSpeed() > 0.0f) { + items[COL_COURSE]->setData(Qt::DisplayRole, msg->getCourse()); + } + items[COL_YAW]->setData(Qt::DisplayRole, msg->m_yaw); + if (msg->hasPilotPosition()) + { + items[COL_PILOT_LATITUDE]->setData(Qt::DisplayRole, msg->m_pilotLatitude); + items[COL_PILOT_LONGITUDE]->setData(Qt::DisplayRole, msg->m_pilotLongitude); + } + if (msg->hasHomePosition()) + { + items[COL_HOME_LATITUDE]->setData(Qt::DisplayRole, msg->m_homeLatitude); + items[COL_HOME_LONGITUDE]->setData(Qt::DisplayRole, msg->m_homeLongitude); + } + items[COL_UUID]->setText(msg->m_uuid); + items[COL_STATE]->setText(msg->getStateInfoString()); + items[COL_STATE]->setToolTip(QString("0x%1").arg(msg->m_stateInfo, 4, 16, QChar('0'))); + if (msg->m_gpsTime.isValid()) { + items[COL_GPS_TIME]->setData(Qt::DisplayRole, msg->m_gpsTime); + } + } + else + { + items[COL_TYPE]->setText("Purpose"); + items[COL_TYPE]->setToolTip(msg->m_purpose.toHex()); + } + + if (live) + { + items[COL_SNR]->setData(Qt::DisplayRole, snr); + items[COL_CFO]->setData(Qt::DisplayRole, (int) std::round(cfo)); + } + if (frequency != 0) { + items[COL_FREQUENCY]->setData(Qt::DisplayRole, frequency / 1e6); + } + + filterRow(row); + ui->messages->setSortingEnabled(true); + if (scrollToBottom) { + ui->messages->scrollToBottom(); + } + + delete msg; +} + +void DroneIDDemodGUI::burstResult(const DroneIDDemod::MsgBurstResult& result) +{ + if (result.getDetected()) + { + ui->snr->setText(QString("%1 dB %2 Hz") + .arg(result.getSNR(), 0, 'f', 1) + .arg((int) std::round(result.getCFO()))); + } + + if (result.getDecoded() && !result.getMessage().isEmpty()) { + messageReceived(result.getMessage(), result.getDateTime(), result.getSNR(), result.getCFO(), result.getFrequency(), true); + } +} + +bool DroneIDDemodGUI::handleMessage(const Message& message) +{ + if (DroneIDDemod::MsgConfigureDroneIDDemod::match(message)) + { + qDebug("DroneIDDemodGUI::handleMessage: DroneIDDemod::MsgConfigureDroneIDDemod"); + const DroneIDDemod::MsgConfigureDroneIDDemod& cfg = (DroneIDDemod::MsgConfigureDroneIDDemod&) message; + m_settings = cfg.getSettings(); + blockApplySettings(true); + m_channelMarker.updateSettings(static_cast(m_settings.m_channelMarker)); + displaySettings(); + blockApplySettings(false); + return true; + } + else if (DroneIDDemod::MsgBurstResult::match(message)) + { + burstResult((const DroneIDDemod::MsgBurstResult&) message); + return true; + } + else if (DSPSignalNotification::match(message)) + { + const DSPSignalNotification& notif = (const DSPSignalNotification&) message; + m_deviceCenterFrequency = notif.getCenterFrequency(); + m_basebandSampleRate = notif.getSampleRate(); + ui->deltaFrequency->setValueRange(false, 8, -m_basebandSampleRate/2, m_basebandSampleRate/2); + ui->deltaFrequencyLabel->setToolTip(tr("Range %1 %L2 Hz").arg(QChar(0xB1)).arg(m_basebandSampleRate/2)); + updateAbsoluteCenterFrequency(); + updateChannelSelection(); + return true; + } + + return false; +} + +void DroneIDDemodGUI::handleInputMessages() +{ + Message* message; + + while ((message = getInputMessageQueue()->pop()) != nullptr) + { + if (!handleMessage(*message)) { + qDebug("%s: unhandled message: %s", Q_FUNC_INFO, message->getIdentifier()); + } + delete message; + } +} + +void DroneIDDemodGUI::channelMarkerChangedByCursor() +{ + ui->deltaFrequency->setValue(m_channelMarker.getCenterFrequency()); + m_settings.m_inputFrequencyOffset = m_channelMarker.getCenterFrequency(); + updateChannelSelection(); + applySettings(QStringList("inputFrequencyOffset")); +} + +void DroneIDDemodGUI::channelMarkerHighlightedByCursor() +{ + setHighlighted(m_channelMarker.getHighlighted()); +} + +void DroneIDDemodGUI::on_deltaFrequency_changed(qint64 value) +{ + m_channelMarker.setCenterFrequency(value); + m_settings.m_inputFrequencyOffset = m_channelMarker.getCenterFrequency(); + updateAbsoluteCenterFrequency(); + updateChannelSelection(); + applySettings(QStringList("inputFrequencyOffset")); +} + +// Select entry in channel combo box that matches current frequency, or Custom if none match +void DroneIDDemodGUI::updateChannelSelection() +{ + qint64 frequency = m_deviceCenterFrequency + m_settings.m_inputFrequencyOffset; + int index = 0; + + for (int i = 1; i < ui->channel->count(); i++) + { + qint64 channelFrequency = (qint64) std::round(ui->channel->itemText(i).toDouble() * 1e6); + // Allow for small differences due to LO correction or tuning resolution + if (std::abs(channelFrequency - frequency) <= 1000) + { + index = i; + break; + } + } + + ui->channel->blockSignals(true); + ui->channel->setCurrentIndex(index); + ui->channel->blockSignals(false); +} + +void DroneIDDemodGUI::on_channel_currentIndexChanged(int index) +{ + if (index <= 0) { + return; + } + + // Manually selecting a channel stops scanning, otherwise scan would immediately move away + if (m_settings.m_scan) + { + m_settings.m_scan = false; + ui->scan->blockSignals(true); + ui->scan->setChecked(false); + ui->scan->blockSignals(false); + ui->scan->setText("Scan"); + applySettings(QStringList("scan")); + } + + // Tune the device so the channel, at its current offset, is on the selected frequency + qint64 frequency = (qint64) std::round(ui->channel->itemText(index).toDouble() * 1e6); + qint64 centerFrequency = frequency - m_settings.m_inputFrequencyOffset; + + if (!ChannelWebAPIUtils::setCenterFrequency(m_droneIDDemod->getDeviceSetIndex(), centerFrequency)) + { + MessageDialog::warning(this, "DroneID Demodulator", + QString("Failed to set device center frequency to %1 MHz.").arg(centerFrequency / 1e6, 0, 'f', 3)); + updateChannelSelection(); + } +} + +void DroneIDDemodGUI::on_scan_toggled(bool checked) +{ + m_settings.m_scan = checked; + if (!checked) { + ui->scan->setText("Scan"); + } + applySettings(QStringList("scan")); +} + +void DroneIDDemodGUI::on_scanBand_currentIndexChanged(int index) +{ + m_settings.m_scanBand = (DroneIDDemodSettings::ScanBand) index; + applySettings(QStringList("scanBand")); +} + +void DroneIDDemodGUI::on_scan_rightClicked(const QPoint& point) +{ + (void) point; + + QDialog dialog(this); + dialog.setWindowTitle("Scan Settings"); + QFormLayout *layout = new QFormLayout(&dialog); + + QDoubleSpinBox *dwell = new QDoubleSpinBox(); + dwell->setRange(0.5, 60.0); + dwell->setDecimals(1); + dwell->setSingleStep(0.1); + dwell->setSuffix(" s"); + dwell->setValue(m_settings.m_scanDwell); + dwell->setToolTip("Time to wait on each channel for a burst. Bursts are transmitted every 640ms."); + layout->addRow("Dwell", dwell); + + QDoubleSpinBox *hold = new QDoubleSpinBox(); + hold->setRange(0.5, 600.0); + hold->setDecimals(1); + hold->setSingleStep(0.5); + hold->setSuffix(" s"); + hold->setValue(m_settings.m_scanHold); + hold->setToolTip("Time to remain on a channel after the last burst was detected."); + layout->addRow("Hold", hold); + + QDialogButtonBox *buttons = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel); + connect(buttons, &QDialogButtonBox::accepted, &dialog, &QDialog::accept); + connect(buttons, &QDialogButtonBox::rejected, &dialog, &QDialog::reject); + layout->addRow(buttons); + + new DialogPositioner(&dialog, true); + + if (dialog.exec() == QDialog::Accepted) + { + m_settings.m_scanDwell = (float) dwell->value(); + m_settings.m_scanHold = (float) hold->value(); + applySettings({"scanDwell", "scanHold"}); + } +} + +void DroneIDDemodGUI::on_threshold_valueChanged(int value) +{ + m_settings.m_detectionThreshold = value / 100.0f; + ui->thresholdText->setText(QString::number(m_settings.m_detectionThreshold, 'f', 2)); + applySettings(QStringList("detectionThreshold")); +} + +void DroneIDDemodGUI::on_turboIterations_valueChanged(int value) +{ + m_settings.m_turboIterations = value; + applySettings(QStringList("turboIterations")); +} + +void DroneIDDemodGUI::on_mapTimeout_valueChanged(int value) +{ + m_settings.m_mapTimeout = value; + applySettings(QStringList("mapTimeout")); +} + +void DroneIDDemodGUI::on_mapAltitude_currentIndexChanged(int index) +{ + m_settings.m_mapAltitude = (DroneIDDemodSettings::MapAltitude) index; + applySettings(QStringList("mapAltitude")); +} + +void DroneIDDemodGUI::on_filterSerial_editingFinished() +{ + m_settings.m_filterSerial = ui->filterSerial->text(); + filter(); + applySettings(QStringList("filterSerial")); +} + +void DroneIDDemodGUI::on_clearTable_clicked() +{ + ui->messages->setRowCount(0); +} + +void DroneIDDemodGUI::on_udpEnabled_clicked(bool checked) +{ + m_settings.m_udpEnabled = checked; + applySettings(QStringList("udpEnabled")); +} + +void DroneIDDemodGUI::on_udpAddress_editingFinished() +{ + m_settings.m_udpAddress = ui->udpAddress->text(); + applySettings(QStringList("udpAddress")); +} + +void DroneIDDemodGUI::on_udpPort_editingFinished() +{ + m_settings.m_udpPort = ui->udpPort->text().toInt(); + applySettings(QStringList("udpPort")); +} + +void DroneIDDemodGUI::on_messages_cellDoubleClicked(int row, int column) +{ + QString serial = ui->messages->item(row, COL_SERIAL)->text(); + + if ((column == COL_LATITUDE) || (column == COL_LONGITUDE)) { + FeatureWebAPIUtils::mapFind(serial); + } else if ((column == COL_PILOT_LATITUDE) || (column == COL_PILOT_LONGITUDE)) { + FeatureWebAPIUtils::mapFind(serial + " Pilot"); + } else if ((column == COL_HOME_LATITUDE) || (column == COL_HOME_LONGITUDE)) { + FeatureWebAPIUtils::mapFind(serial + " Home"); + } +} + +void DroneIDDemodGUI::filterRow(int row) +{ + bool hidden = false; + if (m_settings.m_filterSerial != "") + { + QRegularExpression re(QRegularExpression::anchoredPattern(m_settings.m_filterSerial)); + QTableWidgetItem *serialItem = ui->messages->item(row, COL_SERIAL); + QRegularExpressionMatch match = re.match(serialItem->text()); + if (!match.hasMatch()) { + hidden = true; + } + } + ui->messages->setRowHidden(row, hidden); +} + +void DroneIDDemodGUI::filter() +{ + for (int i = 0; i < ui->messages->rowCount(); i++) { + filterRow(i); + } +} + +void DroneIDDemodGUI::onWidgetRolled(QWidget* widget, bool rollDown) +{ + (void) widget; + (void) rollDown; + + getRollupContents()->saveState(m_rollupState); + applySettings(QStringList("rollupState")); +} + +void DroneIDDemodGUI::onMenuDialogCalled(const QPoint &p) +{ + if (m_contextMenuType == ContextMenuType::ContextMenuChannelSettings) + { + BasicChannelSettingsDialog dialog(&m_channelMarker, this); + dialog.setUseReverseAPI(m_settings.m_useReverseAPI); + dialog.setReverseAPIAddress(m_settings.m_reverseAPIAddress); + dialog.setReverseAPIPort(m_settings.m_reverseAPIPort); + dialog.setReverseAPIDeviceIndex(m_settings.m_reverseAPIDeviceIndex); + dialog.setReverseAPIChannelIndex(m_settings.m_reverseAPIChannelIndex); + dialog.setDefaultTitle(m_displayedName); + + if (m_deviceUISet->m_deviceMIMOEngine) + { + dialog.setNumberOfStreams(m_droneIDDemod->getNumberOfDeviceStreams()); + dialog.setStreamIndex(m_settings.m_streamIndex); + } + + dialog.move(p); + new DialogPositioner(&dialog, false); + dialog.exec(); + + m_settings.m_rgbColor = m_channelMarker.getColor().rgb(); + m_settings.m_title = m_channelMarker.getTitle(); + m_settings.m_useReverseAPI = dialog.useReverseAPI(); + m_settings.m_reverseAPIAddress = dialog.getReverseAPIAddress(); + m_settings.m_reverseAPIPort = dialog.getReverseAPIPort(); + m_settings.m_reverseAPIDeviceIndex = dialog.getReverseAPIDeviceIndex(); + m_settings.m_reverseAPIChannelIndex = dialog.getReverseAPIChannelIndex(); + + setWindowTitle(m_settings.m_title); + setTitle(m_channelMarker.getTitle()); + setTitleColor(m_settings.m_rgbColor); + + if (m_deviceUISet->m_deviceMIMOEngine) + { + m_settings.m_streamIndex = dialog.getSelectedStreamIndex(); + m_channelMarker.clearStreamIndexes(); + m_channelMarker.addStreamIndex(m_settings.m_streamIndex); + updateIndexLabel(); + } + + applySettings(QStringList({"title", "rgbColor", "useReverseAPI", "reverseAPIAddress", + "reverseAPIPort", "reverseAPIDeviceIndex", "reverseAPIChannelIndex", "streamIndex"})); + } + + resetContextMenuType(); +} + +DroneIDDemodGUI::DroneIDDemodGUI(PluginAPI* pluginAPI, DeviceUISet *deviceUISet, BasebandSampleSink *rxChannel, QWidget* parent) : + ChannelGUI(parent), + ui(new Ui::DroneIDDemodGUI), + m_pluginAPI(pluginAPI), + m_deviceUISet(deviceUISet), + m_channelMarker(this), + m_deviceCenterFrequency(0), + m_basebandSampleRate(1), + m_doApplySettings(true), + m_tickCount(0), + m_burstsDetected(-1), + m_burstsDecoded(-1) +{ + setAttribute(Qt::WA_DeleteOnClose, true); + m_helpURL = "plugins/channelrx/demoddroneid/readme.md"; + RollupContents *rollupContents = getRollupContents(); + ui->setupUi(rollupContents); + setSizePolicy(rollupContents->sizePolicy()); + rollupContents->arrangeRollups(); + connect(rollupContents, SIGNAL(widgetRolled(QWidget*,bool)), this, SLOT(onWidgetRolled(QWidget*,bool))); + connect(this, SIGNAL(customContextMenuRequested(const QPoint &)), this, SLOT(onMenuDialogCalled(const QPoint &))); + + m_droneIDDemod = reinterpret_cast(rxChannel); + m_droneIDDemod->setMessageQueueToGUI(getInputMessageQueue()); + + connect(&MainCore::instance()->getMasterTimer(), SIGNAL(timeout()), this, SLOT(tick())); // 50 ms + + ui->deltaFrequencyLabel->setText(QString("%1f").arg(QChar(0x94, 0x03))); + ui->deltaFrequency->setColorMapper(ColorMapper(ColorMapper::GrayGold)); + ui->deltaFrequency->setValueRange(false, 8, -99999999, 99999999); + for (auto frequency : DroneIDDemodSettings::getScanFrequencies(DroneIDDemodSettings::BAND_2_4_AND_5_8_GHZ)) { + ui->channel->addItem(QString::number(frequency / 1e6, 'f', 1)); + } + ui->scan->setContextMenuPolicy(Qt::CustomContextMenu); + ui->channelPowerMeter->setColorTheme(LevelMeterSignalDB::ColorGreenAndBlue); + + m_channelMarker.blockSignals(true); + m_channelMarker.setColor(Qt::yellow); + m_channelMarker.setBandwidth(m_occupiedBandwidth); + m_channelMarker.setCenterFrequency(m_settings.m_inputFrequencyOffset); + m_channelMarker.setTitle("DroneID Demodulator"); + m_channelMarker.blockSignals(false); + m_channelMarker.setVisible(true); // activate signal on the last setting only + + setTitleColor(m_channelMarker.getColor()); + m_settings.setChannelMarker(&m_channelMarker); + m_settings.setRollupState(&m_rollupState); + + m_deviceUISet->addChannelMarker(&m_channelMarker); + + connect(&m_channelMarker, SIGNAL(changedByCursor()), this, SLOT(channelMarkerChangedByCursor())); + connect(&m_channelMarker, SIGNAL(highlightedByCursor()), this, SLOT(channelMarkerHighlightedByCursor())); + connect(getInputMessageQueue(), SIGNAL(messageEnqueued()), this, SLOT(handleInputMessages())); + + // Resize the table using dummy data + resizeTable(); + // Allow user to reorder columns + ui->messages->horizontalHeader()->setSectionsMovable(true); + // Allow user to sort table by clicking on headers + ui->messages->setSortingEnabled(true); + // Add context menu to allow hiding/showing of columns + m_messagesMenu = new QMenu(ui->messages); + for (int i = 0; i < ui->messages->horizontalHeader()->count(); i++) + { + QString text = ui->messages->horizontalHeaderItem(i)->text(); + m_messagesMenu->addAction(createCheckableItem(text, i, true, SLOT(messagesColumnSelectMenuChecked()))); + } + ui->messages->horizontalHeader()->setContextMenuPolicy(Qt::CustomContextMenu); + connect(ui->messages->horizontalHeader(), SIGNAL(customContextMenuRequested(QPoint)), SLOT(messagesColumnSelectMenu(QPoint))); + // Get signals when columns change + connect(ui->messages->horizontalHeader(), SIGNAL(sectionMoved(int, int, int)), SLOT(messages_sectionMoved(int, int, int))); + connect(ui->messages->horizontalHeader(), SIGNAL(sectionResized(int, int, int)), SLOT(messages_sectionResized(int, int, int))); + ui->messages->setContextMenuPolicy(Qt::CustomContextMenu); + connect(ui->messages, SIGNAL(customContextMenuRequested(QPoint)), SLOT(customContextMenuRequested(QPoint))); + TableTapAndHold *tableTapAndHold = new TableTapAndHold(ui->messages); + connect(tableTapAndHold, &TableTapAndHold::tapAndHold, this, &DroneIDDemodGUI::customContextMenuRequested); + + ui->messages->setItemDelegateForColumn(COL_DATE_TIME, new DateTimeDelegate("yyyy/MM/dd hh:mm:ss", ui->messages)); + ui->messages->setItemDelegateForColumn(COL_LATITUDE, new DecimalDelegate(6, ui->messages)); + ui->messages->setItemDelegateForColumn(COL_LONGITUDE, new DecimalDelegate(6, ui->messages)); + ui->messages->setItemDelegateForColumn(COL_HEIGHT, new DecimalDelegate(1, ui->messages)); + ui->messages->setItemDelegateForColumn(COL_SPEED, new DecimalDelegate(1, ui->messages)); + ui->messages->setItemDelegateForColumn(COL_VERTICAL_SPEED, new DecimalDelegate(1, ui->messages)); + ui->messages->setItemDelegateForColumn(COL_COURSE, new DecimalDelegate(0, ui->messages)); + ui->messages->setItemDelegateForColumn(COL_YAW, new DecimalDelegate(1, ui->messages)); + ui->messages->setItemDelegateForColumn(COL_PILOT_LATITUDE, new DecimalDelegate(6, ui->messages)); + ui->messages->setItemDelegateForColumn(COL_PILOT_LONGITUDE, new DecimalDelegate(6, ui->messages)); + ui->messages->setItemDelegateForColumn(COL_HOME_LATITUDE, new DecimalDelegate(6, ui->messages)); + ui->messages->setItemDelegateForColumn(COL_HOME_LONGITUDE, new DecimalDelegate(6, ui->messages)); + ui->messages->setItemDelegateForColumn(COL_GPS_TIME, new DateTimeDelegate("yyyy/MM/dd hh:mm:ss", ui->messages)); + ui->messages->setItemDelegateForColumn(COL_SNR, new DecimalDelegate(1, ui->messages)); + ui->messages->setItemDelegateForColumn(COL_FREQUENCY, new DecimalDelegate(1, ui->messages)); + + displaySettings(); + makeUIConnections(); + applySettings(QStringList(), true); + DialPopup::addPopupsToChildDials(this); + m_resizer.enableChildMouseTracking(); +} + +void DroneIDDemodGUI::customContextMenuRequested(QPoint pos) +{ + QTableWidgetItem *item = ui->messages->itemAt(pos); + if (item) + { + int row = item->row(); + QString serial = ui->messages->item(row, COL_SERIAL)->text(); + + QMenu* tableContextMenu = new QMenu(ui->messages); + connect(tableContextMenu, &QMenu::aboutToHide, tableContextMenu, &QMenu::deleteLater); + + // Copy current cell + QAction* copyAction = new QAction("Copy", tableContextMenu); + const QString text = item->text(); + connect(copyAction, &QAction::triggered, this, [text]()->void { + QClipboard *clipboard = QGuiApplication::clipboard(); + clipboard->setText(text); + }); + tableContextMenu->addAction(copyAction); + + // Find on Map + tableContextMenu->addSeparator(); + QAction* findDroneAction = new QAction(QString("Find drone %1 on map").arg(serial), tableContextMenu); + connect(findDroneAction, &QAction::triggered, this, [serial]()->void { + FeatureWebAPIUtils::mapFind(serial); + }); + tableContextMenu->addAction(findDroneAction); + QAction* findPilotAction = new QAction(QString("Find pilot of %1 on map").arg(serial), tableContextMenu); + connect(findPilotAction, &QAction::triggered, this, [serial]()->void { + FeatureWebAPIUtils::mapFind(serial + " Pilot"); + }); + tableContextMenu->addAction(findPilotAction); + QAction* findHomeAction = new QAction(QString("Find home of %1 on map").arg(serial), tableContextMenu); + connect(findHomeAction, &QAction::triggered, this, [serial]()->void { + FeatureWebAPIUtils::mapFind(serial + " Home"); + }); + tableContextMenu->addAction(findHomeAction); + + tableContextMenu->popup(ui->messages->viewport()->mapToGlobal(pos)); + } +} + +DroneIDDemodGUI::~DroneIDDemodGUI() +{ + delete ui; +} + +void DroneIDDemodGUI::blockApplySettings(bool block) +{ + m_doApplySettings = !block; +} + +void DroneIDDemodGUI::applySettings(const QStringList& settingsKeys, bool force) +{ + if (m_doApplySettings) + { + DroneIDDemod::MsgConfigureDroneIDDemod* message = DroneIDDemod::MsgConfigureDroneIDDemod::create(settingsKeys, m_settings, force); + m_droneIDDemod->getInputMessageQueue()->push(message); + } +} + +void DroneIDDemodGUI::displaySettings() +{ + m_channelMarker.blockSignals(true); + m_channelMarker.setBandwidth(m_occupiedBandwidth); + m_channelMarker.setCenterFrequency(m_settings.m_inputFrequencyOffset); + m_channelMarker.setTitle(m_settings.m_title); + m_channelMarker.blockSignals(false); + m_channelMarker.setColor(m_settings.m_rgbColor); // activate signal on the last setting only + + setTitleColor(m_settings.m_rgbColor); + setWindowTitle(m_channelMarker.getTitle()); + setTitle(m_channelMarker.getTitle()); + + blockApplySettings(true); + + ui->deltaFrequency->setValue(m_channelMarker.getCenterFrequency()); + updateChannelSelection(); + + // Block signals, so any rounding or clamping by the widgets doesn't modify the settings + ui->threshold->blockSignals(true); + ui->threshold->setValue((int) std::round(m_settings.m_detectionThreshold * 100.0f)); + ui->threshold->blockSignals(false); + ui->thresholdText->setText(QString::number(m_settings.m_detectionThreshold, 'f', 2)); + ui->turboIterations->blockSignals(true); + ui->turboIterations->setValue(m_settings.m_turboIterations); + ui->turboIterations->blockSignals(false); + ui->mapTimeout->blockSignals(true); + ui->mapTimeout->setValue(m_settings.m_mapTimeout); + ui->mapTimeout->blockSignals(false); + ui->mapAltitude->blockSignals(true); + ui->mapAltitude->setCurrentIndex((int) m_settings.m_mapAltitude); + ui->mapAltitude->blockSignals(false); + ui->scan->blockSignals(true); + ui->scan->setChecked(m_settings.m_scan); + ui->scan->blockSignals(false); + ui->scanBand->blockSignals(true); + ui->scanBand->setCurrentIndex((int) m_settings.m_scanBand); + ui->scanBand->blockSignals(false); + + updateIndexLabel(); + + ui->filterSerial->setText(m_settings.m_filterSerial); + + ui->udpEnabled->setChecked(m_settings.m_udpEnabled); + ui->udpAddress->setText(m_settings.m_udpAddress); + ui->udpPort->setText(QString::number(m_settings.m_udpPort)); + + ui->logFilename->setToolTip(QString(".csv log filename: %1").arg(m_settings.m_logFilename)); + ui->logEnable->setChecked(m_settings.m_logEnabled); + + ui->useFileTime->setChecked(m_settings.m_useFileTime); + + // Order and size columns + QHeaderView *header = ui->messages->horizontalHeader(); + for (int i = 0; i < DRONEIDDEMOD_COLUMNS; i++) + { + bool hidden = m_settings.m_columnSizes[i] == 0; + header->setSectionHidden(i, hidden); + m_messagesMenu->actions().at(i)->setChecked(!hidden); + if (m_settings.m_columnSizes[i] > 0) { + ui->messages->setColumnWidth(i, m_settings.m_columnSizes[i]); + } + header->moveSection(header->visualIndex(i), m_settings.m_columnIndexes[i]); + } + + filter(); + + getRollupContents()->restoreState(m_rollupState); + updateAbsoluteCenterFrequency(); + blockApplySettings(false); +} + +void DroneIDDemodGUI::leaveEvent(QEvent* event) +{ + m_channelMarker.setHighlighted(false); + ChannelGUI::leaveEvent(event); +} + +void DroneIDDemodGUI::enterEvent(EnterEventType* event) +{ + m_channelMarker.setHighlighted(true); + ChannelGUI::enterEvent(event); +} + +void DroneIDDemodGUI::tick() +{ + double magsqAvg, magsqPeak; + int nbMagsqSamples; + m_droneIDDemod->getMagSqLevels(magsqAvg, magsqPeak, nbMagsqSamples); + double powDbAvg = CalcDb::dbPower(magsqAvg); + double powDbPeak = CalcDb::dbPower(magsqPeak); + + ui->channelPowerMeter->levelChanged( + (100.0f + powDbAvg) / 100.0f, + (100.0f + powDbPeak) / 100.0f, + nbMagsqSamples); + + if (m_tickCount % 4 == 0) + { + ui->channelPower->setText(QString::number(powDbAvg, 'f', 1)); + if (m_settings.m_scan) { + ui->scan->setText(m_droneIDDemod->isScanLocked() ? "Lock" : "Scan"); + } + } + + if (m_tickCount % 20 == 0) + { + int sampleRate = m_droneIDDemod->getChannelSampleRate(); + ui->sampleRate->setText(QString("%1 MS/s").arg(sampleRate / 1e6, 0, 'f', 2)); + if (sampleRate < DroneIDDemodSettings::DRONEIDDEMOD_CHANNEL_SAMPLE_RATE) + { + ui->sampleRate->setStyleSheet("QLabel { color: red }"); + ui->sampleRate->setToolTip("Channel sample rate is too low. Device sample rate must be at least 15.36 MS/s."); + } + else + { + ui->sampleRate->setStyleSheet(""); + ui->sampleRate->setToolTip("Channel sample rate"); + } + + int detected = m_droneIDDemod->getBurstsDetected(); + int decoded = m_droneIDDemod->getBurstsDecoded(); + if ((detected != m_burstsDetected) || (decoded != m_burstsDecoded)) + { + ui->bursts->setText(QString("%1 / %2").arg(detected).arg(decoded)); + m_burstsDetected = detected; + m_burstsDecoded = decoded; + } + int dropped = m_droneIDDemod->getBurstsDropped(); + ui->bursts->setToolTip(QString("Bursts detected / decoded (%1 dropped due to decoder being busy)").arg(dropped)); + } + + m_tickCount++; +} + +void DroneIDDemodGUI::on_logEnable_clicked(bool checked) +{ + m_settings.m_logEnabled = checked; + applySettings(QStringList("logEnabled")); +} + +void DroneIDDemodGUI::on_logFilename_clicked() +{ + // Get filename to save to + QFileDialog fileDialog(nullptr, "Select file to log received messages to", "", "*.csv"); + fileDialog.setDefaultSuffix("csv"); + fileDialog.setAcceptMode(QFileDialog::AcceptSave); + if (fileDialog.exec()) + { + QStringList fileNames = fileDialog.selectedFiles(); + if (fileNames.size() > 0) + { + m_settings.m_logFilename = fileNames[0]; + ui->logFilename->setToolTip(QString(".csv log filename: %1").arg(m_settings.m_logFilename)); + applySettings(QStringList("logFilename")); + } + } +} + +// Read .csv log and process as received messages +void DroneIDDemodGUI::on_logOpen_clicked() +{ + QFileDialog fileDialog(nullptr, "Select .csv log file to read", "", "*.csv"); + if (fileDialog.exec()) + { + QStringList fileNames = fileDialog.selectedFiles(); + if (fileNames.size() > 0) + { + QFile file(fileNames[0]); + if (file.open(QIODevice::ReadOnly | QIODevice::Text)) + { + QTextStream in(&file); + QString error; + QHash colIndexes = CSV::readHeader(in, {"Date", "Time", "Data"}, error); + if (error.isEmpty()) + { + int dateCol = colIndexes.value("Date"); + int timeCol = colIndexes.value("Time"); + int dataCol = colIndexes.value("Data"); + int frequencyCol = colIndexes.value("Frequency (MHz)", -1); // Not in older logs + int maxCol = std::max({dateCol, timeCol, dataCol}); + + QMessageBox dialog(this); + dialog.setText("Reading messages"); + dialog.addButton(QMessageBox::Cancel); + dialog.show(); + QApplication::processEvents(); + int count = 0; + bool cancelled = false; + QStringList cols; + + while (!cancelled && CSV::readRow(in, &cols)) + { + if (cols.size() > maxCol) + { + QDate date = QDate::fromString(cols[dateCol]); + QTime time = QTime::fromString(cols[timeCol]); + QDateTime dateTime(date, time); + QByteArray bytes = QByteArray::fromHex(cols[dataCol].toLatin1()); + + qint64 frequency = 0; + if ((frequencyCol >= 0) && (frequencyCol < cols.size())) { + frequency = (qint64) std::round(cols[frequencyCol].toDouble() * 1e6); + } + + messageReceived(bytes, dateTime, 0.0f, 0.0f, frequency, false); + + if (count % 100 == 0) + { + QApplication::processEvents(); + if (dialog.clickedButton()) { + cancelled = true; + } + } + count++; + } + } + dialog.close(); + } + else + { + MessageDialog::critical(this, "DroneID Demodulator", error); + } + } + else + { + MessageDialog::critical(this, "DroneID Demodulator", QString("Failed to open file %1").arg(fileNames[0])); + } + } + } +} + +void DroneIDDemodGUI::on_useFileTime_toggled(bool checked) +{ + m_settings.m_useFileTime = checked; + applySettings(QStringList("useFileTime")); +} + +void DroneIDDemodGUI::makeUIConnections() +{ + QObject::connect(ui->deltaFrequency, &ValueDialZ::changed, this, &DroneIDDemodGUI::on_deltaFrequency_changed); + QObject::connect(ui->channel, qOverload(&QComboBox::currentIndexChanged), this, &DroneIDDemodGUI::on_channel_currentIndexChanged); + QObject::connect(ui->scan, &ButtonSwitch::toggled, this, &DroneIDDemodGUI::on_scan_toggled); + QObject::connect(ui->scan, &ButtonSwitch::customContextMenuRequested, this, &DroneIDDemodGUI::on_scan_rightClicked); + QObject::connect(ui->scanBand, qOverload(&QComboBox::currentIndexChanged), this, &DroneIDDemodGUI::on_scanBand_currentIndexChanged); + QObject::connect(ui->threshold, &QDial::valueChanged, this, &DroneIDDemodGUI::on_threshold_valueChanged); + QObject::connect(ui->turboIterations, qOverload(&QSpinBox::valueChanged), this, &DroneIDDemodGUI::on_turboIterations_valueChanged); + QObject::connect(ui->mapTimeout, qOverload(&QSpinBox::valueChanged), this, &DroneIDDemodGUI::on_mapTimeout_valueChanged); + QObject::connect(ui->mapAltitude, qOverload(&QComboBox::currentIndexChanged), this, &DroneIDDemodGUI::on_mapAltitude_currentIndexChanged); + QObject::connect(ui->filterSerial, &QLineEdit::editingFinished, this, &DroneIDDemodGUI::on_filterSerial_editingFinished); + QObject::connect(ui->clearTable, &QPushButton::clicked, this, &DroneIDDemodGUI::on_clearTable_clicked); + QObject::connect(ui->udpEnabled, &QCheckBox::clicked, this, &DroneIDDemodGUI::on_udpEnabled_clicked); + QObject::connect(ui->udpAddress, &QLineEdit::editingFinished, this, &DroneIDDemodGUI::on_udpAddress_editingFinished); + QObject::connect(ui->udpPort, &QLineEdit::editingFinished, this, &DroneIDDemodGUI::on_udpPort_editingFinished); + QObject::connect(ui->messages, &QTableWidget::cellDoubleClicked, this, &DroneIDDemodGUI::on_messages_cellDoubleClicked); + QObject::connect(ui->logEnable, &ButtonSwitch::clicked, this, &DroneIDDemodGUI::on_logEnable_clicked); + QObject::connect(ui->logFilename, &QToolButton::clicked, this, &DroneIDDemodGUI::on_logFilename_clicked); + QObject::connect(ui->logOpen, &QToolButton::clicked, this, &DroneIDDemodGUI::on_logOpen_clicked); + QObject::connect(ui->useFileTime, &ButtonSwitch::toggled, this, &DroneIDDemodGUI::on_useFileTime_toggled); +} + +void DroneIDDemodGUI::updateAbsoluteCenterFrequency() +{ + setStatusFrequency(m_deviceCenterFrequency + m_settings.m_inputFrequencyOffset); +} diff --git a/plugins/channelrx/demoddroneid/droneiddemodgui.h b/plugins/channelrx/demoddroneid/droneiddemodgui.h new file mode 100644 index 000000000..09922b003 --- /dev/null +++ b/plugins/channelrx/demoddroneid/droneiddemodgui.h @@ -0,0 +1,171 @@ +/////////////////////////////////////////////////////////////////////////////////// +// Copyright (C) 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 . // +/////////////////////////////////////////////////////////////////////////////////// + +#ifndef INCLUDE_DRONEIDDEMODGUI_H +#define INCLUDE_DRONEIDDEMODGUI_H + +#include +#include + +#include "channel/channelgui.h" +#include "dsp/channelmarker.h" +#include "util/messagequeue.h" +#include "settings/rollupstate.h" + +#include "droneiddemodsettings.h" +#include "droneiddemod.h" + +class PluginAPI; +class DeviceUISet; +class BasebandSampleSink; +class DroneIDDemod; +class DroneIDDemodGUI; + +namespace Ui { + class DroneIDDemodGUI; +} + +class DroneIDDemodGUI : public ChannelGUI { + Q_OBJECT + +public: + static DroneIDDemodGUI* create(PluginAPI* pluginAPI, DeviceUISet *deviceUISet, BasebandSampleSink *rxChannel); + virtual void destroy(); + + void resetToDefaults(); + QByteArray serialize() const; + bool deserialize(const QByteArray& data); + virtual MessageQueue *getInputMessageQueue() { return &m_inputMessageQueue; } + virtual void setWorkspaceIndex(int index) { m_settings.m_workspaceIndex = index; }; + virtual int getWorkspaceIndex() const { return m_settings.m_workspaceIndex; }; + virtual void setGeometryBytes(const QByteArray& blob) { m_settings.m_geometryBytes = blob; }; + virtual QByteArray getGeometryBytes() const { return m_settings.m_geometryBytes; }; + virtual QString getTitle() const { return m_settings.m_title; }; + virtual QColor getTitleColor() const { return m_settings.m_rgbColor; }; + virtual void zetHidden(bool hidden) { m_settings.m_hidden = hidden; } + virtual bool getHidden() const { return m_settings.m_hidden; } + virtual ChannelMarker& getChannelMarker() { return m_channelMarker; } + virtual int getStreamIndex() const { return m_settings.m_streamIndex; } + virtual void setStreamIndex(int streamIndex) { m_settings.m_streamIndex = streamIndex; } + +public slots: + void channelMarkerChangedByCursor(); + void channelMarkerHighlightedByCursor(); + +private: + Ui::DroneIDDemodGUI* ui; + PluginAPI* m_pluginAPI; + DeviceUISet* m_deviceUISet; + ChannelMarker m_channelMarker; + RollupState m_rollupState; + DroneIDDemodSettings m_settings; + qint64 m_deviceCenterFrequency; + int m_basebandSampleRate; + bool m_doApplySettings; + + DroneIDDemod* m_droneIDDemod; + uint32_t m_tickCount; + MessageQueue m_inputMessageQueue; + int m_burstsDetected; + int m_burstsDecoded; + + QMenu *m_messagesMenu; // Column select context menu + + static constexpr int m_occupiedBandwidth = 9000000; + static constexpr int m_maxRows = 10000; //!< Maximum number of messages in table + + explicit DroneIDDemodGUI(PluginAPI* pluginAPI, DeviceUISet *deviceUISet, BasebandSampleSink *rxChannel, QWidget* parent = nullptr); + virtual ~DroneIDDemodGUI(); + + void blockApplySettings(bool block); + void applySettings(const QStringList& settingsKeys, bool force = false); + void displaySettings(); + void messageReceived(const QByteArray& message, const QDateTime& dateTime, float snr, float cfo, qint64 frequency, bool live); + void burstResult(const DroneIDDemod::MsgBurstResult& result); + bool handleMessage(const Message& message); + void makeUIConnections(); + void updateAbsoluteCenterFrequency(); + void updateChannelSelection(); + + void leaveEvent(QEvent*); + void enterEvent(EnterEventType*); + + void resizeTable(); + QAction *createCheckableItem(QString& text, int idx, bool checked, const char *slot); + + enum MessageCol { + COL_DATE_TIME, + COL_SERIAL, + COL_MODEL, + COL_TYPE, + COL_SEQUENCE, + COL_LATITUDE, + COL_LONGITUDE, + COL_ALTITUDE, + COL_HEIGHT, + COL_SPEED, + COL_VERTICAL_SPEED, + COL_COURSE, + COL_YAW, + COL_PILOT_LATITUDE, + COL_PILOT_LONGITUDE, + COL_HOME_LATITUDE, + COL_HOME_LONGITUDE, + COL_UUID, + COL_STATE, + COL_GPS_TIME, + COL_SNR, + COL_CFO, + COL_FREQUENCY, + COL_CRC + }; + +private slots: + void on_deltaFrequency_changed(qint64 value); + void on_channel_currentIndexChanged(int index); + void on_scan_toggled(bool checked); + void on_scan_rightClicked(const QPoint& point); + void on_scanBand_currentIndexChanged(int index); + void on_threshold_valueChanged(int value); + void on_turboIterations_valueChanged(int value); + void on_mapTimeout_valueChanged(int value); + void on_mapAltitude_currentIndexChanged(int index); + void on_filterSerial_editingFinished(); + void on_clearTable_clicked(); + void on_udpEnabled_clicked(bool checked); + void on_udpAddress_editingFinished(); + void on_udpPort_editingFinished(); + void on_messages_cellDoubleClicked(int row, int column); + void on_logEnable_clicked(bool checked=false); + void on_logFilename_clicked(); + void on_logOpen_clicked(); + void on_useFileTime_toggled(bool checked=false); + void filterRow(int row); + void filter(); + void messages_sectionMoved(int logicalIndex, int oldVisualIndex, int newVisualIndex); + void messages_sectionResized(int logicalIndex, int oldSize, int newSize); + void messagesColumnSelectMenu(QPoint pos); + void messagesColumnSelectMenuChecked(bool checked = false); + void customContextMenuRequested(QPoint point); + void onWidgetRolled(QWidget* widget, bool rollDown); + void onMenuDialogCalled(const QPoint& p); + void handleInputMessages(); + void tick(); +}; + +#endif // INCLUDE_DRONEIDDEMODGUI_H diff --git a/plugins/channelrx/demoddroneid/droneiddemodgui.ui b/plugins/channelrx/demoddroneid/droneiddemodgui.ui new file mode 100644 index 000000000..462021efb --- /dev/null +++ b/plugins/channelrx/demoddroneid/droneiddemodgui.ui @@ -0,0 +1,1044 @@ + + + DroneIDDemodGUI + + + + 0 + 0 + 404 + 400 + + + + + 0 + 0 + + + + + 352 + 0 + + + + + 9 + + + + Qt::StrongFocus + + + DroneID Demodulator + + + + + 0 + 0 + 390 + 191 + + + + + 350 + 0 + + + + Settings + + + + 3 + + + 2 + + + 2 + + + 2 + + + 2 + + + + + 2 + + + + + + 16 + 0 + + + + Df + + + + + + + + 0 + 0 + + + + + 32 + 16 + + + + + 12 + + + + PointingHandCursor + + + Qt::StrongFocus + + + Demod shift frequency from center in Hz + + + + + + + Hz + + + + + + + Qt::Vertical + + + + + + + Ch + + + + + + + + 70 + 0 + + + + Select a known DroneID channel frequency. The device center frequency is set so that the channel, at its current offset, is on this frequency. + + + + Custom + + + + + + + + MHz + + + + + + + Scan DroneID channels, by changing the device center frequency, pausing on channels where bursts are detected. Shows Lock when paused. Right click for scan settings. + + + Scan + + + true + + + + + + + Channels to scan + + + + 2.4G + + + + + 5.8G + + + + + Both + + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + + Channel power + + + Qt::RightToLeft + + + 0.0 + + + + + + + dB + + + + + + + + + + + + + dB + + + + + + + + 0 + 0 + + + + + 0 + 24 + + + + + 8 + + + + Level meter (dB) top trace: average, bottom trace: instantaneous peak, tip: peak hold + + + + + + + + + Qt::Horizontal + + + + + + + + + TH + + + + + + + + 24 + 24 + + + + Burst detection threshold. Lower values detect weaker bursts, but may increase false detections. + + + 5 + + + 95 + + + 5 + + + 20 + + + + + + + + 24 + 0 + + + + 0.20 + + + + + + + Qt::Vertical + + + + + + + Iter + + + + + + + Maximum number of turbo decoder iterations + + + 1 + + + 16 + + + 8 + + + + + + + Qt::Vertical + + + + + + + Map + + + + + + + Time in seconds after which a drone is removed from the Map if no messages are received. 0 to never remove. + + + s + + + 3600 + + + 10 + + + 300 + + + + + + + Value used for the drone's altitude on the 3D Map. + +Alt - Altitude above WGS84 ellipsoid (GPS height). Correct over any terrain, but GPS error can put the drone slightly below ground on take-off and landing. + +Height - Height above take-off point, displayed relative to the ground at the drone's position. Never below ground, but offset by any difference in ground height from the take-off point. + + + + Alt + + + + + Height + + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + + Qt::Horizontal + + + + + + + + + SR + + + + + + + + 60 + 0 + + + + Channel sample rate. Must be at least 15.36 MS/s. + + + - + + + + + + + Qt::Vertical + + + + + + + Bursts + + + + + + + + 50 + 0 + + + + Number of bursts detected / successfully decoded + + + 0 / 0 + + + + + + + Qt::Vertical + + + + + + + SNR + + + + + + + + 100 + 0 + + + + SNR and frequency offset of last detected burst + + + - + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + + Qt::Horizontal + + + + + + + + + UDP + + + + + + + Forward received messages via UDP + + + Qt::RightToLeft + + + + + + + + + + + 120 + 0 + + + + Qt::ClickFocus + + + Destination UDP address + + + 000.000.000.000 + + + 127.0.0.1 + + + + + + + : + + + Qt::AlignCenter + + + + + + + + 50 + 0 + + + + + 50 + 16777215 + + + + Qt::ClickFocus + + + Destination UDP port + + + 00000 + + + 9999 + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + + Qt::Horizontal + + + + + + + + + Find + + + + + + + Display only messages where the serial number matches the specified regular expression + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + 24 + 16777215 + + + + Check to use date and time from input file. Uncheck to use date and time from clock. + + + + + + + :/clockcurrent.png + :/clockfile.png + :/clockcurrent.png + + + + + + + + + 24 + 16777215 + + + + Start/stop logging of received messages to .csv file + + + + + + + :/record_off.png + :/record_off.png + + + + + + + + Set log .csv filename + + + + + + + :/save.png + :/save.png + + + + false + + + + + + + Read messages from .csv log file + + + + + + + :/load.png + :/load.png + + + + false + + + + + + + Clear messages from table + + + + + + + :/bin.png + :/bin.png + + + + + + + + + + + + 0 + 200 + 391 + 171 + + + + + 0 + 0 + + + + Received Messages + + + + 2 + + + 3 + + + 3 + + + 3 + + + 3 + + + + + Received messages + + + QAbstractItemView::NoEditTriggers + + + + Date/Time + + + Date and time message was received + + + + + Serial + + + Drone serial number + + + + + Model + + + Drone model (product type) + + + + + Type + + + Message type + + + + + Seq + + + Message sequence number + + + + + Lat + + + Drone latitude in degrees + + + + + Lon + + + Drone longitude in degrees + + + + + Alt (m) + + + Drone altitude above WGS84 ellipsoid in metres. This is GPS height, which differs from height above mean sea level by the local geoid height (E.g. ~46m in the UK) + + + + + Height (m) + + + Drone height above take-off point in metres + + + + + Speed (m/s) + + + Drone horizontal speed in metres per second + + + + + V/S (m/s) + + + Drone vertical speed in metres per second + + + + + Course + + + Drone ground track in degrees + + + + + Yaw + + + Drone yaw in degrees + + + + + Pilot Lat + + + Pilot latitude in degrees + + + + + Pilot Lon + + + Pilot longitude in degrees + + + + + Home Lat + + + Home point latitude in degrees + + + + + Home Lon + + + Home point longitude in degrees + + + + + UUID + + + UUID + + + + + State + + + Drone state + + + + + GPS Time + + + Date and time from the pilot's phone GPS + + + + + SNR (dB) + + + Signal to noise ratio of received burst in dB + + + + + CFO (Hz) + + + Carrier frequency offset of received burst in Hz + + + + + Freq (MHz) + + + Channel frequency the burst was received on in MHz + + + + + CRC + + + Whether the message CRC is valid + + + + + + + + + + ButtonSwitch + QToolButton +
gui/buttonswitch.h
+
+ + ValueDialZ + QWidget +
gui/valuedialz.h
+ 1 +
+ + RollupContents + QWidget +
gui/rollupcontents.h
+ 1 +
+ + LevelMeterSignalDB + QWidget +
gui/levelmeter.h
+ 1 +
+
+ + + + +
diff --git a/plugins/channelrx/demoddroneid/droneiddemodplugin.cpp b/plugins/channelrx/demoddroneid/droneiddemodplugin.cpp new file mode 100644 index 000000000..21a5369d3 --- /dev/null +++ b/plugins/channelrx/demoddroneid/droneiddemodplugin.cpp @@ -0,0 +1,92 @@ +/////////////////////////////////////////////////////////////////////////////////// +// Copyright (C) 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 . // +/////////////////////////////////////////////////////////////////////////////////// + +#include +#include "plugin/pluginapi.h" + +#ifndef SERVER_MODE +#include "droneiddemodgui.h" +#endif +#include "droneiddemod.h" +#include "droneiddemodwebapiadapter.h" +#include "droneiddemodplugin.h" + +const PluginDescriptor DroneIDDemodPlugin::m_pluginDescriptor = { + DroneIDDemod::m_channelId, + QStringLiteral("DJI DroneID Demodulator"), + QStringLiteral("7.28.0"), + QStringLiteral("(c) Jon Beniston, M7RCE"), + QStringLiteral("https://github.com/f4exb/sdrangel"), + true, + QStringLiteral("https://github.com/f4exb/sdrangel") +}; + +DroneIDDemodPlugin::DroneIDDemodPlugin(QObject* parent) : + QObject(parent), + m_pluginAPI(nullptr) +{ +} + +const PluginDescriptor& DroneIDDemodPlugin::getPluginDescriptor() const +{ + return m_pluginDescriptor; +} + +void DroneIDDemodPlugin::initPlugin(PluginAPI* pluginAPI) +{ + m_pluginAPI = pluginAPI; + + m_pluginAPI->registerRxChannel(DroneIDDemod::m_channelIdURI, DroneIDDemod::m_channelId, this); +} + +void DroneIDDemodPlugin::createRxChannel(DeviceAPI *deviceAPI, BasebandSampleSink **bs, ChannelAPI **cs) const +{ + if (bs || cs) + { + DroneIDDemod *instance = new DroneIDDemod(deviceAPI); + + if (bs) { + *bs = instance; + } + + if (cs) { + *cs = instance; + } + } +} + +#ifdef SERVER_MODE +ChannelGUI* DroneIDDemodPlugin::createRxChannelGUI( + DeviceUISet *deviceUISet, + BasebandSampleSink *rxChannel) const +{ + (void) deviceUISet; + (void) rxChannel; + return nullptr; +} +#else +ChannelGUI* DroneIDDemodPlugin::createRxChannelGUI(DeviceUISet *deviceUISet, BasebandSampleSink *rxChannel) const +{ + return DroneIDDemodGUI::create(m_pluginAPI, deviceUISet, rxChannel); +} +#endif + +ChannelWebAPIAdapter* DroneIDDemodPlugin::createChannelWebAPIAdapter() const +{ + return new DroneIDDemodWebAPIAdapter(); +} diff --git a/plugins/channelrx/demoddroneid/droneiddemodplugin.h b/plugins/channelrx/demoddroneid/droneiddemodplugin.h new file mode 100644 index 000000000..23c1b3d83 --- /dev/null +++ b/plugins/channelrx/demoddroneid/droneiddemodplugin.h @@ -0,0 +1,49 @@ +/////////////////////////////////////////////////////////////////////////////////// +// Copyright (C) 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 . // +/////////////////////////////////////////////////////////////////////////////////// + +#ifndef INCLUDE_DRONEIDDEMODPLUGIN_H +#define INCLUDE_DRONEIDDEMODPLUGIN_H + +#include +#include "plugin/plugininterface.h" + +class DeviceUISet; +class BasebandSampleSink; + +class DroneIDDemodPlugin : public QObject, PluginInterface { + Q_OBJECT + Q_INTERFACES(PluginInterface) + Q_PLUGIN_METADATA(IID "sdrangel.channel.droneiddemod") + +public: + explicit DroneIDDemodPlugin(QObject* parent = nullptr); + + const PluginDescriptor& getPluginDescriptor() const; + void initPlugin(PluginAPI* pluginAPI); + + virtual void createRxChannel(DeviceAPI *deviceAPI, BasebandSampleSink **bs, ChannelAPI **cs) const; + virtual ChannelGUI* createRxChannelGUI(DeviceUISet *deviceUISet, BasebandSampleSink *rxChannel) const; + virtual ChannelWebAPIAdapter* createChannelWebAPIAdapter() const; + +private: + static const PluginDescriptor m_pluginDescriptor; + + PluginAPI* m_pluginAPI; +}; + +#endif // INCLUDE_DRONEIDDEMODPLUGIN_H diff --git a/plugins/channelrx/demoddroneid/droneiddemodsettings.cpp b/plugins/channelrx/demoddroneid/droneiddemodsettings.cpp new file mode 100644 index 000000000..8335237ce --- /dev/null +++ b/plugins/channelrx/demoddroneid/droneiddemodsettings.cpp @@ -0,0 +1,417 @@ +/////////////////////////////////////////////////////////////////////////////////// +// Copyright (C) 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 . // +/////////////////////////////////////////////////////////////////////////////////// + +#include + +#include + +#include "util/simpleserializer.h" +#include "settings/serializable.h" +#include "droneiddemodsettings.h" + +const QList DroneIDDemodSettings::m_frequencies2_4GHz = { + 2399500000LL, 2414500000LL, 2429500000LL, 2444500000LL, 2459500000LL, 2474500000LL +}; + +const QList DroneIDDemodSettings::m_frequencies5_8GHz = { + 5721500000LL, 5731500000LL, 5741500000LL, 5756500000LL, 5761500000LL, 5771500000LL, + 5776500000LL, 5786500000LL, 5796500000LL, 5801500000LL, 5816500000LL, 5831500000LL +}; + +QList DroneIDDemodSettings::getScanFrequencies(ScanBand band) +{ + switch (band) + { + case BAND_2_4_GHZ: + return m_frequencies2_4GHz; + case BAND_5_8_GHZ: + return m_frequencies5_8GHz; + default: + return m_frequencies2_4GHz + m_frequencies5_8GHz; + } +} + +DroneIDDemodSettings::DroneIDDemodSettings() : + m_channelMarker(nullptr), + m_rollupState(nullptr) +{ + resetToDefaults(); +} + +void DroneIDDemodSettings::resetToDefaults() +{ + m_inputFrequencyOffset = 0; + m_detectionThreshold = 0.2f; + m_turboIterations = 8; + m_filterSerial = ""; + m_mapTimeout = 300; + m_mapAltitude = MAP_ALTITUDE; + m_scan = false; + m_scanBand = BAND_2_4_GHZ; + m_scanDwell = 1.5f; + m_scanHold = 3.0f; + m_udpEnabled = false; + m_udpAddress = "127.0.0.1"; + m_udpPort = 9999; + m_logFilename = "dji_droneid_log.csv"; + m_logEnabled = false; + m_useFileTime = false; + m_rgbColor = QColor(255, 128, 0).rgb(); + m_title = "DJI DroneID Demodulator"; + m_streamIndex = 0; + m_useReverseAPI = false; + m_reverseAPIAddress = "127.0.0.1"; + m_reverseAPIPort = 8888; + m_reverseAPIDeviceIndex = 0; + m_reverseAPIChannelIndex = 0; + m_workspaceIndex = 0; + m_hidden = false; + resetColumns(); +} + +void DroneIDDemodSettings::resetColumns() +{ + m_columnIndexes.clear(); + m_columnSizes.clear(); + + for (int i = 0; i < DRONEIDDEMOD_COLUMNS; i++) + { + m_columnIndexes.append(i); + m_columnSizes.append(-1); // Autosize + } +} + +QByteArray DroneIDDemodSettings::serialize() const +{ + SimpleSerializer s(1); + + s.writeS32(1, m_inputFrequencyOffset); + s.writeFloat(2, m_detectionThreshold); + s.writeS32(3, m_turboIterations); + s.writeString(4, m_filterSerial); + s.writeS32(5, m_mapTimeout); + s.writeBool(6, m_udpEnabled); + s.writeString(7, m_udpAddress); + s.writeU32(8, m_udpPort); + s.writeString(9, m_logFilename); + s.writeBool(10, m_logEnabled); + s.writeBool(11, m_useFileTime); + s.writeU32(12, m_rgbColor); + s.writeString(13, m_title); + + if (m_channelMarker) { + s.writeBlob(14, m_channelMarker->serialize()); + } + + s.writeS32(15, m_streamIndex); + s.writeBool(16, m_useReverseAPI); + s.writeString(17, m_reverseAPIAddress); + s.writeU32(18, m_reverseAPIPort); + s.writeU32(19, m_reverseAPIDeviceIndex); + s.writeU32(20, m_reverseAPIChannelIndex); + + if (m_rollupState) { + s.writeBlob(21, m_rollupState->serialize()); + } + + s.writeS32(22, m_workspaceIndex); + s.writeBlob(23, m_geometryBytes); + s.writeBool(24, m_hidden); + + s.writeList(25, m_columnIndexes); + s.writeList(26, m_columnSizes); + + s.writeBool(27, m_scan); + s.writeS32(28, (int) m_scanBand); + s.writeFloat(29, m_scanDwell); + s.writeFloat(30, m_scanHold); + s.writeS32(31, (int) m_mapAltitude); + + return s.final(); +} + +bool DroneIDDemodSettings::deserialize(const QByteArray& data) +{ + SimpleDeserializer d(data); + + if (!d.isValid()) + { + resetToDefaults(); + return false; + } + + if (d.getVersion() == 1) + { + QByteArray bytetmp; + uint32_t utmp; + int32_t itmp; + + d.readS32(1, &m_inputFrequencyOffset, 0); + d.readFloat(2, &m_detectionThreshold, 0.2f); + d.readS32(3, &m_turboIterations, 8); + d.readString(4, &m_filterSerial, ""); + d.readS32(5, &m_mapTimeout, 300); + d.readBool(6, &m_udpEnabled, false); + d.readString(7, &m_udpAddress, "127.0.0.1"); + d.readU32(8, &utmp); + + if ((utmp > 1023) && (utmp < 65535)) { + m_udpPort = utmp; + } else { + m_udpPort = 9999; + } + + d.readString(9, &m_logFilename, "dji_droneid_log.csv"); + d.readBool(10, &m_logEnabled, false); + d.readBool(11, &m_useFileTime, false); + d.readU32(12, &m_rgbColor, QColor(255, 128, 0).rgb()); + d.readString(13, &m_title, "DJI DroneID Demodulator"); + + if (m_channelMarker) + { + d.readBlob(14, &bytetmp); + m_channelMarker->deserialize(bytetmp); + } + + d.readS32(15, &m_streamIndex, 0); + d.readBool(16, &m_useReverseAPI, false); + d.readString(17, &m_reverseAPIAddress, "127.0.0.1"); + d.readU32(18, &utmp, 0); + + if ((utmp > 1023) && (utmp < 65535)) { + m_reverseAPIPort = utmp; + } else { + m_reverseAPIPort = 8888; + } + + d.readU32(19, &utmp, 0); + m_reverseAPIDeviceIndex = utmp > 99 ? 99 : utmp; + d.readU32(20, &utmp, 0); + m_reverseAPIChannelIndex = utmp > 99 ? 99 : utmp; + + if (m_rollupState) + { + d.readBlob(21, &bytetmp); + m_rollupState->deserialize(bytetmp); + } + + d.readS32(22, &m_workspaceIndex, 0); + d.readBlob(23, &m_geometryBytes); + d.readBool(24, &m_hidden, false); + + d.readList(25, &m_columnIndexes); + d.readList(26, &m_columnSizes); + + // GUI expects an entry for every column + if ((m_columnIndexes.size() != DRONEIDDEMOD_COLUMNS) || (m_columnSizes.size() != DRONEIDDEMOD_COLUMNS)) { + resetColumns(); + } + + d.readBool(27, &m_scan, false); + d.readS32(28, &itmp, (int) BAND_2_4_GHZ); + m_scanBand = (ScanBand) std::clamp(itmp, (int32_t) BAND_2_4_GHZ, (int32_t) BAND_2_4_AND_5_8_GHZ); + d.readFloat(29, &m_scanDwell, 1.5f); + d.readFloat(30, &m_scanHold, 3.0f); + d.readS32(31, &itmp, (int) MAP_ALTITUDE); + m_mapAltitude = (MapAltitude) std::clamp(itmp, (int32_t) MAP_ALTITUDE, (int32_t) MAP_HEIGHT); + + return true; + } + else + { + resetToDefaults(); + return false; + } +} + +void DroneIDDemodSettings::applySettings(const QStringList& settingsKeys, const DroneIDDemodSettings& settings) +{ + if (settingsKeys.contains("inputFrequencyOffset")) { + m_inputFrequencyOffset = settings.m_inputFrequencyOffset; + } + if (settingsKeys.contains("detectionThreshold")) { + m_detectionThreshold = settings.m_detectionThreshold; + } + if (settingsKeys.contains("turboIterations")) { + m_turboIterations = settings.m_turboIterations; + } + if (settingsKeys.contains("filterSerial")) { + m_filterSerial = settings.m_filterSerial; + } + if (settingsKeys.contains("mapTimeout")) { + m_mapTimeout = settings.m_mapTimeout; + } + if (settingsKeys.contains("mapAltitude")) { + m_mapAltitude = settings.m_mapAltitude; + } + if (settingsKeys.contains("scan")) { + m_scan = settings.m_scan; + } + if (settingsKeys.contains("scanBand")) { + m_scanBand = settings.m_scanBand; + } + if (settingsKeys.contains("scanDwell")) { + m_scanDwell = settings.m_scanDwell; + } + if (settingsKeys.contains("scanHold")) { + m_scanHold = settings.m_scanHold; + } + if (settingsKeys.contains("udpEnabled")) { + m_udpEnabled = settings.m_udpEnabled; + } + if (settingsKeys.contains("udpAddress")) { + m_udpAddress = settings.m_udpAddress; + } + if (settingsKeys.contains("udpPort")) { + m_udpPort = settings.m_udpPort; + } + if (settingsKeys.contains("logFilename")) { + m_logFilename = settings.m_logFilename; + } + if (settingsKeys.contains("logEnabled")) { + m_logEnabled = settings.m_logEnabled; + } + if (settingsKeys.contains("useFileTime")) { + m_useFileTime = settings.m_useFileTime; + } + if (settingsKeys.contains("rgbColor")) { + m_rgbColor = settings.m_rgbColor; + } + if (settingsKeys.contains("title")) { + m_title = settings.m_title; + } + if (settingsKeys.contains("streamIndex")) { + m_streamIndex = settings.m_streamIndex; + } + if (settingsKeys.contains("useReverseAPI")) { + m_useReverseAPI = settings.m_useReverseAPI; + } + if (settingsKeys.contains("reverseAPIAddress")) { + m_reverseAPIAddress = settings.m_reverseAPIAddress; + } + if (settingsKeys.contains("reverseAPIPort")) { + m_reverseAPIPort = settings.m_reverseAPIPort; + } + if (settingsKeys.contains("reverseAPIDeviceIndex")) { + m_reverseAPIDeviceIndex = settings.m_reverseAPIDeviceIndex; + } + if (settingsKeys.contains("reverseAPIChannelIndex")) { + m_reverseAPIChannelIndex = settings.m_reverseAPIChannelIndex; + } + if (settingsKeys.contains("workspaceIndex")) { + m_workspaceIndex = settings.m_workspaceIndex; + } + if (settingsKeys.contains("geometryBytes")) { + m_geometryBytes = settings.m_geometryBytes; + } + if (settingsKeys.contains("hidden")) { + m_hidden = settings.m_hidden; + } + if (settingsKeys.contains("columnIndexes")) { + m_columnIndexes = settings.m_columnIndexes; + } + if (settingsKeys.contains("columnSizes")) { + m_columnSizes = settings.m_columnSizes; + } +} + +QString DroneIDDemodSettings::getDebugString(const QStringList& settingsKeys, bool force) const +{ + std::ostringstream ostr; + + if (settingsKeys.contains("inputFrequencyOffset") || force) { + ostr << " m_inputFrequencyOffset: " << m_inputFrequencyOffset; + } + if (settingsKeys.contains("detectionThreshold") || force) { + ostr << " m_detectionThreshold: " << m_detectionThreshold; + } + if (settingsKeys.contains("turboIterations") || force) { + ostr << " m_turboIterations: " << m_turboIterations; + } + if (settingsKeys.contains("filterSerial") || force) { + ostr << " m_filterSerial: " << m_filterSerial.toStdString(); + } + if (settingsKeys.contains("mapTimeout") || force) { + ostr << " m_mapTimeout: " << m_mapTimeout; + } + if (settingsKeys.contains("mapAltitude") || force) { + ostr << " m_mapAltitude: " << m_mapAltitude; + } + if (settingsKeys.contains("scan") || force) { + ostr << " m_scan: " << m_scan; + } + if (settingsKeys.contains("scanBand") || force) { + ostr << " m_scanBand: " << m_scanBand; + } + if (settingsKeys.contains("scanDwell") || force) { + ostr << " m_scanDwell: " << m_scanDwell; + } + if (settingsKeys.contains("scanHold") || force) { + ostr << " m_scanHold: " << m_scanHold; + } + if (settingsKeys.contains("udpEnabled") || force) { + ostr << " m_udpEnabled: " << m_udpEnabled; + } + if (settingsKeys.contains("udpAddress") || force) { + ostr << " m_udpAddress: " << m_udpAddress.toStdString(); + } + if (settingsKeys.contains("udpPort") || force) { + ostr << " m_udpPort: " << m_udpPort; + } + if (settingsKeys.contains("logFilename") || force) { + ostr << " m_logFilename: " << m_logFilename.toStdString(); + } + if (settingsKeys.contains("logEnabled") || force) { + ostr << " m_logEnabled: " << m_logEnabled; + } + if (settingsKeys.contains("useFileTime") || force) { + ostr << " m_useFileTime: " << m_useFileTime; + } + if (settingsKeys.contains("rgbColor") || force) { + ostr << " m_rgbColor: " << m_rgbColor; + } + if (settingsKeys.contains("title") || force) { + ostr << " m_title: " << m_title.toStdString(); + } + if (settingsKeys.contains("streamIndex") || force) { + ostr << " m_streamIndex: " << m_streamIndex; + } + if (settingsKeys.contains("useReverseAPI") || force) { + ostr << " m_useReverseAPI: " << m_useReverseAPI; + } + if (settingsKeys.contains("reverseAPIAddress") || force) { + ostr << " m_reverseAPIAddress: " << m_reverseAPIAddress.toStdString(); + } + if (settingsKeys.contains("reverseAPIPort") || force) { + ostr << " m_reverseAPIPort: " << m_reverseAPIPort; + } + if (settingsKeys.contains("reverseAPIDeviceIndex") || force) { + ostr << " m_reverseAPIDeviceIndex: " << m_reverseAPIDeviceIndex; + } + if (settingsKeys.contains("reverseAPIChannelIndex") || force) { + ostr << " m_reverseAPIChannelIndex: " << m_reverseAPIChannelIndex; + } + if (settingsKeys.contains("workspaceIndex") || force) { + ostr << " m_workspaceIndex: " << m_workspaceIndex; + } + if (settingsKeys.contains("hidden") || force) { + ostr << " m_hidden: " << m_hidden; + } + + return QString(ostr.str().c_str()); +} diff --git a/plugins/channelrx/demoddroneid/droneiddemodsettings.h b/plugins/channelrx/demoddroneid/droneiddemodsettings.h new file mode 100644 index 000000000..02b076fa3 --- /dev/null +++ b/plugins/channelrx/demoddroneid/droneiddemodsettings.h @@ -0,0 +1,100 @@ +/////////////////////////////////////////////////////////////////////////////////// +// Copyright (C) 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 . // +/////////////////////////////////////////////////////////////////////////////////// + +#ifndef INCLUDE_DRONEIDDEMODSETTINGS_H +#define INCLUDE_DRONEIDDEMODSETTINGS_H + +#include +#include +#include + +#include "dsp/dsptypes.h" + +class Serializable; + +// Number of columns in the table +#define DRONEIDDEMOD_COLUMNS 24 + +struct DroneIDDemodSettings +{ + enum ScanBand { + BAND_2_4_GHZ, + BAND_5_8_GHZ, + BAND_2_4_AND_5_8_GHZ + }; + + enum MapAltitude { + MAP_ALTITUDE, //!< Altitude above WGS84 ellipsoid + MAP_HEIGHT //!< Height above take-off point, displayed relative to ground + }; + + qint32 m_inputFrequencyOffset; + Real m_detectionThreshold; //!< Normalised cyclic prefix correlation threshold for burst detection + int m_turboIterations; //!< Maximum turbo decoder iterations + QString m_filterSerial; //!< Regular expression to filter serial numbers in table + int m_mapTimeout; //!< Seconds without a message before drone is removed from Map (0 to never remove) + MapAltitude m_mapAltitude; //!< Which of the drone's altitude or height is used for its position on the Map + bool m_scan; //!< Step device center frequency through DroneID channels, until a burst is detected + ScanBand m_scanBand; //!< Which channels to scan + float m_scanDwell; //!< Seconds to wait on each channel for a burst + float m_scanHold; //!< Seconds to remain on a channel after the last burst was detected + bool m_udpEnabled; + QString m_udpAddress; + uint16_t m_udpPort; + + QString m_logFilename; + bool m_logEnabled; + bool m_useFileTime; + + quint32 m_rgbColor; + QString m_title; + Serializable *m_channelMarker; + 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_rollupState; + int m_workspaceIndex; + QByteArray m_geometryBytes; + bool m_hidden; + + QList m_columnIndexes; //!< How the columns are ordered in the table + QList m_columnSizes; //!< Size of the columns in the table + + static constexpr int DRONEIDDEMOD_CHANNEL_SAMPLE_RATE = 15360000; //!< 1024 point FFT with 15kHz subcarrier spacing + static const QList m_frequencies2_4GHz; //!< DroneID center frequencies in Hz + static const QList m_frequencies5_8GHz; + + static QList getScanFrequencies(ScanBand band); + + DroneIDDemodSettings(); + void resetToDefaults(); + void setChannelMarker(Serializable *channelMarker) { m_channelMarker = channelMarker; } + void setRollupState(Serializable *rollupState) { m_rollupState = rollupState; } + QByteArray serialize() const; + bool deserialize(const QByteArray& data); + void applySettings(const QStringList& settingsKeys, const DroneIDDemodSettings& settings); + QString getDebugString(const QStringList& settingsKeys, bool force=false) const; + +private: + void resetColumns(); +}; + +#endif /* INCLUDE_DRONEIDDEMODSETTINGS_H */ diff --git a/plugins/channelrx/demoddroneid/droneiddemodsink.cpp b/plugins/channelrx/demoddroneid/droneiddemodsink.cpp new file mode 100644 index 000000000..989dda90b --- /dev/null +++ b/plugins/channelrx/demoddroneid/droneiddemodsink.cpp @@ -0,0 +1,198 @@ +/////////////////////////////////////////////////////////////////////////////////// +// Copyright (C) 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 . // +/////////////////////////////////////////////////////////////////////////////////// + +#include + +#include + +#include "device/deviceapi.h" +#include "channel/channelwebapiutils.h" + +#include "droneiddemod.h" +#include "droneiddemodsink.h" +#include "droneiddemodworker.h" + +DroneIDDemodSink::DroneIDDemodSink(DroneIDDemod *droneIDDemod) : + m_droneIDDemod(droneIDDemod), + m_channel(nullptr), + m_worker(nullptr), + m_channelSampleRate(DroneIDDemodSettings::DRONEIDDEMOD_CHANNEL_SAMPLE_RATE), + m_channelFrequencyOffset(0), + m_centerFrequency(0), + m_interpolatorDistance(1.0f), + m_interpolatorDistanceRemain(1.0f), + m_resample(false), + m_magsq(0.0), + m_magsqSum(0.0), + m_magsqPeak(0.0), + m_magsqCount(0), + m_burstsDetected(0), + m_burstsDropped(0) +{ + applySettings(QStringList(), m_settings, true); + applyChannelSettings(m_channelSampleRate, m_channelFrequencyOffset, true); +} + +DroneIDDemodSink::~DroneIDDemodSink() +{ +} + +void DroneIDDemodSink::feed(const SampleVector::const_iterator& begin, const SampleVector::const_iterator& end) +{ + Complex ci; + const bool shift = m_channelFrequencyOffset != 0; + const Real scale = 1.0f / SDR_RX_SCALEF; + + for (SampleVector::const_iterator it = begin; it != end; ++it) + { + Complex c(it->real() * scale, it->imag() * scale); + + if (shift) { + c *= m_nco.nextIQ(); + } + + if (!m_resample) + { + processOneSample(c); + } + else if (m_interpolatorDistance < 1.0f) // interpolate + { + while (!m_interpolator.interpolate(&m_interpolatorDistanceRemain, c, &ci)) + { + processOneSample(ci); + m_interpolatorDistanceRemain += m_interpolatorDistance; + } + } + else // decimate + { + if (m_interpolator.decimate(&m_interpolatorDistanceRemain, c, &ci)) + { + processOneSample(ci); + m_interpolatorDistanceRemain += m_interpolatorDistance; + } + } + } +} + +void DroneIDDemodSink::processOneSample(Complex &ci) +{ + // Calculate average and peak levels for level meter + Real magsq = std::norm(ci); + m_magsqSum += magsq; + if (magsq > m_magsqPeak) { + m_magsqPeak = magsq; + } + m_magsqCount++; + + if (m_detector.process(ci)) + { + m_burstsDetected++; + + if (m_worker) + { + // Count rather than log when dropped, as this can happen at a high rate + if (m_worker->isQueueFull()) { + m_burstsDropped++; + } else { + // Record frequency now, as device may be retuned (E.g. by scanning) before burst is decoded + m_worker->queueBurst(m_detector.getBurst(), burstDateTime(), m_centerFrequency + m_settings.m_inputFrequencyOffset); + } + } + } +} + +QDateTime DroneIDDemodSink::burstDateTime() +{ + QDateTime dateTime = QDateTime::currentDateTime(); + + if (m_settings.m_useFileTime) + { + QString hardwareId = m_droneIDDemod->getDeviceAPI()->getHardwareId(); + + if ((hardwareId == "FileInput") || (hardwareId == "SigMFFileInput")) + { + QString dateTimeStr; + int deviceIdx = m_droneIDDemod->getDeviceSetIndex(); + + if (ChannelWebAPIUtils::getDeviceReportValue(deviceIdx, "absoluteTime", dateTimeStr)) { + dateTime = QDateTime::fromString(dateTimeStr, Qt::ISODateWithMs); + } + } + } + + return dateTime; +} + +void DroneIDDemodSink::reset() +{ + m_detector.reset(); + m_interpolatorDistanceRemain = m_interpolatorDistance; +} + +void DroneIDDemodSink::applyChannelSettings(int channelSampleRate, int channelFrequencyOffset, bool force) +{ + qDebug() << "DroneIDDemodSink::applyChannelSettings:" + << " channelSampleRate: " << channelSampleRate + << " channelFrequencyOffset: " << channelFrequencyOffset; + + if ((m_channelFrequencyOffset != channelFrequencyOffset) || + (m_channelSampleRate != channelSampleRate) || force) + { + m_nco.setFreq(-channelFrequencyOffset, channelSampleRate); + } + + if ((m_channelSampleRate != channelSampleRate) || force) + { + // Sample rate is 0 until device sample rate is known + m_resample = (channelSampleRate > 0) && (channelSampleRate != DroneIDDemodSettings::DRONEIDDEMOD_CHANNEL_SAMPLE_RATE); + + if (m_resample) + { + double taps = std::max(m_interpolatorMinTaps, m_interpolatorTapsPerSampleRate * channelSampleRate); + m_interpolator.create(m_interpolatorPhaseSteps, channelSampleRate, m_interpolatorCutoff, taps / m_interpolatorPhaseSteps); + m_interpolatorDistance = (Real) channelSampleRate / (Real) DroneIDDemodSettings::DRONEIDDEMOD_CHANNEL_SAMPLE_RATE; + m_interpolatorDistanceRemain = m_interpolatorDistance; + } + + if ((channelSampleRate > 0) && (channelSampleRate < DroneIDDemodSettings::DRONEIDDEMOD_CHANNEL_SAMPLE_RATE)) { + qWarning() << "DroneIDDemodSink::applyChannelSettings: Channel sample rate" << channelSampleRate << "is too low to receive DroneID"; + } + + m_detector.reset(); + } + + m_channelSampleRate = channelSampleRate; + m_channelFrequencyOffset = channelFrequencyOffset; +} + +void DroneIDDemodSink::applySettings(const QStringList& settingsKeys, const DroneIDDemodSettings& settings, bool force) +{ + qDebug() << "DroneIDDemodSink::applySettings:" + << settings.getDebugString(settingsKeys, force) + << " force: " << force; + + if (settingsKeys.contains("detectionThreshold") || force) { + m_detector.setThreshold(settings.m_detectionThreshold); + } + + if (force) { + m_settings = settings; + } else { + m_settings.applySettings(settingsKeys, settings); + } +} diff --git a/plugins/channelrx/demoddroneid/droneiddemodsink.h b/plugins/channelrx/demoddroneid/droneiddemodsink.h new file mode 100644 index 000000000..d9db93b3a --- /dev/null +++ b/plugins/channelrx/demoddroneid/droneiddemodsink.h @@ -0,0 +1,120 @@ +/////////////////////////////////////////////////////////////////////////////////// +// Copyright (C) 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 . // +/////////////////////////////////////////////////////////////////////////////////// + +#ifndef INCLUDE_DRONEIDDEMODSINK_H +#define INCLUDE_DRONEIDDEMODSINK_H + +#include + +#include "dsp/channelsamplesink.h" +#include "dsp/nco.h" +#include "dsp/interpolator.h" + +#include "droneiddemodsettings.h" +#include "droneiddetector.h" + +class ChannelAPI; +class DroneIDDemod; +class DroneIDDemodWorker; + +class DroneIDDemodSink : public ChannelSampleSink { +public: + DroneIDDemodSink(DroneIDDemod *droneIDDemod); + ~DroneIDDemodSink(); + + virtual void feed(const SampleVector::const_iterator& begin, const SampleVector::const_iterator& end); + + void applyChannelSettings(int channelSampleRate, int channelFrequencyOffset, bool force = false); + void applySettings(const QStringList& settingsKeys, const DroneIDDemodSettings& settings, bool force = false); + void setWorker(DroneIDDemodWorker *worker) { m_worker = worker; } + void reset(); //!< Clear detector state, when restarting + void setChannel(ChannelAPI *channel) { m_channel = channel; } + void setCenterFrequency(qint64 centerFrequency) { m_centerFrequency = centerFrequency; } //!< Device center frequency + + double getMagSq() const { return m_magsq; } + + void getMagSqLevels(double& avg, double& peak, int& nbSamples) + { + if (m_magsqCount > 0) + { + m_magsq = m_magsqSum / m_magsqCount; + m_magSqLevelStore.m_magsq = m_magsq; + m_magSqLevelStore.m_magsqPeak = m_magsqPeak; + } + + avg = m_magSqLevelStore.m_magsq; + peak = m_magSqLevelStore.m_magsqPeak; + nbSamples = m_magsqCount == 0 ? 1 : m_magsqCount; + + m_magsqSum = 0.0f; + m_magsqPeak = 0.0f; + m_magsqCount = 0; + } + + // Number of bursts detected, and dropped because decoder couldn't keep up + int getBurstsDetected() const { return m_burstsDetected; } + int getBurstsDropped() const { return m_burstsDropped; } + +private: + struct MagSqLevelsStore + { + MagSqLevelsStore() : + m_magsq(1e-12), + m_magsqPeak(1e-12) + {} + double m_magsq; + double m_magsqPeak; + }; + + // Signal occupies +/-4.5MHz. When resampling from a channel rate of less than 2*15.36MS/s, only + // frequencies above 15.36-4.5MHz alias on to the signal, so a short filter with a wide transition + // band can be used. Length is scaled with sample rate to keep transition width constant. + static constexpr Real m_interpolatorCutoff = 5.5e6f; + static constexpr int m_interpolatorPhaseSteps = 16; + static constexpr double m_interpolatorTapsPerSampleRate = 24.0 / 20.0e6; // 24 taps at 20MS/s + static constexpr double m_interpolatorMinTaps = 8.0; + + DroneIDDemod *m_droneIDDemod; + DroneIDDemodSettings m_settings; + ChannelAPI *m_channel; + DroneIDDemodWorker *m_worker; + int m_channelSampleRate; + int m_channelFrequencyOffset; + qint64 m_centerFrequency; + + NCO m_nco; + Interpolator m_interpolator; + Real m_interpolatorDistance; + Real m_interpolatorDistanceRemain; + bool m_resample; + + double m_magsq; + double m_magsqSum; + double m_magsqPeak; + int m_magsqCount; + MagSqLevelsStore m_magSqLevelStore; + + DroneIDDetector m_detector; + std::atomic m_burstsDetected; + std::atomic m_burstsDropped; + + void processOneSample(Complex &ci); + QDateTime burstDateTime(); +}; + +#endif // INCLUDE_DRONEIDDEMODSINK_H diff --git a/plugins/channelrx/demoddroneid/droneiddemodwebapiadapter.cpp b/plugins/channelrx/demoddroneid/droneiddemodwebapiadapter.cpp new file mode 100644 index 000000000..40d71c250 --- /dev/null +++ b/plugins/channelrx/demoddroneid/droneiddemodwebapiadapter.cpp @@ -0,0 +1,54 @@ +/////////////////////////////////////////////////////////////////////////////////// +// Copyright (C) 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 . // +/////////////////////////////////////////////////////////////////////////////////// + +#include "SWGChannelSettings.h" +#include "droneiddemod.h" +#include "droneiddemodwebapiadapter.h" + +DroneIDDemodWebAPIAdapter::DroneIDDemodWebAPIAdapter() +{ +} + +DroneIDDemodWebAPIAdapter::~DroneIDDemodWebAPIAdapter() +{ +} + +int DroneIDDemodWebAPIAdapter::webapiSettingsGet( + SWGSDRangel::SWGChannelSettings& response, + QString& errorMessage) +{ + (void) errorMessage; + response.setDroneIdDemodSettings(new SWGSDRangel::SWGDroneIDDemodSettings()); + response.getDroneIdDemodSettings()->init(); + DroneIDDemod::webapiFormatChannelSettings(response, m_settings); + + return 200; +} + +int DroneIDDemodWebAPIAdapter::webapiSettingsPutPatch( + bool force, + const QStringList& channelSettingsKeys, + SWGSDRangel::SWGChannelSettings& response, + QString& errorMessage) +{ + (void) force; + (void) errorMessage; + DroneIDDemod::webapiUpdateChannelSettings(m_settings, channelSettingsKeys, response); + + return 200; +} diff --git a/plugins/channelrx/demoddroneid/droneiddemodwebapiadapter.h b/plugins/channelrx/demoddroneid/droneiddemodwebapiadapter.h new file mode 100644 index 000000000..db83413b0 --- /dev/null +++ b/plugins/channelrx/demoddroneid/droneiddemodwebapiadapter.h @@ -0,0 +1,50 @@ +/////////////////////////////////////////////////////////////////////////////////// +// Copyright (C) 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 . // +/////////////////////////////////////////////////////////////////////////////////// + +#ifndef INCLUDE_DRONEIDDEMOD_WEBAPIADAPTER_H +#define INCLUDE_DRONEIDDEMOD_WEBAPIADAPTER_H + +#include "channel/channelwebapiadapter.h" +#include "droneiddemodsettings.h" + +/** + * Standalone API adapter only for the settings + */ +class DroneIDDemodWebAPIAdapter : public ChannelWebAPIAdapter { +public: + DroneIDDemodWebAPIAdapter(); + virtual ~DroneIDDemodWebAPIAdapter(); + + virtual QByteArray serialize() const { return m_settings.serialize(); } + virtual bool deserialize(const QByteArray& data) { return m_settings.deserialize(data); } + + virtual int webapiSettingsGet( + SWGSDRangel::SWGChannelSettings& response, + QString& errorMessage); + + virtual int webapiSettingsPutPatch( + bool force, + const QStringList& channelSettingsKeys, + SWGSDRangel::SWGChannelSettings& response, + QString& errorMessage); + +private: + DroneIDDemodSettings m_settings; +}; + +#endif // INCLUDE_DRONEIDDEMOD_WEBAPIADAPTER_H diff --git a/plugins/channelrx/demoddroneid/droneiddemodworker.cpp b/plugins/channelrx/demoddroneid/droneiddemodworker.cpp new file mode 100644 index 000000000..71c4c64ee --- /dev/null +++ b/plugins/channelrx/demoddroneid/droneiddemodworker.cpp @@ -0,0 +1,98 @@ +/////////////////////////////////////////////////////////////////////////////////// +// Copyright (C) 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 . // +/////////////////////////////////////////////////////////////////////////////////// + +#include + +#include "dsp/dspengine.h" +#include "util/droneid.h" + +#include "droneiddemod.h" +#include "droneiddemodworker.h" + +MESSAGE_CLASS_DEFINITION(DroneIDDemodWorker::MsgBurst, Message) + +DroneIDDemodWorker::DroneIDDemodWorker() : + m_messageQueueToChannel(nullptr), + m_decoder(DSPEngine::instance()->getFFTFactory()), + m_maxIterations(8), + m_queuedBursts(0) +{ + connect(&m_inputMessageQueue, &MessageQueue::messageEnqueued, this, &DroneIDDemodWorker::handleInputMessages); +} + +DroneIDDemodWorker::~DroneIDDemodWorker() +{ + m_inputMessageQueue.clear(); +} + +void DroneIDDemodWorker::queueBurst(const std::vector>& samples, QDateTime dateTime, qint64 frequency) +{ + m_queuedBursts++; + m_inputMessageQueue.push(MsgBurst::create(samples, dateTime, frequency)); +} + +void DroneIDDemodWorker::handleInputMessages() +{ + Message* message; + + while ((message = m_inputMessageQueue.pop()) != nullptr) + { + if (MsgBurst::match(*message)) + { + decodeBurst(*(MsgBurst *) message); + m_queuedBursts--; + } + delete message; + } +} + +void DroneIDDemodWorker::decodeBurst(const MsgBurst& burst) +{ + DroneIDDecoder::Result result; + const std::vector>& samples = burst.getSamples(); + + m_decoder.setMaxIterations(m_maxIterations); + bool detected = m_decoder.decode(samples.data(), (int) samples.size(), result); + + QByteArray message; + if (detected && result.m_crcValid) + { + QByteArray data((const char *) result.m_payload.data(), (int) result.m_payload.size()); + int length = DroneIDMessage::messageLength(data); + // Strip zero padding + message = length > 0 ? data.left(length) : data; + } + + if (m_messageQueueToChannel) + { + DroneIDDemod::MsgBurstResult *msg = DroneIDDemod::MsgBurstResult::create( + detected, + result.m_crcValid, + message, + burst.getDateTime(), + result.m_snr, + result.m_cfo, + result.m_evm, + result.m_zcMetric, + result.m_iterations, + result.m_legacy, + burst.getFrequency() + ); + m_messageQueueToChannel->push(msg); + } +} diff --git a/plugins/channelrx/demoddroneid/droneiddemodworker.h b/plugins/channelrx/demoddroneid/droneiddemodworker.h new file mode 100644 index 000000000..c66ed7300 --- /dev/null +++ b/plugins/channelrx/demoddroneid/droneiddemodworker.h @@ -0,0 +1,92 @@ +/////////////////////////////////////////////////////////////////////////////////// +// Copyright (C) 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 . // +/////////////////////////////////////////////////////////////////////////////////// + +#ifndef INCLUDE_DRONEIDDEMODWORKER_H +#define INCLUDE_DRONEIDDEMODWORKER_H + +#include +#include +#include + +#include +#include + +#include "util/message.h" +#include "util/messagequeue.h" + +#include "droneiddecoder.h" + +// Decodes bursts found by the detector in the sink. Runs in its own thread, as decoding a +// burst takes much longer than the time between samples. +class DroneIDDemodWorker : public QObject +{ + Q_OBJECT +public: + class MsgBurst : public Message { + MESSAGE_CLASS_DECLARATION + + public: + const std::vector>& getSamples() const { return m_samples; } + QDateTime getDateTime() const { return m_dateTime; } + qint64 getFrequency() const { return m_frequency; } + + static MsgBurst* create(const std::vector>& samples, QDateTime dateTime, qint64 frequency) { + return new MsgBurst(samples, dateTime, frequency); + } + + private: + std::vector> m_samples; + QDateTime m_dateTime; + qint64 m_frequency; + + MsgBurst(const std::vector>& samples, QDateTime dateTime, qint64 frequency) : + Message(), + m_samples(samples), + m_dateTime(dateTime), + m_frequency(frequency) + { } + }; + + DroneIDDemodWorker(); + ~DroneIDDemodWorker(); + + MessageQueue *getInputMessageQueue() { return &m_inputMessageQueue; } + void setMessageQueueToChannel(MessageQueue *messageQueue) { m_messageQueueToChannel = messageQueue; } + void setMaxIterations(int iterations) { m_maxIterations = iterations; } + + // Whether the decoder is busy, so further bursts should be dropped + bool isQueueFull() const { return m_queuedBursts >= m_maxQueuedBursts; } + // Queue a burst for decoding. The caller (the single producer) should check isQueueFull() first. + void queueBurst(const std::vector>& samples, QDateTime dateTime, qint64 frequency); + + static constexpr int m_maxQueuedBursts = 4; + +private: + MessageQueue m_inputMessageQueue; + MessageQueue *m_messageQueueToChannel; + DroneIDDecoder m_decoder; + std::atomic m_maxIterations; + std::atomic m_queuedBursts; + + void decodeBurst(const MsgBurst& burst); + +private slots: + void handleInputMessages(); +}; + +#endif // INCLUDE_DRONEIDDEMODWORKER_H diff --git a/plugins/channelrx/demoddroneid/droneiddetector.cpp b/plugins/channelrx/demoddroneid/droneiddetector.cpp new file mode 100644 index 000000000..57e4c6188 --- /dev/null +++ b/plugins/channelrx/demoddroneid/droneiddetector.cpp @@ -0,0 +1,231 @@ +/////////////////////////////////////////////////////////////////////////////////// +// Copyright (C) 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 . // +/////////////////////////////////////////////////////////////////////////////////// + +#include +#include + +#include "droneiddecoder.h" +#include "droneiddetector.h" + +DroneIDDetector::DroneIDDetector() : + m_threshold(0.20f), + m_x(m_historySize), + m_c(m_productSize), + m_c2(m_productSize), + m_e(m_productSize), + m_p(m_corrSize), + m_p2(m_corrSize), + m_r(m_corrSize), + m_rr(m_corrSize) +{ + std::vector starts; + DroneIDDecoder::symbolStarts(starts); + const int last = DroneIDDecoder::m_nbSymbols - 1; + for (int k = 0; k < DroneIDDecoder::m_nbSymbols; k++) + { + m_offsets[k] = (starts[last] + DroneIDDecoder::m_cpLengths[last]) + - (starts[k] + DroneIDDecoder::m_cpLengths[k]); + } + reset(); +} + +void DroneIDDetector::reset() +{ + std::fill(m_x.begin(), m_x.end(), cf(0.0f, 0.0f)); + std::fill(m_c.begin(), m_c.end(), cf(0.0f, 0.0f)); + std::fill(m_c2.begin(), m_c2.end(), cf(0.0f, 0.0f)); + std::fill(m_e.begin(), m_e.end(), 0.0f); + std::fill(m_p.begin(), m_p.end(), cf(0.0f, 0.0f)); + std::fill(m_p2.begin(), m_p2.end(), cf(0.0f, 0.0f)); + std::fill(m_r.begin(), m_r.end(), 0.0f); + std::fill(m_rr.begin(), m_rr.end(), 0.0f); + m_pSum = 0.0; + m_p2Sum = 0.0; + m_rSum = 0.0; + m_n = 0; + m_state = Searching; + m_peakMetric = 0.0f; + m_peakScore = 0.0f; + m_peakIndex = 0; + m_searchStart = 0; + m_captureEnd = 0; + m_holdoffEnd = 0; + m_burstMetric = 0.0f; + m_burstIndex = 0; +} + +// Recalculate running sums from stored products, to prevent accumulation of rounding errors +void DroneIDDetector::recalculate() +{ + m_pSum = 0.0; + m_p2Sum = 0.0; + m_rSum = 0.0; + for (int i = 0; i < m_window; i++) + { + int64_t n = m_n - i; + m_pSum += (std::complex) m_c[n & m_productMask]; + m_p2Sum += (std::complex) m_c2[n & m_productMask]; + m_rSum += m_e[n & m_productMask]; + } +} + +// Frame correlation for frame whose last symbol's CP correlation ends at sample n. +// Returns normalised metric, and sets score to the unnormalised value. +// If gate is true, returns 0 as soon as the metric is known to be below the threshold, +// to save computation while searching. +float DroneIDDetector::metric(int64_t n, float& score, bool gate) const +{ + cf f = 0.0f; + float e = 0.0f; + + for (int k = 0; k < DroneIDDecoder::m_nbSymbols; k++) + { + int i = (int) ((n - m_offsets[k]) & m_corrMask); + f += m_p[i]; + e += m_rr[i]; + } + + // The metric can not exceed |f|/e, so skip the square roots when below the threshold + float te = m_threshold * e; + if (gate && (std::norm(f) <= te * te)) + { + score = 0.0f; + return 0.0f; + } + + cf f2 = 0.0f; + for (int k = 0; k < DroneIDDecoder::m_nbSymbols; k++) { + f2 += m_p2[(n - m_offsets[k]) & m_corrMask]; + } + score = std::abs(f) - std::abs(f2); + if (e <= 0.0f) { + return 0.0f; + } + return score / e; +} + +bool DroneIDDetector::process(cf x) +{ + m_n++; + const int64_t n = m_n; + + m_x[n & m_historyMask] = x; + + // Products of this sample with earlier samples. These are stored, so they don't need to be + // recalculated when they leave the window, and exactly what was added is subtracted + const cf xl = m_x[(n - m_lag) & m_historyMask]; + const cf xl2 = m_x[(n - m_lag2) & m_historyMask]; + const cf c(x.real() * xl.real() + x.imag() * xl.imag(), x.imag() * xl.real() - x.real() * xl.imag()); + const cf c2(x.real() * xl2.real() + x.imag() * xl2.imag(), x.imag() * xl2.real() - x.real() * xl2.imag()); + const float e = x.real() * x.real() + x.imag() * x.imag(); + const int pi = (int) (n & m_productMask); + const int po = (int) ((n - m_window) & m_productMask); + + // Update windowed correlations and energy + m_pSum += std::complex((double) c.real() - (double) m_c[po].real(), (double) c.imag() - (double) m_c[po].imag()); + m_p2Sum += std::complex((double) c2.real() - (double) m_c2[po].real(), (double) c2.imag() - (double) m_c2[po].imag()); + m_rSum += (double) e - (double) m_e[po]; + m_c[pi] = c; + m_c2[pi] = c2; + m_e[pi] = e; + + if ((n & (m_recalcInterval - 1)) == 0) { + recalculate(); + } + + const int ci = (int) (n & m_corrMask); + const float r = (float) std::max(m_rSum, 0.0); + m_p[ci] = cf((float) m_pSum.real(), (float) m_pSum.imag()); + m_p2[ci] = cf((float) m_p2Sum.real(), (float) m_p2Sum.imag()); + m_r[ci] = r; + m_rr[ci] = 0.5f * (r + m_r[(n - m_lag) & m_corrMask]); + + // Wait until there's enough history for a frame + if (n < DroneIDDecoder::m_frameLength + m_lag + m_window) { + return false; + } + + // Frame start, if last symbol's correlation peak is at n + const int lastPeakOffset = m_offsets[0] + DroneIDDecoder::m_cpLengths[0] + m_lag - 1; + + switch (m_state) + { + case Searching: + { + if ((n < m_holdoffEnd) || ((n % m_searchStride) != 0)) { + break; + } + float score; + float m = metric(n, score, true); + if (m > m_threshold) + { + m_peakMetric = m; + m_peakScore = score; + m_peakIndex = n; + m_searchStart = n; + m_state = FindingPeak; + } + break; + } + case FindingPeak: + { + float score; + float m = metric(n, score, false); + if ((m > m_threshold) && (score > m_peakScore)) + { + m_peakMetric = m; + m_peakScore = score; + m_peakIndex = n; + } + if (n - m_searchStart >= m_peakSearchLength) + { + int64_t frameStart = m_peakIndex - lastPeakOffset; + m_captureEnd = frameStart + DroneIDDecoder::m_frameLength + m_margin; + m_state = Capturing; + } + else + { + break; + } + } + [[fallthrough]]; + case Capturing: + { + if (n >= m_captureEnd) + { + int64_t frameStart = m_peakIndex - lastPeakOffset; + int64_t start = frameStart - m_margin; + int length = (int) (m_captureEnd - start + 1); + + m_burst.resize(length); + for (int i = 0; i < length; i++) { + m_burst[i] = m_x[(start + i) & m_historyMask]; + } + m_burstMetric = m_peakMetric; + m_burstIndex = start; + // Partial alignments with the end of this frame give high metrics for another frame's duration + m_holdoffEnd = m_peakIndex + DroneIDDecoder::m_frameLength; + m_state = Searching; + return true; + } + break; + } + } + + return false; +} diff --git a/plugins/channelrx/demoddroneid/droneiddetector.h b/plugins/channelrx/demoddroneid/droneiddetector.h new file mode 100644 index 000000000..a2e78ad64 --- /dev/null +++ b/plugins/channelrx/demoddroneid/droneiddetector.h @@ -0,0 +1,110 @@ +/////////////////////////////////////////////////////////////////////////////////// +// Copyright (C) 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 . // +/////////////////////////////////////////////////////////////////////////////////// + +#ifndef INCLUDE_DRONEIDDETECTOR_H +#define INCLUDE_DRONEIDDETECTOR_H + +#include +#include +#include + +#include "droneiddecoder.h" + +// Streaming detector for DroneID bursts at 15.36 MS/s. +// +// Correlates each sample window with the window one FFT length earlier (as the cyclic prefix +// is a copy of the end of each symbol), and sums this over the 9 symbol positions of a frame. +// The same sum with a lag of half an FFT is subtracted, so continuous tones, which correlate +// at all lags, are rejected. When a frame is detected, a window of samples around it is +// made available for the decoder. +class DroneIDDetector +{ +public: + typedef std::complex cf; + + // Samples either side of frame in burst window. Allows for the detector's timing being a + // couple of symbols out at low SNR, which the decoder can correct. + static constexpr int m_margin = 3300; + + DroneIDDetector(); + + void setThreshold(float threshold) { m_threshold = threshold; } + void reset(); + + // Process one sample. Returns true when a burst window is ready. + bool process(cf x); + + const std::vector& getBurst() const { return m_burst; } + float getBurstMetric() const { return m_burstMetric; } + // Sample number (count of samples processed) of first sample in burst window + int64_t getBurstSampleIndex() const { return m_burstIndex; } + +private: + static constexpr int m_historySize = 32768; // Samples, for burst capture + static constexpr int m_historyMask = m_historySize - 1; + static constexpr int m_corrSize = 16384; // Correlations, for frame metric + static constexpr int m_corrMask = m_corrSize - 1; + static constexpr int m_productSize = 128; // Products, for windowed sums + static constexpr int m_productMask = m_productSize - 1; + static constexpr int m_window = 72; + static constexpr int m_lag = 1024; + static constexpr int m_lag2 = 512; + static constexpr int m_recalcInterval = 4096; + static constexpr int m_searchStride = 4; // Correlation peak is ~2 CPs wide, so needn't check every sample when searching + // The normalised metric is also high when the frame is offset by a whole number of symbols + // from the template, as most of the cyclic prefixes still align. So after the threshold is + // first crossed, we search for the peak of the unnormalised score for a frame's duration, + // which is greatest when all symbols align. + static constexpr int m_peakSearchLength = DroneIDDecoder::m_frameLength; + + float m_threshold; + std::vector m_x; // Sample history + std::vector m_c; // Product of sample with that m_lag earlier + std::vector m_c2; // Product of sample with that m_lag2 earlier + std::vector m_e; // Sample energy + std::vector m_p; // Windowed correlation at lag m_lag + std::vector m_p2; // Windowed correlation at lag m_lag2 + std::vector m_r; // Windowed energy + std::vector m_rr; // Average of windowed energy and that m_lag earlier + std::complex m_pSum; + std::complex m_p2Sum; + double m_rSum; + int64_t m_n; // Number of samples processed + int m_offsets[9]; // Offset from last symbol's correlation peak to each symbol's + + enum State { + Searching, + FindingPeak, + Capturing + } m_state; + float m_peakMetric; + float m_peakScore; + int64_t m_peakIndex; + int64_t m_searchStart; + int64_t m_captureEnd; + int64_t m_holdoffEnd; + + std::vector m_burst; + float m_burstMetric; + int64_t m_burstIndex; + + float metric(int64_t n, float& score, bool gate) const; + void recalculate(); +}; + +#endif // INCLUDE_DRONEIDDETECTOR_H diff --git a/plugins/channelrx/demoddroneid/map/drone.png b/plugins/channelrx/demoddroneid/map/drone.png new file mode 100644 index 000000000..e5a9b2c41 Binary files /dev/null and b/plugins/channelrx/demoddroneid/map/drone.png differ diff --git a/plugins/channelrx/demoddroneid/map/home.png b/plugins/channelrx/demoddroneid/map/home.png new file mode 100644 index 000000000..08cba9200 Binary files /dev/null and b/plugins/channelrx/demoddroneid/map/home.png differ diff --git a/plugins/channelrx/demoddroneid/map/pilot.png b/plugins/channelrx/demoddroneid/map/pilot.png new file mode 100644 index 000000000..56d08aef9 Binary files /dev/null and b/plugins/channelrx/demoddroneid/map/pilot.png differ diff --git a/plugins/channelrx/demoddroneid/readme.md b/plugins/channelrx/demoddroneid/readme.md new file mode 100644 index 000000000..ca8a3f386 --- /dev/null +++ b/plugins/channelrx/demoddroneid/readme.md @@ -0,0 +1,200 @@ +

DJI DroneID Demodulator Plugin

+ +

Introduction

+ +This plugin can be used to demodulate DJI DroneID broadcasts. DroneID is transmitted by DJI drones that use the OcuSync / O2 / O3 video links (such as the Mini 2, Mini 3, Mini 3 Pro, Air 2S, Mavic Air 2 and Mavic 3). +It contains the drone's serial number, model, position, altitude, velocity and yaw, as well as the position of the pilot and the drone's home point. +Drones with O4 video links (E.g. Mini 4 Pro, Mini 5) encrypt DroneID, so can not be decoded. + +The drone transmits a DroneID burst approximately every 640ms while the motors are running, on one of a number of channels in the 2.4GHz and 5.8GHz bands. Known channel center frequencies are: + +- 2.4GHz: 2399.5, 2414.5, 2429.5, 2444.5, 2459.5 and 2474.5 MHz +- 5.8GHz: 5721.5, 5731.5, 5741.5, 5756.5, 5761.5, 5771.5, 5776.5, 5786.5, 5796.5, 5801.5, 5816.5 and 5831.5 MHz + +The drone remains on a channel for many bursts, but can change channel and band from time to time. How the channel is chosen is not documented (it may be related to the video link, which adapts to interference). +The Scan option (3) can be used to search the channels for DroneID bursts, pausing on a channel while bursts are being received. + +DroneID is an OFDM signal, similar to LTE: 9 symbols with a 1024 point FFT at 15.36 MS/s (15kHz subcarrier spacing) and 600 occupied subcarriers, giving an occupied bandwidth of 9MHz. +Symbols 4 and 6 contain Zadoff-Chu sequences, that are used for synchronisation and channel estimation, while the remaining symbols are QPSK modulated. +Data is protected with a CRC24 and an LTE turbo code, and is scrambled with a Gold sequence. +Older drones (E.g. Mavic 2) do not transmit the first symbol, and these are also supported. + +The demodulator requires a baseband sample rate of at least 15.36 MS/s, so an SDR such as a HackRF, USRP, BladeRF or PlutoSDR is required. An RTL SDR can not be used. +It is best to set the device sample rate to exactly 15.36 MS/s or 30.72 MS/s, to avoid the need for fractional resampling. +As DroneID has no DC subcarrier, the device can be tuned directly to the DroneID channel frequency. +The drone's video link uses the same bands. Its transmissions may trigger the burst detector, which uses CPU, but they are rejected by the decoder, as they do not contain the DroneID synchronisation sequences. +To see which channels a drone uses, enable Scan (3) for both bands and check the Freq column in the table. + +Decoded drone, pilot and home positions are sent to the [Map feature](../../feature/map/readme.md). +On the 3D map, the drone is displayed with a 3D model, oriented according to its yaw, with its propellers spinning while its motors are on. +The drone can be positioned using either its altitude or its height above its take-off point (10), while the pilot and home point are displayed on the ground. +Note that the 3D map draws tracks at the absolute heights sent, so a drone's track can be hidden by the terrain when it is flying low. +Decoded messages are also made available to other plugins (E.g. MCP Server) and can be forwarded via UDP and logged to a .csv file. + +

Interface

+ +The top and bottom bars of the channel window are described [here](../../../sdrgui/channel/readme.md) + +![DJI DroneID Demodulator plugin GUI](../../../doc/img/DroneIDDemod_plugin.png) + +

1: Frequency shift from center frequency of reception

+ +Use the wheels to adjust the frequency shift in Hz from the center frequency of reception. Left click on a digit sets the cursor position at this digit. +Right click on a digit sets all digits on the right to zero. This effectively floors value at the digit position. +Wheels are moved with the mousewheel while pointing at the wheel or by selecting the wheel with the left mouse click and using the keyboard arrows. +Pressing shift simultaneously moves digit by 5 and pressing control moves it by 2. + +

2: Ch - Channel

+ +Select one of the known DroneID channels. The device center frequency is set so that the channel, at its current frequency shift (1), is on the selected frequency. +If the channel's frequency is not a known DroneID channel, Custom is displayed. + +

3: Scan

+ +When checked, the device center frequency is stepped through the DroneID channels in the band selected by (4), so that this channel is tuned to each of them in turn. +When a burst with DroneID synchronisation sequences is detected, the scan pauses on that channel, and the button displays Lock. Scanning resumes once no bursts have been detected for the hold time. + +As drones often reuse channels, each pass through the channels starts with those that bursts have previously been detected on (most recent first), followed by the remaining channels in frequency order. +When bursts stop on a channel, a new pass is started immediately, so other previously used channels are checked next. + +Right click to set: + +- Dwell - Time in seconds to wait on each channel for a burst. As bursts are transmitted every 640ms, this should be at least 1 second. Default is 1.5 seconds. +- Hold - Time in seconds to remain on a channel after the last burst was detected. Default is 3 seconds. + +Selecting a channel in (2) stops scanning. As the device center frequency is changed, only one channel in a device set should have scanning enabled. + +

4: Scan Band

+ +Select which channels to scan: 2.4GHz, 5.8GHz or both bands. + +

5: Channel power

+ +Average total power in dB relative to a +/- 1.0 amplitude signal received in the pass band. + +

6: Level meter in dB

+ + - top bar (green): average value + - bottom bar (blue green): instantaneous peak value + - tip vertical bar (bright green): peak hold value + +

7: TH - Detection Threshold

+ +Bursts are detected by correlating each OFDM symbol's cyclic prefix with the end of the symbol, summed over all symbols in a burst. +This sets the normalised correlation threshold (0.05 to 0.95) required to detect a burst. Lower values can detect weaker bursts, but will result in more false detections, which increases CPU usage. +The default value is 0.20. + +

8: Iter - Turbo decoder iterations

+ +Maximum number of turbo decoder iterations. Decoding stops as soon as the CRC is valid, so more iterations only cost CPU for weak bursts. + +

9: Map - Map timeout

+ +Time in seconds after which a drone, its pilot and home point are removed from the Map, if no further messages are received. Set to 0 to never remove. + +

10: Map Altitude

+ +Selects which value is used for the drone's altitude on the 3D Map: + +- Alt - The drone's altitude, which is GPS height above the WGS84 ellipsoid. This is correct over any terrain, but GPS error can put the drone slightly below ground (and so hidden) on take-off and landing. +- Height - The drone's height above its take-off point, displayed relative to the ground at the drone's position. + +

11: SR - Channel sample rate

+ +Displays the channel sample rate. This is displayed in red if it is less than the required 15.36 MS/s. + +

12: Bursts

+ +Displays the number of bursts detected and the number successfully decoded (I.e. with a valid CRC24). + +

13: SNR

+ +Displays the SNR and carrier frequency offset of the last detected burst. + +

14: UDP

+ +When checked, received messages are forwarded to the specified UDP address (15) and port (16). + +

15: UDP address

+ +IP address of the host to forward received messages to via UDP. + +

16: UDP port

+ +UDP port number to forward received messages to. + +

17: Find

+ +Entering a regular expression in the Find field displays only messages where the drone serial number matches the given regular expression. + +

18: Use Date and Time from File

+ +When checked, if the source device is a File Input device, the date and time used for messages are taken from the file playback time. Otherwise, the current system clock time is used. + +

19: Start/stop Logging Messages to .csv File

+ +When checked, writes all received messages to a .csv file. + +

20: .csv Log Filename

+ +Click to specify the name of the .csv file which received messages are logged to. + +

21: Read Data from .csv File

+ +Click to specify a previously written .csv log file, which is read and used to update the table. + +

22: Clear Messages from table

+ +Pressing this button clears all messages from the table. + +

Received Messages Table

+ +The received messages table displays information about each DroneID message received. + +* Date/Time - The date and time the message was received. +* Serial - The drone's serial number. +* Model - The drone's model, determined from the product type. +* Type - Message type. Flight (flight information) or Purpose (flight purpose, which contains only the serial number). +* Seq - Message sequence number. +* Lat - Drone latitude in degrees. Double click to centre the map on the drone. +* Lon - Drone longitude in degrees. Double click to centre the map on the drone. +* Alt - Drone altitude in metres above the WGS84 ellipsoid. This is GPS height, which differs from height above mean sea level (as typically displayed by phones and maps) by the local geoid height. +* Height - Drone height above take-off point in metres. +* Speed - Horizontal ground speed in metres per second. +* V/S - Vertical speed in metres per second. +* Course - Ground track in degrees, calculated from the velocity. +* Yaw - Drone yaw in degrees. +* Pilot Lat - Pilot's latitude in degrees, from the GPS in the pilot's phone. Double click to centre the map on the pilot. +* Pilot Lon - Pilot's longitude in degrees, from the GPS in the pilot's phone. Double click to centre the map on the pilot. +* Home Lat - Home point latitude in degrees. Double click to centre the map on the home point. +* Home Lon - Home point longitude in degrees. Double click to centre the map on the home point. +* UUID - UUID, if set. +* State - Drone state flags. +* GPS Time - Date and time from the pilot's phone GPS. +* SNR - Signal to noise ratio of the burst in dB. +* CFO - Carrier frequency offset of the burst in Hz. +* Freq - Channel frequency the burst was received on in MHz. Useful when scanning, to see which channel the drone is using. +* CRC - Whether the message's CRC16 is valid. + +Right clicking on the table header allows you to select which columns to show. The columns can be reordered by left clicking and dragging the column header. +Right clicking on a row allows the drone, pilot or home point to be found on the map. + +The meanings of the State flags are provisional, as they are taken from the Wi-Fi beacon variant of DroneID. + +

API

+ +Full details of the API can be found in the Swagger documentation. Here is a quick example of how to set the frequency offset of the demodulator: + + curl -X PATCH "http://127.0.0.1:8091/sdrangel/deviceset/0/channel/0/settings" -d '{"channelType": "DroneIDDemod", "direction": 0, "DroneIDDemodSettings": { "inputFrequencyOffset": 0 }}' + +And to scan the 2.4GHz and 5.8GHz channels (scanBand: 0 - 2.4GHz, 1 - 5.8GHz, 2 - both): + + curl -X PATCH "http://127.0.0.1:8091/sdrangel/deviceset/0/channel/0/settings" -d '{"channelType": "DroneIDDemod", "direction": 0, "DroneIDDemodSettings": { "scan": 1, "scanBand": 2 }}' + +The channel report contains the number of bursts detected, decoded and dropped, the number of drones being tracked, and scanLocked, which is 1 when scanning is paused on a channel where DroneID bursts are being received: + + curl "http://127.0.0.1:8091/sdrangel/deviceset/0/channel/0/report" + +

Attribution

+ +This plugin was developed using the information published in "Drone Security and the Mysterious Case of DJI's DroneID" (N. Schiller et al., NDSS 2023), and David Protzman's [dji_droneid](https://github.com/proto17/dji_droneid) project. diff --git a/plugins/feature/map/mapsettings.cpp b/plugins/feature/map/mapsettings.cpp index 04844d48c..2ad85642e 100644 --- a/plugins/feature/map/mapsettings.cpp +++ b/plugins/feature/map/mapsettings.cpp @@ -35,6 +35,7 @@ const QStringList MapSettings::m_pipeTypes = { QStringLiteral("APRS"), QStringLiteral("APTDemod"), QStringLiteral("DSCDemod"), + QStringLiteral("DroneIDDemod"), QStringLiteral("FT8Demod"), QStringLiteral("HeatMap"), QStringLiteral("ILSDemod"), @@ -54,6 +55,7 @@ const QStringList MapSettings::m_pipeURIs = { QStringLiteral("sdrangel.feature.aprs"), QStringLiteral("sdrangel.channel.aptdemod"), QStringLiteral("sdrangel.channel.dscdemod"), + QStringLiteral("sdrangel.channel.droneiddemod"), QStringLiteral("sdrangel.channel.ft8demod"), QStringLiteral("sdrangel.channel.heatmap"), QStringLiteral("sdrangel.channel.ilsdemod"), @@ -98,6 +100,7 @@ MapSettings::MapSettings() : aprsSettings->m_extrapolate = 0; m_itemSettings.insert("APRS", aprsSettings); m_itemSettings.insert("DSCDemod", new MapItemSettings("DSCDemod", true, QColor(181, 230, 29), true, true, 3)); + m_itemSettings.insert("DroneIDDemod", new MapItemSettings("DroneIDDemod", true, QColor(255, 128, 0), true, false, 11, modelMinPixelSize)); m_itemSettings.insert("StarTracker", new MapItemSettings("StarTracker", true, QColor(230, 230, 230), true, true, 3)); m_itemSettings.insert("SatelliteTracker", new MapItemSettings("SatelliteTracker", true, QColor(0, 0, 255), true, false, 0, modelMinPixelSize)); m_itemSettings.insert("Beacons", new MapItemSettings("Beacons", true, QColor(255, 0, 0), false, true, 8)); diff --git a/plugins/feature/map/readme.md b/plugins/feature/map/readme.md index b7d6b7260..bbea10657 100644 --- a/plugins/feature/map/readme.md +++ b/plugins/feature/map/readme.md @@ -19,6 +19,7 @@ On top of this, it can plot data from other plugins, such as: * Inmarsat C message geographic areas, * SID paths, * Pager messages that contain coordinates. +* DJI drones from the DJI DroneID Demodulator. As well as internet and built-in data sources: diff --git a/plugins/feature/mcpserver/bandguide.md b/plugins/feature/mcpserver/bandguide.md index 24c5731a2..c29d3143c 100644 --- a/plugins/feature/mcpserver/bandguide.md +++ b/plugins/feature/mcpserver/bandguide.md @@ -31,6 +31,7 @@ Minimum device sample rates: | DAB | 2.048 MS/s | Fixed by the standard | | DVB-T and DVB-T2 | 9.142857 MS/s for 8 MHz channels | 8/7 times the `bandwidth` is the native rate (64/7 MS/s for 8 MHz; 131/71, about 1.845 MS/s, for DVB-T2's 1.7 MHz). Rates from 0.875 to 2.2 times it are resampled, at a CPU cost. An RTL-SDR can't run fast enough for 5 MHz and over | | DVB-S and DVB-S2 | 1.2 times the symbol rate | The signal is 1 + roll-off times the `symbolRate` wide, and losing a little of its edges costs under 0.3 dB. More leaves room for it being off centre and for the device's filter: 33 MS/s or more for 27.5 MS/s broadcasts (a USRP B210 or similar), 27.6 MS/s or more for 23 MS/s, 1 MS/s for QO-100's 333 or 500 kS/s. Measuring the symbol rate (`symbolRate` 0) needs about 1.7 times, to see the noise floor beside the signal. Use `standard` 4, 5 or 6: `standard` 0 is terrestrial, and needs 8 MS/s for an 8 MHz channel whatever the signal | +| DJI DroneID | 15.36 MS/s | 9 MHz wide OFDM with a 1024 point FFT. Beyond an RTL-SDR: use a HackRF, USRP, PlutoSDR or similar | | Broadcast FM | 240 kS/s | Must exceed the channel RF bandwidth. 256 kS/s is recommended for a 180 kHz channel | ## Aircraft @@ -42,6 +43,7 @@ Minimum device sample rates: | VOR navaids | `VORDemod`, `VORDemodMC` | 108 to 117.975 MHz | `VORDemodMC` receives several VORs at once for a position fix | | ILS localizer | `ILSDemod` | 108 to 112 MHz | Horizontal guidance | | ILS glide slope | `ILSDemod` | 329 to 335 MHz | Vertical guidance, paired with the localizer | +| DJI drones (DroneID) | `DroneIDDemod` | 2399.5 to 2474.5 MHz and 5721.5 to 5831.5 MHz | Needs at least 15.36 MS/s. OcuSync drones (Mini 2, Mini 3, Air 2S, Mavic 3...) send a burst every 640 ms while the motors run, staying on a channel for a while, then changing channel or band. Gives drone, pilot and home positions. `listen` with mode `droneid` | ## Ships @@ -132,6 +134,10 @@ usual for the mode. Do not scan for these; they are on fixed frequencies, so `listen` or `add_channel` is the tool: - **ADS-B**: 1090 MHz only. +- **DroneID**: 2399.5, 2414.5, 2429.5, 2444.5, 2459.5 and 2474.5 MHz, and 5721.5 to 5831.5 MHz. + A drone stays on one channel for many bursts, but can change channel and band. Set the + channel's `scan` setting to 1 to step through them, pausing where bursts are found (`scanBand` 0 = 2.4 GHz, + 1 = 5.8 GHz, 2 = both). It retunes the device, so don't use it while other channels need the device frequency. - **DAB**: fixed Band III blocks 5A to 13F (174.928 to 239.200 MHz, 1.712 MHz apart). Start a `dab` channel on each block in turn and read the programme list from its report. - **AIS**: 161.975 and 162.025 MHz. @@ -182,13 +188,15 @@ looks like an empty band. | DVB-T and DVB-T2 (and DVB-S and S2) | Channel report | `DVBDemodReport`: `state` (Locked when the transport stream is being decoded), `standard`, `mode`, `constellation`, `codeRate`, `mer`, and `postViterbiBER` for DVB-T and DVB-S (below 2e-4 is error free) or `ldpcIterations` and `bchFailures` for DVB-T2 and DVB-S2; for DVB-S2 also `modcod`, `esN0` (dB, compare with the MODCOD's threshold), `plFrames` and `plHeaderMisses`, and `measuredSymbolRate` for both satellite standards. What's on: `epgNowTitle`, `epgNowStart` (UTC), `epgNowDuration` (s), `epgNowDescription` and `epgNextTitle`, `epgNextStart` of `epgServiceId` (the `serviceId` setting, or the first TV service); the guide takes a minute or so to arrive, and is cached. Recording to .ts files in `recordDirectory`: channel_action `{"record": 1}` (or 0 to stop) records the service selected, or with `recordMode` 0 the whole multiplex; `{"recordEvent": 1, "serviceId": id, "eventId": id}` records a programme from the guide (0 cancels), starting `recordStartPadding` s early and ending `recordEndPadding` s late; the report has `recording`, `recordingFile`, `recordingSize` and `scheduledRecordings`. channel_action `{"play": 1, "serviceId": id}` plays a service from the guide, retuning the device to its multiplex if it's on another. Audio and subtitles: `audioLanguage` and `subtitleLanguage` (ISO 639-2, e.g. eng), `audioDescription` 1 to mix in audio description and `subtitles` 1 to show subtitles, where the service has them. Video, the service list and the full guide are in the GUI; with `udpEnabled` the transport stream goes to `udpAddress`:`udpPort` for VLC | | ADS-B | Map items | `get_map_items` lists the aircraft with position, altitude, heading and callsign; the channel report only has counts and the tracked target | | AIS, APRS and AX.25, LoRa, M17, Meshtastic, MeshCore, Inmarsat, radiosondes | Packet buffer | `get_packets`, which decodes AIS position reports, APRS positions and RS41 frames. Ships, stations and sondes also appear in `get_map_items` when the Map feature is present | +| DroneID | Packet buffer and map items | `get_packets` decodes serial number, model, drone position, altitude and speed, and pilot and home positions. `get_map_items` lists the drone, pilot and home point when the Map feature is present | | VOR | Channel report | `VORDemodReport.radial` with `validRadial`, and the Morse ident | | Pagers, DSC, NAVTEX, RTTY, FT8 | GUI only | The decoded messages are shown in the plugin's window; the API carries the channel power only. Say so rather than reporting the band as empty | How long to wait before reading: RDS a few seconds, the full station name up to ten; DAB sync about two seconds and the programme list five to ten; ADS-B ten seconds if aircraft are in range; AIS half a minute, as each ship transmits every few seconds at most; APRS minutes, -as stations transmit rarely; radiosonde frames once a second while a sonde is up; VOR a few +as stations transmit rarely; radiosonde frames once a second while a sonde is up; DroneID +several seconds, as the drone only spends part of the time on any one channel; VOR a few seconds for a valid radial. A single read immediately after tuning proves nothing; read the report again after the interval before concluding a signal has no data. diff --git a/plugins/feature/mcpserver/mcpdatafeed.cpp b/plugins/feature/mcpserver/mcpdatafeed.cpp index 8393276bd..718ab06cf 100644 --- a/plugins/feature/mcpserver/mcpdatafeed.cpp +++ b/plugins/feature/mcpserver/mcpdatafeed.cpp @@ -30,6 +30,7 @@ #include "util/ax25.h" #include "util/aprs.h" #include "util/radiosonde.h" +#include "util/droneid.h" #include "mcpdatafeed.h" @@ -43,6 +44,7 @@ static const QStringList packetURIs = { QStringLiteral("sdrangel.channel.meshcoredemod"), QStringLiteral("sdrangel.channel.inmarsatdemod"), QStringLiteral("sdrangel.channel.radiosondedemod"), + QStringLiteral("sdrangel.channel.droneiddemod"), }; static const QStringList packetPipes = {"packets", "ais", "radiosonde"}; @@ -54,6 +56,7 @@ static const QStringList mapURIs = { QStringLiteral("sdrangel.feature.aprs"), QStringLiteral("sdrangel.channel.aptdemod"), QStringLiteral("sdrangel.channel.dscdemod"), + QStringLiteral("sdrangel.channel.droneiddemod"), QStringLiteral("sdrangel.channel.ft8demod"), QStringLiteral("sdrangel.channel.heatmap"), QStringLiteral("sdrangel.channel.ilsdemod"), @@ -359,6 +362,58 @@ QJsonObject MCPDataFeed::decodePacket(const QString& sourceType, const QByteArra decoded["heading"] = frame.m_heading; } } + else if (sourceType == "DroneIDDemod") + { + DroneIDMessage *msg = DroneIDMessage::decode(bytes); + decoded["protocol"] = "DroneID"; + + if (msg) + { + decoded["serial"] = msg->m_serial; + decoded["crcValid"] = msg->m_crcValid; + + if (msg->isFlightInformation()) + { + decoded["messageType"] = "FlightInformation"; + decoded["model"] = msg->getProductTypeName(); + decoded["productType"] = msg->m_productType; + decoded["sequence"] = msg->m_sequence; + decoded["state"] = msg->getStateInfoString(); + if (msg->hasPosition()) + { + decoded["latitude"] = msg->m_latitude; + decoded["longitude"] = msg->m_longitude; + } + decoded["altitudeWgs84Metres"] = msg->m_altitude; // GPS height above WGS84 ellipsoid, not MSL + decoded["heightAboveTakeoffMetres"] = msg->m_height; + decoded["speedMetresPerSecond"] = msg->getSpeed(); + decoded["verticalSpeedMetresPerSecond"] = msg->m_vUp; + decoded["yaw"] = msg->m_yaw; + if (msg->hasPilotPosition()) + { + decoded["pilotLatitude"] = msg->m_pilotLatitude; + decoded["pilotLongitude"] = msg->m_pilotLongitude; + } + if (msg->hasHomePosition()) + { + decoded["homeLatitude"] = msg->m_homeLatitude; + decoded["homeLongitude"] = msg->m_homeLongitude; + } + if (msg->m_gpsTime.isValid()) { + decoded["gpsTime"] = msg->m_gpsTime.toString(Qt::ISODateWithMs); + } + if (!msg->m_uuid.isEmpty()) { + decoded["uuid"] = msg->m_uuid; + } + } + else + { + decoded["messageType"] = "FlightPurpose"; + } + + delete msg; + } + } else if ((sourceType == "PacketDemod") || (sourceType == "ChirpChatDemod") || (sourceType == "M17Demod")) { AX25Packet ax25; diff --git a/plugins/feature/mcpserver/mcptools.cpp b/plugins/feature/mcpserver/mcptools.cpp index b2ee0b916..e525df2b6 100644 --- a/plugins/feature/mcpserver/mcptools.cpp +++ b/plugins/feature/mcpserver/mcptools.cpp @@ -2354,9 +2354,10 @@ void MCPTools::registerInstanceTools() add("get_packets", "Get recently decoded packets from packet-oriented demodulators (AIS, APRS/AX.25 packet, LoRa/ChirpChat, M17, Meshtastic, " - "MeshCore, Inmarsat, radiosonde). Each packet has the raw bytes (hex and printable text) and, where SDRangel can decode it, " + "MeshCore, Inmarsat, radiosonde, DJI DroneID). Each packet has the raw bytes (hex and printable text) and, where SDRangel can decode it, " "a decoded object: AIS message type, MMSI, position, course and speed; AX.25 from/to/via and data with APRS position and " - "comment; RS41 radiosonde serial, position and height. Packets are kept in a buffer of the last 1000; use sinceSequence " + "comment; RS41 radiosonde serial, position and height; DroneID drone serial, model, position, altitude and speed, and pilot " + "and home positions. Packets are kept in a buffer of the last 1000; use sinceSequence " "with the lastSequence of a previous call to read only new packets.", schema({ {"source", strProp("Only packets from this channel, e.g. \"R0:1\" (device set 0, channel 1)")}, @@ -3921,9 +3922,11 @@ const ListenMode listenModes[] = { // with the APRS feature to plot the stations {"packet", "PacketDemod", 12500, 48000, "{}", 0, nullptr, 0}, {"aprs", "PacketDemod", 12500, 48000, "{}", 0, "APRS", 0}, + // DJI DroneID is a 9 MHz wide OFDM burst, needing a 15.36 MS/s baseband + {"droneid", "DroneIDDemod", 0, 15360000, "{}", 0, nullptr, 0}, }; -const char *const listenModeList = "bfm, wfm, nfm, am, ssb, usb, lsb, dab, adsb, ais, dsc, dsd, dmr, dpmr, dstar, ysf, nxdn, pager, sonde, packet, aprs"; +const char *const listenModeList = "bfm, wfm, nfm, am, ssb, usb, lsb, dab, adsb, ais, dsc, dsd, dmr, dpmr, dstar, ysf, nxdn, pager, sonde, packet, aprs, droneid"; // The feature a demodulator of this type feeds, by the modes that add one; null for none const char *featureForChannelType(const QString& channelType) @@ -3970,7 +3973,8 @@ void rateFor(int minBaseband, int& devSampleRate, int& log2Decim) else if (minBaseband <= 512000) { devSampleRate = 1024000; log2Decim = 1; } else if (minBaseband <= 1024000) { devSampleRate = 1024000; log2Decim = 0; } else if (minBaseband <= 2048000) { devSampleRate = 2048000; log2Decim = 0; } - else { devSampleRate = 2400000; log2Decim = 0; } + else if (minBaseband <= 2400000) { devSampleRate = 2400000; log2Decim = 0; } + else { devSampleRate = minBaseband; log2Decim = 0; } // Beyond an RTL-SDR } // The baseband a channel type needs, from the table listen uses, so that there is one set of @@ -4573,6 +4577,17 @@ QJsonObject MCPTools::pickReceiver(const QJsonObject& args, int minBaseband, con rateKey = "sampleRate"; } + // An RTL-SDR tops out at about 3.2 MS/s, so a wider mode (E.g. DroneID) can't be received with it + const int rtlSdrMaxRate = 3200000; + QString unsupportedRateNote; + + if ((hwType == "RTLSDR") && (minBaseband > rtlSdrMaxRate)) + { + rateKey.clear(); + unsupportedRateNote = QString("An RTL-SDR can not provide the %1 S/s this mode needs: use a wider band device such as a HackRF, USRP or PlutoSDR.") + .arg(minBaseband); + } + // A reused device set is already feeding its other channels the width it has. Widening it for // the new channel leaves them working, narrowing it to what only the new one needs takes their // signal away, so the width already configured is a floor rather than something to overwrite @@ -4591,7 +4606,7 @@ QJsonObject MCPTools::pickReceiver(const QJsonObject& args, int minBaseband, con int log2Decim = 0; rateFor(qMax(minBaseband, existingBaseband), devSampleRate, log2Decim); QJsonObject partial; - QString rateNote; + QString rateNote = unsupportedRateNote; int baseband = 0; if (!rateKey.isEmpty()) diff --git a/sdrbase/CMakeLists.txt b/sdrbase/CMakeLists.txt index d8b8e428c..683309b1b 100644 --- a/sdrbase/CMakeLists.txt +++ b/sdrbase/CMakeLists.txt @@ -138,6 +138,7 @@ set(sdrbase_SOURCES dsp/dspdevicesinkengine.cpp dsp/dspdevicemimoengine.cpp dsp/fftcorr.cpp + dsp/lteturbo.cpp dsp/fftengine.cpp dsp/fftfactory.cpp dsp/fftfilt.cpp @@ -228,6 +229,7 @@ set(sdrbase_SOURCES util/corsproxy.cpp util/countrydat.cpp util/crc.cpp + util/droneid.cpp util/CRC64.cpp util/csv.cpp util/db.cpp @@ -245,6 +247,7 @@ set(sdrbase_SOURCES util/jplhorizons.cpp util/kiwisdrlist.cpp util/lfsr.cpp + util/ltegold.cpp util/maidenhead.cpp util/message.cpp util/messagequeue.cpp @@ -372,6 +375,7 @@ set(sdrbase_HEADERS dsp/dspdevicemimoengine.h dsp/dsptypes.h dsp/fftcorr.h + dsp/lteturbo.h dsp/fftengine.h dsp/fftfactory.h dsp/fftfilt.h @@ -515,6 +519,7 @@ set(sdrbase_HEADERS util/jplhorizons.h util/kiwisdrlist.h util/lfsr.h + util/ltegold.h util/maidenhead.h util/message.h util/messagequeue.h @@ -534,6 +539,7 @@ set(sdrbase_HEADERS util/prettyprint.h util/profiler.h util/psk31.h + util/droneid.h util/radiosonde.h util/rainviewer.h util/rds.h diff --git a/sdrbase/dsp/lteturbo.cpp b/sdrbase/dsp/lteturbo.cpp new file mode 100644 index 000000000..e9b15bbf0 --- /dev/null +++ b/sdrbase/dsp/lteturbo.cpp @@ -0,0 +1,440 @@ +/////////////////////////////////////////////////////////////////////////////////// +// Copyright (C) 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 . // +/////////////////////////////////////////////////////////////////////////////////// + +#include + +#include "lteturbo.h" + +// TS 36.212 Table 5.1.3-3: QPP interleaver parameters for the 188 block sizes +// K = 40..512 step 8, 528..1024 step 16, 1056..2048 step 32, 2112..6144 step 64 +const uint16_t LTETurbo::m_qppF1[188] = { + 3, 7, 19, 7, 7, 11, 5, 11, 7, 41, 103, 15, 9, 17, 9, 21, 101, 21, 57, 23, 13, + 27, 11, 27, 85, 29, 33, 15, 17, 33, 103, 19, 19, 37, 19, 21, 21, 115, 193, 21, + 133, 81, 45, 23, 243, 151, 155, 25, 51, 47, 91, 29, 29, 247, 29, 89, 91, 157, + 55, 31, 17, 35, 227, 65, 19, 37, 41, 39, 185, 43, 21, 155, 79, 139, 23, 217, + 25, 17, 127, 25, 239, 17, 137, 215, 29, 15, 147, 29, 59, 65, 55, 31, 17, 171, + 67, 35, 19, 39, 19, 199, 21, 211, 21, 43, 149, 45, 49, 71, 13, 17, 25, 183, 55, + 127, 27, 29, 29, 57, 45, 31, 59, 185, 113, 31, 17, 171, 209, 253, 367, 265, 181, + 39, 27, 127, 143, 43, 29, 45, 157, 47, 13, 111, 443, 51, 51, 451, 257, 57, 313, + 271, 179, 331, 363, 375, 127, 31, 33, 43, 33, 477, 35, 233, 357, 337, 37, 71, + 71, 37, 39, 127, 39, 39, 31, 113, 41, 251, 43, 21, 43, 45, 45, 161, 89, 323, 47, 23, 47, 263 +}; + +const uint16_t LTETurbo::m_qppF2[188] = { + 10, 12, 42, 16, 18, 20, 22, 24, 26, 84, 90, 32, 34, 108, 38, 120, 84, 44, 46, + 48, 50, 52, 36, 56, 58, 60, 62, 32, 198, 68, 210, 36, 74, 76, 78, 120, 82, 84, + 86, 44, 90, 46, 94, 48, 98, 40, 102, 52, 106, 72, 110, 168, 114, 58, 118, 180, + 122, 62, 84, 64, 66, 68, 420, 96, 74, 76, 234, 80, 82, 252, 86, 44, 120, 92, + 94, 48, 98, 80, 102, 52, 106, 48, 110, 112, 114, 58, 118, 60, 122, 124, 84, + 64, 66, 204, 140, 72, 74, 76, 78, 240, 82, 252, 86, 88, 60, 92, 846, 48, 28, + 80, 102, 104, 954, 96, 110, 112, 114, 116, 354, 120, 610, 124, 420, 64, 66, + 136, 420, 216, 444, 456, 468, 80, 164, 504, 172, 88, 300, 92, 188, 96, 28, 240, + 204, 104, 212, 192, 220, 336, 228, 232, 236, 120, 244, 248, 168, 64, 130, 264, + 134, 408, 138, 280, 142, 480, 146, 444, 120, 152, 462, 234, 158, 80, 96, 902, + 166, 336, 170, 86, 174, 176, 178, 120, 182, 184, 186, 94, 190, 480 +}; + +int LTETurbo::qppIndex(int K) +{ + if ((K >= 40) && (K <= 512) && ((K % 8) == 0)) { + return (K - 40) / 8; + } else if ((K > 512) && (K <= 1024) && ((K % 16) == 0)) { + return 60 + (K - 528) / 16; + } else if ((K > 1024) && (K <= 2048) && ((K % 32) == 0)) { + return 92 + (K - 1056) / 32; + } else if ((K > 2048) && (K <= 6144) && ((K % 64) == 0)) { + return 124 + (K - 2112) / 64; + } else { + return -1; + } +} + +bool LTETurbo::isValidBlockSize(int K) +{ + return qppIndex(K) >= 0; +} + +bool LTETurbo::qppParameters(int K, int& f1, int& f2) +{ + int idx = qppIndex(K); + + if (idx < 0) { + return false; + } + f1 = m_qppF1[idx]; + f2 = m_qppF2[idx]; + return true; +} + +void LTETurbo::interleaver(int K, std::vector& pi) +{ + int f1, f2; + + pi.resize(K); + if (!qppParameters(K, f1, f2)) { + return; + } + for (int i = 0; i < K; i++) + { + // Use 64-bit to avoid overflow of f2*i*i + int64_t ii = i; + pi[i] = (int) ((f1 * ii + f2 * ii * ii) % K); + } +} + +// Encode one constituent RSC, including termination. +void LTETurboEncoder::rscEncode(const std::vector& in, const int *pi, + std::vector& parity, uint8_t tailSys[3], uint8_t tailParity[3]) +{ + int K = (int) in.size(); + int s = 0; + + parity.resize(K); + for (int k = 0; k < K; k++) + { + int u = pi ? in[pi[k]] : in[k]; + int a = LTETurbo::rscFeedback(s, u); + parity[k] = LTETurbo::rscParity(s, a); + s = LTETurbo::rscNext(s, a); + } + // Termination: input is chosen so the register input is 0 + for (int k = 0; k < 3; k++) + { + int u = ((s >> 1) & 1) ^ (s & 1); + tailSys[k] = u; + tailParity[k] = LTETurbo::rscParity(s, 0); + s = LTETurbo::rscNext(s, 0); + } +} + +void LTETurboEncoder::encode(const std::vector& in, + std::vector& d0, std::vector& d1, std::vector& d2) +{ + int K = (int) in.size(); + std::vector pi; + std::vector z1, z2; + uint8_t x1t[3], z1t[3], x2t[3], z2t[3]; + + LTETurbo::interleaver(K, pi); + rscEncode(in, nullptr, z1, x1t, z1t); + rscEncode(in, pi.data(), z2, x2t, z2t); + + d0.resize(K + 4); + d1.resize(K + 4); + d2.resize(K + 4); + for (int k = 0; k < K; k++) + { + d0[k] = in[k]; + d1[k] = z1[k]; + d2[k] = z2[k]; + } + // Tail bits multiplexing, TS 36.212 5.1.3.2.2 + d0[K] = x1t[0]; d0[K+1] = z1t[1]; d0[K+2] = x2t[0]; d0[K+3] = z2t[1]; + d1[K] = z1t[0]; d1[K+1] = x1t[2]; d1[K+2] = z2t[0]; d1[K+3] = x2t[2]; + d2[K] = x1t[1]; d2[K+1] = z1t[2]; d2[K+2] = x2t[1]; d2[K+3] = z2t[2]; +} + +LTETurboDecoder::LTETurboDecoder() : + m_K(0) +{ +} + +void LTETurboDecoder::setBlockSize(int K) +{ + if (K != m_K) + { + m_K = K; + LTETurbo::interleaver(K, m_pi); + m_alpha.resize((K + 4) * 8); + m_gammaSys.resize(K + 3); + m_gammaPar.resize(K + 3); + } +} + +LTETurboDecoder::Trellis::Trellis() +{ + int count[8] = {0}; + + for (int s = 0; s < 8; s++) + { + for (int u = 0; u < 2; u++) + { + int a = LTETurbo::rscFeedback(s, u); + int ns = LTETurbo::rscNext(s, a); + m_next[s][u] = ns; + m_gamma[s][u] = 2 * u + LTETurbo::rscParity(s, a); + m_prev[ns][count[ns]] = s; + m_prevGamma[ns][count[ns]] = m_gamma[s][u]; + count[ns]++; + } + } +} + +const LTETurboDecoder::Trellis& LTETurboDecoder::trellis() +{ + static const Trellis trellis; + return trellis; +} + +// Max-log-MAP BCJR for one constituent decoder. Outputs a posteriori LLRs for the K information bits. +// Branch metric for bit b with LLR L is +L/2 if b = 0, -L/2 if b = 1. +// Metrics are normalised relative to state 0, which is reachable at every step. +void LTETurboDecoder::bcjr(const float *sys, const float *apriori, const float *parity, + const float *tailSys, const float *tailParity, float *llrOut) +{ + const int K = m_K; + const Trellis& t = trellis(); + float *alpha = m_alpha.data(); + + for (int k = 0; k < K; k++) + { + m_gammaSys[k] = 0.5f * (sys[k] + apriori[k]); + m_gammaPar[k] = 0.5f * parity[k]; + } + for (int k = 0; k < 3; k++) + { + m_gammaSys[K + k] = 0.5f * tailSys[k]; + m_gammaPar[K + k] = 0.5f * tailParity[k]; + } + + // Forward recursion + alpha[0] = 0.0f; + for (int s = 1; s < 8; s++) { + alpha[s] = m_minusInf; + } + for (int k = 0; k < K; k++) + { + const float *a = &alpha[k * 8]; + float *an = &alpha[(k + 1) * 8]; + const float gs = m_gammaSys[k]; + const float gp = m_gammaPar[k]; + const float g[4] = {gs + gp, gs - gp, -gs + gp, -gs - gp}; + + for (int ns = 0; ns < 8; ns++) + { + an[ns] = std::max(a[t.m_prev[ns][0]] + g[t.m_prevGamma[ns][0]], + a[t.m_prev[ns][1]] + g[t.m_prevGamma[ns][1]]); + } + const float norm = an[0]; + for (int s = 0; s < 8; s++) { + an[s] -= norm; + } + } + // Termination: register input is forced to 0, so systematic input depends on state + for (int k = K; k < K + 3; k++) + { + const float *a = &alpha[k * 8]; + float *an = &alpha[(k + 1) * 8]; + const float gs = m_gammaSys[k]; + const float gp = m_gammaPar[k]; + const float g[4] = {gs + gp, gs - gp, -gs + gp, -gs - gp}; + + for (int s = 0; s < 8; s++) { + an[s] = m_minusInf; + } + for (int s = 0; s < 8; s++) + { + const int u = LTETurbo::rscFeedback(s, 0); + an[t.m_next[s][u]] = std::max(an[t.m_next[s][u]], a[s] + g[t.m_gamma[s][u]]); + } + const float norm = an[0]; + for (int s = 0; s < 8; s++) { + an[s] -= norm; + } + } + + // Backward recursion, ending in state 0 + float beta[8], betaPrev[8]; + beta[0] = 0.0f; + for (int s = 1; s < 8; s++) { + beta[s] = m_minusInf; + } + for (int k = K + 2; k >= K; k--) + { + const float gs = m_gammaSys[k]; + const float gp = m_gammaPar[k]; + const float g[4] = {gs + gp, gs - gp, -gs + gp, -gs - gp}; + + for (int s = 0; s < 8; s++) + { + const int u = LTETurbo::rscFeedback(s, 0); + betaPrev[s] = g[t.m_gamma[s][u]] + beta[t.m_next[s][u]]; + } + const float norm = betaPrev[0]; + for (int s = 0; s < 8; s++) { + beta[s] = betaPrev[s] - norm; + } + } + for (int k = K - 1; k >= 0; k--) + { + const float *a = &alpha[k * 8]; + const float gs = m_gammaSys[k]; + const float gp = m_gammaPar[k]; + const float g[4] = {gs + gp, gs - gp, -gs + gp, -gs - gp}; + float m0 = m_minusInf; + float m1 = m_minusInf; + + for (int s = 0; s < 8; s++) + { + const float b0 = g[t.m_gamma[s][0]] + beta[t.m_next[s][0]]; + const float b1 = g[t.m_gamma[s][1]] + beta[t.m_next[s][1]]; + betaPrev[s] = std::max(b0, b1); + m0 = std::max(m0, a[s] + b0); + m1 = std::max(m1, a[s] + b1); + } + llrOut[k] = m0 - m1; + const float norm = betaPrev[0]; + for (int s = 0; s < 8; s++) { + beta[s] = betaPrev[s] - norm; + } + } +} + +int LTETurboDecoder::decode(const std::vector& d0, const std::vector& d1, const std::vector& d2, + std::vector& out, int maxIterations, EarlyStop earlyStop) +{ + const int K = m_K; + const float extrinsicScale = 0.75f; // Compensates for max-log approximation optimism + std::vector sys1(K), sys2(K), par1(K), par2(K); + std::vector apriori1(K, 0.0f), apriori2(K), llr1(K), llr2(K); + float tailSys1[3], tailPar1[3], tailSys2[3], tailPar2[3]; + + out.resize(K); + if ((K == 0) || ((int) d0.size() < K + 4) || ((int) d1.size() < K + 4) || ((int) d2.size() < K + 4)) { + return -1; + } + + for (int k = 0; k < K; k++) + { + sys1[k] = d0[k]; + sys2[k] = d0[m_pi[k]]; + par1[k] = d1[k]; + par2[k] = d2[k]; + } + // Tail bits demultiplexing, inverse of TS 36.212 5.1.3.2.2 + tailSys1[0] = d0[K]; tailPar1[0] = d1[K]; + tailSys1[1] = d2[K]; tailPar1[1] = d0[K+1]; + tailSys1[2] = d1[K+1]; tailPar1[2] = d2[K+1]; + tailSys2[0] = d0[K+2]; tailPar2[0] = d1[K+2]; + tailSys2[1] = d2[K+2]; tailPar2[1] = d0[K+3]; + tailSys2[2] = d1[K+3]; tailPar2[2] = d2[K+3]; + + for (int iter = 1; iter <= maxIterations; iter++) + { + bcjr(sys1.data(), apriori1.data(), par1.data(), tailSys1, tailPar1, llr1.data()); + for (int k = 0; k < K; k++) + { + int j = m_pi[k]; + apriori2[k] = extrinsicScale * (llr1[j] - sys1[j] - apriori1[j]); + } + bcjr(sys2.data(), apriori2.data(), par2.data(), tailSys2, tailPar2, llr2.data()); + for (int k = 0; k < K; k++) + { + int j = m_pi[k]; + apriori1[j] = extrinsicScale * (llr2[k] - sys2[k] - apriori2[k]); + out[j] = llr2[k] < 0.0f ? 1 : 0; + } + if (earlyStop && earlyStop(out)) { + return iter; + } + } + + return earlyStop ? -maxIterations : maxIterations; +} + +void LTERateMatcher::bufferMap(int D, std::vector& stream, std::vector& index) +{ + // Inter-column permutation pattern for sub-block interleaver, TS 36.212 Table 5.1.4-1 + static const int P[32] = { + 0, 16, 8, 24, 4, 20, 12, 28, 2, 18, 10, 26, 6, 22, 14, 30, + 1, 17, 9, 25, 5, 21, 13, 29, 3, 19, 11, 27, 7, 23, 15, 31 + }; + const int R = (D + 31) / 32; + const int Kpi = R * 32; + const int ND = Kpi - D; + + stream.resize(3 * Kpi); + index.resize(3 * Kpi); + + for (int k = 0; k < Kpi; k++) + { + int y01 = P[k / R] + 32 * (k % R); + int y2 = (P[k / R] + 32 * (k % R) + 1) % Kpi; + + // Systematic + stream[k] = y01 < ND ? -1 : 0; + index[k] = y01 - ND; + // Interlaced parity streams + stream[Kpi + 2 * k] = y01 < ND ? -1 : 1; + index[Kpi + 2 * k] = y01 - ND; + stream[Kpi + 2 * k + 1] = y2 < ND ? -1 : 2; + index[Kpi + 2 * k + 1] = y2 - ND; + } +} + +int LTERateMatcher::startPosition(int D, int rv) +{ + const int R = (D + 31) / 32; + const int Ncb = 3 * R * 32; + const int c = (Ncb + 8 * R - 1) / (8 * R); + return R * (2 * c * rv + 2); +} + +void LTERateMatcher::match(const std::vector& d0, const std::vector& d1, const std::vector& d2, + int E, int rv, std::vector& e) +{ + const int D = (int) d0.size(); + std::vector stream, index; + const std::vector *d[3] = {&d0, &d1, &d2}; + + bufferMap(D, stream, index); + const int Ncb = (int) stream.size(); + const int k0 = startPosition(D, rv); + + e.resize(E); + for (int k = 0, j = 0; k < E; j++) + { + int pos = (k0 + j) % Ncb; + if (stream[pos] >= 0) { + e[k++] = (*d[stream[pos]])[index[pos]]; + } + } +} + +void LTERateMatcher::dematch(const std::vector& e, int D, int rv, + std::vector& d0, std::vector& d1, std::vector& d2) +{ + const int E = (int) e.size(); + std::vector stream, index; + std::vector *d[3] = {&d0, &d1, &d2}; + + bufferMap(D, stream, index); + const int Ncb = (int) stream.size(); + const int k0 = startPosition(D, rv); + + d0.assign(D, 0.0f); + d1.assign(D, 0.0f); + d2.assign(D, 0.0f); + for (int k = 0, j = 0; k < E; j++) + { + int pos = (k0 + j) % Ncb; + if (stream[pos] >= 0) { + (*d[stream[pos]])[index[pos]] += e[k++]; + } + } +} diff --git a/sdrbase/dsp/lteturbo.h b/sdrbase/dsp/lteturbo.h new file mode 100644 index 000000000..909792f13 --- /dev/null +++ b/sdrbase/dsp/lteturbo.h @@ -0,0 +1,132 @@ +/////////////////////////////////////////////////////////////////////////////////// +// Copyright (C) 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 . // +/////////////////////////////////////////////////////////////////////////////////// + +#ifndef INCLUDE_LTETURBO_H +#define INCLUDE_LTETURBO_H + +#include +#include +#include + +#include "export.h" + +// LTE turbo code as specified in 3GPP TS 36.212 section 5.1.3.2: +// two 8-state RSC encoders (g0 = 13, g1 = 15 octal) with a QPP interleaver +// and trellis termination, giving three output streams d0, d1, d2 of K+4 bits. +// +// Soft values throughout are LLRs with the convention: positive means bit 0. + +class SDRBASE_API LTETurbo +{ +public: + // Whether K is one of the 188 block sizes in TS 36.212 Table 5.1.3-3 + static bool isValidBlockSize(int K); + // QPP interleaver parameters for block size K. Returns false if K is invalid. + static bool qppParameters(int K, int& f1, int& f2); + // QPP interleaver: output bit i of the interleaver is input bit pi[i] + static void interleaver(int K, std::vector& pi); + + // RSC trellis. State S = r0*4 + r1*2 + r2, where r0 holds the most recent register input. + // Feedback g0 = 1 + D^2 + D^3, feedforward g1 = 1 + D + D^3. + static int rscFeedback(int s, int u) { return u ^ ((s >> 1) & 1) ^ (s & 1); } // Register input a for state s and systematic input u + static int rscParity(int s, int a) { return a ^ ((s >> 2) & 1) ^ (s & 1); } + static int rscNext(int s, int a) { return (a << 2) | (s >> 1); } + +private: + // TS 36.212 Table 5.1.3-3: QPP interleaver parameters for the 188 block sizes + static const uint16_t m_qppF1[188]; + static const uint16_t m_qppF2[188]; + + static int qppIndex(int K); +}; + +class SDRBASE_API LTETurboEncoder +{ +public: + // Encode K bits (one bit per byte, 0 or 1) into d0, d1, d2 (each K+4 bits) + static void encode(const std::vector& in, + std::vector& d0, std::vector& d1, std::vector& d2); + +private: + static void rscEncode(const std::vector& in, const int *pi, + std::vector& parity, uint8_t tailSys[3], uint8_t tailParity[3]); +}; + +class SDRBASE_API LTETurboDecoder +{ +public: + // Called after each iteration with the hard decisions. Return true to stop early. + typedef std::function& bits)> EarlyStop; + + LTETurboDecoder(); + + void setBlockSize(int K); + int getBlockSize() const { return m_K; } + + // Max-log-MAP decoding of d0, d1, d2 LLRs (each K+4 values). + // Writes K hard bits to out. Returns number of iterations performed, + // or a negative value if earlyStop never returned true. + int decode(const std::vector& d0, const std::vector& d1, const std::vector& d2, + std::vector& out, int maxIterations, EarlyStop earlyStop = nullptr); + +private: + // Trellis branches, so they needn't be calculated in the inner loops + struct Trellis + { + int m_next[8][2]; // Next state for state and systematic input + int m_gamma[8][2]; // Branch metric index (2*input + parity) for state and systematic input + int m_prev[8][2]; // The two states leading to a state + int m_prevGamma[8][2]; // Branch metric index for those transitions + + Trellis(); + }; + + static constexpr float m_minusInf = -1.0e30f; + + static const Trellis& trellis(); + + void bcjr(const float *sys, const float *apriori, const float *parity, + const float *tailSys, const float *tailParity, float *llrOut); + + int m_K; + std::vector m_pi; + std::vector m_alpha; + std::vector m_gammaSys; // Systematic+apriori contribution per step + std::vector m_gammaPar; // Parity contribution per step +}; + +// Circular buffer rate matching for turbo coded transport channels, TS 36.212 section 5.1.4.1. +// No soft buffer limitation is applied (Ncb = Kw). +class SDRBASE_API LTERateMatcher +{ +public: + // Select E bits from d0, d1, d2 (each D bits) for redundancy version rv + static void match(const std::vector& d0, const std::vector& d1, const std::vector& d2, + int E, int rv, std::vector& e); + // Reverse of match: accumulate E LLRs in to d0, d1, d2 (each resized to D, zeroed first) + static void dematch(const std::vector& e, int D, int rv, + std::vector& d0, std::vector& d1, std::vector& d2); + +private: + // For each position in the circular buffer, the stream (0..2) and index of the bit it holds, + // or stream -1 for filler bits + static void bufferMap(int D, std::vector& stream, std::vector& index); + static int startPosition(int D, int rv); +}; + +#endif // INCLUDE_LTETURBO_H diff --git a/sdrbase/resources/webapi.qrc b/sdrbase/resources/webapi.qrc index cb8d63630..c961ddbcb 100644 --- a/sdrbase/resources/webapi.qrc +++ b/sdrbase/resources/webapi.qrc @@ -49,6 +49,7 @@ webapi/doc/swagger/include/DOA2.yaml webapi/doc/swagger/include/DSCDemod.yaml webapi/doc/swagger/include/DSDDemod.yaml + webapi/doc/swagger/include/DroneIDDemod.yaml webapi/doc/swagger/include/EndOfTrainDemod.yaml webapi/doc/swagger/include/FCDPro.yaml webapi/doc/swagger/include/FCDProPlus.yaml diff --git a/sdrbase/resources/webapi/doc/swagger/include/ChannelReport.yaml b/sdrbase/resources/webapi/doc/swagger/include/ChannelReport.yaml index fe8fbfaf8..6bf4ca33f 100644 --- a/sdrbase/resources/webapi/doc/swagger/include/ChannelReport.yaml +++ b/sdrbase/resources/webapi/doc/swagger/include/ChannelReport.yaml @@ -69,6 +69,9 @@ ChannelReport: DSDDemodReport: $ref: "/doc/swagger/include/DSDDemod.yaml#/DSDDemodReport" description: "Dsd demod report data for Channel." + DroneIDDemodReport: + $ref: "/doc/swagger/include/DroneIDDemod.yaml#/DroneIDDemodReport" + description: "DroneID demod report data for Channel." EndOfTrainDemodReport: $ref: "/doc/swagger/include/EndOfTrainDemod.yaml#/EndOfTrainDemodReport" description: "End of train demod report data for Channel." diff --git a/sdrbase/resources/webapi/doc/swagger/include/ChannelSettings.yaml b/sdrbase/resources/webapi/doc/swagger/include/ChannelSettings.yaml index d3754b4dd..085f6f3b4 100644 --- a/sdrbase/resources/webapi/doc/swagger/include/ChannelSettings.yaml +++ b/sdrbase/resources/webapi/doc/swagger/include/ChannelSettings.yaml @@ -87,6 +87,9 @@ ChannelSettings: DSDDemodSettings: $ref: "/doc/swagger/include/DSDDemod.yaml#/DSDDemodSettings" description: "Dsd demod settings configuration for Channel." + DroneIDDemodSettings: + $ref: "/doc/swagger/include/DroneIDDemod.yaml#/DroneIDDemodSettings" + description: "DroneID demod settings configuration for Channel." EndOfTrainDemodSettings: $ref: "/doc/swagger/include/EndOfTrainDemod.yaml#/EndOfTrainDemodSettings" description: "End of train demod settings configuration for Channel." diff --git a/sdrbase/resources/webapi/doc/swagger/include/DroneIDDemod.yaml b/sdrbase/resources/webapi/doc/swagger/include/DroneIDDemod.yaml new file mode 100644 index 000000000..fcfdc7924 --- /dev/null +++ b/sdrbase/resources/webapi/doc/swagger/include/DroneIDDemod.yaml @@ -0,0 +1,125 @@ +DroneIDDemodSettings: + description: DroneIDDemod + properties: + inputFrequencyOffset: + type: integer + format: int64 + description: "Channel frequency offset from the device center frequency in Hz." + detectionThreshold: + type: number + format: float + description: "Normalised cyclic prefix correlation threshold (0-1) for burst detection." + turboIterations: + type: integer + description: "Maximum number of turbo decoder iterations." + filterSerial: + type: string + description: "Regular expression to filter serial numbers displayed in the table." + mapTimeout: + type: integer + description: "Time in seconds after last message, before drone is removed from the map. 0 to never remove." + mapAltitude: + description: "Which value is used for the drone's altitude on the map (0 - Altitude above WGS84 ellipsoid, 1 - Height above take-off point, relative to ground)" + type: integer + scan: + description: "Whether to scan DroneID channels, by changing the device center frequency" + type: integer + minimum: 0 + maximum: 1 + scanBand: + description: "Channels to scan (0 - 2.4GHz, 1 - 5.8GHz, 2 - 2.4 and 5.8GHz)" + type: integer + scanDwell: + description: "Time in seconds to wait on each channel for a burst when scanning." + type: number + format: float + scanHold: + description: "Time in seconds to remain on a channel after the last burst was detected when scanning." + type: number + format: float + udpEnabled: + description: "Whether to forward received messages to specified UDP port" + type: integer + minimum: 0 + maximum: 1 + udpAddress: + description: "UDP address to forward received messages to" + type: string + udpPort: + description: "UDP port to forward received messages to" + type: integer + minimum: 1 + maximum: 65535 + logFilename: + type: string + description: "Log file name or path." + logEnabled: + type: integer + description: "Enable logging to the configured file (1 enabled, 0 disabled)." + minimum: 0 + maximum: 1 + useFileTime: + type: integer + description: "Use time from File Input device rather than system time (1 enabled, 0 disabled)." + minimum: 0 + maximum: 1 + rgbColor: + type: integer + description: "Display color encoded as an RGB integer." + title: + type: string + description: "User-visible title." + streamIndex: + description: MIMO channel. Not relevant when connected to SI (single Rx). + type: integer + useReverseAPI: + description: Synchronize with reverse API (1 for yes, 0 for no) + type: integer + minimum: 0 + maximum: 1 + reverseAPIAddress: + type: string + description: "IPv4 address or host name of the reverse API peer." + reverseAPIPort: + type: integer + description: "TCP port of the reverse API peer." + minimum: 1 + maximum: 65535 + reverseAPIDeviceIndex: + type: integer + description: "Device-set index used by the reverse API peer." + reverseAPIChannelIndex: + type: integer + description: "Channel index used by the reverse API peer." + channelMarker: + $ref: "/doc/swagger/include/ChannelMarker.yaml#/ChannelMarker" + description: "Channel-marker display configuration." + rollupState: + $ref: "/doc/swagger/include/RollupState.yaml#/RollupState" + description: "Saved expanded or collapsed state of the GUI sections." + +DroneIDDemodReport: + description: DroneIDDemod + properties: + channelPowerDB: + description: power received in channel (dB) + type: number + format: float + channelSampleRate: + type: integer + description: "Effective sample rate delivered to the channel in samples per second." + burstsDetected: + type: integer + description: "Number of bursts detected." + burstsDecoded: + type: integer + description: "Number of bursts successfully decoded." + burstsDropped: + type: integer + description: "Number of bursts dropped because the decoder was busy." + dronesTracked: + type: integer + description: "Number of drones currently being tracked." + scanLocked: + type: integer + description: "1 if scanning is paused on a channel where DroneID bursts are being received, 0 otherwise." diff --git a/sdrbase/util/crc.h b/sdrbase/util/crc.h index 8d15ba23f..0b372f887 100644 --- a/sdrbase/util/crc.h +++ b/sdrbase/util/crc.h @@ -131,4 +131,18 @@ public: crcadsb() : crc(24, 0xfff409, true, 0, 0) {} }; +// LTE CRC24A - 3GPP TS 36.212 section 5.1.1 +class SDRBASE_API crc24a : public crc +{ +public: + crc24a() : crc(24, 0x864cfb, true, 0, 0) {} +}; + +// DJI DroneID payload CRC +class SDRBASE_API crc16droneid : public crc +{ +public: + crc16droneid() : crc(16, 0x1021, false, 0x3692, 0) {} +}; + #endif diff --git a/sdrbase/util/droneid.cpp b/sdrbase/util/droneid.cpp new file mode 100644 index 000000000..ddc992f05 --- /dev/null +++ b/sdrbase/util/droneid.cpp @@ -0,0 +1,299 @@ +/////////////////////////////////////////////////////////////////////////////////// +// Copyright (C) 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 . // +/////////////////////////////////////////////////////////////////////////////////// + +#include +#include + +#include +#include + +#include "util/crc.h" + +#include "droneid.h" + +uint16_t DroneIDMessage::getU16(const uint8_t *p) +{ + return p[0] | (p[1] << 8); +} + +int16_t DroneIDMessage::getS16(const uint8_t *p) +{ + return (int16_t) getU16(p); +} + +int32_t DroneIDMessage::getS32(const uint8_t *p) +{ + return (int32_t) ((uint32_t) p[0] | ((uint32_t) p[1] << 8) | ((uint32_t) p[2] << 16) | ((uint32_t) p[3] << 24)); +} + +uint64_t DroneIDMessage::getU64(const uint8_t *p) +{ + uint64_t v = 0; + for (int i = 7; i >= 0; i--) { + v = (v << 8) | p[i]; + } + return v; +} + +// Positions are transmitted in radians * 1e7 +double DroneIDMessage::toDegrees(int32_t v) +{ + return (v / 1.0e7) * (180.0 / M_PI); +} + +QString DroneIDMessage::getString(const uint8_t *p, int maxLength) +{ + int len = 0; + while ((len < maxLength) && (p[len] != 0)) { + len++; + } + return QString::fromLatin1((const char *) p, len).trimmed(); +} + +uint16_t DroneIDMessage::calcCRC(const uint8_t *bytes, int length) +{ + crc16droneid crc; + crc.calculate(bytes, length); + return crc.get(); +} + +int DroneIDMessage::messageLength(const QByteArray& bytes) +{ + if (bytes.size() < 3) { + return -1; + } + int length = (uint8_t) bytes[0] + 3; + if (length > bytes.size()) { + return -1; + } + return length; +} + +DroneIDMessage* DroneIDMessage::decode(const QByteArray& bytes) +{ + int length = messageLength(bytes); + if (length < 0) { + return nullptr; + } + + const uint8_t *p = (const uint8_t *) bytes.data(); + uint8_t type = p[1]; + + if (type == FlightInformation) + { + // Versions 1 to 3 seen + if ((length < m_flightInfoLength) || (p[2] < 1) || (p[2] > 3)) { + return nullptr; + } + } + else if (type == FlightPurpose) + { + if (length < 2 + 16 + 2) { + return nullptr; + } + } + else + { + return nullptr; + } + + DroneIDMessage *msg = new DroneIDMessage(); + + msg->m_packetLength = p[0]; + msg->m_type = type; + msg->m_crc = getU16(&p[length - 2]); + msg->m_crcValid = calcCRC(p, length - 2) == msg->m_crc; + + if (type == FlightInformation) + { + msg->m_version = p[2]; + msg->m_sequence = getU16(&p[3]); + msg->m_stateInfo = getU16(&p[5]); + msg->m_serial = getString(&p[7], 16); + msg->m_longitude = toDegrees(getS32(&p[23])); + msg->m_latitude = toDegrees(getS32(&p[27])); + // Units of altitude and height are not documented. Sources differ, so these need confirming with real data. + msg->m_altitude = getS16(&p[31]); + msg->m_height = getS16(&p[33]) / 10.0f; + msg->m_vNorth = getS16(&p[35]) / 100.0f; + msg->m_vEast = getS16(&p[37]) / 100.0f; + msg->m_vUp = getS16(&p[39]) / 100.0f; + msg->m_yaw = getS16(&p[41]) / 100.0f; + uint64_t gpsTime = getU64(&p[43]); + if (gpsTime != 0) { + msg->m_gpsTime = QDateTime::fromMSecsSinceEpoch((qint64) gpsTime).toUTC(); + } + msg->m_pilotLatitude = toDegrees(getS32(&p[51])); + msg->m_pilotLongitude = toDegrees(getS32(&p[55])); + msg->m_homeLongitude = toDegrees(getS32(&p[59])); + msg->m_homeLatitude = toDegrees(getS32(&p[63])); + msg->m_productType = p[67]; + int uuidLength = std::min((int) p[68], 20); + msg->m_uuid = getString(&p[69], uuidLength); + } + else + { + msg->m_serial = getString(&p[2], 16); + msg->m_purpose = bytes.mid(18, length - 18 - 2); + } + + return msg; +} + +bool DroneIDMessage::validPosition(double latitude, double longitude) +{ + return (latitude != 0.0) && (longitude != 0.0) + && (std::abs(latitude) <= 90.0) && (std::abs(longitude) <= 180.0); +} + +bool DroneIDMessage::hasPosition() const +{ + return validPosition(m_latitude, m_longitude); +} + +bool DroneIDMessage::hasPilotPosition() const +{ + return validPosition(m_pilotLatitude, m_pilotLongitude); +} + +bool DroneIDMessage::hasHomePosition() const +{ + return validPosition(m_homeLatitude, m_homeLongitude); +} + +float DroneIDMessage::getSpeed() const +{ + return std::sqrt(m_vNorth * m_vNorth + m_vEast * m_vEast); +} + +float DroneIDMessage::getCourse() const +{ + float course = std::atan2(m_vEast, m_vNorth) * (180.0f / (float) M_PI); + if (course < 0.0f) { + course += 360.0f; + } + return course; +} + +QString DroneIDMessage::getStateInfoString() const +{ + QStringList flags; + + if (m_stateInfo & MotorsOn) { + flags.append("Motors on"); + } + if (m_stateInfo & InAir) { + flags.append("In air"); + } + if (m_stateInfo & GPSValid) { + flags.append("GPS"); + } + if (m_stateInfo & HomeValid) { + flags.append("Home"); + } + if (m_stateInfo & PrivacyEnabled) { + flags.append("Privacy"); + } + return flags.join(", "); +} + +QString DroneIDMessage::productTypeName(int productType) +{ + // Codes from DroneSecurity, Kismet and others. Codes above 70 are less well verified. + static const QMap names = { + {1, "Inspire 1"}, + {2, "Phantom 3 Series"}, + {3, "Phantom 3 Series Pro"}, + {4, "Phantom 3 Std"}, + {5, "M100"}, + {6, "ACEONE"}, + {7, "WKM"}, + {8, "NAZA"}, + {9, "A2"}, + {10, "A3"}, + {11, "Phantom 4"}, + {12, "MG1"}, + {14, "M600"}, + {15, "Phantom 3 4K"}, + {16, "Mavic Pro"}, + {17, "Inspire 2"}, + {18, "Phantom 4 Pro"}, + {20, "N2"}, + {21, "Spark"}, + {23, "M600 Pro"}, + {24, "Mavic Air"}, + {25, "M200"}, + {26, "Phantom 4 Series"}, + {27, "Phantom 4 Adv"}, + {28, "M210"}, + {30, "M210 RTK"}, + {31, "A3 AG"}, + {32, "MG2"}, + {34, "MG1A"}, + {35, "Phantom 4 RTK"}, + {36, "Phantom 4 Pro V2.0"}, + {38, "MG1P"}, + {40, "MG1P-RTK"}, + {41, "Mavic 2"}, + {44, "M200 V2 Series"}, + {51, "Mavic 2 Enterprise"}, + {53, "Mavic Mini"}, + {58, "Mavic Air 2"}, + {59, "P4M"}, + {60, "M300 RTK"}, + {61, "DJI FPV"}, + {63, "Mini 2"}, + {64, "AGRAS T10"}, + {65, "AGRAS T30"}, + {66, "Air 2S"}, + {67, "M30"}, + {68, "Mavic 3"}, + {69, "Mavic 2 Enterprise Advanced"}, + {70, "Mini SE"}, + {73, "Mini 3 Pro"}, + {75, "Avata"}, + {77, "Mavic 3 Enterprise"}, + {82, "AGRAS T25"}, + {83, "AGRAS T50"}, + {86, "Mavic 3 Classic"}, + {87, "Mini 3"}, + {88, "Mini 2 SE"}, + {90, "Air 3"} + }; + + return names.value(productType, QString("Unknown (%1)").arg(productType)); +} + +QString DroneIDMessage::toString() const +{ + if (!isFlightInformation()) { + return QString("Flight purpose %1").arg(m_serial); + } + return QString("%1 %2 seq %3 lat %4 lon %5 alt %6 height %7 pilot %8,%9 home %10,%11") + .arg(getProductTypeName()) + .arg(m_serial) + .arg(m_sequence) + .arg(m_latitude, 0, 'f', 6) + .arg(m_longitude, 0, 'f', 6) + .arg(m_altitude) + .arg(m_height) + .arg(m_pilotLatitude, 0, 'f', 6) + .arg(m_pilotLongitude, 0, 'f', 6) + .arg(m_homeLatitude, 0, 'f', 6) + .arg(m_homeLongitude, 0, 'f', 6); +} diff --git a/sdrbase/util/droneid.h b/sdrbase/util/droneid.h new file mode 100644 index 000000000..eb3b3b882 --- /dev/null +++ b/sdrbase/util/droneid.h @@ -0,0 +1,142 @@ +/////////////////////////////////////////////////////////////////////////////////// +// Copyright (C) 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 . // +/////////////////////////////////////////////////////////////////////////////////// + +#ifndef INCLUDE_DRONEID_H +#define INCLUDE_DRONEID_H + +#include + +#include +#include +#include + +#include "export.h" + +// DJI DroneID message, as broadcast by OcuSync drones. +// Flight information message layout from "Drone Security and the Mysterious Case of DJI's DroneID", NDSS 2023, Fig. 13. +// Messages start with a length byte (excluding first 3 bytes) and type, and end with a CRC16. +class SDRBASE_API DroneIDMessage { +public: + + enum MessageType { + FlightInformation = 0x10, // Position, velocity, pilot and home position + FlightPurpose = 0x11 // Serial number and (optional) flight purpose + }; + + static constexpr int m_flightInfoLength = 91; // Bytes, including CRC + + // state_info flags (provisional, from the Wi-Fi beacon variant of DroneID) + enum StateFlags { + SerialValid = 0x0001, + PrivacyEnabled = 0x0002, + HomeValid = 0x0004, + UUIDValid = 0x0008, + MotorsOn = 0x0010, + InAir = 0x0020, + GPSValid = 0x0040, + AltitudeValid = 0x0080, + HeightValid = 0x0100, + HorizontalVelocityValid = 0x0200, + VerticalVelocityValid = 0x0400 + }; + + uint8_t m_packetLength; + uint8_t m_type; + uint8_t m_version; + uint16_t m_sequence; + uint16_t m_stateInfo; + QString m_serial; + double m_latitude; // Degrees + double m_longitude; // Degrees + float m_altitude; // Metres above WGS84 ellipsoid (GPS height, not MSL) + float m_height; // Metres above take-off point + float m_vNorth; // m/s + float m_vEast; // m/s + float m_vUp; // m/s + float m_yaw; // Degrees + QDateTime m_gpsTime; // From the pilot's phone + double m_pilotLatitude; // Degrees + double m_pilotLongitude; // Degrees + double m_homeLatitude; // Degrees + double m_homeLongitude; // Degrees + uint8_t m_productType; + QString m_uuid; + QByteArray m_purpose; // Remaining bytes of flight purpose message + uint16_t m_crc; // CRC in message + bool m_crcValid; // Whether CRC in message matches calculated + + DroneIDMessage() : + m_packetLength(0), + m_type(0), + m_version(0), + m_sequence(0), + m_stateInfo(0), + m_latitude(0.0), + m_longitude(0.0), + m_altitude(0.0f), + m_height(0.0f), + m_vNorth(0.0f), + m_vEast(0.0f), + m_vUp(0.0f), + m_yaw(0.0f), + m_pilotLatitude(0.0), + m_pilotLongitude(0.0), + m_homeLatitude(0.0), + m_homeLongitude(0.0), + m_productType(0), + m_crc(0), + m_crcValid(false) + {} + + // Decode a DroneID message. Returns nullptr if bytes is too short or doesn't look like a DroneID message. + // Message is still returned if CRC is invalid, as it is protected by the PHY layer CRC. + static DroneIDMessage* decode(const QByteArray& bytes); + + // Length of message at start of bytes, including CRC, or -1 if invalid + static int messageLength(const QByteArray& bytes); + + bool isFlightInformation() const { return m_type == FlightInformation; } + + // Calculate CRC for first length-2 bytes of message + static uint16_t calcCRC(const uint8_t *bytes, int length); + + bool hasPosition() const; + bool hasPilotPosition() const; + bool hasHomePosition() const; + float getSpeed() const; // Horizontal ground speed in m/s + float getCourse() const; // Ground track in degrees from velocity + QString getProductTypeName() const { return productTypeName(m_productType); } + QString getStateInfoString() const; + + static QString productTypeName(int productType); + + QString toString() const; + +private: + static bool validPosition(double latitude, double longitude); + + // Little-endian field access + static uint16_t getU16(const uint8_t *p); + static int16_t getS16(const uint8_t *p); + static int32_t getS32(const uint8_t *p); + static uint64_t getU64(const uint8_t *p); + static double toDegrees(int32_t v); + static QString getString(const uint8_t *p, int maxLength); +}; + +#endif // INCLUDE_DRONEID_H diff --git a/sdrbase/util/ltegold.cpp b/sdrbase/util/ltegold.cpp new file mode 100644 index 000000000..70bf9a97e --- /dev/null +++ b/sdrbase/util/ltegold.cpp @@ -0,0 +1,41 @@ +/////////////////////////////////////////////////////////////////////////////////// +// Copyright (C) 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 . // +/////////////////////////////////////////////////////////////////////////////////// + +#include "ltegold.h" + +void LTEGold::generate(uint32_t cInit, int length, std::vector& c) +{ + const int Nc = 1600; + // Bit n of each register holds x(n+i) for the current position i + uint32_t x1 = 1; + uint32_t x2 = cInit & 0x7fffffff; + + c.resize(length); + for (int n = 0; n < Nc + length; n++) + { + if (n >= Nc) { + c[n - Nc] = (x1 ^ x2) & 1; + } + // x1(n+31) = x1(n+3) + x1(n) + uint32_t b1 = ((x1 >> 3) ^ x1) & 1; + // x2(n+31) = x2(n+3) + x2(n+2) + x2(n+1) + x2(n) + uint32_t b2 = ((x2 >> 3) ^ (x2 >> 2) ^ (x2 >> 1) ^ x2) & 1; + x1 = (x1 >> 1) | (b1 << 30); + x2 = (x2 >> 1) | (b2 << 30); + } +} diff --git a/sdrbase/util/ltegold.h b/sdrbase/util/ltegold.h new file mode 100644 index 000000000..6860779c2 --- /dev/null +++ b/sdrbase/util/ltegold.h @@ -0,0 +1,36 @@ +/////////////////////////////////////////////////////////////////////////////////// +// Copyright (C) 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 . // +/////////////////////////////////////////////////////////////////////////////////// + +#ifndef INCLUDE_LTEGOLD_H +#define INCLUDE_LTEGOLD_H + +#include +#include + +#include "export.h" + +// Length-31 Gold sequence pseudo-random generator, as used for scrambling in LTE. +// See 3GPP TS 36.211 section 7.2. +class SDRBASE_API LTEGold +{ +public: + // Generate length bits c(0)..c(length-1) (one bit per byte) for initialisation value cInit + static void generate(uint32_t cInit, int length, std::vector& c); +}; + +#endif // INCLUDE_LTEGOLD_H diff --git a/sdrbase/webapi/webapirequestmapper.cpp b/sdrbase/webapi/webapirequestmapper.cpp index 603b5233f..31e09dbc1 100644 --- a/sdrbase/webapi/webapirequestmapper.cpp +++ b/sdrbase/webapi/webapirequestmapper.cpp @@ -4990,6 +4990,12 @@ bool WebAPIRequestMapper::getChannelSettings( channelSettings->getDsdDemodSettings()->init(); channelSettings->getDsdDemodSettings()->fromJsonObject(settingsJsonObject); } + else if (channelSettingsKey == "DroneIDDemodSettings") + { + channelSettings->setDroneIdDemodSettings(new SWGSDRangel::SWGDroneIDDemodSettings()); + channelSettings->getDroneIdDemodSettings()->init(); + channelSettings->getDroneIdDemodSettings()->fromJsonObject(settingsJsonObject); + } else if (channelSettingsKey == "EndOfTrainDemodSettings") { channelSettings->setEndOfTrainDemodSettings(new SWGSDRangel::SWGEndOfTrainDemodSettings()); @@ -6089,6 +6095,7 @@ void WebAPIRequestMapper::resetChannelSettings(SWGSDRangel::SWGChannelSettings& channelSettings.setDvbDemodSettings(nullptr); channelSettings.setDabDemodSettings(nullptr); channelSettings.setDsdDemodSettings(nullptr); + channelSettings.setDroneIdDemodSettings(nullptr); channelSettings.setEndOfTrainDemodSettings(nullptr); channelSettings.setFreqScannerSettings(nullptr); channelSettings.setFreqTrackerSettings(nullptr); @@ -6139,6 +6146,7 @@ void WebAPIRequestMapper::resetChannelReport(SWGSDRangel::SWGChannelReport& chan channelReport.setDatvModReport(nullptr); channelReport.setDvbDemodReport(nullptr); channelReport.setDsdDemodReport(nullptr); + channelReport.setDroneIdDemodReport(nullptr); channelReport.setEndOfTrainDemodReport(nullptr); channelReport.setFreqScannerReport(nullptr); channelReport.setFreqTrackerReport(nullptr); diff --git a/sdrbase/webapi/webapiutils.cpp b/sdrbase/webapi/webapiutils.cpp index 7823beea3..040e1cb69 100644 --- a/sdrbase/webapi/webapiutils.cpp +++ b/sdrbase/webapi/webapiutils.cpp @@ -49,6 +49,7 @@ const QMap WebAPIUtils::m_channelURIToSettingsKey = { {"sdrangel.channel.doa2", "DOA2Settings"}, {"sdrangel.channel.dscdemod", "DSCDemodSettings"}, {"sdrangel.channel.dsddemod", "DSDDemodSettings"}, + {"sdrangel.channel.droneiddemod", "DroneIDDemodSettings"}, {"sdrangel.channel.endoftraindemod", "EndOfTrainDemodSettings"}, {"sdrangel.channel.filesink", "FileSinkSettings"}, {"sdrangel.channeltx.filesource", "FileSourceSettings"}, @@ -184,6 +185,7 @@ const QMap WebAPIUtils::m_channelTypeToSettingsKey = { {"DOA2", "DOA2Settings"}, {"DSCDemod", "DSCDemodSettings"}, {"DSDDemod", "DSDDemodSettings"}, + {"DroneIDDemod", "DroneIDDemodSettings"}, {"EndOfTrainDemod", "EndOfTrainDemodSettings"}, {"FileSink", "FileSinkSettings"}, {"FileSource", "FileSourceSettings"}, diff --git a/swagger/sdrangel/api/swagger/include/ChannelReport.yaml b/swagger/sdrangel/api/swagger/include/ChannelReport.yaml index 82360044b..087712907 100644 --- a/swagger/sdrangel/api/swagger/include/ChannelReport.yaml +++ b/swagger/sdrangel/api/swagger/include/ChannelReport.yaml @@ -69,6 +69,9 @@ ChannelReport: DSDDemodReport: $ref: "http://swgserver:8081/api/swagger/include/DSDDemod.yaml#/DSDDemodReport" description: "Dsd demod report data for Channel." + DroneIDDemodReport: + $ref: "http://swgserver:8081/api/swagger/include/DroneIDDemod.yaml#/DroneIDDemodReport" + description: "DroneID demod report data for Channel." EndOfTrainDemodReport: $ref: "http://swgserver:8081/api/swagger/include/EndOfTrainDemod.yaml#/EndOfTrainDemodReport" description: "End of train demod report data for Channel." diff --git a/swagger/sdrangel/api/swagger/include/ChannelSettings.yaml b/swagger/sdrangel/api/swagger/include/ChannelSettings.yaml index f9ca7a1bd..79e9b8c29 100644 --- a/swagger/sdrangel/api/swagger/include/ChannelSettings.yaml +++ b/swagger/sdrangel/api/swagger/include/ChannelSettings.yaml @@ -87,6 +87,9 @@ ChannelSettings: DSDDemodSettings: $ref: "http://swgserver:8081/api/swagger/include/DSDDemod.yaml#/DSDDemodSettings" description: "Dsd demod settings configuration for Channel." + DroneIDDemodSettings: + $ref: "http://swgserver:8081/api/swagger/include/DroneIDDemod.yaml#/DroneIDDemodSettings" + description: "DroneID demod settings configuration for Channel." EndOfTrainDemodSettings: $ref: "http://swgserver:8081/api/swagger/include/EndOfTrainDemod.yaml#/EndOfTrainDemodSettings" description: "End of train demod settings configuration for Channel." diff --git a/swagger/sdrangel/api/swagger/include/DroneIDDemod.yaml b/swagger/sdrangel/api/swagger/include/DroneIDDemod.yaml new file mode 100644 index 000000000..a8eb0be75 --- /dev/null +++ b/swagger/sdrangel/api/swagger/include/DroneIDDemod.yaml @@ -0,0 +1,125 @@ +DroneIDDemodSettings: + description: DroneIDDemod + properties: + inputFrequencyOffset: + type: integer + format: int64 + description: "Channel frequency offset from the device center frequency in Hz." + detectionThreshold: + type: number + format: float + description: "Normalised cyclic prefix correlation threshold (0-1) for burst detection." + turboIterations: + type: integer + description: "Maximum number of turbo decoder iterations." + filterSerial: + type: string + description: "Regular expression to filter serial numbers displayed in the table." + mapTimeout: + type: integer + description: "Time in seconds after last message, before drone is removed from the map. 0 to never remove." + mapAltitude: + description: "Which value is used for the drone's altitude on the map (0 - Altitude above WGS84 ellipsoid, 1 - Height above take-off point, relative to ground)" + type: integer + scan: + description: "Whether to scan DroneID channels, by changing the device center frequency" + type: integer + minimum: 0 + maximum: 1 + scanBand: + description: "Channels to scan (0 - 2.4GHz, 1 - 5.8GHz, 2 - 2.4 and 5.8GHz)" + type: integer + scanDwell: + description: "Time in seconds to wait on each channel for a burst when scanning." + type: number + format: float + scanHold: + description: "Time in seconds to remain on a channel after the last burst was detected when scanning." + type: number + format: float + udpEnabled: + description: "Whether to forward received messages to specified UDP port" + type: integer + minimum: 0 + maximum: 1 + udpAddress: + description: "UDP address to forward received messages to" + type: string + udpPort: + description: "UDP port to forward received messages to" + type: integer + minimum: 1 + maximum: 65535 + logFilename: + type: string + description: "Log file name or path." + logEnabled: + type: integer + description: "Enable logging to the configured file (1 enabled, 0 disabled)." + minimum: 0 + maximum: 1 + useFileTime: + type: integer + description: "Use time from File Input device rather than system time (1 enabled, 0 disabled)." + minimum: 0 + maximum: 1 + rgbColor: + type: integer + description: "Display color encoded as an RGB integer." + title: + type: string + description: "User-visible title." + streamIndex: + description: MIMO channel. Not relevant when connected to SI (single Rx). + type: integer + useReverseAPI: + description: Synchronize with reverse API (1 for yes, 0 for no) + type: integer + minimum: 0 + maximum: 1 + reverseAPIAddress: + type: string + description: "IPv4 address or host name of the reverse API peer." + reverseAPIPort: + type: integer + description: "TCP port of the reverse API peer." + minimum: 1 + maximum: 65535 + reverseAPIDeviceIndex: + type: integer + description: "Device-set index used by the reverse API peer." + reverseAPIChannelIndex: + type: integer + description: "Channel index used by the reverse API peer." + channelMarker: + $ref: "http://swgserver:8081/api/swagger/include/ChannelMarker.yaml#/ChannelMarker" + description: "Channel-marker display configuration." + rollupState: + $ref: "http://swgserver:8081/api/swagger/include/RollupState.yaml#/RollupState" + description: "Saved expanded or collapsed state of the GUI sections." + +DroneIDDemodReport: + description: DroneIDDemod + properties: + channelPowerDB: + description: power received in channel (dB) + type: number + format: float + channelSampleRate: + type: integer + description: "Effective sample rate delivered to the channel in samples per second." + burstsDetected: + type: integer + description: "Number of bursts detected." + burstsDecoded: + type: integer + description: "Number of bursts successfully decoded." + burstsDropped: + type: integer + description: "Number of bursts dropped because the decoder was busy." + dronesTracked: + type: integer + description: "Number of drones currently being tracked." + scanLocked: + type: integer + description: "1 if scanning is paused on a channel where DroneID bursts are being received, 0 otherwise." diff --git a/swagger/sdrangel/code/qt5/client/SWGChannelReport.cpp b/swagger/sdrangel/code/qt5/client/SWGChannelReport.cpp index 39a9613f2..ed42ee962 100644 --- a/swagger/sdrangel/code/qt5/client/SWGChannelReport.cpp +++ b/swagger/sdrangel/code/qt5/client/SWGChannelReport.cpp @@ -70,6 +70,8 @@ SWGChannelReport::SWGChannelReport() { m_dsc_demod_report_isSet = false; dsd_demod_report = nullptr; m_dsd_demod_report_isSet = false; + drone_id_demod_report = nullptr; + m_drone_id_demod_report_isSet = false; end_of_train_demod_report = nullptr; m_end_of_train_demod_report_isSet = false; ieee_802_15_4_mod_report = nullptr; @@ -204,6 +206,8 @@ SWGChannelReport::init() { m_dsc_demod_report_isSet = false; dsd_demod_report = new SWGDSDDemodReport(); m_dsd_demod_report_isSet = false; + drone_id_demod_report = new SWGDroneIDDemodReport(); + m_drone_id_demod_report_isSet = false; end_of_train_demod_report = new SWGEndOfTrainDemodReport(); m_end_of_train_demod_report_isSet = false; ieee_802_15_4_mod_report = new SWGIEEE_802_15_4_ModReport(); @@ -353,6 +357,9 @@ SWGChannelReport::cleanup() { if(dsd_demod_report != nullptr) { delete dsd_demod_report; } + if(drone_id_demod_report != nullptr) { + delete drone_id_demod_report; + } if(end_of_train_demod_report != nullptr) { delete end_of_train_demod_report; } @@ -532,6 +539,8 @@ SWGChannelReport::fromJsonObject(QJsonObject &pJson) { ::SWGSDRangel::setValue(&dsd_demod_report, pJson["DSDDemodReport"], "SWGDSDDemodReport", "SWGDSDDemodReport"); + ::SWGSDRangel::setValue(&drone_id_demod_report, pJson["DroneIDDemodReport"], "SWGDroneIDDemodReport", "SWGDroneIDDemodReport"); + ::SWGSDRangel::setValue(&end_of_train_demod_report, pJson["EndOfTrainDemodReport"], "SWGEndOfTrainDemodReport", "SWGEndOfTrainDemodReport"); ::SWGSDRangel::setValue(&ieee_802_15_4_mod_report, pJson["IEEE_802_15_4_ModReport"], "SWGIEEE_802_15_4_ModReport", "SWGIEEE_802_15_4_ModReport"); @@ -694,6 +703,9 @@ SWGChannelReport::asJsonObject() { if((dsd_demod_report != nullptr) && (dsd_demod_report->isSet())){ toJsonValue(QString("DSDDemodReport"), dsd_demod_report, obj, QString("SWGDSDDemodReport")); } + if((drone_id_demod_report != nullptr) && (drone_id_demod_report->isSet())){ + toJsonValue(QString("DroneIDDemodReport"), drone_id_demod_report, obj, QString("SWGDroneIDDemodReport")); + } if((end_of_train_demod_report != nullptr) && (end_of_train_demod_report->isSet())){ toJsonValue(QString("EndOfTrainDemodReport"), end_of_train_demod_report, obj, QString("SWGEndOfTrainDemodReport")); } @@ -1034,6 +1046,16 @@ SWGChannelReport::setDsdDemodReport(SWGDSDDemodReport* dsd_demod_report) { this->m_dsd_demod_report_isSet = true; } +SWGDroneIDDemodReport* +SWGChannelReport::getDroneIdDemodReport() { + return drone_id_demod_report; +} +void +SWGChannelReport::setDroneIdDemodReport(SWGDroneIDDemodReport* drone_id_demod_report) { + this->drone_id_demod_report = drone_id_demod_report; + this->m_drone_id_demod_report_isSet = true; +} + SWGEndOfTrainDemodReport* SWGChannelReport::getEndOfTrainDemodReport() { return end_of_train_demod_report; @@ -1522,6 +1544,9 @@ SWGChannelReport::isSet(){ if(dsd_demod_report && dsd_demod_report->isSet()){ isObjectUpdated = true; break; } + if(drone_id_demod_report && drone_id_demod_report->isSet()){ + isObjectUpdated = true; break; + } if(end_of_train_demod_report && end_of_train_demod_report->isSet()){ isObjectUpdated = true; break; } diff --git a/swagger/sdrangel/code/qt5/client/SWGChannelReport.h b/swagger/sdrangel/code/qt5/client/SWGChannelReport.h index 43129d375..0a0592a2f 100644 --- a/swagger/sdrangel/code/qt5/client/SWGChannelReport.h +++ b/swagger/sdrangel/code/qt5/client/SWGChannelReport.h @@ -41,6 +41,7 @@ #include "SWGDOA2Report.h" #include "SWGDSCDemodReport.h" #include "SWGDSDDemodReport.h" +#include "SWGDroneIDDemodReport.h" #include "SWGEndOfTrainDemodReport.h" #include "SWGFT8DemodReport.h" #include "SWGFileSinkReport.h" @@ -166,6 +167,9 @@ public: SWGDSDDemodReport* getDsdDemodReport(); void setDsdDemodReport(SWGDSDDemodReport* dsd_demod_report); + SWGDroneIDDemodReport* getDroneIdDemodReport(); + void setDroneIdDemodReport(SWGDroneIDDemodReport* drone_id_demod_report); + SWGEndOfTrainDemodReport* getEndOfTrainDemodReport(); void setEndOfTrainDemodReport(SWGEndOfTrainDemodReport* end_of_train_demod_report); @@ -359,6 +363,9 @@ private: SWGDSDDemodReport* dsd_demod_report; bool m_dsd_demod_report_isSet; + SWGDroneIDDemodReport* drone_id_demod_report; + bool m_drone_id_demod_report_isSet; + SWGEndOfTrainDemodReport* end_of_train_demod_report; bool m_end_of_train_demod_report_isSet; diff --git a/swagger/sdrangel/code/qt5/client/SWGChannelSettings.cpp b/swagger/sdrangel/code/qt5/client/SWGChannelSettings.cpp index 15c903635..c5c90969f 100644 --- a/swagger/sdrangel/code/qt5/client/SWGChannelSettings.cpp +++ b/swagger/sdrangel/code/qt5/client/SWGChannelSettings.cpp @@ -82,6 +82,8 @@ SWGChannelSettings::SWGChannelSettings() { m_dsc_demod_settings_isSet = false; dsd_demod_settings = nullptr; m_dsd_demod_settings_isSet = false; + drone_id_demod_settings = nullptr; + m_drone_id_demod_settings_isSet = false; end_of_train_demod_settings = nullptr; m_end_of_train_demod_settings_isSet = false; file_sink_settings = nullptr; @@ -238,6 +240,8 @@ SWGChannelSettings::init() { m_dsc_demod_settings_isSet = false; dsd_demod_settings = new SWGDSDDemodSettings(); m_dsd_demod_settings_isSet = false; + drone_id_demod_settings = new SWGDroneIDDemodSettings(); + m_drone_id_demod_settings_isSet = false; end_of_train_demod_settings = new SWGEndOfTrainDemodSettings(); m_end_of_train_demod_settings_isSet = false; file_sink_settings = new SWGFileSinkSettings(); @@ -411,6 +415,9 @@ SWGChannelSettings::cleanup() { if(dsd_demod_settings != nullptr) { delete dsd_demod_settings; } + if(drone_id_demod_settings != nullptr) { + delete drone_id_demod_settings; + } if(end_of_train_demod_settings != nullptr) { delete end_of_train_demod_settings; } @@ -617,6 +624,8 @@ SWGChannelSettings::fromJsonObject(QJsonObject &pJson) { ::SWGSDRangel::setValue(&dsd_demod_settings, pJson["DSDDemodSettings"], "SWGDSDDemodSettings", "SWGDSDDemodSettings"); + ::SWGSDRangel::setValue(&drone_id_demod_settings, pJson["DroneIDDemodSettings"], "SWGDroneIDDemodSettings", "SWGDroneIDDemodSettings"); + ::SWGSDRangel::setValue(&end_of_train_demod_settings, pJson["EndOfTrainDemodSettings"], "SWGEndOfTrainDemodSettings", "SWGEndOfTrainDemodSettings"); ::SWGSDRangel::setValue(&file_sink_settings, pJson["FileSinkSettings"], "SWGFileSinkSettings", "SWGFileSinkSettings"); @@ -807,6 +816,9 @@ SWGChannelSettings::asJsonObject() { if((dsd_demod_settings != nullptr) && (dsd_demod_settings->isSet())){ toJsonValue(QString("DSDDemodSettings"), dsd_demod_settings, obj, QString("SWGDSDDemodSettings")); } + if((drone_id_demod_settings != nullptr) && (drone_id_demod_settings->isSet())){ + toJsonValue(QString("DroneIDDemodSettings"), drone_id_demod_settings, obj, QString("SWGDroneIDDemodSettings")); + } if((end_of_train_demod_settings != nullptr) && (end_of_train_demod_settings->isSet())){ toJsonValue(QString("EndOfTrainDemodSettings"), end_of_train_demod_settings, obj, QString("SWGEndOfTrainDemodSettings")); } @@ -1222,6 +1234,16 @@ SWGChannelSettings::setDsdDemodSettings(SWGDSDDemodSettings* dsd_demod_settings) this->m_dsd_demod_settings_isSet = true; } +SWGDroneIDDemodSettings* +SWGChannelSettings::getDroneIdDemodSettings() { + return drone_id_demod_settings; +} +void +SWGChannelSettings::setDroneIdDemodSettings(SWGDroneIDDemodSettings* drone_id_demod_settings) { + this->drone_id_demod_settings = drone_id_demod_settings; + this->m_drone_id_demod_settings_isSet = true; +} + SWGEndOfTrainDemodSettings* SWGChannelSettings::getEndOfTrainDemodSettings() { return end_of_train_demod_settings; @@ -1778,6 +1800,9 @@ SWGChannelSettings::isSet(){ if(dsd_demod_settings && dsd_demod_settings->isSet()){ isObjectUpdated = true; break; } + if(drone_id_demod_settings && drone_id_demod_settings->isSet()){ + isObjectUpdated = true; break; + } if(end_of_train_demod_settings && end_of_train_demod_settings->isSet()){ isObjectUpdated = true; break; } diff --git a/swagger/sdrangel/code/qt5/client/SWGChannelSettings.h b/swagger/sdrangel/code/qt5/client/SWGChannelSettings.h index 2b53cd94e..b42b69692 100644 --- a/swagger/sdrangel/code/qt5/client/SWGChannelSettings.h +++ b/swagger/sdrangel/code/qt5/client/SWGChannelSettings.h @@ -45,6 +45,7 @@ #include "SWGDOA2Settings.h" #include "SWGDSCDemodSettings.h" #include "SWGDSDDemodSettings.h" +#include "SWGDroneIDDemodSettings.h" #include "SWGEndOfTrainDemodSettings.h" #include "SWGFT8DemodSettings.h" #include "SWGFileSinkSettings.h" @@ -193,6 +194,9 @@ public: SWGDSDDemodSettings* getDsdDemodSettings(); void setDsdDemodSettings(SWGDSDDemodSettings* dsd_demod_settings); + SWGDroneIDDemodSettings* getDroneIdDemodSettings(); + void setDroneIdDemodSettings(SWGDroneIDDemodSettings* drone_id_demod_settings); + SWGEndOfTrainDemodSettings* getEndOfTrainDemodSettings(); void setEndOfTrainDemodSettings(SWGEndOfTrainDemodSettings* end_of_train_demod_settings); @@ -419,6 +423,9 @@ private: SWGDSDDemodSettings* dsd_demod_settings; bool m_dsd_demod_settings_isSet; + SWGDroneIDDemodSettings* drone_id_demod_settings; + bool m_drone_id_demod_settings_isSet; + SWGEndOfTrainDemodSettings* end_of_train_demod_settings; bool m_end_of_train_demod_settings_isSet; diff --git a/swagger/sdrangel/code/qt5/client/SWGDroneIDDemodReport.cpp b/swagger/sdrangel/code/qt5/client/SWGDroneIDDemodReport.cpp new file mode 100644 index 000000000..a5620c50e --- /dev/null +++ b/swagger/sdrangel/code/qt5/client/SWGDroneIDDemodReport.cpp @@ -0,0 +1,244 @@ +/** + * SDRangel + * This is the web REST/JSON API of SDRangel SDR software. SDRangel is an Open Source Qt5/OpenGL 3.0+ (4.3+ in Windows) GUI and server Software Defined Radio and signal analyzer in software. It supports Airspy, BladeRF, HackRF, LimeSDR, PlutoSDR, RTL-SDR, SDRplay RSP1 and FunCube --- Limitations and specifcities: * In SDRangel GUI the first Rx device set cannot be deleted. Conversely the server starts with no device sets and its number of device sets can be reduced to zero by as many calls as necessary to /sdrangel/deviceset with DELETE method. * Preset import and export from/to file is a server only feature. * Device set focus is a GUI only feature. * The following channels are not implemented (status 501 is returned): ATV and DATV demodulators, Channel Analyzer NG, LoRa demodulator * The device settings and report structures contains only the sub-structure corresponding to the device type. The DeviceSettings and DeviceReport structures documented here shows all of them but only one will be or should be present at a time * The channel settings and report structures contains only the sub-structure corresponding to the channel type. The ChannelSettings and ChannelReport structures documented here shows all of them but only one will be or should be present at a time --- + * + * OpenAPI spec version: 7.0.0 + * Contact: f4exb06@gmail.com + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + + +#include "SWGDroneIDDemodReport.h" + +#include "SWGHelpers.h" + +#include +#include +#include +#include + +namespace SWGSDRangel { + +SWGDroneIDDemodReport::SWGDroneIDDemodReport(QString* json) { + init(); + this->fromJson(*json); +} + +SWGDroneIDDemodReport::SWGDroneIDDemodReport() { + channel_power_db = 0.0f; + m_channel_power_db_isSet = false; + channel_sample_rate = 0; + m_channel_sample_rate_isSet = false; + bursts_detected = 0; + m_bursts_detected_isSet = false; + bursts_decoded = 0; + m_bursts_decoded_isSet = false; + bursts_dropped = 0; + m_bursts_dropped_isSet = false; + drones_tracked = 0; + m_drones_tracked_isSet = false; + scan_locked = 0; + m_scan_locked_isSet = false; +} + +SWGDroneIDDemodReport::~SWGDroneIDDemodReport() { + this->cleanup(); +} + +void +SWGDroneIDDemodReport::init() { + channel_power_db = 0.0f; + m_channel_power_db_isSet = false; + channel_sample_rate = 0; + m_channel_sample_rate_isSet = false; + bursts_detected = 0; + m_bursts_detected_isSet = false; + bursts_decoded = 0; + m_bursts_decoded_isSet = false; + bursts_dropped = 0; + m_bursts_dropped_isSet = false; + drones_tracked = 0; + m_drones_tracked_isSet = false; + scan_locked = 0; + m_scan_locked_isSet = false; +} + +void +SWGDroneIDDemodReport::cleanup() { + + + + + + +} + +SWGDroneIDDemodReport* +SWGDroneIDDemodReport::fromJson(QString &json) { + QByteArray array (json.toStdString().c_str()); + QJsonDocument doc = QJsonDocument::fromJson(array); + QJsonObject jsonObject = doc.object(); + this->fromJsonObject(jsonObject); + return this; +} + +void +SWGDroneIDDemodReport::fromJsonObject(QJsonObject &pJson) { + ::SWGSDRangel::setValue(&channel_power_db, pJson["channelPowerDB"], "float", ""); + + ::SWGSDRangel::setValue(&channel_sample_rate, pJson["channelSampleRate"], "qint32", ""); + + ::SWGSDRangel::setValue(&bursts_detected, pJson["burstsDetected"], "qint32", ""); + + ::SWGSDRangel::setValue(&bursts_decoded, pJson["burstsDecoded"], "qint32", ""); + + ::SWGSDRangel::setValue(&bursts_dropped, pJson["burstsDropped"], "qint32", ""); + + ::SWGSDRangel::setValue(&drones_tracked, pJson["dronesTracked"], "qint32", ""); + + ::SWGSDRangel::setValue(&scan_locked, pJson["scanLocked"], "qint32", ""); + +} + +QString +SWGDroneIDDemodReport::asJson () +{ + QJsonObject* obj = this->asJsonObject(); + + QJsonDocument doc(*obj); + QByteArray bytes = doc.toJson(); + delete obj; + return QString(bytes); +} + +QJsonObject* +SWGDroneIDDemodReport::asJsonObject() { + QJsonObject* obj = new QJsonObject(); + if(m_channel_power_db_isSet){ + obj->insert("channelPowerDB", QJsonValue(channel_power_db)); + } + if(m_channel_sample_rate_isSet){ + obj->insert("channelSampleRate", QJsonValue(channel_sample_rate)); + } + if(m_bursts_detected_isSet){ + obj->insert("burstsDetected", QJsonValue(bursts_detected)); + } + if(m_bursts_decoded_isSet){ + obj->insert("burstsDecoded", QJsonValue(bursts_decoded)); + } + if(m_bursts_dropped_isSet){ + obj->insert("burstsDropped", QJsonValue(bursts_dropped)); + } + if(m_drones_tracked_isSet){ + obj->insert("dronesTracked", QJsonValue(drones_tracked)); + } + if(m_scan_locked_isSet){ + obj->insert("scanLocked", QJsonValue(scan_locked)); + } + + return obj; +} + +float +SWGDroneIDDemodReport::getChannelPowerDb() { + return channel_power_db; +} +void +SWGDroneIDDemodReport::setChannelPowerDb(float channel_power_db) { + this->channel_power_db = channel_power_db; + this->m_channel_power_db_isSet = true; +} + +qint32 +SWGDroneIDDemodReport::getChannelSampleRate() { + return channel_sample_rate; +} +void +SWGDroneIDDemodReport::setChannelSampleRate(qint32 channel_sample_rate) { + this->channel_sample_rate = channel_sample_rate; + this->m_channel_sample_rate_isSet = true; +} + +qint32 +SWGDroneIDDemodReport::getBurstsDetected() { + return bursts_detected; +} +void +SWGDroneIDDemodReport::setBurstsDetected(qint32 bursts_detected) { + this->bursts_detected = bursts_detected; + this->m_bursts_detected_isSet = true; +} + +qint32 +SWGDroneIDDemodReport::getBurstsDecoded() { + return bursts_decoded; +} +void +SWGDroneIDDemodReport::setBurstsDecoded(qint32 bursts_decoded) { + this->bursts_decoded = bursts_decoded; + this->m_bursts_decoded_isSet = true; +} + +qint32 +SWGDroneIDDemodReport::getBurstsDropped() { + return bursts_dropped; +} +void +SWGDroneIDDemodReport::setBurstsDropped(qint32 bursts_dropped) { + this->bursts_dropped = bursts_dropped; + this->m_bursts_dropped_isSet = true; +} + +qint32 +SWGDroneIDDemodReport::getDronesTracked() { + return drones_tracked; +} +void +SWGDroneIDDemodReport::setDronesTracked(qint32 drones_tracked) { + this->drones_tracked = drones_tracked; + this->m_drones_tracked_isSet = true; +} + +qint32 +SWGDroneIDDemodReport::getScanLocked() { + return scan_locked; +} +void +SWGDroneIDDemodReport::setScanLocked(qint32 scan_locked) { + this->scan_locked = scan_locked; + this->m_scan_locked_isSet = true; +} + + +bool +SWGDroneIDDemodReport::isSet(){ + bool isObjectUpdated = false; + do{ + if(m_channel_power_db_isSet){ + isObjectUpdated = true; break; + } + if(m_channel_sample_rate_isSet){ + isObjectUpdated = true; break; + } + if(m_bursts_detected_isSet){ + isObjectUpdated = true; break; + } + if(m_bursts_decoded_isSet){ + isObjectUpdated = true; break; + } + if(m_bursts_dropped_isSet){ + isObjectUpdated = true; break; + } + if(m_drones_tracked_isSet){ + isObjectUpdated = true; break; + } + if(m_scan_locked_isSet){ + isObjectUpdated = true; break; + } + }while(false); + return isObjectUpdated; +} +} diff --git a/swagger/sdrangel/code/qt5/client/SWGDroneIDDemodReport.h b/swagger/sdrangel/code/qt5/client/SWGDroneIDDemodReport.h new file mode 100644 index 000000000..d56edffb5 --- /dev/null +++ b/swagger/sdrangel/code/qt5/client/SWGDroneIDDemodReport.h @@ -0,0 +1,94 @@ +/** + * SDRangel + * This is the web REST/JSON API of SDRangel SDR software. SDRangel is an Open Source Qt5/OpenGL 3.0+ (4.3+ in Windows) GUI and server Software Defined Radio and signal analyzer in software. It supports Airspy, BladeRF, HackRF, LimeSDR, PlutoSDR, RTL-SDR, SDRplay RSP1 and FunCube --- Limitations and specifcities: * In SDRangel GUI the first Rx device set cannot be deleted. Conversely the server starts with no device sets and its number of device sets can be reduced to zero by as many calls as necessary to /sdrangel/deviceset with DELETE method. * Preset import and export from/to file is a server only feature. * Device set focus is a GUI only feature. * The following channels are not implemented (status 501 is returned): ATV and DATV demodulators, Channel Analyzer NG, LoRa demodulator * The device settings and report structures contains only the sub-structure corresponding to the device type. The DeviceSettings and DeviceReport structures documented here shows all of them but only one will be or should be present at a time * The channel settings and report structures contains only the sub-structure corresponding to the channel type. The ChannelSettings and ChannelReport structures documented here shows all of them but only one will be or should be present at a time --- + * + * OpenAPI spec version: 7.0.0 + * Contact: f4exb06@gmail.com + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + +/* + * SWGDroneIDDemodReport.h + * + * DroneIDDemod + */ + +#ifndef SWGDroneIDDemodReport_H_ +#define SWGDroneIDDemodReport_H_ + +#include + + + +#include "SWGObject.h" +#include "export.h" + +namespace SWGSDRangel { + +class SWG_API SWGDroneIDDemodReport: public SWGObject { +public: + SWGDroneIDDemodReport(); + SWGDroneIDDemodReport(QString* json); + virtual ~SWGDroneIDDemodReport(); + void init(); + void cleanup(); + + virtual QString asJson () override; + virtual QJsonObject* asJsonObject() override; + virtual void fromJsonObject(QJsonObject &json) override; + virtual SWGDroneIDDemodReport* fromJson(QString &jsonString) override; + + float getChannelPowerDb(); + void setChannelPowerDb(float channel_power_db); + + qint32 getChannelSampleRate(); + void setChannelSampleRate(qint32 channel_sample_rate); + + qint32 getBurstsDetected(); + void setBurstsDetected(qint32 bursts_detected); + + qint32 getBurstsDecoded(); + void setBurstsDecoded(qint32 bursts_decoded); + + qint32 getBurstsDropped(); + void setBurstsDropped(qint32 bursts_dropped); + + qint32 getDronesTracked(); + void setDronesTracked(qint32 drones_tracked); + + qint32 getScanLocked(); + void setScanLocked(qint32 scan_locked); + + + virtual bool isSet() override; + +private: + float channel_power_db; + bool m_channel_power_db_isSet; + + qint32 channel_sample_rate; + bool m_channel_sample_rate_isSet; + + qint32 bursts_detected; + bool m_bursts_detected_isSet; + + qint32 bursts_decoded; + bool m_bursts_decoded_isSet; + + qint32 bursts_dropped; + bool m_bursts_dropped_isSet; + + qint32 drones_tracked; + bool m_drones_tracked_isSet; + + qint32 scan_locked; + bool m_scan_locked_isSet; + +}; + +} + +#endif /* SWGDroneIDDemodReport_H_ */ diff --git a/swagger/sdrangel/code/qt5/client/SWGDroneIDDemodSettings.cpp b/swagger/sdrangel/code/qt5/client/SWGDroneIDDemodSettings.cpp new file mode 100644 index 000000000..4bde9d855 --- /dev/null +++ b/swagger/sdrangel/code/qt5/client/SWGDroneIDDemodSettings.cpp @@ -0,0 +1,691 @@ +/** + * SDRangel + * This is the web REST/JSON API of SDRangel SDR software. SDRangel is an Open Source Qt5/OpenGL 3.0+ (4.3+ in Windows) GUI and server Software Defined Radio and signal analyzer in software. It supports Airspy, BladeRF, HackRF, LimeSDR, PlutoSDR, RTL-SDR, SDRplay RSP1 and FunCube --- Limitations and specifcities: * In SDRangel GUI the first Rx device set cannot be deleted. Conversely the server starts with no device sets and its number of device sets can be reduced to zero by as many calls as necessary to /sdrangel/deviceset with DELETE method. * Preset import and export from/to file is a server only feature. * Device set focus is a GUI only feature. * The following channels are not implemented (status 501 is returned): ATV and DATV demodulators, Channel Analyzer NG, LoRa demodulator * The device settings and report structures contains only the sub-structure corresponding to the device type. The DeviceSettings and DeviceReport structures documented here shows all of them but only one will be or should be present at a time * The channel settings and report structures contains only the sub-structure corresponding to the channel type. The ChannelSettings and ChannelReport structures documented here shows all of them but only one will be or should be present at a time --- + * + * OpenAPI spec version: 7.0.0 + * Contact: f4exb06@gmail.com + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + + +#include "SWGDroneIDDemodSettings.h" + +#include "SWGHelpers.h" + +#include +#include +#include +#include + +namespace SWGSDRangel { + +SWGDroneIDDemodSettings::SWGDroneIDDemodSettings(QString* json) { + init(); + this->fromJson(*json); +} + +SWGDroneIDDemodSettings::SWGDroneIDDemodSettings() { + input_frequency_offset = 0L; + m_input_frequency_offset_isSet = false; + detection_threshold = 0.0f; + m_detection_threshold_isSet = false; + turbo_iterations = 0; + m_turbo_iterations_isSet = false; + filter_serial = nullptr; + m_filter_serial_isSet = false; + map_timeout = 0; + m_map_timeout_isSet = false; + map_altitude = 0; + m_map_altitude_isSet = false; + scan = 0; + m_scan_isSet = false; + scan_band = 0; + m_scan_band_isSet = false; + scan_dwell = 0.0f; + m_scan_dwell_isSet = false; + scan_hold = 0.0f; + m_scan_hold_isSet = false; + udp_enabled = 0; + m_udp_enabled_isSet = false; + udp_address = nullptr; + m_udp_address_isSet = false; + udp_port = 0; + m_udp_port_isSet = false; + log_filename = nullptr; + m_log_filename_isSet = false; + log_enabled = 0; + m_log_enabled_isSet = false; + use_file_time = 0; + m_use_file_time_isSet = false; + rgb_color = 0; + m_rgb_color_isSet = false; + title = nullptr; + m_title_isSet = false; + stream_index = 0; + m_stream_index_isSet = false; + use_reverse_api = 0; + m_use_reverse_api_isSet = false; + reverse_api_address = nullptr; + m_reverse_api_address_isSet = false; + reverse_api_port = 0; + m_reverse_api_port_isSet = false; + reverse_api_device_index = 0; + m_reverse_api_device_index_isSet = false; + reverse_api_channel_index = 0; + m_reverse_api_channel_index_isSet = false; + channel_marker = nullptr; + m_channel_marker_isSet = false; + rollup_state = nullptr; + m_rollup_state_isSet = false; +} + +SWGDroneIDDemodSettings::~SWGDroneIDDemodSettings() { + this->cleanup(); +} + +void +SWGDroneIDDemodSettings::init() { + input_frequency_offset = 0L; + m_input_frequency_offset_isSet = false; + detection_threshold = 0.0f; + m_detection_threshold_isSet = false; + turbo_iterations = 0; + m_turbo_iterations_isSet = false; + filter_serial = new QString(""); + m_filter_serial_isSet = false; + map_timeout = 0; + m_map_timeout_isSet = false; + map_altitude = 0; + m_map_altitude_isSet = false; + scan = 0; + m_scan_isSet = false; + scan_band = 0; + m_scan_band_isSet = false; + scan_dwell = 0.0f; + m_scan_dwell_isSet = false; + scan_hold = 0.0f; + m_scan_hold_isSet = false; + udp_enabled = 0; + m_udp_enabled_isSet = false; + udp_address = new QString(""); + m_udp_address_isSet = false; + udp_port = 0; + m_udp_port_isSet = false; + log_filename = new QString(""); + m_log_filename_isSet = false; + log_enabled = 0; + m_log_enabled_isSet = false; + use_file_time = 0; + m_use_file_time_isSet = false; + rgb_color = 0; + m_rgb_color_isSet = false; + title = new QString(""); + m_title_isSet = false; + stream_index = 0; + m_stream_index_isSet = false; + use_reverse_api = 0; + m_use_reverse_api_isSet = false; + reverse_api_address = new QString(""); + m_reverse_api_address_isSet = false; + reverse_api_port = 0; + m_reverse_api_port_isSet = false; + reverse_api_device_index = 0; + m_reverse_api_device_index_isSet = false; + reverse_api_channel_index = 0; + m_reverse_api_channel_index_isSet = false; + channel_marker = new SWGChannelMarker(); + m_channel_marker_isSet = false; + rollup_state = new SWGRollupState(); + m_rollup_state_isSet = false; +} + +void +SWGDroneIDDemodSettings::cleanup() { + + + + if(filter_serial != nullptr) { + delete filter_serial; + } + + + if(udp_address != nullptr) { + delete udp_address; + } + + if(log_filename != nullptr) { + delete log_filename; + } + + + + if(title != nullptr) { + delete title; + } + + + if(reverse_api_address != nullptr) { + delete reverse_api_address; + } + + + + if(channel_marker != nullptr) { + delete channel_marker; + } + if(rollup_state != nullptr) { + delete rollup_state; + } +} + +SWGDroneIDDemodSettings* +SWGDroneIDDemodSettings::fromJson(QString &json) { + QByteArray array (json.toStdString().c_str()); + QJsonDocument doc = QJsonDocument::fromJson(array); + QJsonObject jsonObject = doc.object(); + this->fromJsonObject(jsonObject); + return this; +} + +void +SWGDroneIDDemodSettings::fromJsonObject(QJsonObject &pJson) { + ::SWGSDRangel::setValue(&input_frequency_offset, pJson["inputFrequencyOffset"], "qint64", ""); + + ::SWGSDRangel::setValue(&detection_threshold, pJson["detectionThreshold"], "float", ""); + + ::SWGSDRangel::setValue(&turbo_iterations, pJson["turboIterations"], "qint32", ""); + + ::SWGSDRangel::setValue(&filter_serial, pJson["filterSerial"], "QString", "QString"); + + ::SWGSDRangel::setValue(&map_timeout, pJson["mapTimeout"], "qint32", ""); + + ::SWGSDRangel::setValue(&map_altitude, pJson["mapAltitude"], "qint32", ""); + + ::SWGSDRangel::setValue(&scan, pJson["scan"], "qint32", ""); + + ::SWGSDRangel::setValue(&scan_band, pJson["scanBand"], "qint32", ""); + + ::SWGSDRangel::setValue(&scan_dwell, pJson["scanDwell"], "float", ""); + + ::SWGSDRangel::setValue(&scan_hold, pJson["scanHold"], "float", ""); + + ::SWGSDRangel::setValue(&udp_enabled, pJson["udpEnabled"], "qint32", ""); + + ::SWGSDRangel::setValue(&udp_address, pJson["udpAddress"], "QString", "QString"); + + ::SWGSDRangel::setValue(&udp_port, pJson["udpPort"], "qint32", ""); + + ::SWGSDRangel::setValue(&log_filename, pJson["logFilename"], "QString", "QString"); + + ::SWGSDRangel::setValue(&log_enabled, pJson["logEnabled"], "qint32", ""); + + ::SWGSDRangel::setValue(&use_file_time, pJson["useFileTime"], "qint32", ""); + + ::SWGSDRangel::setValue(&rgb_color, pJson["rgbColor"], "qint32", ""); + + ::SWGSDRangel::setValue(&title, pJson["title"], "QString", "QString"); + + ::SWGSDRangel::setValue(&stream_index, pJson["streamIndex"], "qint32", ""); + + ::SWGSDRangel::setValue(&use_reverse_api, pJson["useReverseAPI"], "qint32", ""); + + ::SWGSDRangel::setValue(&reverse_api_address, pJson["reverseAPIAddress"], "QString", "QString"); + + ::SWGSDRangel::setValue(&reverse_api_port, pJson["reverseAPIPort"], "qint32", ""); + + ::SWGSDRangel::setValue(&reverse_api_device_index, pJson["reverseAPIDeviceIndex"], "qint32", ""); + + ::SWGSDRangel::setValue(&reverse_api_channel_index, pJson["reverseAPIChannelIndex"], "qint32", ""); + + ::SWGSDRangel::setValue(&channel_marker, pJson["channelMarker"], "SWGChannelMarker", "SWGChannelMarker"); + + ::SWGSDRangel::setValue(&rollup_state, pJson["rollupState"], "SWGRollupState", "SWGRollupState"); + +} + +QString +SWGDroneIDDemodSettings::asJson () +{ + QJsonObject* obj = this->asJsonObject(); + + QJsonDocument doc(*obj); + QByteArray bytes = doc.toJson(); + delete obj; + return QString(bytes); +} + +QJsonObject* +SWGDroneIDDemodSettings::asJsonObject() { + QJsonObject* obj = new QJsonObject(); + if(m_input_frequency_offset_isSet){ + obj->insert("inputFrequencyOffset", QJsonValue(input_frequency_offset)); + } + if(m_detection_threshold_isSet){ + obj->insert("detectionThreshold", QJsonValue(detection_threshold)); + } + if(m_turbo_iterations_isSet){ + obj->insert("turboIterations", QJsonValue(turbo_iterations)); + } + if(filter_serial != nullptr && *filter_serial != QString("")){ + toJsonValue(QString("filterSerial"), filter_serial, obj, QString("QString")); + } + if(m_map_timeout_isSet){ + obj->insert("mapTimeout", QJsonValue(map_timeout)); + } + if(m_map_altitude_isSet){ + obj->insert("mapAltitude", QJsonValue(map_altitude)); + } + if(m_scan_isSet){ + obj->insert("scan", QJsonValue(scan)); + } + if(m_scan_band_isSet){ + obj->insert("scanBand", QJsonValue(scan_band)); + } + if(m_scan_dwell_isSet){ + obj->insert("scanDwell", QJsonValue(scan_dwell)); + } + if(m_scan_hold_isSet){ + obj->insert("scanHold", QJsonValue(scan_hold)); + } + if(m_udp_enabled_isSet){ + obj->insert("udpEnabled", QJsonValue(udp_enabled)); + } + if(udp_address != nullptr && *udp_address != QString("")){ + toJsonValue(QString("udpAddress"), udp_address, obj, QString("QString")); + } + if(m_udp_port_isSet){ + obj->insert("udpPort", QJsonValue(udp_port)); + } + if(log_filename != nullptr && *log_filename != QString("")){ + toJsonValue(QString("logFilename"), log_filename, obj, QString("QString")); + } + if(m_log_enabled_isSet){ + obj->insert("logEnabled", QJsonValue(log_enabled)); + } + if(m_use_file_time_isSet){ + obj->insert("useFileTime", QJsonValue(use_file_time)); + } + if(m_rgb_color_isSet){ + obj->insert("rgbColor", QJsonValue(rgb_color)); + } + if(title != nullptr && *title != QString("")){ + toJsonValue(QString("title"), title, obj, QString("QString")); + } + if(m_stream_index_isSet){ + obj->insert("streamIndex", QJsonValue(stream_index)); + } + if(m_use_reverse_api_isSet){ + obj->insert("useReverseAPI", QJsonValue(use_reverse_api)); + } + if(reverse_api_address != nullptr && *reverse_api_address != QString("")){ + toJsonValue(QString("reverseAPIAddress"), reverse_api_address, obj, QString("QString")); + } + if(m_reverse_api_port_isSet){ + obj->insert("reverseAPIPort", QJsonValue(reverse_api_port)); + } + if(m_reverse_api_device_index_isSet){ + obj->insert("reverseAPIDeviceIndex", QJsonValue(reverse_api_device_index)); + } + if(m_reverse_api_channel_index_isSet){ + obj->insert("reverseAPIChannelIndex", QJsonValue(reverse_api_channel_index)); + } + if((channel_marker != nullptr) && (channel_marker->isSet())){ + toJsonValue(QString("channelMarker"), channel_marker, obj, QString("SWGChannelMarker")); + } + if((rollup_state != nullptr) && (rollup_state->isSet())){ + toJsonValue(QString("rollupState"), rollup_state, obj, QString("SWGRollupState")); + } + + return obj; +} + +qint64 +SWGDroneIDDemodSettings::getInputFrequencyOffset() { + return input_frequency_offset; +} +void +SWGDroneIDDemodSettings::setInputFrequencyOffset(qint64 input_frequency_offset) { + this->input_frequency_offset = input_frequency_offset; + this->m_input_frequency_offset_isSet = true; +} + +float +SWGDroneIDDemodSettings::getDetectionThreshold() { + return detection_threshold; +} +void +SWGDroneIDDemodSettings::setDetectionThreshold(float detection_threshold) { + this->detection_threshold = detection_threshold; + this->m_detection_threshold_isSet = true; +} + +qint32 +SWGDroneIDDemodSettings::getTurboIterations() { + return turbo_iterations; +} +void +SWGDroneIDDemodSettings::setTurboIterations(qint32 turbo_iterations) { + this->turbo_iterations = turbo_iterations; + this->m_turbo_iterations_isSet = true; +} + +QString* +SWGDroneIDDemodSettings::getFilterSerial() { + return filter_serial; +} +void +SWGDroneIDDemodSettings::setFilterSerial(QString* filter_serial) { + this->filter_serial = filter_serial; + this->m_filter_serial_isSet = true; +} + +qint32 +SWGDroneIDDemodSettings::getMapTimeout() { + return map_timeout; +} +void +SWGDroneIDDemodSettings::setMapTimeout(qint32 map_timeout) { + this->map_timeout = map_timeout; + this->m_map_timeout_isSet = true; +} + +qint32 +SWGDroneIDDemodSettings::getMapAltitude() { + return map_altitude; +} +void +SWGDroneIDDemodSettings::setMapAltitude(qint32 map_altitude) { + this->map_altitude = map_altitude; + this->m_map_altitude_isSet = true; +} + +qint32 +SWGDroneIDDemodSettings::getScan() { + return scan; +} +void +SWGDroneIDDemodSettings::setScan(qint32 scan) { + this->scan = scan; + this->m_scan_isSet = true; +} + +qint32 +SWGDroneIDDemodSettings::getScanBand() { + return scan_band; +} +void +SWGDroneIDDemodSettings::setScanBand(qint32 scan_band) { + this->scan_band = scan_band; + this->m_scan_band_isSet = true; +} + +float +SWGDroneIDDemodSettings::getScanDwell() { + return scan_dwell; +} +void +SWGDroneIDDemodSettings::setScanDwell(float scan_dwell) { + this->scan_dwell = scan_dwell; + this->m_scan_dwell_isSet = true; +} + +float +SWGDroneIDDemodSettings::getScanHold() { + return scan_hold; +} +void +SWGDroneIDDemodSettings::setScanHold(float scan_hold) { + this->scan_hold = scan_hold; + this->m_scan_hold_isSet = true; +} + +qint32 +SWGDroneIDDemodSettings::getUdpEnabled() { + return udp_enabled; +} +void +SWGDroneIDDemodSettings::setUdpEnabled(qint32 udp_enabled) { + this->udp_enabled = udp_enabled; + this->m_udp_enabled_isSet = true; +} + +QString* +SWGDroneIDDemodSettings::getUdpAddress() { + return udp_address; +} +void +SWGDroneIDDemodSettings::setUdpAddress(QString* udp_address) { + this->udp_address = udp_address; + this->m_udp_address_isSet = true; +} + +qint32 +SWGDroneIDDemodSettings::getUdpPort() { + return udp_port; +} +void +SWGDroneIDDemodSettings::setUdpPort(qint32 udp_port) { + this->udp_port = udp_port; + this->m_udp_port_isSet = true; +} + +QString* +SWGDroneIDDemodSettings::getLogFilename() { + return log_filename; +} +void +SWGDroneIDDemodSettings::setLogFilename(QString* log_filename) { + this->log_filename = log_filename; + this->m_log_filename_isSet = true; +} + +qint32 +SWGDroneIDDemodSettings::getLogEnabled() { + return log_enabled; +} +void +SWGDroneIDDemodSettings::setLogEnabled(qint32 log_enabled) { + this->log_enabled = log_enabled; + this->m_log_enabled_isSet = true; +} + +qint32 +SWGDroneIDDemodSettings::getUseFileTime() { + return use_file_time; +} +void +SWGDroneIDDemodSettings::setUseFileTime(qint32 use_file_time) { + this->use_file_time = use_file_time; + this->m_use_file_time_isSet = true; +} + +qint32 +SWGDroneIDDemodSettings::getRgbColor() { + return rgb_color; +} +void +SWGDroneIDDemodSettings::setRgbColor(qint32 rgb_color) { + this->rgb_color = rgb_color; + this->m_rgb_color_isSet = true; +} + +QString* +SWGDroneIDDemodSettings::getTitle() { + return title; +} +void +SWGDroneIDDemodSettings::setTitle(QString* title) { + this->title = title; + this->m_title_isSet = true; +} + +qint32 +SWGDroneIDDemodSettings::getStreamIndex() { + return stream_index; +} +void +SWGDroneIDDemodSettings::setStreamIndex(qint32 stream_index) { + this->stream_index = stream_index; + this->m_stream_index_isSet = true; +} + +qint32 +SWGDroneIDDemodSettings::getUseReverseApi() { + return use_reverse_api; +} +void +SWGDroneIDDemodSettings::setUseReverseApi(qint32 use_reverse_api) { + this->use_reverse_api = use_reverse_api; + this->m_use_reverse_api_isSet = true; +} + +QString* +SWGDroneIDDemodSettings::getReverseApiAddress() { + return reverse_api_address; +} +void +SWGDroneIDDemodSettings::setReverseApiAddress(QString* reverse_api_address) { + this->reverse_api_address = reverse_api_address; + this->m_reverse_api_address_isSet = true; +} + +qint32 +SWGDroneIDDemodSettings::getReverseApiPort() { + return reverse_api_port; +} +void +SWGDroneIDDemodSettings::setReverseApiPort(qint32 reverse_api_port) { + this->reverse_api_port = reverse_api_port; + this->m_reverse_api_port_isSet = true; +} + +qint32 +SWGDroneIDDemodSettings::getReverseApiDeviceIndex() { + return reverse_api_device_index; +} +void +SWGDroneIDDemodSettings::setReverseApiDeviceIndex(qint32 reverse_api_device_index) { + this->reverse_api_device_index = reverse_api_device_index; + this->m_reverse_api_device_index_isSet = true; +} + +qint32 +SWGDroneIDDemodSettings::getReverseApiChannelIndex() { + return reverse_api_channel_index; +} +void +SWGDroneIDDemodSettings::setReverseApiChannelIndex(qint32 reverse_api_channel_index) { + this->reverse_api_channel_index = reverse_api_channel_index; + this->m_reverse_api_channel_index_isSet = true; +} + +SWGChannelMarker* +SWGDroneIDDemodSettings::getChannelMarker() { + return channel_marker; +} +void +SWGDroneIDDemodSettings::setChannelMarker(SWGChannelMarker* channel_marker) { + this->channel_marker = channel_marker; + this->m_channel_marker_isSet = true; +} + +SWGRollupState* +SWGDroneIDDemodSettings::getRollupState() { + return rollup_state; +} +void +SWGDroneIDDemodSettings::setRollupState(SWGRollupState* rollup_state) { + this->rollup_state = rollup_state; + this->m_rollup_state_isSet = true; +} + + +bool +SWGDroneIDDemodSettings::isSet(){ + bool isObjectUpdated = false; + do{ + if(m_input_frequency_offset_isSet){ + isObjectUpdated = true; break; + } + if(m_detection_threshold_isSet){ + isObjectUpdated = true; break; + } + if(m_turbo_iterations_isSet){ + isObjectUpdated = true; break; + } + if(filter_serial && *filter_serial != QString("")){ + isObjectUpdated = true; break; + } + if(m_map_timeout_isSet){ + isObjectUpdated = true; break; + } + if(m_map_altitude_isSet){ + isObjectUpdated = true; break; + } + if(m_scan_isSet){ + isObjectUpdated = true; break; + } + if(m_scan_band_isSet){ + isObjectUpdated = true; break; + } + if(m_scan_dwell_isSet){ + isObjectUpdated = true; break; + } + if(m_scan_hold_isSet){ + isObjectUpdated = true; break; + } + if(m_udp_enabled_isSet){ + isObjectUpdated = true; break; + } + if(udp_address && *udp_address != QString("")){ + isObjectUpdated = true; break; + } + if(m_udp_port_isSet){ + isObjectUpdated = true; break; + } + if(log_filename && *log_filename != QString("")){ + isObjectUpdated = true; break; + } + if(m_log_enabled_isSet){ + isObjectUpdated = true; break; + } + if(m_use_file_time_isSet){ + isObjectUpdated = true; break; + } + if(m_rgb_color_isSet){ + isObjectUpdated = true; break; + } + if(title && *title != QString("")){ + isObjectUpdated = true; break; + } + if(m_stream_index_isSet){ + isObjectUpdated = true; break; + } + if(m_use_reverse_api_isSet){ + isObjectUpdated = true; break; + } + if(reverse_api_address && *reverse_api_address != QString("")){ + isObjectUpdated = true; break; + } + if(m_reverse_api_port_isSet){ + isObjectUpdated = true; break; + } + if(m_reverse_api_device_index_isSet){ + isObjectUpdated = true; break; + } + if(m_reverse_api_channel_index_isSet){ + isObjectUpdated = true; break; + } + if(channel_marker && channel_marker->isSet()){ + isObjectUpdated = true; break; + } + if(rollup_state && rollup_state->isSet()){ + isObjectUpdated = true; break; + } + }while(false); + return isObjectUpdated; +} +} diff --git a/swagger/sdrangel/code/qt5/client/SWGDroneIDDemodSettings.h b/swagger/sdrangel/code/qt5/client/SWGDroneIDDemodSettings.h new file mode 100644 index 000000000..7a3a3f82f --- /dev/null +++ b/swagger/sdrangel/code/qt5/client/SWGDroneIDDemodSettings.h @@ -0,0 +1,211 @@ +/** + * SDRangel + * This is the web REST/JSON API of SDRangel SDR software. SDRangel is an Open Source Qt5/OpenGL 3.0+ (4.3+ in Windows) GUI and server Software Defined Radio and signal analyzer in software. It supports Airspy, BladeRF, HackRF, LimeSDR, PlutoSDR, RTL-SDR, SDRplay RSP1 and FunCube --- Limitations and specifcities: * In SDRangel GUI the first Rx device set cannot be deleted. Conversely the server starts with no device sets and its number of device sets can be reduced to zero by as many calls as necessary to /sdrangel/deviceset with DELETE method. * Preset import and export from/to file is a server only feature. * Device set focus is a GUI only feature. * The following channels are not implemented (status 501 is returned): ATV and DATV demodulators, Channel Analyzer NG, LoRa demodulator * The device settings and report structures contains only the sub-structure corresponding to the device type. The DeviceSettings and DeviceReport structures documented here shows all of them but only one will be or should be present at a time * The channel settings and report structures contains only the sub-structure corresponding to the channel type. The ChannelSettings and ChannelReport structures documented here shows all of them but only one will be or should be present at a time --- + * + * OpenAPI spec version: 7.0.0 + * Contact: f4exb06@gmail.com + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + +/* + * SWGDroneIDDemodSettings.h + * + * DroneIDDemod + */ + +#ifndef SWGDroneIDDemodSettings_H_ +#define SWGDroneIDDemodSettings_H_ + +#include + + +#include "SWGChannelMarker.h" +#include "SWGRollupState.h" +#include + +#include "SWGObject.h" +#include "export.h" + +namespace SWGSDRangel { + +class SWG_API SWGDroneIDDemodSettings: public SWGObject { +public: + SWGDroneIDDemodSettings(); + SWGDroneIDDemodSettings(QString* json); + virtual ~SWGDroneIDDemodSettings(); + void init(); + void cleanup(); + + virtual QString asJson () override; + virtual QJsonObject* asJsonObject() override; + virtual void fromJsonObject(QJsonObject &json) override; + virtual SWGDroneIDDemodSettings* fromJson(QString &jsonString) override; + + qint64 getInputFrequencyOffset(); + void setInputFrequencyOffset(qint64 input_frequency_offset); + + float getDetectionThreshold(); + void setDetectionThreshold(float detection_threshold); + + qint32 getTurboIterations(); + void setTurboIterations(qint32 turbo_iterations); + + QString* getFilterSerial(); + void setFilterSerial(QString* filter_serial); + + qint32 getMapTimeout(); + void setMapTimeout(qint32 map_timeout); + + qint32 getMapAltitude(); + void setMapAltitude(qint32 map_altitude); + + qint32 getScan(); + void setScan(qint32 scan); + + qint32 getScanBand(); + void setScanBand(qint32 scan_band); + + float getScanDwell(); + void setScanDwell(float scan_dwell); + + float getScanHold(); + void setScanHold(float scan_hold); + + qint32 getUdpEnabled(); + void setUdpEnabled(qint32 udp_enabled); + + QString* getUdpAddress(); + void setUdpAddress(QString* udp_address); + + qint32 getUdpPort(); + void setUdpPort(qint32 udp_port); + + QString* getLogFilename(); + void setLogFilename(QString* log_filename); + + qint32 getLogEnabled(); + void setLogEnabled(qint32 log_enabled); + + qint32 getUseFileTime(); + void setUseFileTime(qint32 use_file_time); + + qint32 getRgbColor(); + void setRgbColor(qint32 rgb_color); + + QString* getTitle(); + void setTitle(QString* title); + + qint32 getStreamIndex(); + void setStreamIndex(qint32 stream_index); + + qint32 getUseReverseApi(); + void setUseReverseApi(qint32 use_reverse_api); + + QString* getReverseApiAddress(); + void setReverseApiAddress(QString* reverse_api_address); + + qint32 getReverseApiPort(); + void setReverseApiPort(qint32 reverse_api_port); + + qint32 getReverseApiDeviceIndex(); + void setReverseApiDeviceIndex(qint32 reverse_api_device_index); + + qint32 getReverseApiChannelIndex(); + void setReverseApiChannelIndex(qint32 reverse_api_channel_index); + + SWGChannelMarker* getChannelMarker(); + void setChannelMarker(SWGChannelMarker* channel_marker); + + SWGRollupState* getRollupState(); + void setRollupState(SWGRollupState* rollup_state); + + + virtual bool isSet() override; + +private: + qint64 input_frequency_offset; + bool m_input_frequency_offset_isSet; + + float detection_threshold; + bool m_detection_threshold_isSet; + + qint32 turbo_iterations; + bool m_turbo_iterations_isSet; + + QString* filter_serial; + bool m_filter_serial_isSet; + + qint32 map_timeout; + bool m_map_timeout_isSet; + + qint32 map_altitude; + bool m_map_altitude_isSet; + + qint32 scan; + bool m_scan_isSet; + + qint32 scan_band; + bool m_scan_band_isSet; + + float scan_dwell; + bool m_scan_dwell_isSet; + + float scan_hold; + bool m_scan_hold_isSet; + + qint32 udp_enabled; + bool m_udp_enabled_isSet; + + QString* udp_address; + bool m_udp_address_isSet; + + qint32 udp_port; + bool m_udp_port_isSet; + + QString* log_filename; + bool m_log_filename_isSet; + + qint32 log_enabled; + bool m_log_enabled_isSet; + + qint32 use_file_time; + bool m_use_file_time_isSet; + + qint32 rgb_color; + bool m_rgb_color_isSet; + + QString* title; + bool m_title_isSet; + + qint32 stream_index; + bool m_stream_index_isSet; + + qint32 use_reverse_api; + bool m_use_reverse_api_isSet; + + QString* reverse_api_address; + bool m_reverse_api_address_isSet; + + qint32 reverse_api_port; + bool m_reverse_api_port_isSet; + + qint32 reverse_api_device_index; + bool m_reverse_api_device_index_isSet; + + qint32 reverse_api_channel_index; + bool m_reverse_api_channel_index_isSet; + + SWGChannelMarker* channel_marker; + bool m_channel_marker_isSet; + + SWGRollupState* rollup_state; + bool m_rollup_state_isSet; + +}; + +} + +#endif /* SWGDroneIDDemodSettings_H_ */ diff --git a/swagger/sdrangel/code/qt5/client/SWGModelFactory.h b/swagger/sdrangel/code/qt5/client/SWGModelFactory.h index 75750d841..8dc750cab 100644 --- a/swagger/sdrangel/code/qt5/client/SWGModelFactory.h +++ b/swagger/sdrangel/code/qt5/client/SWGModelFactory.h @@ -127,6 +127,8 @@ #include "SWGDSCDemodSettings.h" #include "SWGDSDDemodReport.h" #include "SWGDSDDemodSettings.h" +#include "SWGDroneIDDemodReport.h" +#include "SWGDroneIDDemodSettings.h" #include "SWGDVSerialDevice.h" #include "SWGDVSerialDevices.h" #include "SWGDemodAnalyzerActions.h" @@ -1002,6 +1004,16 @@ namespace SWGSDRangel { obj->init(); return obj; } + if(QString("SWGDroneIDDemodReport").compare(type) == 0) { + SWGDroneIDDemodReport *obj = new SWGDroneIDDemodReport(); + obj->init(); + return obj; + } + if(QString("SWGDroneIDDemodSettings").compare(type) == 0) { + SWGDroneIDDemodSettings *obj = new SWGDroneIDDemodSettings(); + obj->init(); + return obj; + } if(QString("SWGDVSerialDevice").compare(type) == 0) { SWGDVSerialDevice *obj = new SWGDVSerialDevice(); obj->init();