diff --git a/CMakeLists.txt b/CMakeLists.txt index fa8d84225..d6a42b481 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -176,6 +176,7 @@ option(ENABLE_CHANNELRX_DEMODRTTY "Enable channelrx demodrtty plugin" ON) option(ENABLE_CHANNELRX_DEMODPSK31 "Enable channelrx demodpsk31 plugin" ON) option(ENABLE_CHANNELRX_DEMODILS "Enable channelrx demodils plugin" ON) option(ENABLE_CHANNELRX_DEMODSELCAL "Enable channelrx demodselcal plugin" ON) +option(ENABLE_CHANNELRX_DEMOD802.15.4 "Enable channelrx demod802.15.4 plugin" ON) option(ENABLE_CHANNELRX_DEMODDSC "Enable channelrx demoddsc plugin" ON) option(ENABLE_CHANNELRX_HEATMAP "Enable channelrx heatmap plugin" ON) option(ENABLE_CHANNELRX_FREQSCANNER "Enable channelrx freqscanner plugin" ON) diff --git a/doc/img/IEEE_802_15_4_Demod_frames.png b/doc/img/IEEE_802_15_4_Demod_frames.png new file mode 100644 index 000000000..7dd032f13 Binary files /dev/null and b/doc/img/IEEE_802_15_4_Demod_frames.png differ diff --git a/doc/img/IEEE_802_15_4_Demod_plugin.png b/doc/img/IEEE_802_15_4_Demod_plugin.png new file mode 100644 index 000000000..96a12bacb Binary files /dev/null and b/doc/img/IEEE_802_15_4_Demod_plugin.png differ diff --git a/plugins/channelrx/CMakeLists.txt b/plugins/channelrx/CMakeLists.txt index 4b9c3a11f..58a60c440 100644 --- a/plugins/channelrx/CMakeLists.txt +++ b/plugins/channelrx/CMakeLists.txt @@ -306,3 +306,9 @@ if(ENABLE_CHANNELRX_DEMODSELCAL) else() message(STATUS "Not building demodselcal (ENABLE_CHANNELRX_DEMODSELCAL=${ENABLE_CHANNELRX_DEMODSELCAL})") endif() + +if (ENABLE_CHANNELRX_DEMOD802.15.4) + add_subdirectory(demod802.15.4) +else() + message(STATUS "Not building demod802.15.4 (ENABLE_CHANNELRX_DEMOD802.15.4=${ENABLE_CHANNELRX_DEMOD802.15.4})") +endif() diff --git a/plugins/channelrx/demod802.15.4/CMakeLists.txt b/plugins/channelrx/demod802.15.4/CMakeLists.txt new file mode 100644 index 000000000..47d47dda7 --- /dev/null +++ b/plugins/channelrx/demod802.15.4/CMakeLists.txt @@ -0,0 +1,73 @@ +project(demod_ieee_802_15_4) + +set(demod_ieee_802_15_4_SOURCES + ieee_802_15_4_demod.cpp + ieee_802_15_4_demodsettings.cpp + ieee_802_15_4_demodbaseband.cpp + ieee_802_15_4_demodsink.cpp + ieee_802_15_4_demodreceiver.cpp + ieee_802_15_4_demodplugin.cpp + ieee_802_15_4_demodwebapiadapter.cpp +) + +set(demod_ieee_802_15_4_HEADERS + ieee_802_15_4_demod.h + ieee_802_15_4_demodsettings.h + ieee_802_15_4_demodbaseband.h + ieee_802_15_4_demodsink.h + ieee_802_15_4_demodreceiver.h + ieee_802_15_4_demodplugin.h + ieee_802_15_4_demodwebapiadapter.h +) + +include_directories( + ${CMAKE_SOURCE_DIR}/swagger/sdrangel/code/qt5/client +) + +if(NOT SERVER_MODE) + set(demod_ieee_802_15_4_SOURCES + ${demod_ieee_802_15_4_SOURCES} + ieee_802_15_4_demodgui.cpp + ieee_802_15_4_demodgui.ui + ) + set(demod_ieee_802_15_4_HEADERS + ${demod_ieee_802_15_4_HEADERS} + ieee_802_15_4_demodgui.h + ) + set(TARGET_NAME ${PLUGINS_PREFIX}demodieee_802_15_4) + set(TARGET_LIB "Qt::Widgets") + set(TARGET_LIB_GUI "sdrgui") + set(INSTALL_FOLDER ${INSTALL_PLUGINS_DIR}) +else() + set(TARGET_NAME ${PLUGINSSRV_PREFIX}demodieee_802_15_4srv) + set(TARGET_LIB "") + set(TARGET_LIB_GUI "") + set(INSTALL_FOLDER ${INSTALL_PLUGINSSRV_DIR}) +endif() + +if(NOT Qt6_FOUND) + add_library(${TARGET_NAME} ${demod_ieee_802_15_4_SOURCES}) +else() + qt_add_plugin(${TARGET_NAME} CLASS_NAME IEEE_802_15_4_DemodPlugin) + target_sources(${TARGET_NAME} PRIVATE ${demod_ieee_802_15_4_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} + swagger +) + +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/demod802.15.4/ieee_802_15_4_demod.cpp b/plugins/channelrx/demod802.15.4/ieee_802_15_4_demod.cpp new file mode 100644 index 000000000..7bb7bc121 --- /dev/null +++ b/plugins/channelrx/demod802.15.4/ieee_802_15_4_demod.cpp @@ -0,0 +1,898 @@ +/////////////////////////////////////////////////////////////////////////////////// +// 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 "SWGChannelSettings.h" +#include "SWGWorkspaceInfo.h" +#include "SWGIEEE_802_15_4_DemodSettings.h" +#include "SWGChannelReport.h" + +#include "dsp/dspcommands.h" +#include "device/deviceapi.h" +#include "settings/serializable.h" +#include "util/db.h" +#include "util/ieee_802_15_4.h" +#include "maincore.h" + +#include "ieee_802_15_4_demod.h" + +MESSAGE_CLASS_DEFINITION(IEEE_802_15_4_Demod::MsgConfigureIEEE_802_15_4_Demod, Message) +MESSAGE_CLASS_DEFINITION(IEEE_802_15_4_Demod::MsgFrame, Message) + +const char * const IEEE_802_15_4_Demod::m_channelIdURI = "sdrangel.channelrx.demod802.15.4"; +const char * const IEEE_802_15_4_Demod::m_channelId = "IEEE_802_15_4_Demod"; + +IEEE_802_15_4_Demod::IEEE_802_15_4_Demod(DeviceAPI *deviceAPI) : + ChannelAPI(m_channelIdURI, ChannelAPI::StreamSingleSink), + m_deviceAPI(deviceAPI), + m_basebandSampleRate(0), + m_centerFrequency(0), + m_zepSequenceNumber(0), + m_logPCAP(false), + m_framesOK(0), + m_framesBad(0) +{ + setObjectName(m_channelId); + m_thread.setObjectName("802154DemodBB"); + + m_basebandSink = new IEEE_802_15_4_DemodBaseband(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, + &IEEE_802_15_4_Demod::networkManagerFinished + ); + QObject::connect( + this, + &ChannelAPI::indexInDeviceSetChanged, + this, + &IEEE_802_15_4_Demod::handleIndexInDeviceSetChanged + ); +} + +IEEE_802_15_4_Demod::~IEEE_802_15_4_Demod() +{ + QObject::disconnect( + m_networkManager, + &QNetworkAccessManager::finished, + this, + &IEEE_802_15_4_Demod::networkManagerFinished + ); + delete m_networkManager; + m_deviceAPI->removeChannelSinkAPI(this); + m_deviceAPI->removeChannelSink(this, true); + + if (m_basebandSink->isRunning()) { + stop(); + } + + delete m_basebandSink; + + if (m_logFile.isOpen()) + { + m_logStream.flush(); + m_logFile.close(); + } +} + +void IEEE_802_15_4_Demod::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 IEEE_802_15_4_Demod::getNumberOfDeviceStreams() const +{ + return m_deviceAPI->getNbSourceStreams(); +} + +void IEEE_802_15_4_Demod::feed(const SampleVector::const_iterator& begin, const SampleVector::const_iterator& end, bool firstOfBurst) +{ + (void) firstOfBurst; + m_basebandSink->feed(begin, end); +} + +void IEEE_802_15_4_Demod::start() +{ + qDebug("IEEE_802_15_4_Demod::start"); + + m_basebandSink->reset(); + m_basebandSink->startWork(); + m_thread.start(); + + DSPSignalNotification *dspMsg = new DSPSignalNotification(m_basebandSampleRate, m_centerFrequency); + m_basebandSink->getInputMessageQueue()->push(dspMsg); + + IEEE_802_15_4_DemodBaseband::MsgConfigureIEEE_802_15_4_DemodBaseband *msg = IEEE_802_15_4_DemodBaseband::MsgConfigureIEEE_802_15_4_DemodBaseband::create(QStringList(), m_settings, true); + m_basebandSink->getInputMessageQueue()->push(msg); +} + +void IEEE_802_15_4_Demod::stop() +{ + qDebug("IEEE_802_15_4_Demod::stop"); + m_basebandSink->stopWork(); + m_thread.quit(); + m_thread.wait(); +} + +bool IEEE_802_15_4_Demod::handleMessage(const Message& cmd) +{ + if (MsgConfigureIEEE_802_15_4_Demod::match(cmd)) + { + MsgConfigureIEEE_802_15_4_Demod& cfg = (MsgConfigureIEEE_802_15_4_Demod&) cmd; + qDebug() << "IEEE_802_15_4_Demod::handleMessage: MsgConfigureIEEE_802_15_4_Demod"; + 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() << "IEEE_802_15_4_Demod::handleMessage: DSPSignalNotification"; + m_basebandSink->getInputMessageQueue()->push(rep); + + if (getMessageQueueToGUI()) { + getMessageQueueToGUI()->push(new DSPSignalNotification(notif)); + } + + return true; + } + else if (MsgFrame::match(cmd)) + { + const MsgFrame& frame = (const MsgFrame&) cmd; + + if (frame.getFCSOK()) { + m_framesOK++; + } else { + m_framesBad++; + } + + if (!frame.getFCSOK() && !m_settings.m_showBadFCS) { + return true; + } + + // Forward to GUI + if (getMessageQueueToGUI()) { + getMessageQueueToGUI()->push(new MsgFrame(frame)); + } + + // Forward via UDP + if (m_settings.m_udpEnabled) + { + if (m_settings.m_udpFormat == IEEE_802_15_4_DemodSettings::ZEP) + { + int channel = getChannelNumber(m_centerFrequency + m_settings.m_inputFrequencyOffset); + int lqi = std::max(0, std::min(255, (int) std::round(frame.getLQI() * 255.0f))); + QByteArray zep = encodeZEP(frame.getPSDU(), frame.getDateTime(), channel < 0 ? 0 : channel, lqi, m_zepSequenceNumber++); + m_udpSocket.writeDatagram(zep, QHostAddress(m_settings.m_udpAddress), m_settings.m_udpPort); + } + else + { + m_udpSocket.writeDatagram(frame.getPSDU(), QHostAddress(m_settings.m_udpAddress), m_settings.m_udpPort); + } + } + + // Write to log file + if (m_logFile.isOpen()) { + logFrame(frame); + } + + return true; + } + else + { + return false; + } +} + +int IEEE_802_15_4_Demod::getChannelNumber(qint64 frequency) +{ + // 10.1.2.2 - Channel numbering for 868 MHz, 915 MHz, and 2450 MHz bands + const qint64 tolerance = 100000; + + if (std::abs(frequency - 868300000LL) <= tolerance) { + return 0; + } + for (int k = 1; k <= 10; k++) + { + if (std::abs(frequency - (906000000LL + 2000000LL * (k - 1))) <= tolerance) { + return k; + } + } + for (int k = 11; k <= 26; k++) + { + if (std::abs(frequency - (2405000000LL + 5000000LL * (k - 11))) <= tolerance) { + return k; + } + } + + return -1; +} + +QByteArray IEEE_802_15_4_Demod::encodeZEP(const QByteArray& psdu, const QDateTime& dateTime, int channel, int lqi, quint32 sequenceNumber) +{ + QByteArray zep; + QDataStream s(&zep, QIODevice::WriteOnly); + s.setByteOrder(QDataStream::BigEndian); + + // NTP timestamp: seconds since 1900 and fraction + const quint64 ntpEpochOffset = 2208988800ULL; + qint64 ms = dateTime.toMSecsSinceEpoch(); + quint32 seconds = (quint32) (ms / 1000 + ntpEpochOffset); + quint32 fraction = (quint32) (((ms % 1000) * 4294967296ULL) / 1000); + + s << (quint8) 'E' << (quint8) 'X'; // Preamble + s << (quint8) 2; // Version + s << (quint8) 1; // Type: Data + s << (quint8) channel; // Channel ID + s << (quint16) 0; // Device ID + s << (quint8) 1; // CRC mode: PSDU includes FCS + s << (quint8) lqi; // LQI + s << seconds << fraction; // Timestamp + s << sequenceNumber; + for (int i = 0; i < 10; i++) { + s << (quint8) 0; // Reserved + } + s << (quint8) psdu.size(); // Length + zep.append(psdu); + + return zep; +} + +void IEEE_802_15_4_Demod::openLog(const QString& filename) +{ + m_logFile.setFileName(filename); + m_logPCAP = filename.endsWith(".pcap", Qt::CaseInsensitive); + + // Only append to an existing PCAP file if it has the same link type, otherwise + // the frames would be misinterpreted, or the file wouldn't be readable at all + if (m_logPCAP && (m_logFile.size() > 0)) + { + bool valid = false; + QFile existing(filename); + + if (existing.open(QIODevice::ReadOnly)) + { + QByteArray header = existing.read(24); + + if (header.size() == 24) + { + quint32 magic = qFromLittleEndian(header.constData()); + quint32 linkType = qFromLittleEndian(header.constData() + 20); + valid = (magic == 0xa1b2c3d4) && (linkType == m_pcapLinkTypeIEEE802154WithFCS); + } + } + + if (!valid) + { + qWarning() << "IEEE_802_15_4_Demod::openLog - Not logging to" << filename << "as it is not a PCAP file with IEEE 802.15.4 link type"; + return; + } + } + + if (m_logFile.open(QIODevice::WriteOnly | QIODevice::Append | (m_logPCAP ? QIODevice::NotOpen : QIODevice::Text))) + { + qDebug() << "IEEE_802_15_4_Demod::openLog - Logging to: " << filename; + bool newFile = m_logFile.size() == 0; + + if (m_logPCAP) + { + if (newFile) + { + // PCAP global header + QDataStream s(&m_logFile); + s.setByteOrder(QDataStream::LittleEndian); + s << (quint32) 0xa1b2c3d4 << (quint16) 2 << (quint16) 4 << (qint32) 0 << (quint32) 0 + << (quint32) 65535 << m_pcapLinkTypeIEEE802154WithFCS; + } + } + else + { + m_logStream.setDevice(&m_logFile); + + if (newFile) { + m_logStream << "Date,Time,Data,FCS,Type,Seq,Dst PAN,Dst Addr,Src PAN,Src Addr,Info,Payload,Power,SNR,LQI,Freq Offset\n"; + } + } + } + else + { + qDebug() << "IEEE_802_15_4_Demod::openLog - Unable to open log file: " << filename; + } +} + +void IEEE_802_15_4_Demod::logFrame(const MsgFrame& frame) +{ + if (m_logPCAP) + { + QDataStream s(&m_logFile); + s.setByteOrder(QDataStream::LittleEndian); + qint64 ms = frame.getDateTime().toMSecsSinceEpoch(); + s << (quint32) (ms / 1000) << (quint32) ((ms % 1000) * 1000) + << (quint32) frame.getPSDU().size() << (quint32) frame.getPSDU().size(); + s.writeRawData(frame.getPSDU().data(), frame.getPSDU().size()); + m_logFile.flush(); + } + else + { + IEEE_802_15_4_FrameDecoder mac; + mac.decode(frame.getPSDU()); + + m_logStream << frame.getDateTime().date().toString() << "," + << frame.getDateTime().time().toString() << "," + << frame.getPSDU().toHex() << "," + << (frame.getFCSOK() ? "OK" : "Bad") << "," + << mac.getFrameTypeString() << "," + << (mac.m_hasSeqNo ? QString::number(mac.m_seqNo) : "") << "," + << mac.getDestPANIDString() << "," + << mac.getDestAddressString() << "," + << mac.getSrcPANIDString() << "," + << mac.getSrcAddressString() << "," + << "\"" << mac.toString() << "\"," + << mac.m_payload.toHex() << "," + << QString::number(frame.getPowerDB(), 'f', 1) << "," + << QString::number(frame.getSNR(), 'f', 1) << "," + << QString::number(frame.getLQI(), 'f', 2) << "," + << QString::number(frame.getFrequencyOffset(), 'f', 0) << "\n"; + m_logStream.flush(); + } +} + +ScopeVis *IEEE_802_15_4_Demod::getScopeSink() +{ + return m_basebandSink->getScopeSink(); +} + +void IEEE_802_15_4_Demod::setCenterFrequency(qint64 frequency) +{ + IEEE_802_15_4_DemodSettings settings = m_settings; + settings.m_inputFrequencyOffset = frequency; + applySettings(QStringList("inputFrequencyOffset"), settings, false); + + if (m_guiMessageQueue) // forward to GUI if any + { + MsgConfigureIEEE_802_15_4_Demod *msgToGUI = MsgConfigureIEEE_802_15_4_Demod::create(QStringList("inputFrequencyOffset"), settings, false); + m_guiMessageQueue->push(msgToGUI); + } +} + +void IEEE_802_15_4_Demod::applySettings(const QStringList& settingsKeys, const IEEE_802_15_4_DemodSettings& settings, bool force) +{ + qDebug() << "IEEE_802_15_4_Demod::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); + } + } + + IEEE_802_15_4_DemodBaseband::MsgConfigureIEEE_802_15_4_DemodBaseband *msg = IEEE_802_15_4_DemodBaseband::MsgConfigureIEEE_802_15_4_DemodBaseband::create(settingsKeys, settings, force); + m_basebandSink->getInputMessageQueue()->push(msg); + + // Forward all settings changes when reverse API is enabled, not just changes to the reverse API settings + bool useReverseAPI = (settingsKeys.contains("useReverseAPI") || force) ? settings.m_useReverseAPI : m_settings.m_useReverseAPI; + + if (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()) { + openLog(settings.m_logFilename); + } + } + + if (force) { + m_settings = settings; + } else { + m_settings.applySettings(settingsKeys, settings); + } +} + +QByteArray IEEE_802_15_4_Demod::serialize() const +{ + return m_settings.serialize(); +} + +bool IEEE_802_15_4_Demod::deserialize(const QByteArray& data) +{ + if (m_settings.deserialize(data)) + { + MsgConfigureIEEE_802_15_4_Demod *msg = MsgConfigureIEEE_802_15_4_Demod::create(QStringList(), m_settings, true); + m_inputMessageQueue.push(msg); + return true; + } + else + { + m_settings.resetToDefaults(); + MsgConfigureIEEE_802_15_4_Demod *msg = MsgConfigureIEEE_802_15_4_Demod::create(QStringList(), m_settings, true); + m_inputMessageQueue.push(msg); + return false; + } +} + +int IEEE_802_15_4_Demod::webapiSettingsGet( + SWGSDRangel::SWGChannelSettings& response, + QString& errorMessage) +{ + (void) errorMessage; + response.setIeee802154DemodSettings(new SWGSDRangel::SWGIEEE_802_15_4_DemodSettings()); + response.getIeee802154DemodSettings()->init(); + webapiFormatChannelSettings(response, m_settings); + return 200; +} + +int IEEE_802_15_4_Demod::webapiWorkspaceGet( + SWGSDRangel::SWGWorkspaceInfo& response, + QString& errorMessage) +{ + (void) errorMessage; + response.setIndex(m_settings.m_workspaceIndex); + return 200; +} + +int IEEE_802_15_4_Demod::webapiSettingsPutPatch( + bool force, + const QStringList& channelSettingsKeys, + SWGSDRangel::SWGChannelSettings& response, + QString& errorMessage) +{ + if (channelSettingsKeys.contains("phy")) + { + IEEE_802_15_4_PHY phy; + QString *phyName = response.getIeee802154DemodSettings()->getPhy(); + + if (!phyName || !phy.fromString(*phyName) || phy.toString().isEmpty()) + { + errorMessage = QString("phy must be one of: %1").arg(IEEE_802_15_4_PHY::getPHYNames().join(", ")); + return 400; + } + } + + IEEE_802_15_4_DemodSettings settings = m_settings; + webapiUpdateChannelSettings(settings, channelSettingsKeys, response); + + MsgConfigureIEEE_802_15_4_Demod *msg = MsgConfigureIEEE_802_15_4_Demod::create(channelSettingsKeys, settings, force); + m_inputMessageQueue.push(msg); + + if (m_guiMessageQueue) // forward to GUI if any + { + MsgConfigureIEEE_802_15_4_Demod *msgToGUI = MsgConfigureIEEE_802_15_4_Demod::create(channelSettingsKeys, settings, force); + m_guiMessageQueue->push(msgToGUI); + } + + webapiFormatChannelSettings(response, settings); + + return 200; +} + +int IEEE_802_15_4_Demod::webapiReportGet( + SWGSDRangel::SWGChannelReport& response, + QString& errorMessage) +{ + (void) errorMessage; + response.setIeee802154DemodReport(new SWGSDRangel::SWGIEEE_802_15_4_DemodReport()); + response.getIeee802154DemodReport()->init(); + webapiFormatChannelReport(response); + return 200; +} + +void IEEE_802_15_4_Demod::webapiUpdateChannelSettings( + IEEE_802_15_4_DemodSettings& settings, + const QStringList& channelSettingsKeys, + SWGSDRangel::SWGChannelSettings& response) +{ + SWGSDRangel::SWGIEEE_802_15_4_DemodSettings *s = response.getIeee802154DemodSettings(); + + if (channelSettingsKeys.contains("inputFrequencyOffset")) { + settings.m_inputFrequencyOffset = s->getInputFrequencyOffset(); + } + if (channelSettingsKeys.contains("phy")) { + settings.m_phy = *s->getPhy(); + } + if (channelSettingsKeys.contains("rfBandwidth")) { + settings.m_rfBandwidth = s->getRfBandwidth(); + } + if (channelSettingsKeys.contains("samplesPerChip")) { + settings.m_samplesPerChip = std::max(2, std::min(16, s->getSamplesPerChip())); + } + if (channelSettingsKeys.contains("maxFrequencyOffset")) { + settings.m_maxFrequencyOffset = s->getMaxFrequencyOffset(); + } + if (channelSettingsKeys.contains("threshold")) { + settings.m_threshold = std::max(IEEE_802_15_4_DemodSettings::m_minThreshold, + std::min(IEEE_802_15_4_DemodSettings::m_maxThreshold, s->getThreshold())); + } + if (channelSettingsKeys.contains("showBadFCS")) { + settings.m_showBadFCS = s->getShowBadFcs() != 0; + } + if (channelSettingsKeys.contains("filterFrameType")) { + settings.m_filterFrameType = (IEEE_802_15_4_DemodSettings::FrameTypeFilter) std::max(0, std::min(5, s->getFilterFrameType())); + } + if (channelSettingsKeys.contains("filterPANID")) { + settings.m_filterPANID = *s->getFilterPanid(); + } + if (channelSettingsKeys.contains("filterAddress")) { + settings.m_filterAddress = *s->getFilterAddress(); + } + if (channelSettingsKeys.contains("udpEnabled")) { + settings.m_udpEnabled = s->getUdpEnabled() != 0; + } + if (channelSettingsKeys.contains("udpAddress")) { + settings.m_udpAddress = *s->getUdpAddress(); + } + if (channelSettingsKeys.contains("udpPort")) { + settings.m_udpPort = s->getUdpPort(); + } + if (channelSettingsKeys.contains("udpFormat")) { + settings.m_udpFormat = s->getUdpFormat() == 1 ? IEEE_802_15_4_DemodSettings::Raw : IEEE_802_15_4_DemodSettings::ZEP; + } + if (channelSettingsKeys.contains("logFilename")) { + settings.m_logFilename = *s->getLogFilename(); + } + if (channelSettingsKeys.contains("logEnabled")) { + settings.m_logEnabled = s->getLogEnabled() != 0; + } + if (channelSettingsKeys.contains("useFileTime")) { + settings.m_useFileTime = s->getUseFileTime() != 0; + } + if (channelSettingsKeys.contains("rgbColor")) { + settings.m_rgbColor = s->getRgbColor(); + } + if (channelSettingsKeys.contains("title")) { + settings.m_title = *s->getTitle(); + } + if (channelSettingsKeys.contains("streamIndex")) { + settings.m_streamIndex = s->getStreamIndex(); + } + if (channelSettingsKeys.contains("useReverseAPI")) { + settings.m_useReverseAPI = s->getUseReverseApi() != 0; + } + if (channelSettingsKeys.contains("reverseAPIAddress")) { + settings.m_reverseAPIAddress = *s->getReverseApiAddress(); + } + if (channelSettingsKeys.contains("reverseAPIPort")) { + settings.m_reverseAPIPort = s->getReverseApiPort(); + } + if (channelSettingsKeys.contains("reverseAPIDeviceIndex")) { + settings.m_reverseAPIDeviceIndex = s->getReverseApiDeviceIndex(); + } + if (channelSettingsKeys.contains("reverseAPIChannelIndex")) { + settings.m_reverseAPIChannelIndex = s->getReverseApiChannelIndex(); + } + if (settings.m_scopeGUI && channelSettingsKeys.contains("scopeConfig")) { + settings.m_scopeGUI->updateFrom(channelSettingsKeys, s->getScopeConfig()); + } + if (settings.m_channelMarker && channelSettingsKeys.contains("channelMarker")) { + settings.m_channelMarker->updateFrom(channelSettingsKeys, s->getChannelMarker()); + } + if (settings.m_rollupState && channelSettingsKeys.contains("rollupState")) { + settings.m_rollupState->updateFrom(channelSettingsKeys, s->getRollupState()); + } +} + +static void setString(QString *(SWGSDRangel::SWGIEEE_802_15_4_DemodSettings::*get)(), + void (SWGSDRangel::SWGIEEE_802_15_4_DemodSettings::*set)(QString*), + SWGSDRangel::SWGIEEE_802_15_4_DemodSettings *s, + const QString& value) +{ + if ((s->*get)()) { + *(s->*get)() = value; + } else { + (s->*set)(new QString(value)); + } +} + +void IEEE_802_15_4_Demod::webapiFormatChannelSettings(SWGSDRangel::SWGChannelSettings& response, const IEEE_802_15_4_DemodSettings& settings) +{ + typedef SWGSDRangel::SWGIEEE_802_15_4_DemodSettings S; + S *s = response.getIeee802154DemodSettings(); + + s->setInputFrequencyOffset(settings.m_inputFrequencyOffset); + setString(&S::getPhy, &S::setPhy, s, settings.m_phy); + s->setRfBandwidth(settings.m_rfBandwidth); + s->setSamplesPerChip(settings.m_samplesPerChip); + s->setMaxFrequencyOffset(settings.m_maxFrequencyOffset); + s->setThreshold(settings.m_threshold); + s->setShowBadFcs(settings.m_showBadFCS ? 1 : 0); + s->setFilterFrameType((int) settings.m_filterFrameType); + setString(&S::getFilterPanid, &S::setFilterPanid, s, settings.m_filterPANID); + setString(&S::getFilterAddress, &S::setFilterAddress, s, settings.m_filterAddress); + s->setUdpEnabled(settings.m_udpEnabled ? 1 : 0); + setString(&S::getUdpAddress, &S::setUdpAddress, s, settings.m_udpAddress); + s->setUdpPort(settings.m_udpPort); + s->setUdpFormat((int) settings.m_udpFormat); + setString(&S::getLogFilename, &S::setLogFilename, s, settings.m_logFilename); + s->setLogEnabled(settings.m_logEnabled ? 1 : 0); + s->setUseFileTime(settings.m_useFileTime ? 1 : 0); + s->setRgbColor(settings.m_rgbColor); + setString(&S::getTitle, &S::setTitle, s, settings.m_title); + s->setStreamIndex(settings.m_streamIndex); + s->setUseReverseApi(settings.m_useReverseAPI ? 1 : 0); + setString(&S::getReverseApiAddress, &S::setReverseApiAddress, s, settings.m_reverseAPIAddress); + s->setReverseApiPort(settings.m_reverseAPIPort); + s->setReverseApiDeviceIndex(settings.m_reverseAPIDeviceIndex); + s->setReverseApiChannelIndex(settings.m_reverseAPIChannelIndex); + + if (settings.m_scopeGUI) + { + if (s->getScopeConfig()) + { + settings.m_scopeGUI->formatTo(s->getScopeConfig()); + } + else + { + SWGSDRangel::SWGGLScope *swgGLScope = new SWGSDRangel::SWGGLScope(); + settings.m_scopeGUI->formatTo(swgGLScope); + s->setScopeConfig(swgGLScope); + } + } + + if (settings.m_channelMarker) + { + if (s->getChannelMarker()) + { + settings.m_channelMarker->formatTo(s->getChannelMarker()); + } + else + { + SWGSDRangel::SWGChannelMarker *swgChannelMarker = new SWGSDRangel::SWGChannelMarker(); + settings.m_channelMarker->formatTo(swgChannelMarker); + s->setChannelMarker(swgChannelMarker); + } + } + + if (settings.m_rollupState) + { + if (s->getRollupState()) + { + settings.m_rollupState->formatTo(s->getRollupState()); + } + else + { + SWGSDRangel::SWGRollupState *swgRollupState = new SWGSDRangel::SWGRollupState(); + settings.m_rollupState->formatTo(swgRollupState); + s->setRollupState(swgRollupState); + } + } +} + +void IEEE_802_15_4_Demod::webapiFormatChannelReport(SWGSDRangel::SWGChannelReport& response) +{ + double magsqAvg, magsqPeak; + int nbMagsqSamples; + getMagSqLevels(magsqAvg, magsqPeak, nbMagsqSamples); + + response.getIeee802154DemodReport()->setChannelPowerDb(CalcDb::dbPower(magsqAvg)); + response.getIeee802154DemodReport()->setChannelSampleRate(m_basebandSink->getChannelSampleRate()); + response.getIeee802154DemodReport()->setFramesOk((qint32) m_framesOK); + response.getIeee802154DemodReport()->setFramesBadFcs((qint32) m_framesBad); +} + +void IEEE_802_15_4_Demod::webapiReverseSendSettings(const QList& channelSettingsKeys, const IEEE_802_15_4_DemodSettings& 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 IEEE_802_15_4_Demod::webapiFormatChannelSettings( + const QList& channelSettingsKeys, + SWGSDRangel::SWGChannelSettings *swgChannelSettings, + const IEEE_802_15_4_DemodSettings& settings, + bool force +) +{ + typedef SWGSDRangel::SWGIEEE_802_15_4_DemodSettings S; + + swgChannelSettings->setDirection(0); // Single sink (Rx) + swgChannelSettings->setOriginatorChannelIndex(getIndexInDeviceSet()); + swgChannelSettings->setOriginatorDeviceSetIndex(getDeviceSetIndex()); + swgChannelSettings->setChannelType(new QString(m_channelId)); + swgChannelSettings->setIeee802154DemodSettings(new S()); + S *s = swgChannelSettings->getIeee802154DemodSettings(); + + // transfer data that has been modified. When force is on transfer all data except reverse API data + + if (channelSettingsKeys.contains("inputFrequencyOffset") || force) { + s->setInputFrequencyOffset(settings.m_inputFrequencyOffset); + } + if (channelSettingsKeys.contains("phy") || force) { + s->setPhy(new QString(settings.m_phy)); + } + if (channelSettingsKeys.contains("rfBandwidth") || force) { + s->setRfBandwidth(settings.m_rfBandwidth); + } + if (channelSettingsKeys.contains("samplesPerChip") || force) { + s->setSamplesPerChip(settings.m_samplesPerChip); + } + if (channelSettingsKeys.contains("maxFrequencyOffset") || force) { + s->setMaxFrequencyOffset(settings.m_maxFrequencyOffset); + } + if (channelSettingsKeys.contains("threshold") || force) { + s->setThreshold(settings.m_threshold); + } + if (channelSettingsKeys.contains("showBadFCS") || force) { + s->setShowBadFcs(settings.m_showBadFCS ? 1 : 0); + } + if (channelSettingsKeys.contains("filterFrameType") || force) { + s->setFilterFrameType((int) settings.m_filterFrameType); + } + if (channelSettingsKeys.contains("filterPANID") || force) { + s->setFilterPanid(new QString(settings.m_filterPANID)); + } + if (channelSettingsKeys.contains("filterAddress") || force) { + s->setFilterAddress(new QString(settings.m_filterAddress)); + } + if (channelSettingsKeys.contains("udpEnabled") || force) { + s->setUdpEnabled(settings.m_udpEnabled ? 1 : 0); + } + if (channelSettingsKeys.contains("udpAddress") || force) { + s->setUdpAddress(new QString(settings.m_udpAddress)); + } + if (channelSettingsKeys.contains("udpPort") || force) { + s->setUdpPort(settings.m_udpPort); + } + if (channelSettingsKeys.contains("udpFormat") || force) { + s->setUdpFormat((int) settings.m_udpFormat); + } + if (channelSettingsKeys.contains("logFilename") || force) { + s->setLogFilename(new QString(settings.m_logFilename)); + } + if (channelSettingsKeys.contains("logEnabled") || force) { + s->setLogEnabled(settings.m_logEnabled ? 1 : 0); + } + if (channelSettingsKeys.contains("useFileTime") || force) { + s->setUseFileTime(settings.m_useFileTime ? 1 : 0); + } + if (channelSettingsKeys.contains("rgbColor") || force) { + s->setRgbColor(settings.m_rgbColor); + } + if (channelSettingsKeys.contains("title") || force) { + s->setTitle(new QString(settings.m_title)); + } + if (channelSettingsKeys.contains("streamIndex") || force) { + s->setStreamIndex(settings.m_streamIndex); + } + + if (settings.m_scopeGUI && (channelSettingsKeys.contains("scopeConfig") || force)) + { + SWGSDRangel::SWGGLScope *swgGLScope = new SWGSDRangel::SWGGLScope(); + settings.m_scopeGUI->formatTo(swgGLScope); + s->setScopeConfig(swgGLScope); + } + + if (settings.m_channelMarker && (channelSettingsKeys.contains("channelMarker") || force)) + { + SWGSDRangel::SWGChannelMarker *swgChannelMarker = new SWGSDRangel::SWGChannelMarker(); + settings.m_channelMarker->formatTo(swgChannelMarker); + s->setChannelMarker(swgChannelMarker); + } + + if (settings.m_rollupState && (channelSettingsKeys.contains("rollupState") || force)) + { + SWGSDRangel::SWGRollupState *swgRollupState = new SWGSDRangel::SWGRollupState(); + settings.m_rollupState->formatTo(swgRollupState); + s->setRollupState(swgRollupState); + } +} + +void IEEE_802_15_4_Demod::networkManagerFinished(QNetworkReply *reply) +{ + QNetworkReply::NetworkError replyError = reply->error(); + + if (replyError) + { + qWarning() << "IEEE_802_15_4_Demod::networkManagerFinished:" + << " error(" << (int) replyError + << "): " << replyError + << ": " << reply->errorString(); + } + else + { + QString answer = reply->readAll(); + answer.chop(1); // remove last \n + qDebug("IEEE_802_15_4_Demod::networkManagerFinished: reply:\n%s", answer.toStdString().c_str()); + } + + reply->deleteLater(); +} + +void IEEE_802_15_4_Demod::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 IEEE_802_15_4_Demod::getChannelSampleRate() const +{ + return m_basebandSink ? m_basebandSink->getChannelSampleRate() : 0; +} diff --git a/plugins/channelrx/demod802.15.4/ieee_802_15_4_demod.h b/plugins/channelrx/demod802.15.4/ieee_802_15_4_demod.h new file mode 100644 index 000000000..a3b76c02d --- /dev/null +++ b/plugins/channelrx/demod802.15.4/ieee_802_15_4_demod.h @@ -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 . // +/////////////////////////////////////////////////////////////////////////////////// + +#ifndef INCLUDE_IEEE_802_15_4_DEMOD_H +#define INCLUDE_IEEE_802_15_4_DEMOD_H + +#include +#include +#include +#include +#include +#include + +#include "dsp/basebandsamplesink.h" +#include "channel/channelapi.h" +#include "util/message.h" + +#include "ieee_802_15_4_demodbaseband.h" +#include "ieee_802_15_4_demodsettings.h" + +class QNetworkAccessManager; +class QNetworkReply; +class DeviceAPI; +class ScopeVis; + +class IEEE_802_15_4_Demod : public BasebandSampleSink, public ChannelAPI { +public: + class MsgConfigureIEEE_802_15_4_Demod : public Message { + MESSAGE_CLASS_DECLARATION + + public: + const IEEE_802_15_4_DemodSettings& getSettings() const { return m_settings; } + const QStringList& getSettingsKeys() const { return m_settingsKeys; } + bool getForce() const { return m_force; } + + static MsgConfigureIEEE_802_15_4_Demod* create(const QStringList& settingsKeys, const IEEE_802_15_4_DemodSettings& settings, bool force) + { + return new MsgConfigureIEEE_802_15_4_Demod(settingsKeys, settings, force); + } + + private: + IEEE_802_15_4_DemodSettings m_settings; + QStringList m_settingsKeys; + bool m_force; + + MsgConfigureIEEE_802_15_4_Demod(const QStringList& settingsKeys, const IEEE_802_15_4_DemodSettings& settings, bool force) : + Message(), + m_settings(settings), + m_settingsKeys(settingsKeys), + m_force(force) + { } + }; + + //! A received frame + class MsgFrame : public Message { + MESSAGE_CLASS_DECLARATION + + public: + const QByteArray& getPSDU() const { return m_psdu; } + QDateTime getDateTime() const { return m_dateTime; } + bool getFCSOK() const { return m_fcsOK; } + bool getCoherent() const { return m_coherent; } + float getFrequencyOffset() const { return m_frequencyOffset; } + float getLQI() const { return m_lqi; } + float getPowerDB() const { return m_powerDB; } + float getSNR() const { return m_snr; } + + static MsgFrame* create(const QByteArray& psdu, const QDateTime& dateTime, bool fcsOK, bool coherent, + float frequencyOffset, float lqi, float powerDB, float snr) + { + return new MsgFrame(psdu, dateTime, fcsOK, coherent, frequencyOffset, lqi, powerDB, snr); + } + + private: + QByteArray m_psdu; //!< MAC frame including FCS + QDateTime m_dateTime; + bool m_fcsOK; + bool m_coherent; //!< Received by coherent rather than non-coherent detector + float m_frequencyOffset; //!< Hz + float m_lqi; //!< 0-1 + float m_powerDB; + float m_snr; //!< dB + + MsgFrame(const QByteArray& psdu, const QDateTime& dateTime, bool fcsOK, bool coherent, + float frequencyOffset, float lqi, float powerDB, float snr) : + Message(), + m_psdu(psdu), + m_dateTime(dateTime), + m_fcsOK(fcsOK), + m_coherent(coherent), + m_frequencyOffset(frequencyOffset), + m_lqi(lqi), + m_powerDB(powerDB), + m_snr(snr) + { } + }; + + IEEE_802_15_4_Demod(DeviceAPI *deviceAPI); + virtual ~IEEE_802_15_4_Demod(); + virtual void destroy() { delete this; } + virtual void setDeviceAPI(DeviceAPI *deviceAPI); + virtual DeviceAPI *getDeviceAPI() { return m_deviceAPI; } + + using BasebandSampleSink::feed; + virtual void feed(const SampleVector::const_iterator& begin, const SampleVector::const_iterator& end, bool po); + virtual void start(); + virtual void stop(); + virtual void pushMessage(Message *msg) { m_inputMessageQueue.push(msg); } + virtual QString getSinkName() { return objectName(); } + + virtual void getIdentifier(QString& id) { id = objectName(); } + virtual QString getIdentifier() const { return objectName(); } + virtual const QString& getURI() const { return getName(); } + virtual void getTitle(QString& title) { title = m_settings.m_title; } + virtual qint64 getCenterFrequency() const { return m_settings.m_inputFrequencyOffset; } + int getChannelSampleRate() const override; + int getAudioSampleRate() const override { return 0; } + 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 IEEE_802_15_4_DemodSettings& settings); + + static void webapiUpdateChannelSettings( + IEEE_802_15_4_DemodSettings& settings, + const QStringList& channelSettingsKeys, + SWGSDRangel::SWGChannelSettings& response); + + ScopeVis *getScopeSink(); + double getMagSq() const { return m_basebandSink->getMagSq(); } + + void getMagSqLevels(double& avg, double& peak, int& nbSamples) { + m_basebandSink->getMagSqLevels(avg, peak, nbSamples); + } + + uint32_t getNumberOfDeviceStreams() const; + + //! 802.15.4 channel number for a frequency, or -1 if not a channel centre frequency + static int getChannelNumber(qint64 frequency); + //! Encapsulate frame in ZEP v2, for Wireshark + static QByteArray encodeZEP(const QByteArray& psdu, const QDateTime& dateTime, int channel, int lqi, quint32 sequenceNumber); + + static const char * const m_channelIdURI; + static const char * const m_channelId; + +private: + static constexpr quint32 m_pcapLinkTypeIEEE802154WithFCS = 195; //!< PCAP link type for IEEE 802.15.4 frames including FCS + + DeviceAPI *m_deviceAPI; + QThread m_thread; + IEEE_802_15_4_DemodBaseband* m_basebandSink; + IEEE_802_15_4_DemodSettings m_settings; + int m_basebandSampleRate; //!< stored from device message used when starting baseband sink + qint64 m_centerFrequency; + QUdpSocket m_udpSocket; + quint32 m_zepSequenceNumber; + QFile m_logFile; + QTextStream m_logStream; + bool m_logPCAP; + quint64 m_framesOK; + quint64 m_framesBad; + + QNetworkAccessManager *m_networkManager; + QNetworkRequest m_networkRequest; + + virtual bool handleMessage(const Message& cmd); + void applySettings(const QStringList& settingsKeys, const IEEE_802_15_4_DemodSettings& settings, bool force = false); + void openLog(const QString& filename); + void logFrame(const MsgFrame& frame); + void webapiFormatChannelReport(SWGSDRangel::SWGChannelReport& response); + void webapiReverseSendSettings(const QList& channelSettingsKeys, const IEEE_802_15_4_DemodSettings& settings, bool force); + void webapiFormatChannelSettings( + const QList& channelSettingsKeys, + SWGSDRangel::SWGChannelSettings *swgChannelSettings, + const IEEE_802_15_4_DemodSettings& settings, + bool force + ); + +private slots: + void networkManagerFinished(QNetworkReply *reply); + void handleIndexInDeviceSetChanged(int index); +}; + +#endif // INCLUDE_IEEE_802_15_4_DEMOD_H diff --git a/plugins/channelrx/demod802.15.4/ieee_802_15_4_demodbaseband.cpp b/plugins/channelrx/demod802.15.4/ieee_802_15_4_demodbaseband.cpp new file mode 100644 index 000000000..89f4ab852 --- /dev/null +++ b/plugins/channelrx/demod802.15.4/ieee_802_15_4_demodbaseband.cpp @@ -0,0 +1,188 @@ +/////////////////////////////////////////////////////////////////////////////////// +// 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 "ieee_802_15_4_demodbaseband.h" + +MESSAGE_CLASS_DEFINITION(IEEE_802_15_4_DemodBaseband::MsgConfigureIEEE_802_15_4_DemodBaseband, Message) + +IEEE_802_15_4_DemodBaseband::IEEE_802_15_4_DemodBaseband(IEEE_802_15_4_Demod *demod) : + m_sink(demod), + m_running(false) +{ + qDebug("IEEE_802_15_4_DemodBaseband::IEEE_802_15_4_DemodBaseband"); + + m_scopeSink.setNbStreams(IEEE_802_15_4_DemodSettings::m_scopeStreams); + m_sink.setScopeSink(&m_scopeSink); + m_sampleFifo.setSize(SampleSinkFifo::getSizePolicy(48000)); + m_channelizer = new DownChannelizer(&m_sink); +} + +IEEE_802_15_4_DemodBaseband::~IEEE_802_15_4_DemodBaseband() +{ + m_inputMessageQueue.clear(); + + delete m_channelizer; +} + +void IEEE_802_15_4_DemodBaseband::reset() +{ + QMutexLocker mutexLocker(&m_mutex); + m_inputMessageQueue.clear(); + m_sampleFifo.reset(); +} + +void IEEE_802_15_4_DemodBaseband::startWork() +{ + QMutexLocker mutexLocker(&m_mutex); + QObject::connect( + &m_sampleFifo, + &SampleSinkFifo::dataReady, + this, + &IEEE_802_15_4_DemodBaseband::handleData, + Qt::QueuedConnection + ); + connect(&m_inputMessageQueue, SIGNAL(messageEnqueued()), this, SLOT(handleInputMessages())); + m_running = true; +} + +void IEEE_802_15_4_DemodBaseband::stopWork() +{ + QMutexLocker mutexLocker(&m_mutex); + disconnect(&m_inputMessageQueue, SIGNAL(messageEnqueued()), this, SLOT(handleInputMessages())); + QObject::disconnect( + &m_sampleFifo, + &SampleSinkFifo::dataReady, + this, + &IEEE_802_15_4_DemodBaseband::handleData + ); + m_running = false; +} + +void IEEE_802_15_4_DemodBaseband::setChannel(ChannelAPI *channel) +{ + m_sink.setChannel(channel); +} + +void IEEE_802_15_4_DemodBaseband::feed(const SampleVector::const_iterator& begin, const SampleVector::const_iterator& end) +{ + m_sampleFifo.write(begin, end); +} + +void IEEE_802_15_4_DemodBaseband::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 IEEE_802_15_4_DemodBaseband::handleInputMessages() +{ + Message* message; + + while ((message = m_inputMessageQueue.pop())) + { + if (!handleMessage(*message)) { + qDebug("%s: unhandled message: %s", Q_FUNC_INFO, message->getIdentifier()); + } + delete message; + } +} + +bool IEEE_802_15_4_DemodBaseband::handleMessage(const Message& cmd) +{ + if (MsgConfigureIEEE_802_15_4_DemodBaseband::match(cmd)) + { + QMutexLocker mutexLocker(&m_mutex); + MsgConfigureIEEE_802_15_4_DemodBaseband& cfg = (MsgConfigureIEEE_802_15_4_DemodBaseband&) cmd; + qDebug() << "IEEE_802_15_4_DemodBaseband::handleMessage: MsgConfigureIEEE_802_15_4_DemodBaseband"; + + applySettings(cfg.getSettingsKeys(), cfg.getSettings(), cfg.getForce()); + + return true; + } + else if (DSPSignalNotification::match(cmd)) + { + QMutexLocker mutexLocker(&m_mutex); + DSPSignalNotification& notif = (DSPSignalNotification&) cmd; + qDebug() << "IEEE_802_15_4_DemodBaseband::handleMessage: DSPSignalNotification: basebandSampleRate: " << notif.getSampleRate(); + setBasebandSampleRate(notif.getSampleRate()); + m_sampleFifo.setSize(SampleSinkFifo::getSizePolicy(notif.getSampleRate())); + + return true; + } + else + { + return false; + } +} + +void IEEE_802_15_4_DemodBaseband::applySettings(const QStringList& settingsKeys, const IEEE_802_15_4_DemodSettings& settings, bool force) +{ + if ((settingsKeys.contains("inputFrequencyOffset") && (settings.m_inputFrequencyOffset != m_settings.m_inputFrequencyOffset)) + || (settingsKeys.contains("phy") && (settings.m_phy != m_settings.m_phy)) + || (settingsKeys.contains("samplesPerChip") && (settings.m_samplesPerChip != m_settings.m_samplesPerChip)) + || force) + { + m_channelizer->setChannelization(settings.getChannelSampleRate(), settings.m_inputFrequencyOffset); + m_sink.applyChannelSettings(m_channelizer->getChannelSampleRate(), m_channelizer->getChannelFrequencyOffset()); + } + + m_sink.applySettings(settingsKeys, settings, force); + + if (force) { + m_settings = settings; + } else { + m_settings.applySettings(settingsKeys, settings); + } +} + +int IEEE_802_15_4_DemodBaseband::getChannelSampleRate() const +{ + return m_channelizer->getChannelSampleRate(); +} + +void IEEE_802_15_4_DemodBaseband::setBasebandSampleRate(int sampleRate) +{ + m_channelizer->setBasebandSampleRate(sampleRate); + m_sink.applyChannelSettings(m_channelizer->getChannelSampleRate(), m_channelizer->getChannelFrequencyOffset()); +} diff --git a/plugins/channelrx/demod802.15.4/ieee_802_15_4_demodbaseband.h b/plugins/channelrx/demod802.15.4/ieee_802_15_4_demodbaseband.h new file mode 100644 index 000000000..4a65048a7 --- /dev/null +++ b/plugins/channelrx/demod802.15.4/ieee_802_15_4_demodbaseband.h @@ -0,0 +1,103 @@ +/////////////////////////////////////////////////////////////////////////////////// +// 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_IEEE_802_15_4_DEMODBASEBAND_H +#define INCLUDE_IEEE_802_15_4_DEMODBASEBAND_H + +#include +#include + +#include "dsp/samplesinkfifo.h" +#include "dsp/scopevis.h" +#include "util/message.h" +#include "util/messagequeue.h" + +#include "ieee_802_15_4_demodsink.h" + +class DownChannelizer; +class ChannelAPI; +class IEEE_802_15_4_Demod; + +class IEEE_802_15_4_DemodBaseband : public QObject +{ + Q_OBJECT +public: + class MsgConfigureIEEE_802_15_4_DemodBaseband : public Message { + MESSAGE_CLASS_DECLARATION + + public: + const IEEE_802_15_4_DemodSettings& getSettings() const { return m_settings; } + const QStringList& getSettingsKeys() const { return m_settingsKeys; } + bool getForce() const { return m_force; } + + static MsgConfigureIEEE_802_15_4_DemodBaseband* create(const QStringList& settingsKeys, const IEEE_802_15_4_DemodSettings& settings, bool force) + { + return new MsgConfigureIEEE_802_15_4_DemodBaseband(settingsKeys, settings, force); + } + + private: + IEEE_802_15_4_DemodSettings m_settings; + QStringList m_settingsKeys; + bool m_force; + + MsgConfigureIEEE_802_15_4_DemodBaseband(const QStringList& settingsKeys, const IEEE_802_15_4_DemodSettings& settings, bool force) : + Message(), + m_settings(settings), + m_settingsKeys(settingsKeys), + m_force(force) + { } + }; + + IEEE_802_15_4_DemodBaseband(IEEE_802_15_4_Demod *demod); + ~IEEE_802_15_4_DemodBaseband(); + 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); + } + void setMessageQueueToChannel(MessageQueue *messageQueue) { m_sink.setMessageQueueToChannel(messageQueue); } + void setBasebandSampleRate(int sampleRate); + int getChannelSampleRate() const; + void setChannel(ChannelAPI *channel); + double getMagSq() const { return m_sink.getMagSq(); } + bool isRunning() const { return m_running; } + void setFifoLabel(const QString& label) { m_sampleFifo.setLabel(label); } + ScopeVis *getScopeSink() { return &m_scopeSink; } + +private: + SampleSinkFifo m_sampleFifo; + DownChannelizer *m_channelizer; + IEEE_802_15_4_DemodSink m_sink; + MessageQueue m_inputMessageQueue; //!< Queue for asynchronous inbound communication + IEEE_802_15_4_DemodSettings m_settings; + ScopeVis m_scopeSink; + bool m_running; + QRecursiveMutex m_mutex; + + bool handleMessage(const Message& cmd); + void applySettings(const QStringList& settingsKeys, const IEEE_802_15_4_DemodSettings& settings, bool force = false); + +private slots: + void handleInputMessages(); + void handleData(); //!< Handle data when samples have to be processed +}; + +#endif // INCLUDE_IEEE_802_15_4_DEMODBASEBAND_H diff --git a/plugins/channelrx/demod802.15.4/ieee_802_15_4_demodgui.cpp b/plugins/channelrx/demod802.15.4/ieee_802_15_4_demodgui.cpp new file mode 100644 index 000000000..d93aca40e --- /dev/null +++ b/plugins/channelrx/demod802.15.4/ieee_802_15_4_demodgui.cpp @@ -0,0 +1,930 @@ +/////////////////////////////////////////////////////////////////////////////////// +// 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 "ieee_802_15_4_demodgui.h" + +#include "device/deviceuiset.h" +#include "dsp/dspcommands.h" +#include "dsp/glscopesettings.h" +#include "dsp/scopevis.h" +#include "ui_ieee_802_15_4_demodgui.h" +#include "plugin/pluginapi.h" +#include "util/csv.h" +#include "util/db.h" +#include "util/ieee_802_15_4.h" +#include "gui/messagedialog.h" +#include "gui/basicchannelsettingsdialog.h" +#include "gui/datetimedelegate.h" +#include "gui/dialpopup.h" +#include "gui/dialogpositioner.h" +#include "gui/tabletapandhold.h" +#include "maincore.h" + +#include "ieee_802_15_4_demod.h" + +void IEEE_802_15_4_DemodGUI::resizeTable() +{ + // Fill table with a row of dummy data that will size the columns nicely + // Trailing spaces are for sort arrow + int row = ui->frames->rowCount(); + ui->frames->setRowCount(row + 1); + ui->frames->setItem(row, FRAME_COL_DATE_TIME, new QTableWidgetItem("2016/04/15 10:17:00-")); + ui->frames->setItem(row, FRAME_COL_TYPE, new QTableWidgetItem("Command-")); + ui->frames->setItem(row, FRAME_COL_SEQ, new QTableWidgetItem("255-")); + ui->frames->setItem(row, FRAME_COL_DST_PAN, new QTableWidgetItem("0xffff-")); + ui->frames->setItem(row, FRAME_COL_DST_ADDR, new QTableWidgetItem("00:11:22:33:44:55:66:77-")); + ui->frames->setItem(row, FRAME_COL_SRC_PAN, new QTableWidgetItem("0xffff-")); + ui->frames->setItem(row, FRAME_COL_SRC_ADDR, new QTableWidgetItem("00:11:22:33:44:55:66:77-")); + ui->frames->setItem(row, FRAME_COL_INFO, new QTableWidgetItem("Association Request")); + ui->frames->setItem(row, FRAME_COL_LENGTH, new QTableWidgetItem("127-")); + ui->frames->setItem(row, FRAME_COL_PAYLOAD, new QTableWidgetItem("000102030405060708090a0b0c0d0e0f")); + ui->frames->setItem(row, FRAME_COL_PSDU, new QTableWidgetItem("000102030405060708090a0b0c0d0e0f")); + ui->frames->setItem(row, FRAME_COL_FCS, new QTableWidgetItem("Bad-")); + ui->frames->setItem(row, FRAME_COL_POWER, new QTableWidgetItem("-100.0-")); + ui->frames->setItem(row, FRAME_COL_SNR, new QTableWidgetItem("30.0-")); + ui->frames->setItem(row, FRAME_COL_LQI, new QTableWidgetItem("0.00-")); + ui->frames->setItem(row, FRAME_COL_FREQUENCY_OFFSET, new QTableWidgetItem("-200000-")); + ui->frames->resizeColumnsToContents(); + ui->frames->removeRow(row); +} + +// Columns in table reordered +void IEEE_802_15_4_DemodGUI::frames_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 IEEE_802_15_4_DemodGUI::frames_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 IEEE_802_15_4_DemodGUI::framesColumnSelectMenu(QPoint pos) +{ + m_framesMenu->popup(ui->frames->horizontalHeader()->viewport()->mapToGlobal(pos)); +} + +// Hide/show column when menu selected +void IEEE_802_15_4_DemodGUI::framesColumnSelectMenuChecked(bool checked) +{ + (void) checked; + + QAction* action = qobject_cast(sender()); + + if (action != nullptr) + { + int idx = action->data().toInt(nullptr); + ui->frames->setColumnHidden(idx, !action->isChecked()); + } +} + +// Create column select menu item +QAction *IEEE_802_15_4_DemodGUI::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; +} + +IEEE_802_15_4_DemodGUI* IEEE_802_15_4_DemodGUI::create(PluginAPI* pluginAPI, DeviceUISet *deviceUISet, BasebandSampleSink *rxChannel) +{ + IEEE_802_15_4_DemodGUI* gui = new IEEE_802_15_4_DemodGUI(pluginAPI, deviceUISet, rxChannel); + return gui; +} + +void IEEE_802_15_4_DemodGUI::destroy() +{ + delete this; +} + +void IEEE_802_15_4_DemodGUI::resetToDefaults() +{ + m_settings.resetToDefaults(); + displaySettings(); + applySettings(QStringList(), true); +} + +QByteArray IEEE_802_15_4_DemodGUI::serialize() const +{ + return m_settings.serialize(); +} + +bool IEEE_802_15_4_DemodGUI::deserialize(const QByteArray& data) +{ + if (m_settings.deserialize(data)) + { + displaySettings(); + applySettings(QStringList(), true); + return true; + } + else + { + resetToDefaults(); + return false; + } +} + +// Add row to table +void IEEE_802_15_4_DemodGUI::frameReceived(const QByteArray& psdu, const QDateTime& dateTime, bool fcsOK, float frequencyOffset, + float lqi, float powerDB, float snr) +{ + IEEE_802_15_4_FrameDecoder mac; + mac.decode(psdu); + + // Is scroll bar at bottom + QScrollBar *sb = ui->frames->verticalScrollBar(); + bool scrollToBottom = sb->value() == sb->maximum(); + + ui->frames->setSortingEnabled(false); + int row = ui->frames->rowCount(); + ui->frames->setRowCount(row + 1); + + QTableWidgetItem *items[IEEE_802_15_4_DEMOD_COLUMNS]; + for (int i = 0; i < IEEE_802_15_4_DEMOD_COLUMNS; i++) + { + items[i] = new QTableWidgetItem(); + ui->frames->setItem(row, i, items[i]); + } + + items[FRAME_COL_DATE_TIME]->setData(Qt::DisplayRole, dateTime); + items[FRAME_COL_TYPE]->setText(mac.m_valid ? mac.getFrameTypeString() : "Invalid"); + items[FRAME_COL_TYPE]->setData(Qt::UserRole, (int) mac.m_frameType); + if (mac.m_hasSeqNo) { + items[FRAME_COL_SEQ]->setData(Qt::DisplayRole, (int) mac.m_seqNo); + } + items[FRAME_COL_DST_PAN]->setText(mac.getDestPANIDString()); + items[FRAME_COL_DST_ADDR]->setText(mac.getDestAddressString()); + items[FRAME_COL_SRC_PAN]->setText(mac.getSrcPANIDString()); + items[FRAME_COL_SRC_ADDR]->setText(mac.getSrcAddressString()); + items[FRAME_COL_INFO]->setText(mac.toString()); + items[FRAME_COL_LENGTH]->setData(Qt::DisplayRole, (int) psdu.size()); + items[FRAME_COL_PAYLOAD]->setText(mac.m_payload.toHex()); + items[FRAME_COL_PSDU]->setText(psdu.toHex()); + items[FRAME_COL_FCS]->setText(fcsOK ? "OK" : "Bad"); + items[FRAME_COL_POWER]->setData(Qt::DisplayRole, std::round(powerDB * 10.0) / 10.0); + items[FRAME_COL_SNR]->setData(Qt::DisplayRole, std::round(snr * 10.0) / 10.0); + items[FRAME_COL_LQI]->setData(Qt::DisplayRole, std::round(lqi * 100.0) / 100.0); + items[FRAME_COL_FREQUENCY_OFFSET]->setData(Qt::DisplayRole, (int) std::round(frequencyOffset)); + + if (!fcsOK) + { + for (int i = 0; i < IEEE_802_15_4_DEMOD_COLUMNS; i++) { + items[i]->setForeground(QBrush(Qt::red)); + } + } + + if (!m_loadingData) + { + filterRow(row); + ui->frames->setSortingEnabled(true); + + if (scrollToBottom) { + ui->frames->scrollToBottom(); + } + } +} + +bool IEEE_802_15_4_DemodGUI::handleMessage(const Message& message) +{ + if (IEEE_802_15_4_Demod::MsgConfigureIEEE_802_15_4_Demod::match(message)) + { + qDebug("IEEE_802_15_4_DemodGUI::handleMessage: IEEE_802_15_4_Demod::MsgConfigureIEEE_802_15_4_Demod"); + const IEEE_802_15_4_Demod::MsgConfigureIEEE_802_15_4_Demod& cfg = (IEEE_802_15_4_Demod::MsgConfigureIEEE_802_15_4_Demod&) message; + + if (cfg.getForce()) { + m_settings = cfg.getSettings(); + } else { + m_settings.applySettings(cfg.getSettingsKeys(), cfg.getSettings()); + } + + blockApplySettings(true); + ui->scopeGUI->updateSettings(); + m_channelMarker.updateSettings(static_cast(m_settings.m_channelMarker)); + displaySettings(); + blockApplySettings(false); + return true; + } + else if (IEEE_802_15_4_Demod::MsgFrame::match(message)) + { + const IEEE_802_15_4_Demod::MsgFrame& frame = (const IEEE_802_15_4_Demod::MsgFrame&) message; + frameReceived(frame.getPSDU(), frame.getDateTime(), frame.getFCSOK(), frame.getFrequencyOffset(), + frame.getLQI(), frame.getPowerDB(), frame.getSNR()); + 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(); + checkSampleRate(); + return true; + } + + return false; +} + +void IEEE_802_15_4_DemodGUI::handleInputMessages() +{ + Message* message; + + while ((message = getInputMessageQueue()->pop())) + { + if (!handleMessage(*message)) { + qDebug("%s: unhandled message: %s", Q_FUNC_INFO, message->getIdentifier()); + } + delete message; + } +} + +void IEEE_802_15_4_DemodGUI::channelMarkerChangedByCursor() +{ + ui->deltaFrequency->setValue(m_channelMarker.getCenterFrequency()); + m_settings.m_inputFrequencyOffset = m_channelMarker.getCenterFrequency(); + applySettings(QStringList({"inputFrequencyOffset"})); +} + +void IEEE_802_15_4_DemodGUI::channelMarkerHighlightedByCursor() +{ + setHighlighted(m_channelMarker.getHighlighted()); +} + +void IEEE_802_15_4_DemodGUI::on_deltaFrequency_changed(qint64 value) +{ + m_channelMarker.setCenterFrequency(value); + m_settings.m_inputFrequencyOffset = m_channelMarker.getCenterFrequency(); + updateAbsoluteCenterFrequency(); + applySettings(QStringList({"inputFrequencyOffset"})); +} + +void IEEE_802_15_4_DemodGUI::on_phy_currentIndexChanged(int index) +{ + (void) index; + + // Also sets RF bandwidth and maximum frequency offset to defaults for the PHY + m_settings.setPHY(ui->phy->currentText()); + displayPHYDependent(); + applySettings(QStringList({"phy", "rfBandwidth", "maxFrequencyOffset"})); +} + +void IEEE_802_15_4_DemodGUI::on_samplesPerChip_valueChanged(int value) +{ + m_settings.m_samplesPerChip = value; + displayPHYDependent(); + applySettings(QStringList({"samplesPerChip"})); +} + +void IEEE_802_15_4_DemodGUI::on_rfBW_valueChanged(int value) +{ + m_settings.m_rfBandwidth = value * 10000.0f; + ui->rfBWText->setText(QString("%1M").arg(m_settings.m_rfBandwidth / 1e6, 0, 'f', 2)); + m_channelMarker.setBandwidth(m_settings.m_rfBandwidth); + checkSampleRate(); + applySettings(QStringList({"rfBandwidth"})); +} + +void IEEE_802_15_4_DemodGUI::on_maxFrequencyOffset_valueChanged(int value) +{ + m_settings.m_maxFrequencyOffset = value * 1000.0f; + applySettings(QStringList({"maxFrequencyOffset"})); +} + +void IEEE_802_15_4_DemodGUI::on_threshold_valueChanged(int value) +{ + m_settings.m_threshold = value / 100.0f; + ui->thresholdText->setText(QString("%1").arg(m_settings.m_threshold, 0, 'f', 2)); + applySettings(QStringList({"threshold"})); +} + +void IEEE_802_15_4_DemodGUI::on_udpEnabled_clicked(bool checked) +{ + m_settings.m_udpEnabled = checked; + applySettings(QStringList({"udpEnabled"})); +} + +void IEEE_802_15_4_DemodGUI::on_udpAddress_editingFinished() +{ + m_settings.m_udpAddress = ui->udpAddress->text(); + applySettings(QStringList({"udpAddress"})); +} + +void IEEE_802_15_4_DemodGUI::on_udpPort_editingFinished() +{ + m_settings.m_udpPort = ui->udpPort->text().toInt(); + applySettings(QStringList({"udpPort"})); +} + +void IEEE_802_15_4_DemodGUI::on_udpFormat_currentIndexChanged(int index) +{ + m_settings.m_udpFormat = (IEEE_802_15_4_DemodSettings::UDPFormat) index; + applySettings(QStringList({"udpFormat"})); +} + +void IEEE_802_15_4_DemodGUI::on_filterFrameType_currentIndexChanged(int index) +{ + m_settings.m_filterFrameType = (IEEE_802_15_4_DemodSettings::FrameTypeFilter) index; + filter(); + applySettings(QStringList({"filterFrameType"})); +} + +void IEEE_802_15_4_DemodGUI::on_filterPANID_editingFinished() +{ + m_settings.m_filterPANID = ui->filterPANID->text(); + filter(); + applySettings(QStringList({"filterPANID"})); +} + +void IEEE_802_15_4_DemodGUI::on_filterAddress_editingFinished() +{ + m_settings.m_filterAddress = ui->filterAddress->text(); + filter(); + applySettings(QStringList({"filterAddress"})); +} + +void IEEE_802_15_4_DemodGUI::on_showBadFCS_toggled(bool checked) +{ + m_settings.m_showBadFCS = checked; + filter(); + applySettings(QStringList({"showBadFCS"})); +} + +void IEEE_802_15_4_DemodGUI::on_useFileTime_toggled(bool checked) +{ + m_settings.m_useFileTime = checked; + applySettings(QStringList({"useFileTime"})); +} + +void IEEE_802_15_4_DemodGUI::on_clearTable_clicked() +{ + ui->frames->setRowCount(0); +} + +void IEEE_802_15_4_DemodGUI::filterRow(int row) +{ + bool hidden = false; + + if (m_settings.m_filterFrameType != IEEE_802_15_4_DemodSettings::FilterAll) + { + int type = ui->frames->item(row, FRAME_COL_TYPE)->data(Qt::UserRole).toInt(); + int filterType; + + switch (m_settings.m_filterFrameType) + { + case IEEE_802_15_4_DemodSettings::FilterBeacon: + filterType = IEEE_802_15_4_FrameDecoder::Beacon; + break; + case IEEE_802_15_4_DemodSettings::FilterData: + filterType = IEEE_802_15_4_FrameDecoder::Data; + break; + case IEEE_802_15_4_DemodSettings::FilterAck: + filterType = IEEE_802_15_4_FrameDecoder::Ack; + break; + case IEEE_802_15_4_DemodSettings::FilterCommand: + filterType = IEEE_802_15_4_FrameDecoder::Command; + break; + default: + filterType = -1; + break; + } + + if (filterType >= 0) { + hidden = type != filterType; + } else { + hidden = type <= IEEE_802_15_4_FrameDecoder::Command; + } + } + + if (!hidden && !m_settings.m_filterPANID.isEmpty()) + { + QRegularExpression re(QRegularExpression::anchoredPattern(m_settings.m_filterPANID), QRegularExpression::CaseInsensitiveOption); + bool match = re.match(ui->frames->item(row, FRAME_COL_DST_PAN)->text()).hasMatch() + || re.match(ui->frames->item(row, FRAME_COL_SRC_PAN)->text()).hasMatch(); + hidden = !match; + } + + if (!hidden && !m_settings.m_filterAddress.isEmpty()) + { + QRegularExpression re(QRegularExpression::anchoredPattern(m_settings.m_filterAddress), QRegularExpression::CaseInsensitiveOption); + bool match = re.match(ui->frames->item(row, FRAME_COL_DST_ADDR)->text()).hasMatch() + || re.match(ui->frames->item(row, FRAME_COL_SRC_ADDR)->text()).hasMatch(); + hidden = !match; + } + + if (!hidden && !m_settings.m_showBadFCS) { + hidden = ui->frames->item(row, FRAME_COL_FCS)->text() != "OK"; + } + + ui->frames->setRowHidden(row, hidden); +} + +void IEEE_802_15_4_DemodGUI::filter() +{ + for (int i = 0; i < ui->frames->rowCount(); i++) { + filterRow(i); + } +} + +void IEEE_802_15_4_DemodGUI::onWidgetRolled(QWidget* widget, bool rollDown) +{ + (void) widget; + (void) rollDown; + + getRollupContents()->saveState(m_rollupState); + applySettings(QStringList({"rollupState"})); +} + +void IEEE_802_15_4_DemodGUI::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_demod->getNumberOfDeviceStreams()); + dialog.setStreamIndex(m_settings.m_streamIndex); + } + + dialog.move(p); + new DialogPositioner(&dialog, true); + 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(); +} + +IEEE_802_15_4_DemodGUI::IEEE_802_15_4_DemodGUI(PluginAPI* pluginAPI, DeviceUISet *deviceUISet, BasebandSampleSink *rxChannel, QWidget* parent) : + ChannelGUI(parent), + ui(new Ui::IEEE_802_15_4_DemodGUI), + m_pluginAPI(pluginAPI), + m_deviceUISet(deviceUISet), + m_channelMarker(this), + m_deviceCenterFrequency(0), + m_basebandSampleRate(1), + m_doApplySettings(true), + m_tickCount(0), + m_loadingData(false) +{ + setAttribute(Qt::WA_DeleteOnClose, true); + m_helpURL = "plugins/channelrx/demod802.15.4/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_demod = reinterpret_cast(rxChannel); + m_demod->setMessageQueueToGUI(getInputMessageQueue()); + + connect(&MainCore::instance()->getMasterTimer(), SIGNAL(timeout()), this, SLOT(tick())); // 50 ms + + m_scopeVis = m_demod->getScopeSink(); + m_scopeVis->setGLScope(ui->glScope); + ui->glScope->connectTimer(MainCore::instance()->getMasterTimer()); + ui->scopeGUI->setBuddies(m_scopeVis->getInputMessageQueue(), m_scopeVis, ui->glScope); + ui->scopeGUI->setStreams(QStringList({"IQ", "MagSq", "Detect", "Correlation", "Chip", "Phase", "State", "FCS"})); + + // Scope settings to display the IQ waveforms + ui->scopeGUI->setPreTrigger(1); + GLScopeSettings::TraceData traceDataI, traceDataQ; + traceDataI.m_projectionType = Projector::ProjectionReal; + traceDataI.m_amp = 1.0; // for -1 to +1 + traceDataI.m_ofs = 0.0; // vertical offset + traceDataQ.m_projectionType = Projector::ProjectionImag; + traceDataQ.m_amp = 1.0; + traceDataQ.m_ofs = 0.0; + ui->scopeGUI->changeTrace(0, traceDataI); + ui->scopeGUI->addTrace(traceDataQ); + ui->scopeGUI->setDisplayMode(GLScopeSettings::DisplayXYV); + ui->scopeGUI->focusOnTrace(0); // re-focus to take changes into account in the GUI + + GLScopeSettings::TriggerData triggerData; + triggerData.m_triggerLevel = 0.1; + triggerData.m_triggerLevelCoarse = 10; + triggerData.m_triggerPositiveEdge = true; + ui->scopeGUI->changeTrigger(0, triggerData); + ui->scopeGUI->focusOnTrigger(0); // re-focus to take changes into account in the GUI + + ui->deltaFrequencyLabel->setText(QString("%1f").arg(QChar(0x94, 0x03))); + ui->deltaFrequency->setColorMapper(ColorMapper(ColorMapper::GrayGold)); + ui->deltaFrequency->setValueRange(false, 8, -99999999, 99999999); + ui->channelPowerMeter->setColorTheme(LevelMeterSignalDB::ColorGreenAndBlue); + + m_channelMarker.blockSignals(true); + m_channelMarker.setColor(QColor(255, 0, 255)); + m_channelMarker.setBandwidth(m_settings.m_rfBandwidth); + m_channelMarker.setCenterFrequency(m_settings.m_inputFrequencyOffset); + m_channelMarker.setTitle("802.15.4 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.setScopeGUI(ui->scopeGUI); + 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())); + + // Display date and time in a single column, which sorts chronologically + ui->frames->setItemDelegateForColumn(FRAME_COL_DATE_TIME, new DateTimeDelegate("yyyy/MM/dd hh:mm:ss", ui->frames)); + + // Resize the table using dummy data + resizeTable(); + // Allow user to reorder columns + ui->frames->horizontalHeader()->setSectionsMovable(true); + // Allow user to sort table by clicking on headers + ui->frames->setSortingEnabled(true); + // Add context menu to allow hiding/showing of columns + m_framesMenu = new QMenu(ui->frames); + for (int i = 0; i < ui->frames->horizontalHeader()->count(); i++) + { + QString text = ui->frames->horizontalHeaderItem(i)->text(); + m_framesMenu->addAction(createCheckableItem(text, i, true, SLOT(framesColumnSelectMenuChecked()))); + } + ui->frames->horizontalHeader()->setContextMenuPolicy(Qt::CustomContextMenu); + connect(ui->frames->horizontalHeader(), SIGNAL(customContextMenuRequested(QPoint)), SLOT(framesColumnSelectMenu(QPoint))); + // Get signals when columns change + connect(ui->frames->horizontalHeader(), SIGNAL(sectionMoved(int, int, int)), SLOT(frames_sectionMoved(int, int, int))); + connect(ui->frames->horizontalHeader(), SIGNAL(sectionResized(int, int, int)), SLOT(frames_sectionResized(int, int, int))); + ui->frames->setContextMenuPolicy(Qt::CustomContextMenu); + connect(ui->frames, SIGNAL(customContextMenuRequested(QPoint)), SLOT(customContextMenuRequested(QPoint))); + TableTapAndHold *tableTapAndHold = new TableTapAndHold(ui->frames); + connect(tableTapAndHold, &TableTapAndHold::tapAndHold, this, &IEEE_802_15_4_DemodGUI::customContextMenuRequested); + + ui->scopeContainer->setVisible(false); + + displaySettings(); + makeUIConnections(); + applySettings(QStringList(), true); + DialPopup::addPopupsToChildDials(this); + m_resizer.enableChildMouseTracking(); +} + +void IEEE_802_15_4_DemodGUI::customContextMenuRequested(QPoint pos) +{ + QTableWidgetItem *item = ui->frames->itemAt(pos); + + if (item) + { + QMenu* tableContextMenu = new QMenu(ui->frames); + connect(tableContextMenu, &QMenu::aboutToHide, tableContextMenu, &QMenu::deleteLater); + 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); + tableContextMenu->popup(ui->frames->viewport()->mapToGlobal(pos)); + } +} + +IEEE_802_15_4_DemodGUI::~IEEE_802_15_4_DemodGUI() +{ + delete ui; +} + +void IEEE_802_15_4_DemodGUI::blockApplySettings(bool block) +{ + m_doApplySettings = !block; +} + +void IEEE_802_15_4_DemodGUI::applySettings(const QStringList& settingsKeys, bool force) +{ + if (m_doApplySettings) + { + IEEE_802_15_4_Demod::MsgConfigureIEEE_802_15_4_Demod* message = IEEE_802_15_4_Demod::MsgConfigureIEEE_802_15_4_Demod::create(settingsKeys, m_settings, force); + m_demod->getInputMessageQueue()->push(message); + } +} + +// Display settings that depend on the PHY or samples per chip +void IEEE_802_15_4_DemodGUI::displayPHYDependent() +{ + bool block = !m_doApplySettings; + blockApplySettings(true); + + // Don't let the widgets' slots round the settings to the widgets' resolution + QSignalBlocker rfBWBlocker(ui->rfBW); + QSignalBlocker maxFrequencyOffsetBlocker(ui->maxFrequencyOffset); + + IEEE_802_15_4_PHY phy = m_settings.getPHY(); + ui->chipRate->setText(QString("%1k").arg(phy.getChipRate() / 1000)); + ui->sampleRate->setText(QString("%1M").arg(m_settings.getChannelSampleRate() / 1e6, 0, 'f', 1)); + ui->rfBW->setValue((int) std::round(m_settings.m_rfBandwidth / 10000.0f)); + ui->rfBWText->setText(QString("%1M").arg(m_settings.m_rfBandwidth / 1e6, 0, 'f', 2)); + ui->maxFrequencyOffset->setValue((int) std::round(m_settings.m_maxFrequencyOffset / 1000.0f)); + m_channelMarker.setBandwidth(m_settings.m_rfBandwidth); + m_scopeVis->setLiveRate(m_settings.getChannelSampleRate()); + checkSampleRate(); + + blockApplySettings(block); +} + +// Warn if the device sample rate is too low for the RF bandwidth +void IEEE_802_15_4_DemodGUI::checkSampleRate() +{ + if (m_basebandSampleRate < m_settings.m_rfBandwidth) + { + ui->rfBWText->setStyleSheet("QLabel { background-color : red; }"); + ui->rfBWText->setToolTip(QString("Device sample rate (%1 MSa/s) is lower than the RF bandwidth").arg(m_basebandSampleRate / 1e6, 0, 'f', 2)); + } + else + { + ui->rfBWText->setStyleSheet(""); + ui->rfBWText->setToolTip(""); + } +} + +void IEEE_802_15_4_DemodGUI::displaySettings() +{ + m_channelMarker.blockSignals(true); + m_channelMarker.setBandwidth(m_settings.m_rfBandwidth); + 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); + + // Widget slots modify m_settings (E.g. selecting a PHY sets the RF bandwidth to the + // default for it), so must not be run when displaying settings + QSignalBlocker phyBlocker(ui->phy); + QSignalBlocker samplesPerChipBlocker(ui->samplesPerChip); + QSignalBlocker thresholdBlocker(ui->threshold); + QSignalBlocker udpFormatBlocker(ui->udpFormat); + QSignalBlocker filterFrameTypeBlocker(ui->filterFrameType); + QSignalBlocker showBadFCSBlocker(ui->showBadFCS); + QSignalBlocker useFileTimeBlocker(ui->useFileTime); + + ui->deltaFrequency->setValue(m_channelMarker.getCenterFrequency()); + + int phyIndex = ui->phy->findText(m_settings.m_phy); + ui->phy->setCurrentIndex(phyIndex >= 0 ? phyIndex : ui->phy->count() - 1); + ui->samplesPerChip->setValue(m_settings.m_samplesPerChip); + displayPHYDependent(); + + ui->thresholdText->setText(QString("%1").arg(m_settings.m_threshold, 0, 'f', 2)); + ui->threshold->setValue((int) std::round(m_settings.m_threshold * 100.0f)); + + updateIndexLabel(); + + ui->udpEnabled->setChecked(m_settings.m_udpEnabled); + ui->udpAddress->setText(m_settings.m_udpAddress); + ui->udpPort->setText(QString::number(m_settings.m_udpPort)); + ui->udpFormat->setCurrentIndex((int) m_settings.m_udpFormat); + + ui->filterFrameType->setCurrentIndex((int) m_settings.m_filterFrameType); + ui->filterPANID->setText(m_settings.m_filterPANID); + ui->filterAddress->setText(m_settings.m_filterAddress); + ui->showBadFCS->setChecked(m_settings.m_showBadFCS); + + ui->logFilename->setToolTip(QString(".csv/.pcap 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->frames->horizontalHeader(); + for (int i = 0; i < IEEE_802_15_4_DEMOD_COLUMNS; i++) + { + bool hidden = m_settings.m_columnSizes[i] == 0; + header->setSectionHidden(i, hidden); + m_framesMenu->actions().at(i)->setChecked(!hidden); + if (m_settings.m_columnSizes[i] > 0) { + ui->frames->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 IEEE_802_15_4_DemodGUI::leaveEvent(QEvent* event) +{ + m_channelMarker.setHighlighted(false); + ChannelGUI::leaveEvent(event); +} + +void IEEE_802_15_4_DemodGUI::enterEvent(EnterEventType* event) +{ + m_channelMarker.setHighlighted(true); + ChannelGUI::enterEvent(event); +} + +void IEEE_802_15_4_DemodGUI::tick() +{ + double magsqAvg, magsqPeak; + int nbMagsqSamples; + m_demod->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)); + } + + m_tickCount++; +} + +void IEEE_802_15_4_DemodGUI::on_logEnable_clicked(bool checked) +{ + m_settings.m_logEnabled = checked; + applySettings(QStringList({"logEnabled"})); +} + +void IEEE_802_15_4_DemodGUI::on_logFilename_clicked() +{ + // Get filename to save to + QFileDialog fileDialog(nullptr, "Select file to log received frames to", "", "*.csv *.pcap"); + 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/.pcap log filename: %1").arg(m_settings.m_logFilename)); + applySettings(QStringList({"logFilename"})); + } + } +} + +// Read .csv log and process as received frames +void IEEE_802_15_4_DemodGUI::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)) + { + m_loadingData = true; + QTextStream in(&file); + QString error; + QHash colIndexes = CSV::readHeader(in, {"Date", "Time", "Data", "FCS"}, error); + + if (error.isEmpty()) + { + int dateCol = colIndexes.value("Date"); + int timeCol = colIndexes.value("Time"); + int dataCol = colIndexes.value("Data"); + int fcsCol = colIndexes.value("FCS"); + int powerCol = colIndexes.value("Power", -1); + int snrCol = colIndexes.value("SNR", -1); + int lqiCol = colIndexes.value("LQI", -1); + int freqCol = colIndexes.value("Freq Offset", -1); + int maxCol = std::max({dateCol, timeCol, dataCol, fcsCol}); + QStringList cols; + + while (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()); + bool fcsOK = cols[fcsCol] == "OK"; + auto value = [&cols](int col) -> float { + return (col >= 0) && (col < cols.size()) ? cols[col].toFloat() : 0.0f; + }; + + frameReceived(bytes, dateTime, fcsOK, value(freqCol), value(lqiCol), value(powerCol), value(snrCol)); + } + } + } + else + { + MessageDialog::critical(this, "802.15.4 Demod", error); + } + + m_loadingData = false; + ui->frames->setSortingEnabled(true); + filter(); + } + else + { + MessageDialog::critical(this, "802.15.4 Demod", QString("Failed to open file %1").arg(fileNames[0])); + } + } + } +} + +void IEEE_802_15_4_DemodGUI::makeUIConnections() +{ + QObject::connect(ui->deltaFrequency, &ValueDialZ::changed, this, &IEEE_802_15_4_DemodGUI::on_deltaFrequency_changed); + QObject::connect(ui->phy, QOverload::of(&QComboBox::currentIndexChanged), this, &IEEE_802_15_4_DemodGUI::on_phy_currentIndexChanged); + QObject::connect(ui->samplesPerChip, QOverload::of(&QSpinBox::valueChanged), this, &IEEE_802_15_4_DemodGUI::on_samplesPerChip_valueChanged); + QObject::connect(ui->rfBW, &QSlider::valueChanged, this, &IEEE_802_15_4_DemodGUI::on_rfBW_valueChanged); + QObject::connect(ui->maxFrequencyOffset, QOverload::of(&QSpinBox::valueChanged), this, &IEEE_802_15_4_DemodGUI::on_maxFrequencyOffset_valueChanged); + QObject::connect(ui->threshold, &QDial::valueChanged, this, &IEEE_802_15_4_DemodGUI::on_threshold_valueChanged); + QObject::connect(ui->udpEnabled, &QCheckBox::clicked, this, &IEEE_802_15_4_DemodGUI::on_udpEnabled_clicked); + QObject::connect(ui->udpAddress, &QLineEdit::editingFinished, this, &IEEE_802_15_4_DemodGUI::on_udpAddress_editingFinished); + QObject::connect(ui->udpPort, &QLineEdit::editingFinished, this, &IEEE_802_15_4_DemodGUI::on_udpPort_editingFinished); + QObject::connect(ui->udpFormat, QOverload::of(&QComboBox::currentIndexChanged), this, &IEEE_802_15_4_DemodGUI::on_udpFormat_currentIndexChanged); + QObject::connect(ui->filterFrameType, QOverload::of(&QComboBox::currentIndexChanged), this, &IEEE_802_15_4_DemodGUI::on_filterFrameType_currentIndexChanged); + QObject::connect(ui->filterPANID, &QLineEdit::editingFinished, this, &IEEE_802_15_4_DemodGUI::on_filterPANID_editingFinished); + QObject::connect(ui->filterAddress, &QLineEdit::editingFinished, this, &IEEE_802_15_4_DemodGUI::on_filterAddress_editingFinished); + QObject::connect(ui->showBadFCS, &ButtonSwitch::toggled, this, &IEEE_802_15_4_DemodGUI::on_showBadFCS_toggled); + QObject::connect(ui->useFileTime, &ButtonSwitch::toggled, this, &IEEE_802_15_4_DemodGUI::on_useFileTime_toggled); + QObject::connect(ui->logEnable, &ButtonSwitch::clicked, this, &IEEE_802_15_4_DemodGUI::on_logEnable_clicked); + QObject::connect(ui->logFilename, &QToolButton::clicked, this, &IEEE_802_15_4_DemodGUI::on_logFilename_clicked); + QObject::connect(ui->logOpen, &QToolButton::clicked, this, &IEEE_802_15_4_DemodGUI::on_logOpen_clicked); + QObject::connect(ui->clearTable, &QPushButton::clicked, this, &IEEE_802_15_4_DemodGUI::on_clearTable_clicked); +} + +void IEEE_802_15_4_DemodGUI::updateAbsoluteCenterFrequency() +{ + setStatusFrequency(m_deviceCenterFrequency + m_settings.m_inputFrequencyOffset); +} diff --git a/plugins/channelrx/demod802.15.4/ieee_802_15_4_demodgui.h b/plugins/channelrx/demod802.15.4/ieee_802_15_4_demodgui.h new file mode 100644 index 000000000..860c86fba --- /dev/null +++ b/plugins/channelrx/demod802.15.4/ieee_802_15_4_demodgui.h @@ -0,0 +1,160 @@ +/////////////////////////////////////////////////////////////////////////////////// +// 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_IEEE_802_15_4_DEMODGUI_H +#define INCLUDE_IEEE_802_15_4_DEMODGUI_H + +#include +#include + +#include "channel/channelgui.h" +#include "dsp/channelmarker.h" +#include "util/messagequeue.h" +#include "settings/rollupstate.h" + +#include "ieee_802_15_4_demodsettings.h" +#include "ieee_802_15_4_demod.h" + +class PluginAPI; +class DeviceUISet; +class BasebandSampleSink; +class ScopeVis; + +namespace Ui { + class IEEE_802_15_4_DemodGUI; +} + +class IEEE_802_15_4_DemodGUI : public ChannelGUI { + Q_OBJECT + +public: + static IEEE_802_15_4_DemodGUI* 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::IEEE_802_15_4_DemodGUI* ui; + PluginAPI* m_pluginAPI; + DeviceUISet* m_deviceUISet; + ChannelMarker m_channelMarker; + RollupState m_rollupState; + IEEE_802_15_4_DemodSettings m_settings; + qint64 m_deviceCenterFrequency; + int m_basebandSampleRate; + bool m_doApplySettings; + ScopeVis* m_scopeVis; + + IEEE_802_15_4_Demod* m_demod; + uint32_t m_tickCount; + MessageQueue m_inputMessageQueue; + bool m_loadingData; + + QMenu *m_framesMenu; // Column select context menu + + enum FrameCol { + FRAME_COL_DATE_TIME, + FRAME_COL_TYPE, + FRAME_COL_SEQ, + FRAME_COL_DST_PAN, + FRAME_COL_DST_ADDR, + FRAME_COL_SRC_PAN, + FRAME_COL_SRC_ADDR, + FRAME_COL_INFO, + FRAME_COL_LENGTH, + FRAME_COL_PAYLOAD, + FRAME_COL_PSDU, + FRAME_COL_FCS, + FRAME_COL_POWER, + FRAME_COL_SNR, + FRAME_COL_LQI, + FRAME_COL_FREQUENCY_OFFSET + }; + + explicit IEEE_802_15_4_DemodGUI(PluginAPI* pluginAPI, DeviceUISet *deviceUISet, BasebandSampleSink *rxChannel, QWidget* parent = nullptr); + virtual ~IEEE_802_15_4_DemodGUI(); + + void blockApplySettings(bool block); + void applySettings(const QStringList& settingsKeys, bool force = false); + void displaySettings(); + void displayPHYDependent(); + void frameReceived(const QByteArray& psdu, const QDateTime& dateTime, bool fcsOK, float frequencyOffset, + float lqi, float powerDB, float snr); + bool handleMessage(const Message& message); + void makeUIConnections(); + void updateAbsoluteCenterFrequency(); + void checkSampleRate(); + + void leaveEvent(QEvent*); + void enterEvent(EnterEventType*); + + void resizeTable(); + QAction *createCheckableItem(QString& text, int idx, bool checked, const char *slot); + +private slots: + void on_deltaFrequency_changed(qint64 value); + void on_phy_currentIndexChanged(int index); + void on_samplesPerChip_valueChanged(int value); + void on_rfBW_valueChanged(int value); + void on_maxFrequencyOffset_valueChanged(int value); + void on_threshold_valueChanged(int value); + void on_udpEnabled_clicked(bool checked); + void on_udpAddress_editingFinished(); + void on_udpPort_editingFinished(); + void on_udpFormat_currentIndexChanged(int index); + void on_filterFrameType_currentIndexChanged(int index); + void on_filterPANID_editingFinished(); + void on_filterAddress_editingFinished(); + void on_showBadFCS_toggled(bool checked); + void on_useFileTime_toggled(bool checked); + void on_logEnable_clicked(bool checked = false); + void on_logFilename_clicked(); + void on_logOpen_clicked(); + void on_clearTable_clicked(); + void filterRow(int row); + void filter(); + void frames_sectionMoved(int logicalIndex, int oldVisualIndex, int newVisualIndex); + void frames_sectionResized(int logicalIndex, int oldSize, int newSize); + void framesColumnSelectMenu(QPoint pos); + void framesColumnSelectMenuChecked(bool checked = false); + void customContextMenuRequested(QPoint point); + void onWidgetRolled(QWidget* widget, bool rollDown); + void onMenuDialogCalled(const QPoint& p); + void handleInputMessages(); + void tick(); +}; + +#endif // INCLUDE_IEEE_802_15_4_DEMODGUI_H diff --git a/plugins/channelrx/demod802.15.4/ieee_802_15_4_demodgui.ui b/plugins/channelrx/demod802.15.4/ieee_802_15_4_demodgui.ui new file mode 100644 index 000000000..62cd777e2 --- /dev/null +++ b/plugins/channelrx/demod802.15.4/ieee_802_15_4_demodgui.ui @@ -0,0 +1,1050 @@ + + + IEEE_802_15_4_DemodGUI + + + + 0 + 0 + 420 + 900 + + + + + 0 + 0 + + + + + 400 + 0 + + + + + Liberation Sans + 9 + + + + Qt::FocusPolicy::StrongFocus + + + 802.15.4 Demodulator + + + + + 0 + 0 + 420 + 191 + + + + + 400 + 0 + + + + Settings + + + + 3 + + + 2 + + + 2 + + + 2 + + + 2 + + + + + 2 + + + + + + 16 + 0 + + + + Df + + + + + + + + 0 + 0 + + + + + 32 + 16 + + + + + Liberation Mono + 12 + + + + PointingHandCursor + + + Qt::FocusPolicy::StrongFocus + + + Demod shift frequency from center in Hz + + + + + + + Hz + + + + + + + Qt::Orientation::Vertical + + + + + + + Qt::Orientation::Horizontal + + + + 40 + 20 + + + + + + + + Channel power + + + 0.0 + + + + + + + dB + + + + + + + + + + + dB + + + + + + + + 0 + 0 + + + + + 0 + 24 + + + + + Liberation Mono + 8 + + + + Level meter (dB) top trace: average, bottom trace: instantaneous peak, tip: peak hold + + + + + + + + + Qt::Orientation::Horizontal + + + + + + + + + PHY + + + + + + + + 170 + 0 + + + + PHY bit rate and modulation + + + + 20kbps BPSK + + + + + 40kbps BPSK + + + + + 100kbps <1GHz O-QPSK + + + + + 250kbps <1GHz O-QPSK (Sine) + + + + + 250kbps <1GHz O-QPSK (RC) + + + + + 250kbps >2GHz O-QPSK + + + + + + + + Qt::Orientation::Vertical + + + + + + + CR + + + + + + + + 40 + 0 + + + + Chip rate + + + 2000k + + + + + + + Qt::Orientation::Vertical + + + + + + + SPC + + + + + + + Samples per chip. The channel sample rate is this multiplied by the chip rate + + + 2 + + + 16 + + + 4 + + + + + + + + 40 + 0 + + + + Channel sample rate + + + 8.0M + + + + + + + Qt::Orientation::Horizontal + + + + 40 + 20 + + + + + + + + + + + + BW + + + + + + + + 0 + 0 + + + + RF bandwidth of the channel filter + + + 10 + + + 400 + + + 1 + + + 300 + + + Qt::Orientation::Horizontal + + + + + + + + 40 + 0 + + + + 3.00M + + + + + + + Qt::Orientation::Vertical + + + + + + + Max ΔF + + + + + + + Maximum carrier frequency offset to search for during acquisition, in kHz + + + k + + + 0 + + + 1000 + + + + + + + Qt::Orientation::Vertical + + + + + + + TH + + + + + + + + 24 + 24 + + + + Preamble detection threshold. Lower values detect weaker signals, at the cost of more CPU spent on false detections + + + 1 + + + 50 + + + 5 + + + 5 + + + + + + + + 28 + 0 + + + + 0.05 + + + + + + + + + Qt::Orientation::Horizontal + + + + + + + + + UDP + + + + + + + Forward received frames via UDP + + + Qt::LayoutDirection::RightToLeft + + + + + + + + + + + 120 + 0 + + + + Qt::FocusPolicy::ClickFocus + + + Destination UDP address + + + 000.000.000.000 + + + 127.0.0.1 + + + + + + + : + + + + + + + + 50 + 0 + + + + + 50 + 16777215 + + + + Qt::FocusPolicy::ClickFocus + + + Destination UDP port. Wireshark decodes ZEP on port 17754 + + + 00000 + + + 17754 + + + + + + + Format + + + + + + + Format used to forward frames: ZEP (ZigBee Encapsulation Protocol, which Wireshark decodes) or raw MAC frame + + + + ZEP + + + + + Raw + + + + + + + + Qt::Orientation::Horizontal + + + + 40 + 20 + + + + + + + + + + Qt::Orientation::Horizontal + + + + + + + + + Display only frames of this type + + + + All + + + + + Beacon + + + + + Data + + + + + Ack + + + + + Command + + + + + Other + + + + + + + + PAN + + + + + + + Display only frames where a PAN ID matches the specified regular expression (E.g. 0x1a62) + + + + + + + Addr + + + + + + + Display only frames where the source or destination address matches the specified regular expression + + + + + + + Show frames with invalid FCS + + + FCS + + + true + + + + + + + Check to use date and time from input file. Uncheck to use date and time from clock. + + + + + + + :/clockcurrent.png + :/clockfile.png:/clockcurrent.png + + + + + + + Start/stop logging of received frames to .csv or .pcap file + + + + + + + :/record_off.png:/record_off.png + + + + + + + Set log filename. Use .pcap extension to log in PCAP format for Wireshark, otherwise .csv format is used + + + + + + + :/save.png:/save.png + + + false + + + + + + + Read frames from .csv log file + + + + + + + :/load.png:/load.png + + + false + + + + + + + Clear frames from table + + + + + + + :/bin.png:/bin.png + + + + + + + + + + + 0 + 200 + 420 + 300 + + + + + 0 + 0 + + + + Received Frames + + + + 2 + + + 0 + + + 0 + + + 0 + + + 0 + + + + + Received frames + + + QAbstractItemView::EditTrigger::NoEditTriggers + + + + Date/Time + + + Date and time frame was received + + + + + Type + + + MAC frame type + + + + + Seq + + + Sequence number + + + + + Dst PAN + + + Destination PAN ID + + + + + Dst Addr + + + Destination address + + + + + Src PAN + + + Source PAN ID + + + + + Src Addr + + + Source address + + + + + Info + + + Command, security and information elements + + + + + Len + + + PSDU length in bytes, including FCS + + + + + Payload + + + MAC payload as hex + + + + + PSDU + + + Complete MAC frame (PSDU), including FCS, as hex + + + + + FCS + + + Whether the frame check sequence is valid + + + + + Power + + + Received power during the frame in dB + + + + + SNR + + + Estimated symbol signal to noise ratio (Es/N0) in dB, after despreading + + + + + LQI + + + Link quality indicator: mean normalised correlation of symbols, from 0 to 1 + + + + + ΔF + + + Estimated carrier frequency offset in Hz + + + + + + + + + + 0 + 510 + 716 + 341 + + + + + 714 + 0 + + + + Waveforms + + + + 2 + + + 3 + + + 3 + + + 3 + + + 3 + + + + + + 200 + 250 + + + + + Liberation Mono + 8 + + + + + + + + + + + + + RollupContents + QWidget +
gui/rollupcontents.h
+ 1 +
+ + ValueDialZ + QWidget +
gui/valuedialz.h
+ 1 +
+ + LevelMeterSignalDB + QWidget +
gui/levelmeter.h
+ 1 +
+ + ButtonSwitch + QToolButton +
gui/buttonswitch.h
+
+ + GLScope + QWidget +
gui/glscope.h
+ 1 +
+ + GLScopeGUI + QWidget +
gui/glscopegui.h
+ 1 +
+
+ + + + +
diff --git a/plugins/channelrx/demod802.15.4/ieee_802_15_4_demodplugin.cpp b/plugins/channelrx/demod802.15.4/ieee_802_15_4_demodplugin.cpp new file mode 100644 index 000000000..c6f8f3126 --- /dev/null +++ b/plugins/channelrx/demod802.15.4/ieee_802_15_4_demodplugin.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 "ieee_802_15_4_demodgui.h" +#endif +#include "ieee_802_15_4_demod.h" +#include "ieee_802_15_4_demodwebapiadapter.h" +#include "ieee_802_15_4_demodplugin.h" + +const PluginDescriptor IEEE_802_15_4_DemodPlugin::m_pluginDescriptor = { + IEEE_802_15_4_Demod::m_channelId, + QStringLiteral("802.15.4 Demodulator"), + QStringLiteral("7.28.0"), + QStringLiteral("(c) Jon Beniston, M7RCE"), + QStringLiteral("https://github.com/f4exb/sdrangel"), + true, + QStringLiteral("https://github.com/f4exb/sdrangel") +}; + +IEEE_802_15_4_DemodPlugin::IEEE_802_15_4_DemodPlugin(QObject* parent) : + QObject(parent), + m_pluginAPI(nullptr) +{ +} + +const PluginDescriptor& IEEE_802_15_4_DemodPlugin::getPluginDescriptor() const +{ + return m_pluginDescriptor; +} + +void IEEE_802_15_4_DemodPlugin::initPlugin(PluginAPI* pluginAPI) +{ + m_pluginAPI = pluginAPI; + + m_pluginAPI->registerRxChannel(IEEE_802_15_4_Demod::m_channelIdURI, IEEE_802_15_4_Demod::m_channelId, this); +} + +void IEEE_802_15_4_DemodPlugin::createRxChannel(DeviceAPI *deviceAPI, BasebandSampleSink **bs, ChannelAPI **cs) const +{ + if (bs || cs) + { + IEEE_802_15_4_Demod *instance = new IEEE_802_15_4_Demod(deviceAPI); + + if (bs) { + *bs = instance; + } + + if (cs) { + *cs = instance; + } + } +} + +#ifdef SERVER_MODE +ChannelGUI* IEEE_802_15_4_DemodPlugin::createRxChannelGUI( + DeviceUISet *deviceUISet, + BasebandSampleSink *rxChannel) const +{ + (void) deviceUISet; + (void) rxChannel; + return nullptr; +} +#else +ChannelGUI* IEEE_802_15_4_DemodPlugin::createRxChannelGUI(DeviceUISet *deviceUISet, BasebandSampleSink *rxChannel) const +{ + return IEEE_802_15_4_DemodGUI::create(m_pluginAPI, deviceUISet, rxChannel); +} +#endif + +ChannelWebAPIAdapter* IEEE_802_15_4_DemodPlugin::createChannelWebAPIAdapter() const +{ + return new IEEE_802_15_4_DemodWebAPIAdapter(); +} diff --git a/plugins/channelrx/demod802.15.4/ieee_802_15_4_demodplugin.h b/plugins/channelrx/demod802.15.4/ieee_802_15_4_demodplugin.h new file mode 100644 index 000000000..2f1167a88 --- /dev/null +++ b/plugins/channelrx/demod802.15.4/ieee_802_15_4_demodplugin.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_IEEE_802_15_4_DEMODPLUGIN_H +#define INCLUDE_IEEE_802_15_4_DEMODPLUGIN_H + +#include +#include "plugin/plugininterface.h" + +class DeviceUISet; +class BasebandSampleSink; + +class IEEE_802_15_4_DemodPlugin : public QObject, PluginInterface { + Q_OBJECT + Q_INTERFACES(PluginInterface) + Q_PLUGIN_METADATA(IID "sdrangel.channelrx.demod802.15.4") + +public: + explicit IEEE_802_15_4_DemodPlugin(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_IEEE_802_15_4_DEMODPLUGIN_H diff --git a/plugins/channelrx/demod802.15.4/ieee_802_15_4_demodreceiver.cpp b/plugins/channelrx/demod802.15.4/ieee_802_15_4_demodreceiver.cpp new file mode 100644 index 000000000..7fbe8a942 --- /dev/null +++ b/plugins/channelrx/demod802.15.4/ieee_802_15_4_demodreceiver.cpp @@ -0,0 +1,935 @@ +/////////////////////////////////////////////////////////////////////////////////// +// 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 "ieee_802_15_4_demodreceiver.h" + +IEEE_802_15_4_DemodReceiver::IEEE_802_15_4_DemodReceiver() : + m_bpsk(false), + m_spc(4), + m_chipsPerSymbol(32), + m_numSymbols(16), + m_P(128), + m_window(4), + m_threshold(0.1f), + m_maxFrequencyOffset(200000.0f), + m_maxOmega(0.0), + m_pulseLength(0), + m_coherentLane(true), + m_nonCoherentLane(true), + m_mask(0), + m_n(0), + m_crcScopeCount(0) +{ + m_stats = Statistics{0, 0, 0, 0, 0, 0}; + configure(m_phy, m_spc, m_maxFrequencyOffset, m_threshold); +} + +void IEEE_802_15_4_DemodReceiver::configure(const IEEE_802_15_4_PHY& phy, int samplesPerChip, float maxFrequencyOffset, float threshold) +{ + m_phy = phy; + m_bpsk = phy.m_modulation == IEEE_802_15_4_PHY::BPSK; + m_spc = std::max(2, samplesPerChip); + m_chipsPerSymbol = phy.getChipsPerSymbol(); + m_numSymbols = m_bpsk ? 1 : 16; + m_P = m_chipsPerSymbol * m_spc; + // BPSK has a 32 bit preamble, O-QPSK 8 symbols. The detector needs m_window + 1 symbols + // of preamble to fill, and the longer the window, the lower the false alarm rate + m_window = m_bpsk ? 16 : 6; + m_verifyThreshold = m_chipsPerSymbol >= 32 ? m_verifyThreshold32 : m_verifyThreshold16; + m_lostThreshold = m_lostThresholdFactor * std::sqrt(M_PI / 4.0) / std::sqrt((double) m_chipsPerSymbol); + m_threshold = threshold; + m_pulse = phy.getPulse(m_spc); + m_pulseLength = (int) m_pulse.size(); + + // Normalise pulse energy, so correlation values are comparable between PHYs + double energy = 0.0; + for (auto p : m_pulse) { + energy += p * p; + } + for (auto& p : m_pulse) { + p /= std::sqrt(energy); + } + + m_chipSigns.resize(m_numSymbols); + for (int s = 0; s < m_numSymbols; s++) + { + m_chipSigns[s].resize(m_chipsPerSymbol); + for (int k = 0; k < m_chipsPerSymbol; k++) { + m_chipSigns[s][k] = phy.getChip(s, k) ? 1.0f : -1.0f; + } + } + + m_chipValues.resize(m_chipsPerSymbol); + + // O-QPSK: even chips on I, odd chips on Q + m_chipRotation.resize(m_chipsPerSymbol); + for (int k = 0; k < m_chipsPerSymbol; k++) { + m_chipRotation[k] = (m_bpsk || !(k & 1)) ? Cf(1.0f, 0.0f) : Cf(0.0f, -1.0f); + } + + setMaxFrequencyOffset(maxFrequencyOffset); + allocate(); + reset(); +} + +void IEEE_802_15_4_DemodReceiver::setMaxFrequencyOffset(float maxFrequencyOffset) +{ + m_maxFrequencyOffset = maxFrequencyOffset; + m_maxOmega = 2.0 * M_PI * maxFrequencyOffset / (double) getSampleRate(); +} + +void IEEE_802_15_4_DemodReceiver::allocate() +{ + // Enough history for the detector window, the acquisition segment and the matched filter + int64_t required = (2 * m_window + 6) * (int64_t) m_P + m_pulseLength + 64; + int64_t size = 1; + + while (size < required) { + size <<= 1; + } + + m_x.assign(size, Cf(0.0f, 0.0f)); + m_xf.assign(size, Cf(0.0f, 0.0f)); + m_d.assign(size, Cf(0.0f, 0.0f)); + m_y.assign(size, Cf(0.0f, 0.0f)); + m_mask = size - 1; +} + +void IEEE_802_15_4_DemodReceiver::reset() +{ + std::fill(m_x.begin(), m_x.end(), Cf(0.0f, 0.0f)); + std::fill(m_xf.begin(), m_xf.end(), Cf(0.0f, 0.0f)); + m_n = 0; + m_R = Cd(0.0, 0.0); + m_E1 = 0.0; + m_E2 = 0.0; + m_detectorPeakEnergy = 0.0; + m_state = Search; + m_waitUntil = 0; + m_holdoffUntil = 0; + m_frames.clear(); + m_scope = Scope{0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}; + m_crcScopeCount = 0; +} + +IEEE_802_15_4_DemodReceiver::Frame IEEE_802_15_4_DemodReceiver::popFrame() +{ + Frame frame = m_frames.front(); + m_frames.pop_front(); + return frame; +} + +void IEEE_802_15_4_DemodReceiver::process(const Cf& x) +{ + m_x[m_n & m_mask] = x; + + // Detector input is averaged over a chip, so its noise bandwidth is close to the signal + // bandwidth, whatever the number of samples per chip + Cf xf(0.0f, 0.0f); + for (int i = 0; i < m_spc; i++) { + xf += m_x[(m_n - i) & m_mask]; + } + m_xf[m_n & m_mask] = xf; + + updateDetector(); + m_n++; + + if (m_crcScopeCount > 0) + { + m_crcScopeCount--; + if (m_crcScopeCount == 0) { + m_scope.m_crc = 0.0f; + } + } + + if (m_state == Receive) + { + m_powerSum += std::norm(x); + m_powerCount++; + + // If we haven't found the SFD yet, the acquisition may have been false (E.g. on a + // run of zeros at the end of a BPSK frame, with the next frame following shortly + // after), so allow a fresh detection, or one from a detector window that is entirely + // after the acquisition, to restart acquisition + if (m_scope.m_detectMetric < m_threshold / 2.0f) { + m_detectorCleared = true; + } + bool newWindow = m_n - m_acquisitionN >= (int64_t) (m_window + 1) * m_P; + if ((m_detectorCleared || newWindow) && (m_scope.m_detectMetric >= m_threshold) && searchingForSFD()) + { + m_stats.m_detections++; + m_state = Wait; + m_waitUntil = m_n + (m_window + 2) * m_P; + m_waitMax = m_scope.m_detectMetric; + m_waitMaxN = m_n; + m_waitR = m_R; + } + else + { + processReceive(); + } + } + else if (m_state == Wait) + { + // Acquire once the detector has peaked, which is when its window is inside the + // preamble, so the acquisition segment that ends a symbol later is too + if (m_scope.m_detectMetric > m_waitMax) + { + m_waitMax = m_scope.m_detectMetric; + m_waitMaxN = m_n; + m_waitR = m_R; + } + if ((m_n - m_waitMaxN >= m_P) || (m_n >= m_waitUntil)) + { + if (!acquire()) + { + m_state = Search; + m_holdoffUntil = m_n + m_P; + } + } + } + else if ((m_n >= m_holdoffUntil) && (m_scope.m_detectMetric >= m_threshold)) + { + // Wait for more of the preamble to arrive, so the acquisition segment is + // inside the preamble even for a signal that has only just crossed the threshold + m_stats.m_detections++; + m_state = Wait; + m_waitUntil = m_n + (m_window + 2) * m_P; + m_waitMax = m_scope.m_detectMetric; + m_waitMaxN = m_n; + m_waitR = m_R; + } + + m_scope.m_state = (float) m_state; +} + +// Delay-and-correlate over one symbol period, summed over m_window symbols +void IEEE_802_15_4_DemodReceiver::updateDetector() +{ + int64_t windowSamples = (int64_t) m_window * m_P; + + if (m_n < windowSamples + m_P) + { + m_scope.m_detectMetric = 0.0f; + if (m_n == windowSamples + m_P - 1) { + recalculateDetector(); + } + return; + } + + // Periodically recalculate, to stop rounding errors accumulating + if ((m_n & 0xffff) == 0) + { + recalculateDetector(); + } + else + { + Cd x0(m_xf[m_n & m_mask]); + Cd x1(m_xf[(m_n - m_P) & m_mask]); + int64_t l = m_n - windowSamples; + Cd l0(m_xf[l & m_mask]); + Cd l1(m_xf[(l - m_P) & m_mask]); + + m_R += x0 * std::conj(x1) - l0 * std::conj(l1); + m_E1 += std::norm(x0) - std::norm(l0); + m_E2 += std::norm(x1) - std::norm(l1); + + // The running sums have rounding errors relative to the largest energy they've held. + // If the energy has since fallen to near that level (E.g. a strong frame followed by + // zero samples), the errors dominate and can give a large metric, so recalculate + m_detectorPeakEnergy = std::max(m_detectorPeakEnergy, std::max(m_E1, m_E2)); + if ((m_E1 < m_detectorRelativeError * m_detectorPeakEnergy) || (m_E2 < m_detectorRelativeError * m_detectorPeakEnergy)) { + recalculateDetector(); + } + } + + double denom = m_E1 * m_E2; + m_scope.m_detectMetric = ((m_E1 > 0.0) && (m_E2 > 0.0) && (denom > 1e-30)) ? (float) (std::norm(m_R) / denom) : 0.0f; +} + +void IEEE_802_15_4_DemodReceiver::recalculateDetector() +{ + int64_t windowSamples = (int64_t) m_window * m_P; + + m_R = Cd(0.0, 0.0); + m_E1 = 0.0; + m_E2 = 0.0; + + for (int64_t i = m_n - windowSamples + 1; i <= m_n; i++) + { + Cd x0(m_xf[i & m_mask]); + Cd x1(m_xf[(i - m_P) & m_mask]); + m_R += x0 * std::conj(x1); + m_E1 += std::norm(x0); + m_E2 += std::norm(x1); + } + + m_detectorPeakEnergy = std::max(m_E1, m_E2); +} + +// Find frequency offset and symbol timing from the preamble +bool IEEE_802_15_4_DemodReceiver::acquire() +{ + const int64_t newest = m_n - 1; + const int segLength = (m_window + 2) * m_P; + const int64_t segStart = newest - segLength + 1; + const int N = m_chipsPerSymbol; + + if (segStart - m_pulseLength < 0) { + return false; + } + + // Frequency, modulo the symbol rate, from the detector at its peak + const double omegaFine = std::arg(m_waitR) / m_P; + const double omegaStep = 2.0 * M_PI / m_P; + int mMax = (int) std::ceil((m_maxOmega + omegaStep / 2.0) / omegaStep); + + std::vector d(segLength + m_pulseLength - 1); + std::vector y(segLength); + std::vector bestY; + std::vector metric(m_P); + std::vector bestMetric; + double bestValue = -1.0; + int bestO = 0; + double bestOmega = 0.0; + + for (int m = -mMax; m <= mMax; m++) + { + double omega = omegaFine + m * omegaStep; + + if ((std::abs(omega) > m_maxOmega + omegaStep / 2.0) && (m != 0)) { + continue; + } + + // De-rotate and matched filter the segment + int64_t dStart = segStart - m_pulseLength + 1; + for (int i = 0; i < (int) d.size(); i++) + { + double a = -omega * (double) (dStart + i - segStart); + d[i] = m_x[(dStart + i) & m_mask] * Cf((float) std::cos(a), (float) std::sin(a)); + } + for (int i = 0; i < segLength; i++) + { + Cf acc(0.0f, 0.0f); + for (int j = 0; j < m_pulseLength; j++) { + acc += m_pulse[j] * d[i + j]; + } + y[i] = acc; + } + + // Correlate against the preamble symbol at each timing offset, + // combining symbols non-coherently + double maxValue = -1.0; + int maxO = 0; + + for (int o = 0; o < m_P; o++) + { + double sum = 0.0; + + for (int j = 0; j <= m_window; j++) + { + int idx = o + j * m_P; + Cf c(0.0f, 0.0f); + for (int k = 0; k < N; k++) { + c += m_chipSigns[0][k] * (y[idx + k * m_spc] * m_chipRotation[k]); + } + sum += std::abs(c); + } + + metric[o] = sum; + if (sum > maxValue) + { + maxValue = sum; + maxO = o; + } + } + + if (maxValue > bestValue) + { + bestValue = maxValue; + bestO = maxO; + bestOmega = omega; + bestY = y; + bestMetric = metric; + } + } + + if (bestValue <= 0.0) { + return false; + } + + // Normalised correlation of each symbol at the best timing + std::vector C; + std::vector q; + double qMax = 0.0; + + for (int j = 0; j <= m_window; j++) + { + int idx = bestO + j * m_P; + Cf c(0.0f, 0.0f); + double energy = 0.0; + + for (int k = 0; k < N; k++) + { + Cf u = bestY[idx + k * m_spc] * m_chipRotation[k]; + c += m_chipSigns[0][k] * u; + energy += std::norm(u); + } + + double qj = std::abs(c) / std::sqrt(N * energy + 1e-30); + C.push_back(Cd(c)); + q.push_back(qj); + qMax = std::max(qMax, qj); + } + + // BPSK data also correlates with the preamble chips, as a 1 is just the inverse + // sequence, so also check the differentially decoded bits are 0 + int good = 0; + std::vector preamble(q.size()); + for (int j = 0; j < (int) q.size(); j++) + { + bool zero = !m_bpsk || ((j > 0) && ((C[j] * std::conj(C[j - 1])).real() > 0.0)); + good += (q[j] >= m_verifyThreshold) && zero ? 1 : 0; + preamble[j] = (q[j] >= m_verifyThreshold * 0.8) && zero; + } + + if (good < m_verifySymbols) + { + if (m_debug) + { + fprintf(stderr, "acquire failed: n %lld omega %f good %d q:", (long long) m_n, bestOmega, good); + for (auto v : q) fprintf(stderr, " %.2f", v); + fprintf(stderr, "\n"); + } + return false; + } + + // Start decoding at the start of the longest run of preamble symbols. Starting before + // it, on noise, would use up the number of symbols the framer allows to find the SFD, + // and the segment may end with symbols after the preamble that happen to correlate, + // such as the zero bits in a BPSK SFD + int j0 = 0; + int bestRun = 0; + for (int j = 0; j < (int) q.size(); ) + { + if (preamble[j]) + { + int k = j; + while ((k < (int) q.size()) && preamble[k]) { + k++; + } + if (k - j >= bestRun) + { + bestRun = k - j; + j0 = j; + } + j = k; + } + else + { + j++; + } + } + // For BPSK, preamble[] marks a symbol whose differential with the previous is 0, so + // the previous symbol is part of the preamble too + if (m_bpsk && (j0 > 0)) { + j0--; + } + + // Fractional timing from the shape of the correlation peak + double mm = bestMetric[(bestO + m_P - 1) % m_P]; + double m0 = bestMetric[bestO]; + double mp = bestMetric[(bestO + 1) % m_P]; + double denom = mm - 2.0 * m0 + mp; + double delta = (std::abs(denom) > 1e-30) ? 0.5 * (mm - mp) / denom : 0.0; + delta = std::max(-0.5, std::min(0.5, delta)); + + // Refine frequency from the phase change between consecutive preamble symbols + Cd acc(0.0, 0.0); + for (int j = j0 + 1; j < (int) C.size(); j++) + { + if ((q[j] >= m_verifyThreshold * 0.8) && (q[j - 1] >= m_verifyThreshold * 0.8)) { + acc += C[j] * std::conj(C[j - 1]); + } + } + if (std::abs(acc) > 0.0) { + bestOmega += std::arg(acc) / m_P; + } + + m_stats.m_acquisitions++; + if (m_debug) { + fprintf(stderr, "acquire: n %lld omega %f (%.0f Hz) o %d delta %.2f j0 %d qMax %.2f q:", (long long) m_n, bestOmega, bestOmega * getSampleRate() / (2.0 * M_PI), bestO, delta, j0, qMax); + for (auto v : q) fprintf(stderr, " %.2f", v); + fprintf(stderr, "\n"); + } + startReceive(bestOmega, segStart, segStart + bestO + delta + j0 * m_P); + + return true; +} + +void IEEE_802_15_4_DemodReceiver::startReceive(double omega, int64_t segStart, double tau) +{ + m_state = Receive; + m_omega = omega; + m_ncoRef = segStart; + // Start a little before the segment, so early-late and the interpolator have history + m_yNext = segStart - m_spc - 2; + m_dNext = m_yNext - m_pulseLength + 1; + m_rot = std::polar(1.0, -omega * (double) (m_dNext - m_ncoRef)); + m_rotStep = std::polar(1.0, -omega); + m_tau = tau; + m_phi = 0.0; + m_dphi = 0.0; + m_phaseInit = false; + m_frameStart = segStart; + m_powerSum = 0.0; + m_powerCount = 0; + m_qSum = 0.0; + m_qCount = 0; + m_ampSum = 0.0; + m_ampSumSq = 0.0; + m_ampCount = 0; + m_recentQ.clear(); + m_detectorCleared = false; + m_acquisitionN = m_n; + + m_framers[0].reset(); + m_framers[1].reset(); + m_prevECoh = -1; + m_prevC = Cd(0.0, 0.0); + + for (int64_t i = segStart; i < m_n; i++) { + m_powerSum += std::norm(m_x[i & m_mask]); + m_powerCount++; + } + + processReceive(); +} + +// Cubic (Catmull-Rom) interpolation of matched filter output +IEEE_802_15_4_DemodReceiver::Cf IEEE_802_15_4_DemodReceiver::yAt(double t) const +{ + int64_t i = (int64_t) std::floor(t); + float mu = (float) (t - (double) i); + Cf p0 = m_y[(i - 1) & m_mask]; + Cf p1 = m_y[i & m_mask]; + Cf p2 = m_y[(i + 1) & m_mask]; + Cf p3 = m_y[(i + 2) & m_mask]; + Cf a = -0.5f * p0 + 1.5f * p1 - 1.5f * p2 + 0.5f * p3; + Cf b = p0 - 2.5f * p1 + 2.0f * p2 - 0.5f * p3; + Cf c = -0.5f * p0 + 0.5f * p2; + + return ((a * mu + b) * mu + c) * mu + p1; +} + +void IEEE_802_15_4_DemodReceiver::processReceive() +{ + // De-rotate and matched filter all samples received so far + while (m_dNext < m_n) + { + m_d[m_dNext & m_mask] = m_x[m_dNext & m_mask] * Cf((float) m_rot.real(), (float) m_rot.imag()); + m_rot *= m_rotStep; + if ((m_dNext & 0x3ff) == 0) { + m_rot /= std::abs(m_rot); + } + m_dNext++; + } + + while (m_yNext < m_dNext) + { + Cf acc(0.0f, 0.0f); + int64_t start = m_yNext - m_pulseLength + 1; + for (int j = 0; j < m_pulseLength; j++) { + acc += m_pulse[j] * m_d[(start + j) & m_mask]; + } + m_y[m_yNext & m_mask] = acc; + m_yNext++; + } + + // Decode all symbols for which we have samples, including early-late margin and interpolator + while ((m_state == Receive) && (m_tau + (m_chipsPerSymbol - 1) * m_spc + m_spc / 2.0 + 3.0 < (double) m_yNext)) { + decodeSymbol(); + } +} + +IEEE_802_15_4_DemodReceiver::Cd IEEE_802_15_4_DemodReceiver::correlate(double tau, int symbol) const +{ + Cf c(0.0f, 0.0f); + const std::vector& signs = m_chipSigns[symbol]; + + for (int k = 0; k < m_chipsPerSymbol; k++) { + c += signs[k] * (yAt(tau + k * m_spc) * m_chipRotation[k]); + } + + return Cd(c); +} + +void IEEE_802_15_4_DemodReceiver::decodeSymbol() +{ + const int N = m_chipsPerSymbol; + std::vector& u = m_chipValues; + double energy = 0.0; + + for (int k = 0; k < N; k++) + { + u[k] = yAt(m_tau + k * m_spc) * m_chipRotation[k]; + energy += std::norm(u[k]); + } + + Cd rot; + double q; + double phaseError; + int decided; // Symbol (O-QPSK) or chip sequence (BPSK) used for timing + + if (!m_bpsk) + { + Cd C[16]; + int bestNC = 0; + double bestNCValue = -1.0; + + for (int s = 0; s < 16; s++) + { + Cf c(0.0f, 0.0f); + const std::vector& signs = m_chipSigns[s]; + for (int k = 0; k < N; k++) { + c += signs[k] * u[k]; + } + C[s] = Cd(c); + double mag = std::abs(C[s]); + if (mag > bestNCValue) + { + bestNCValue = mag; + bestNC = s; + } + } + + if (!m_phaseInit) + { + m_phi = std::arg(C[bestNC]); + m_phaseInit = true; + } + + rot = std::polar(1.0, -m_phi); + int bestCoh = 0; + double bestCohValue = -1e30; + + for (int s = 0; s < 16; s++) + { + double v = (C[s] * rot).real(); + if (v > bestCohValue) + { + bestCohValue = v; + bestCoh = s; + } + } + + Cd cr = C[bestCoh] * rot; + phaseError = std::arg(cr); + q = bestNCValue / std::sqrt(N * energy + 1e-30); + decided = bestCoh; + + // SNR estimate from the in-phase component of the decided correlation. The + // quadrature component also contains ISI between the I and Q chips, so isn't used + m_ampSum += cr.real(); + m_ampSumSq += cr.real() * cr.real(); + m_ampCount++; + + frameSymbol(m_coherentLane ? bestCoh : bestNC, m_nonCoherentLane ? bestNC : bestCoh); + } + else + { + Cf c(0.0f, 0.0f); + const std::vector& signs = m_chipSigns[0]; + for (int k = 0; k < N; k++) { + c += signs[k] * u[k]; + } + Cd C(c); + + if (!m_phaseInit) + { + m_phi = std::arg(C); + m_phaseInit = true; + m_prevC = C; + } + + rot = std::polar(1.0, -m_phi); + Cd cr = C * rot; + int eCoh = cr.real() < 0.0 ? 1 : 0; + if (m_prevECoh < 0) { + m_prevECoh = eCoh; + } + int bitCoh = eCoh ^ m_prevECoh; + m_prevECoh = eCoh; + int bitNC = (C * std::conj(m_prevC)).real() < 0.0 ? 1 : 0; + m_prevC = C; + + if (eCoh) { + cr = -cr; + } + phaseError = std::arg(cr); + q = std::abs(C) / std::sqrt(N * energy + 1e-30); + decided = 0; + + m_ampSum += cr.real(); + m_ampSumSq += cr.real() * cr.real(); + m_ampCount++; + + frameBits(m_coherentLane ? bitCoh : bitNC, m_nonCoherentLane ? bitNC : bitCoh); + } + + if (m_debug) { + fprintf(stderr, "sym tau %.2f q %.2f dec %d phi %.2f perr %.2f\n", m_tau, q, decided, m_phi, phaseError); + } + m_scope.m_correlation = (float) q; + Cf chip = u[N - 1] * Cf((float) rot.real(), (float) rot.imag()); + m_scope.m_chip = std::sqrt(energy / N) > 0.0 ? (chip.real() / (float) std::sqrt(energy / N)) : 0.0f; + m_qSum += q; + m_qCount++; + + // Abandon frame quickly if signal lost, as an acknowledgement can follow a frame + // after only 12 symbol periods + const int lostSymbols = m_bpsk ? 8 : 4; + m_recentQ.push_back(q); + if ((int) m_recentQ.size() > lostSymbols) { + m_recentQ.pop_front(); + } + bool lost = false; + if ((int) m_recentQ.size() == lostSymbols) + { + double sum = 0.0; + for (auto v : m_recentQ) { + sum += v; + } + lost = sum / lostSymbols < m_lostThreshold; + } + + if (m_state != Receive) { + return; // Frame finished + } + + // Carrier phase loop + m_dphi += m_phaseFreqGain * phaseError; + m_phi += m_dphi + m_phaseGain * phaseError; + m_phi = std::remainder(m_phi, 2.0 * M_PI); + m_scope.m_phase = (float) (m_phi / M_PI); + + // Early-late timing + double offset = m_spc / 2.0; + double early = std::abs(correlate(m_tau - offset, decided)); + double late = std::abs(correlate(m_tau + offset, decided)); + double timingError = (early + late) > 0.0 ? (late - early) / (late + early) : 0.0; + + m_tau += m_P + m_timingGain * timingError * m_spc; + + if (lost) { + abortFrame(); + } +} + +void IEEE_802_15_4_DemodReceiver::frameSymbol(int symCoh, int symNC) +{ + // Least significant bit first + for (int i = 0; (i < 4) && (m_state == Receive); i++) { + frameBits((symCoh >> i) & 1, (symNC >> i) & 1); + } +} + +void IEEE_802_15_4_DemodReceiver::Framer::reset() +{ + m_state = FramerPreamble; + m_preambleBits = 0; + m_sfd = 0xffff; + m_bitCount = 0; + m_phr = 0; + m_length = 0; + m_bits.clear(); + m_psdu.clear(); + m_fcsOK = false; + m_checked = false; +} + +void IEEE_802_15_4_DemodReceiver::Framer::addBit(int bit) +{ + switch (m_state) + { + case FramerPreamble: + // Look for 8 zero bits followed by SFD (0xa7), received LSB first + m_sfd = (m_sfd >> 1) | (bit << 15); + m_preambleBits++; + if (m_sfd == 0xa700) + { + m_state = FramerPHR; + m_bitCount = 0; + m_phr = 0; + } + else if (m_preambleBits > 32 + 8 + 4) + { + m_state = FramerFailed; + } + break; + + case FramerPHR: + m_phr |= bit << m_bitCount; + m_bitCount++; + if (m_bitCount == 8) + { + m_length = m_phr & 0x7f; + if (lengthValid(m_length)) + { + m_bits.clear(); + m_bits.reserve(m_length * 8); + m_state = FramerPSDU; + } + else + { + m_state = FramerFailed; + } + } + break; + + case FramerPSDU: + m_bits.push_back(bit); + if ((int) m_bits.size() >= m_length * 8) + { + m_psdu.assign(m_length, 0); + for (int i = 0; i < m_length * 8; i++) { + m_psdu[i / 8] |= m_bits[i] << (i % 8); + } + uint16_t fcs = IEEE_802_15_4_FrameDecoder::calcFCS(m_psdu.data(), m_length - 2); + m_fcsOK = (m_psdu[m_length - 2] == (fcs & 0xff)) && (m_psdu[m_length - 1] == (fcs >> 8)); + m_state = FramerDone; + } + break; + + default: + break; + } +} + +bool IEEE_802_15_4_DemodReceiver::searchingForSFD() const +{ + for (const auto& framer : m_framers) + { + if ((framer.m_state == FramerPHR) || (framer.m_state == FramerPSDU) || (framer.m_state == FramerDone)) { + return false; + } + } + + return true; +} + +void IEEE_802_15_4_DemodReceiver::frameBits(int bitCoh, int bitNC) +{ + m_framers[0].addBit(bitCoh); + m_framers[1].addBit(bitNC); + + // Output as soon as either lane has a frame with a valid FCS + for (int lane = 0; lane < 2; lane++) + { + Framer& framer = m_framers[lane]; + + if ((framer.m_state == FramerDone) && !framer.m_checked) + { + framer.m_checked = true; + + if (framer.m_fcsOK) + { + finishFrame(lane); + return; + } + } + } + + // Neither lane has a valid frame, and neither will + if (!m_framers[0].active() && !m_framers[1].active()) { + abortFrame(); + } +} + +void IEEE_802_15_4_DemodReceiver::finishFrame(int lane) +{ + Frame frame; + const Framer& framer = m_framers[lane]; + + frame.m_psdu = framer.m_psdu; + frame.m_fcsOK = framer.m_fcsOK; + frame.m_coherent = lane == 0; + + if (frame.m_fcsOK) + { + m_stats.m_framesOK++; + if (frame.m_coherent) { + m_stats.m_framesCoherent++; + } else { + m_stats.m_framesNonCoherent++; + } + } + else + { + m_stats.m_framesBad++; + } + + if (!frame.m_psdu.empty()) + { + frame.m_frequencyOffset = (float) ((m_omega + m_dphi / m_P) * getSampleRate() / (2.0 * M_PI)); + frame.m_lqi = m_qCount > 0 ? (float) (m_qSum / m_qCount) : 0.0f; + frame.m_power = m_powerCount > 0 ? (float) (m_powerSum / m_powerCount) : 0.0f; + if (m_ampCount > 1) + { + double mean = m_ampSum / m_ampCount; + double var = m_ampSumSq / m_ampCount - mean * mean; + frame.m_snr = (var > 0.0) ? (float) (10.0 * std::log10(mean * mean / (2.0 * var))) : 99.0f; + } + else + { + frame.m_snr = 0.0f; + } + frame.m_startSample = m_frameStart; + frame.m_endSample = m_n - 1; + m_frames.push_back(frame); + m_scope.m_crc = frame.m_fcsOK ? 1.0f : -1.0f; + m_crcScopeCount = 4 * m_P; + } + + endReceive(); +} + +// Stop receiving, outputting a complete frame from either lane if there is one, +// even though its FCS is invalid. The other lane may still be active if it decoded +// a different (longer) length, and has now lost the signal +void IEEE_802_15_4_DemodReceiver::abortFrame() +{ + if (m_framers[0].m_state == FramerDone) { + finishFrame(0); + } else if (m_framers[1].m_state == FramerDone) { + finishFrame(1); + } else { + endReceive(); + } +} + +void IEEE_802_15_4_DemodReceiver::endReceive() +{ + m_state = Search; + // Allow detector window to clear of the frame just received + m_holdoffUntil = m_n + m_P; +} diff --git a/plugins/channelrx/demod802.15.4/ieee_802_15_4_demodreceiver.h b/plugins/channelrx/demod802.15.4/ieee_802_15_4_demodreceiver.h new file mode 100644 index 000000000..d37669dc4 --- /dev/null +++ b/plugins/channelrx/demod802.15.4/ieee_802_15_4_demodreceiver.h @@ -0,0 +1,273 @@ +/////////////////////////////////////////////////////////////////////////////////// +// 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_IEEE_802_15_4_DEMODRECEIVER_H +#define INCLUDE_IEEE_802_15_4_DEMODRECEIVER_H + +#include +#include +#include +#include + +#include "util/ieee_802_15_4.h" + +// Receiver for the IEEE 802.15.4 O-QPSK and BPSK DSSS PHYs. +// +// O-QPSK with half-sine pulses is MSK, and could be received non-coherently with an FM +// discriminator, but the chip tables are defined on the O-QPSK chips, so a discriminator +// effectively detects each chip XORed with its neighbour - a product of two noisy samples - +// and does so at a chip SNR of Eb/N0 - 9 dB (2.4 GHz), well below its FM threshold. +// Instead this receiver correlates against the transmitted waveform: a matched filter for +// the chip pulse (half-sine or RC), sampled at each chip time, then despread against the +// 16 (or 2 for BPSK) chip sequences. That correlation is exactly the inner product of the +// received signal with the reference waveform of each symbol, so it is the matched filter +// for the whole symbol, ISI between chips included. +// +// Acquisition: +// 1. The preamble is a symbol (O-QPSK) or bit (BPSK) repeated, so it is detected with a +// delay-and-correlate (Schmidl-Cox) metric over one symbol period, which is insensitive +// to carrier frequency offset, and whose phase gives the frequency offset modulo the +// symbol rate. +// 2. The ambiguity is resolved, and symbol timing found, by correlating against the +// preamble symbol for each candidate frequency within the configured maximum offset and +// each sample offset within a symbol, combining symbols non-coherently. +// +// Tracking: the input is de-rotated by the estimated offset, and a second order +// decision-directed loop tracks the carrier phase using the decided symbol's correlation, +// which benefits from the full processing gain of the spreading so is far more reliable +// than chip decisions. Symbol timing is tracked with an early-late correlator. +// +// Detection is done in two lanes. The coherent lane picks the symbol whose correlation has +// the largest real part after phase correction. The non-coherent lane picks the largest +// magnitude (O-QPSK) or uses differential detection (BPSK), so needs no phase lock, and still +// works if the phase loop slips. The frame from the first lane to pass the FCS is used. +class IEEE_802_15_4_DemodReceiver +{ +public: + typedef std::complex Cf; + typedef std::complex Cd; + + struct Frame + { + std::vector m_psdu; //!< PSDU (MAC frame including FCS) + bool m_fcsOK; + bool m_coherent; //!< Frame from coherent lane (true) or non-coherent lane (false) + float m_frequencyOffset; //!< Estimated carrier frequency offset in Hz + float m_lqi; //!< Mean normalised symbol correlation, 0-1 + float m_power; //!< Mean power during frame (linear) + float m_snr; //!< Estimated SNR in dB (Es/N0 per symbol, after despreading) + int64_t m_startSample; //!< Index of first sample of acquisition window + int64_t m_endSample; //!< Index of last sample of frame + }; + + struct Scope + { + float m_detectMetric; //!< Preamble detection metric + float m_correlation; //!< Normalised correlation of last symbol + float m_phase; //!< Tracked carrier phase / pi + float m_state; //!< 0 = searching, 1 = acquiring, 2 = receiving frame + float m_crc; //!< 1 = FCS OK, -1 = FCS bad, briefly at end of frame + float m_chip; //!< Phase corrected soft value of last chip (I/Q) + }; + + struct Statistics + { + uint64_t m_detections; //!< Preamble detections + uint64_t m_acquisitions; //!< Successful acquisitions + uint64_t m_framesOK; //!< Frames with valid FCS + uint64_t m_framesBad; //!< Frames with invalid FCS + uint64_t m_framesCoherent; //!< Frames with valid FCS from coherent lane + uint64_t m_framesNonCoherent; //!< Frames with valid FCS only from non-coherent lane + }; + + IEEE_802_15_4_DemodReceiver(); + + //! Configure for a PHY. Sample rate must be samplesPerChip * PHY chip rate. + //! maxFrequencyOffset in Hz. threshold is the preamble detection threshold (0-1). + void configure(const IEEE_802_15_4_PHY& phy, int samplesPerChip, float maxFrequencyOffset, float threshold); + void setThreshold(float threshold) { m_threshold = threshold; } + void setMaxFrequencyOffset(float maxFrequencyOffset); + void reset(); + + int getSampleRate() const { return m_spc * m_phy.getChipRate(); } + + //! Process one sample + void process(const Cf& x); + + bool frameAvailable() const { return !m_frames.empty(); } + Frame popFrame(); + + const Scope& getScope() const { return m_scope; } + const Statistics& getStatistics() const { return m_stats; } + + //! For diagnostics: enable/disable lanes + void setLanes(bool coherent, bool nonCoherent) { m_coherentLane = coherent; m_nonCoherentLane = nonCoherent; } + + static const int m_maxPSDULength = 127; + + void setDebug(bool debug) { m_debug = debug; } + +private: + // Normalised correlation preamble symbols must reach at acquisition, and how many must. + // Noise alone gives a Rayleigh distributed value with mean sqrt(pi/4)/sqrt(chips per symbol): + // 0.16 for 32 chips, 0.22 for 16 and 15, and P(q > x) = exp(-chips * x^2). A symbol at + // Ec/N0 = -4 dB, around the sensitivity limit, gives about 0.53. + static constexpr double m_verifyThreshold32 = 0.4; + static constexpr double m_verifyThreshold16 = 0.5; + static constexpr int m_verifySymbols = 3; + // A frame is abandoned when the mean normalised correlation of recent symbols falls below + // this multiple of the mean for noise + static constexpr double m_lostThresholdFactor = 1.6; + // Carrier phase loop gains, per symbol + static constexpr double m_phaseGain = 0.25; + static constexpr double m_phaseFreqGain = 0.02; + // Symbol timing loop gain, in samples per unit early-late error per chip + static constexpr double m_timingGain = 0.1; + // Detector running sums are recalculated when an energy falls below this fraction of the + // largest energy since the last recalculation, before rounding errors become significant + static constexpr double m_detectorRelativeError = 1e-9; + + enum State { + Search, + Wait, + Receive + }; + + enum FramerState { + FramerPreamble, //!< Looking for SFD + FramerPHR, + FramerPSDU, + FramerDone, //!< Frame complete + FramerFailed //!< No SFD found or invalid length + }; + + // Each detection lane has its own framer, so a symbol error in one lane, such as a false + // SFD, can't misalign the other + struct Framer + { + FramerState m_state; + int m_preambleBits; + uint32_t m_sfd; + int m_bitCount; + uint32_t m_phr; + int m_length; + std::vector m_bits; + std::vector m_psdu; + bool m_fcsOK; + bool m_checked; + + void reset(); + void addBit(int bit); + bool active() const { return (m_state != FramerDone) && (m_state != FramerFailed); } + }; + + // Configuration + IEEE_802_15_4_PHY m_phy; + bool m_bpsk; + int m_spc; //!< Samples per chip + int m_chipsPerSymbol; + int m_numSymbols; //!< 16 for O-QPSK, 1 (+inverse) for BPSK + int m_P; //!< Samples per symbol + int m_window; //!< Detection window in symbols + float m_threshold; + float m_maxFrequencyOffset; + double m_maxOmega; //!< Max offset in radians per sample + std::vector m_pulse; + int m_pulseLength; + std::vector> m_chipSigns; //!< +-1 for each chip of each symbol + std::vector m_chipRotation; //!< Conjugate of chip carrier: 1 for I chips, -j for Q chips + std::vector m_chipValues; //!< Matched filter output for each chip of the symbol being decoded, with the I/Q chip carrier removed + bool m_coherentLane; + bool m_nonCoherentLane; + bool m_debug = false; + + // Sample history + std::vector m_x; //!< Input + std::vector m_xf; //!< Input averaged over a chip, for the detector + std::vector m_d; //!< Input de-rotated by frequency estimate (receive state) + std::vector m_y; //!< Matched filter output of m_d (receive state) + int64_t m_mask; + int64_t m_n; //!< Number of samples processed + + // Preamble detection + Cd m_R; + double m_E1; + double m_E2; + double m_detectorPeakEnergy; //!< Largest of m_E1 and m_E2 since last recalculation + State m_state; + int64_t m_waitUntil; + float m_waitMax; //!< Peak detector metric while waiting + int64_t m_waitMaxN; //!< Sample index of peak + Cd m_waitR; //!< Detector correlation at peak + double m_verifyThreshold; + double m_lostThreshold; + int64_t m_holdoffUntil; + + // Receive state + double m_omega; //!< Frequency offset in radians per sample + int64_t m_ncoRef; //!< Sample index where de-rotation phase is 0 + int64_t m_dNext; //!< Next index of m_d to calculate + int64_t m_yNext; //!< Next index of m_y to calculate + Cd m_rot; //!< De-rotation phasor for m_dNext + Cd m_rotStep; + double m_tau; //!< Sample index (in m_y) of first chip of next symbol + double m_phi; //!< Carrier phase + double m_dphi; //!< Carrier phase change per symbol + bool m_phaseInit; + int64_t m_frameStart; + double m_powerSum; + int64_t m_powerCount; + double m_qSum; + int m_qCount; + double m_ampSum; //!< For SNR estimate + double m_ampSumSq; + int m_ampCount; + std::deque m_recentQ; //!< Normalised correlation of recent symbols + int64_t m_acquisitionN; //!< Sample index when acquired + bool m_detectorCleared; //!< Detector has dropped below threshold since acquisition + + // Framers for coherent [0] and non-coherent [1] lanes + Framer m_framers[2]; + int m_prevECoh; //!< BPSK previous coherent (differentially encoded) bit + Cd m_prevC; //!< BPSK previous correlation for differential detection + + // Outputs + std::deque m_frames; + Scope m_scope; + Statistics m_stats; + int m_crcScopeCount; + + void allocate(); + Cf yAt(double t) const; + void updateDetector(); + void recalculateDetector(); + bool acquire(); + void startReceive(double omega, int64_t segStart, double tau); + void processReceive(); + void decodeSymbol(); + Cd correlate(double tau, int symbol) const; + void frameSymbol(int symCoh, int symNC); + void frameBits(int bitCoh, int bitNC); + void finishFrame(int lane); + bool searchingForSFD() const; + void abortFrame(); + void endReceive(); + static bool lengthValid(int length) { return (length >= 4) && (length <= m_maxPSDULength); } +}; + +#endif // INCLUDE_IEEE_802_15_4_DEMODRECEIVER_H diff --git a/plugins/channelrx/demod802.15.4/ieee_802_15_4_demodsettings.cpp b/plugins/channelrx/demod802.15.4/ieee_802_15_4_demodsettings.cpp new file mode 100644 index 000000000..df2e315a0 --- /dev/null +++ b/plugins/channelrx/demod802.15.4/ieee_802_15_4_demodsettings.cpp @@ -0,0 +1,468 @@ +/////////////////////////////////////////////////////////////////////////////////// +// 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 "util/simpleserializer.h" +#include "settings/serializable.h" +#include "ieee_802_15_4_demodsettings.h" + +IEEE_802_15_4_DemodSettings::IEEE_802_15_4_DemodSettings() : + m_channelMarker(nullptr), + m_scopeGUI(nullptr), + m_rollupState(nullptr) +{ + resetToDefaults(); +} + +void IEEE_802_15_4_DemodSettings::resetToDefaults() +{ + m_inputFrequencyOffset = 0; + setPHY("250kbps >2GHz O-QPSK"); + m_samplesPerChip = 4; + m_threshold = 0.05f; + m_showBadFCS = false; + m_filterFrameType = FilterAll; + m_filterPANID = ""; + m_filterAddress = ""; + m_udpEnabled = false; + m_udpAddress = "127.0.0.1"; + m_udpPort = m_zepPort; + m_udpFormat = ZEP; + m_logFilename = "802_15_4_log.csv"; + m_logEnabled = false; + m_useFileTime = false; + m_rgbColor = QColor(255, 0, 255).rgb(); + m_title = "802.15.4 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; + + for (int i = 0; i < IEEE_802_15_4_DEMOD_COLUMNS; i++) + { + m_columnIndexes[i] = i; + m_columnSizes[i] = -1; // Autosize + } +} + +IEEE_802_15_4_PHY IEEE_802_15_4_DemodSettings::getPHY() const +{ + IEEE_802_15_4_PHY phy; + + if (!phy.fromString(m_phy)) { + phy.fromString("250kbps >2GHz O-QPSK"); + } + + return phy; +} + +int IEEE_802_15_4_DemodSettings::getChannelSampleRate() const +{ + return m_samplesPerChip * getPHY().getChipRate(); +} + +Real IEEE_802_15_4_DemodSettings::getDefaultMaxFrequencyOffset(const IEEE_802_15_4_PHY& phy) +{ + double frequency; + + if (phy.m_modulation == IEEE_802_15_4_PHY::BPSK) { + frequency = phy.m_bitRate == 20000 ? 868.6e6 : 928e6; + } else if (!phy.m_subGHzBand) { + frequency = 2483.5e6; + } else if (phy.m_bitRate == 100000) { + frequency = 868.6e6; + } else if (phy.m_pulseShaping == IEEE_802_15_4_PHY::RC) { + frequency = 787e6; + } else { + frequency = 928e6; + } + + return (Real) (frequency * 80e-6); +} + +bool IEEE_802_15_4_DemodSettings::setPHY(const QString& phyName) +{ + IEEE_802_15_4_PHY phy; + + if (!phy.fromString(phyName)) { + return false; + } + + m_phy = phy.toString().isEmpty() ? phyName : phy.toString(); + m_rfBandwidth = phy.getOccupiedBandwidth(); + m_maxFrequencyOffset = getDefaultMaxFrequencyOffset(phy); + + return true; +} + +QByteArray IEEE_802_15_4_DemodSettings::serialize() const +{ + SimpleSerializer s(1); + + s.writeS64(1, m_inputFrequencyOffset); + s.writeString(2, m_phy); + s.writeFloat(3, m_rfBandwidth); + s.writeS32(4, m_samplesPerChip); + s.writeFloat(5, m_maxFrequencyOffset); + s.writeFloat(6, m_threshold); + s.writeBool(7, m_showBadFCS); + s.writeS32(8, (int) m_filterFrameType); + s.writeString(9, m_filterPANID); + s.writeString(10, m_filterAddress); + s.writeBool(11, m_udpEnabled); + s.writeString(12, m_udpAddress); + s.writeU32(13, m_udpPort); + s.writeS32(14, (int) m_udpFormat); + s.writeString(15, m_logFilename); + s.writeBool(16, m_logEnabled); + s.writeBool(17, m_useFileTime); + + s.writeU32(20, m_rgbColor); + s.writeString(21, m_title); + + if (m_channelMarker) { + s.writeBlob(22, m_channelMarker->serialize()); + } + + s.writeS32(23, m_streamIndex); + s.writeBool(24, m_useReverseAPI); + s.writeString(25, m_reverseAPIAddress); + s.writeU32(26, m_reverseAPIPort); + s.writeU32(27, m_reverseAPIDeviceIndex); + s.writeU32(28, m_reverseAPIChannelIndex); + + if (m_scopeGUI) { + s.writeBlob(29, m_scopeGUI->serialize()); + } + if (m_rollupState) { + s.writeBlob(30, m_rollupState->serialize()); + } + + s.writeS32(31, m_workspaceIndex); + s.writeBlob(32, m_geometryBytes); + s.writeBool(33, m_hidden); + + for (int i = 0; i < IEEE_802_15_4_DEMOD_COLUMNS; i++) { + s.writeS32(100 + i, m_columnIndexes[i]); + } + for (int i = 0; i < IEEE_802_15_4_DEMOD_COLUMNS; i++) { + s.writeS32(200 + i, m_columnSizes[i]); + } + + return s.final(); +} + +bool IEEE_802_15_4_DemodSettings::deserialize(const QByteArray& data) +{ + SimpleDeserializer d(data); + + if (!d.isValid()) + { + resetToDefaults(); + return false; + } + + if (d.getVersion() == 1) + { + QByteArray bytetmp; + uint32_t utmp; + int itmp; + + d.readS64(1, &m_inputFrequencyOffset, 0); + d.readString(2, &m_phy, "250kbps >2GHz O-QPSK"); + IEEE_802_15_4_PHY phy = getPHY(); + d.readFloat(3, &m_rfBandwidth, phy.getOccupiedBandwidth()); + d.readS32(4, &m_samplesPerChip, 4); + m_samplesPerChip = std::max(2, std::min(16, m_samplesPerChip)); + d.readFloat(5, &m_maxFrequencyOffset, getDefaultMaxFrequencyOffset(phy)); + d.readFloat(6, &m_threshold, 0.05f); + m_threshold = std::max(m_minThreshold, std::min(m_maxThreshold, m_threshold)); + d.readBool(7, &m_showBadFCS, false); + d.readS32(8, &itmp, (int) FilterAll); + m_filterFrameType = (FrameTypeFilter) std::max((int) FilterAll, std::min((int) FilterOther, itmp)); + d.readString(9, &m_filterPANID, ""); + d.readString(10, &m_filterAddress, ""); + d.readBool(11, &m_udpEnabled, false); + d.readString(12, &m_udpAddress, "127.0.0.1"); + d.readU32(13, &utmp, m_zepPort); + + if ((utmp > 1023) && (utmp <= 65535)) { + m_udpPort = utmp; + } else { + m_udpPort = m_zepPort; + } + + d.readS32(14, &itmp, (int) ZEP); + m_udpFormat = itmp == (int) Raw ? Raw : ZEP; + d.readString(15, &m_logFilename, "802_15_4_log.csv"); + d.readBool(16, &m_logEnabled, false); + d.readBool(17, &m_useFileTime, false); + + d.readU32(20, &m_rgbColor, QColor(255, 0, 255).rgb()); + d.readString(21, &m_title, "802.15.4 Demodulator"); + + if (m_channelMarker) + { + d.readBlob(22, &bytetmp); + m_channelMarker->deserialize(bytetmp); + } + + d.readS32(23, &m_streamIndex, 0); + d.readBool(24, &m_useReverseAPI, false); + d.readString(25, &m_reverseAPIAddress, "127.0.0.1"); + d.readU32(26, &utmp, 0); + + if ((utmp > 1023) && (utmp <= 65535)) { + m_reverseAPIPort = utmp; + } else { + m_reverseAPIPort = 8888; + } + + d.readU32(27, &utmp, 0); + m_reverseAPIDeviceIndex = utmp > 99 ? 99 : utmp; + d.readU32(28, &utmp, 0); + m_reverseAPIChannelIndex = utmp > 99 ? 99 : utmp; + + if (m_scopeGUI) + { + d.readBlob(29, &bytetmp); + m_scopeGUI->deserialize(bytetmp); + } + + if (m_rollupState) + { + d.readBlob(30, &bytetmp); + m_rollupState->deserialize(bytetmp); + } + + d.readS32(31, &m_workspaceIndex, 0); + d.readBlob(32, &m_geometryBytes); + d.readBool(33, &m_hidden, false); + + for (int i = 0; i < IEEE_802_15_4_DEMOD_COLUMNS; i++) { + d.readS32(100 + i, &m_columnIndexes[i], i); + } + for (int i = 0; i < IEEE_802_15_4_DEMOD_COLUMNS; i++) { + d.readS32(200 + i, &m_columnSizes[i], -1); + } + + return true; + } + else + { + resetToDefaults(); + return false; + } +} + +void IEEE_802_15_4_DemodSettings::applySettings(const QStringList& settingsKeys, const IEEE_802_15_4_DemodSettings& settings) +{ + if (settingsKeys.contains("inputFrequencyOffset")) { + m_inputFrequencyOffset = settings.m_inputFrequencyOffset; + } + if (settingsKeys.contains("phy")) { + m_phy = settings.m_phy; + } + if (settingsKeys.contains("rfBandwidth")) { + m_rfBandwidth = settings.m_rfBandwidth; + } + if (settingsKeys.contains("samplesPerChip")) { + m_samplesPerChip = settings.m_samplesPerChip; + } + if (settingsKeys.contains("maxFrequencyOffset")) { + m_maxFrequencyOffset = settings.m_maxFrequencyOffset; + } + if (settingsKeys.contains("threshold")) { + m_threshold = settings.m_threshold; + } + if (settingsKeys.contains("showBadFCS")) { + m_showBadFCS = settings.m_showBadFCS; + } + if (settingsKeys.contains("filterFrameType")) { + m_filterFrameType = settings.m_filterFrameType; + } + if (settingsKeys.contains("filterPANID")) { + m_filterPANID = settings.m_filterPANID; + } + if (settingsKeys.contains("filterAddress")) { + m_filterAddress = settings.m_filterAddress; + } + 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("udpFormat")) { + m_udpFormat = settings.m_udpFormat; + } + 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")) + { + for (int i = 0; i < IEEE_802_15_4_DEMOD_COLUMNS; i++) { + m_columnIndexes[i] = settings.m_columnIndexes[i]; + } + } + if (settingsKeys.contains("columnSizes")) + { + for (int i = 0; i < IEEE_802_15_4_DEMOD_COLUMNS; i++) { + m_columnSizes[i] = settings.m_columnSizes[i]; + } + } +} + +QString IEEE_802_15_4_DemodSettings::getDebugString(const QStringList& settingsKeys, bool force) const +{ + std::ostringstream ostr; + + if (settingsKeys.contains("inputFrequencyOffset") || force) { + ostr << " m_inputFrequencyOffset: " << m_inputFrequencyOffset; + } + if (settingsKeys.contains("phy") || force) { + ostr << " m_phy: " << m_phy.toStdString(); + } + if (settingsKeys.contains("rfBandwidth") || force) { + ostr << " m_rfBandwidth: " << m_rfBandwidth; + } + if (settingsKeys.contains("samplesPerChip") || force) { + ostr << " m_samplesPerChip: " << m_samplesPerChip; + } + if (settingsKeys.contains("maxFrequencyOffset") || force) { + ostr << " m_maxFrequencyOffset: " << m_maxFrequencyOffset; + } + if (settingsKeys.contains("threshold") || force) { + ostr << " m_threshold: " << m_threshold; + } + if (settingsKeys.contains("showBadFCS") || force) { + ostr << " m_showBadFCS: " << m_showBadFCS; + } + if (settingsKeys.contains("filterFrameType") || force) { + ostr << " m_filterFrameType: " << m_filterFrameType; + } + if (settingsKeys.contains("filterPANID") || force) { + ostr << " m_filterPANID: " << m_filterPANID.toStdString(); + } + if (settingsKeys.contains("filterAddress") || force) { + ostr << " m_filterAddress: " << m_filterAddress.toStdString(); + } + 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("udpFormat") || force) { + ostr << " m_udpFormat: " << m_udpFormat; + } + 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/demod802.15.4/ieee_802_15_4_demodsettings.h b/plugins/channelrx/demod802.15.4/ieee_802_15_4_demodsettings.h new file mode 100644 index 000000000..78f165166 --- /dev/null +++ b/plugins/channelrx/demod802.15.4/ieee_802_15_4_demodsettings.h @@ -0,0 +1,108 @@ +/////////////////////////////////////////////////////////////////////////////////// +// 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_IEEE_802_15_4_DEMODSETTINGS_H +#define INCLUDE_IEEE_802_15_4_DEMODSETTINGS_H + +#include +#include + +#include "dsp/dsptypes.h" +#include "util/ieee_802_15_4.h" + +class Serializable; + +#define IEEE_802_15_4_DEMOD_COLUMNS 16 + +struct IEEE_802_15_4_DemodSettings +{ + enum UDPFormat { + ZEP, //!< ZigBee Encapsulation Protocol v2, as decoded by Wireshark + Raw //!< PSDU (MAC frame including FCS) + }; + + enum FrameTypeFilter { + FilterAll, + FilterBeacon, + FilterData, + FilterAck, + FilterCommand, + FilterOther + }; + + qint64 m_inputFrequencyOffset; + QString m_phy; //!< PHY name, as in IEEE_802_15_4_PHY::getPHYNames() + Real m_rfBandwidth; + int m_samplesPerChip; //!< Channel sample rate is this multiplied by the chip rate + Real m_maxFrequencyOffset; //!< Maximum carrier frequency offset to search for during acquisition in Hz + Real m_threshold; //!< Preamble detection threshold (0-1) + bool m_showBadFCS; //!< Show frames with invalid FCS + FrameTypeFilter m_filterFrameType; + QString m_filterPANID; //!< Regular expression to match against PAN IDs + QString m_filterAddress; //!< Regular expression to match against source or destination address + bool m_udpEnabled; + QString m_udpAddress; + uint16_t m_udpPort; + UDPFormat m_udpFormat; + QString m_logFilename; //!< .csv or .pcap + 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_scopeGUI; + Serializable *m_rollupState; + int m_workspaceIndex; + QByteArray m_geometryBytes; + bool m_hidden; + + int m_columnIndexes[IEEE_802_15_4_DEMOD_COLUMNS]; //!< How the columns are ordered in the table + int m_columnSizes[IEEE_802_15_4_DEMOD_COLUMNS]; //!< Size of the columns in the table + + static const int m_scopeStreams = 8; + //! Range of preamble detection threshold. Too low a value results in continuous detections + static constexpr float m_minThreshold = 0.005f; + static constexpr float m_maxThreshold = 1.0f; + static const int m_zepPort = 17754; + + IEEE_802_15_4_DemodSettings(); + void resetToDefaults(); + void setChannelMarker(Serializable *channelMarker) { m_channelMarker = channelMarker; } + void setRollupState(Serializable *rollupState) { m_rollupState = rollupState; } + void setScopeGUI(Serializable *scopeGUI) { m_scopeGUI = scopeGUI; } + QByteArray serialize() const; + bool deserialize(const QByteArray& data); + void applySettings(const QStringList& settingsKeys, const IEEE_802_15_4_DemodSettings& settings); + QString getDebugString(const QStringList& settingsKeys, bool force=false) const; + + IEEE_802_15_4_PHY getPHY() const; + int getChannelSampleRate() const; + //! Set m_phy and parameters that depend on it to default values + bool setPHY(const QString& phy); + //! Default maximum frequency offset for a PHY: +-40ppm at each end at the highest frequency band the PHY is used in + static Real getDefaultMaxFrequencyOffset(const IEEE_802_15_4_PHY& phy); +}; + +#endif /* INCLUDE_IEEE_802_15_4_DEMODSETTINGS_H */ diff --git a/plugins/channelrx/demod802.15.4/ieee_802_15_4_demodsink.cpp b/plugins/channelrx/demod802.15.4/ieee_802_15_4_demodsink.cpp new file mode 100644 index 000000000..9d8915a6b --- /dev/null +++ b/plugins/channelrx/demod802.15.4/ieee_802_15_4_demodsink.cpp @@ -0,0 +1,246 @@ +/////////////////////////////////////////////////////////////////////////////////// +// 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/scopevis.h" +#include "device/deviceapi.h" +#include "channel/channelwebapiutils.h" + +#include "ieee_802_15_4_demod.h" +#include "ieee_802_15_4_demodsink.h" + +IEEE_802_15_4_DemodSink::IEEE_802_15_4_DemodSink(IEEE_802_15_4_Demod *demod) : + m_scopeSink(nullptr), + m_demod(demod), + m_channel(nullptr), + m_channelSampleRate(8000000), + m_channelFrequencyOffset(0), + m_sampleRate(8000000), + m_interpolatorDistance(1.0f), + m_interpolatorDistanceRemain(1.0f), + m_magsq(0.0), + m_magsqSum(0.0), + m_magsqPeak(0.0), + m_magsqCount(0), + m_messageQueueToChannel(nullptr), + m_sampleBufferIndex(0) +{ + for (int i = 0; i < IEEE_802_15_4_DemodSettings::m_scopeStreams; i++) { + m_sampleBuffer[i].resize(m_sampleBufferSize); + } + + applySettings(QStringList(), m_settings, true); + applyChannelSettings(m_channelSampleRate, m_channelFrequencyOffset, true); +} + +IEEE_802_15_4_DemodSink::~IEEE_802_15_4_DemodSink() +{ +} + +void IEEE_802_15_4_DemodSink::sampleToScope(Complex sample, Real magsq) +{ + if (m_scopeSink) + { + const IEEE_802_15_4_DemodReceiver::Scope& scope = m_receiver.getScope(); + + m_sampleBuffer[0][m_sampleBufferIndex] = sample; + m_sampleBuffer[1][m_sampleBufferIndex] = Complex(magsq, 0.0f); + m_sampleBuffer[2][m_sampleBufferIndex] = Complex(scope.m_detectMetric, 0.0f); + m_sampleBuffer[3][m_sampleBufferIndex] = Complex(scope.m_correlation, 0.0f); + m_sampleBuffer[4][m_sampleBufferIndex] = Complex(scope.m_chip, 0.0f); + m_sampleBuffer[5][m_sampleBufferIndex] = Complex(scope.m_phase, 0.0f); + m_sampleBuffer[6][m_sampleBufferIndex] = Complex(scope.m_state, 0.0f); + m_sampleBuffer[7][m_sampleBufferIndex] = Complex(scope.m_crc, 0.0f); + m_sampleBufferIndex++; + + if (m_sampleBufferIndex == m_sampleBufferSize) + { + std::vector vbegin; + + for (int i = 0; i < IEEE_802_15_4_DemodSettings::m_scopeStreams; i++) { + vbegin.push_back(m_sampleBuffer[i].begin()); + } + + m_scopeSink->feed(vbegin, m_sampleBufferSize); + m_sampleBufferIndex = 0; + } + } +} + +void IEEE_802_15_4_DemodSink::feed(const SampleVector::const_iterator& begin, const SampleVector::const_iterator& end) +{ + Complex ci; + + for (SampleVector::const_iterator it = begin; it != end; ++it) + { + Complex c(it->real(), it->imag()); + c *= m_nco.nextIQ(); + + if (m_interpolatorDistance < 1.0f) // 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 IEEE_802_15_4_DemodSink::processOneSample(Complex &ci) +{ + Complex x = ci / SDR_RX_SCALEF; + Real magsq = std::norm(x); + + // Calculate average and peak levels for level meter + m_movingAverage(magsq); + m_magsq = m_movingAverage.asDouble(); + m_magsqSum += magsq; + if (magsq > m_magsqPeak) { + m_magsqPeak = magsq; + } + m_magsqCount++; + + m_receiver.process(IEEE_802_15_4_DemodReceiver::Cf(x.real(), x.imag())); + + while (m_receiver.frameAvailable()) { + sendFrame(m_receiver.popFrame()); + } + + sampleToScope(x, magsq); +} + +void IEEE_802_15_4_DemodSink::sendFrame(const IEEE_802_15_4_DemodReceiver::Frame& frame) +{ + if (!getMessageQueueToChannel()) { + return; + } + + QDateTime dateTime = QDateTime::currentDateTime(); + + if (m_settings.m_useFileTime) + { + QString hardwareId = m_demod->getDeviceAPI()->getHardwareId(); + + if ((hardwareId == "FileInput") || (hardwareId == "SigMFFileInput")) + { + QString dateTimeStr; + int deviceIdx = m_demod->getDeviceSetIndex(); + + if (ChannelWebAPIUtils::getDeviceReportValue(deviceIdx, "absoluteTime", dateTimeStr)) + { + QDateTime fileTime = QDateTime::fromString(dateTimeStr, Qt::ISODateWithMs); + + if (fileTime.isValid()) { + dateTime = fileTime; + } + } + } + } + + QByteArray psdu((const char *) frame.m_psdu.data(), (int) frame.m_psdu.size()); + float powerDB = frame.m_power > 0.0f ? 10.0f * std::log10(frame.m_power) : -150.0f; + + IEEE_802_15_4_Demod::MsgFrame *msg = IEEE_802_15_4_Demod::MsgFrame::create( + psdu, dateTime, frame.m_fcsOK, frame.m_coherent, frame.m_frequencyOffset, frame.m_lqi, powerDB, frame.m_snr); + getMessageQueueToChannel()->push(msg); +} + +void IEEE_802_15_4_DemodSink::configureResampler() +{ + m_sampleRate = m_settings.getChannelSampleRate(); + // Filter to the RF bandwidth, but keep the cutoff below the Nyquist frequency of the + // lower of the input and output sample rates, so nothing aliases on to the signal + double cutoff = std::min(m_settings.m_rfBandwidth / 2.0, 0.45 * std::min(m_channelSampleRate, m_sampleRate)); + m_interpolator.create(16, m_channelSampleRate, cutoff); + m_interpolatorDistance = (Real) m_channelSampleRate / (Real) m_sampleRate; + m_interpolatorDistanceRemain = m_interpolatorDistance; +} + +void IEEE_802_15_4_DemodSink::configureReceiver() +{ + m_receiver.configure(m_settings.getPHY(), m_settings.m_samplesPerChip, m_settings.m_maxFrequencyOffset, m_settings.m_threshold); +} + +void IEEE_802_15_4_DemodSink::applyChannelSettings(int channelSampleRate, int channelFrequencyOffset, bool force) +{ + qDebug() << "IEEE_802_15_4_DemodSink::applyChannelSettings:" + << " channelSampleRate: " << channelSampleRate + << " channelFrequencyOffset: " << channelFrequencyOffset; + + if ((m_channelFrequencyOffset != channelFrequencyOffset) || + (m_channelSampleRate != channelSampleRate) || force) + { + m_nco.setFreq(-channelFrequencyOffset, channelSampleRate); + } + + if ((m_channelSampleRate != channelSampleRate) || force) + { + m_channelSampleRate = channelSampleRate; + configureResampler(); + } + + m_channelSampleRate = channelSampleRate; + m_channelFrequencyOffset = channelFrequencyOffset; +} + +void IEEE_802_15_4_DemodSink::applySettings(const QStringList& settingsKeys, const IEEE_802_15_4_DemodSettings& settings, bool force) +{ + qDebug() << "IEEE_802_15_4_DemodSink::applySettings:" << settings.getDebugString(settingsKeys, force); + + bool resampler = (settingsKeys.contains("rfBandwidth") && (settings.m_rfBandwidth != m_settings.m_rfBandwidth)) + || (settingsKeys.contains("phy") && (settings.m_phy != m_settings.m_phy)) + || (settingsKeys.contains("samplesPerChip") && (settings.m_samplesPerChip != m_settings.m_samplesPerChip)) + || force; + bool receiver = (settingsKeys.contains("phy") && (settings.m_phy != m_settings.m_phy)) + || (settingsKeys.contains("samplesPerChip") && (settings.m_samplesPerChip != m_settings.m_samplesPerChip)) + || force; + + if (force) { + m_settings = settings; + } else { + m_settings.applySettings(settingsKeys, settings); + } + + if (resampler) { + configureResampler(); + } + + if (receiver) + { + configureReceiver(); + } + else + { + if (settingsKeys.contains("maxFrequencyOffset")) { + m_receiver.setMaxFrequencyOffset(m_settings.m_maxFrequencyOffset); + } + if (settingsKeys.contains("threshold")) { + m_receiver.setThreshold(m_settings.m_threshold); + } + } +} diff --git a/plugins/channelrx/demod802.15.4/ieee_802_15_4_demodsink.h b/plugins/channelrx/demod802.15.4/ieee_802_15_4_demodsink.h new file mode 100644 index 000000000..45fd4c50b --- /dev/null +++ b/plugins/channelrx/demod802.15.4/ieee_802_15_4_demodsink.h @@ -0,0 +1,116 @@ +/////////////////////////////////////////////////////////////////////////////////// +// 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_IEEE_802_15_4_DEMODSINK_H +#define INCLUDE_IEEE_802_15_4_DEMODSINK_H + +#include "dsp/channelsamplesink.h" +#include "dsp/nco.h" +#include "dsp/interpolator.h" +#include "util/movingaverage.h" +#include "util/messagequeue.h" + +#include "ieee_802_15_4_demodsettings.h" +#include "ieee_802_15_4_demodreceiver.h" + +class ChannelAPI; +class IEEE_802_15_4_Demod; +class ScopeVis; + +class IEEE_802_15_4_DemodSink : public ChannelSampleSink { +public: + IEEE_802_15_4_DemodSink(IEEE_802_15_4_Demod *demod); + ~IEEE_802_15_4_DemodSink(); + + virtual void feed(const SampleVector::const_iterator& begin, const SampleVector::const_iterator& end); + + void setScopeSink(ScopeVis* scopeSink) { m_scopeSink = scopeSink; } + void applyChannelSettings(int channelSampleRate, int channelFrequencyOffset, bool force = false); + void applySettings(const QStringList& settingsKeys, const IEEE_802_15_4_DemodSettings& settings, bool force = false); + void setMessageQueueToChannel(MessageQueue *messageQueue) { m_messageQueueToChannel = messageQueue; } + void setChannel(ChannelAPI *channel) { m_channel = channel; } + + 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; + } + +private: + struct MagSqLevelsStore + { + MagSqLevelsStore() : + m_magsq(1e-12), + m_magsqPeak(1e-12) + {} + double m_magsq; + double m_magsqPeak; + }; + + ScopeVis* m_scopeSink; + IEEE_802_15_4_Demod *m_demod; + IEEE_802_15_4_DemodSettings m_settings; + ChannelAPI *m_channel; + int m_channelSampleRate; + int m_channelFrequencyOffset; + int m_sampleRate; //!< Receiver sample rate (samples per chip * chip rate) + + NCO m_nco; + Interpolator m_interpolator; + Real m_interpolatorDistance; + Real m_interpolatorDistanceRemain; + + double m_magsq; + double m_magsqSum; + double m_magsqPeak; + int m_magsqCount; + MagSqLevelsStore m_magSqLevelStore; + + MessageQueue *m_messageQueueToChannel; + + MovingAverageUtil m_movingAverage; + + IEEE_802_15_4_DemodReceiver m_receiver; + + ComplexVector m_sampleBuffer[IEEE_802_15_4_DemodSettings::m_scopeStreams]; + static const int m_sampleBufferSize = 4096; + int m_sampleBufferIndex; + + void processOneSample(Complex &ci); + void configureResampler(); + void configureReceiver(); + void sendFrame(const IEEE_802_15_4_DemodReceiver::Frame& frame); + MessageQueue *getMessageQueueToChannel() { return m_messageQueueToChannel; } + void sampleToScope(Complex sample, Real magsq); +}; + +#endif // INCLUDE_IEEE_802_15_4_DEMODSINK_H diff --git a/plugins/channelrx/demod802.15.4/ieee_802_15_4_demodwebapiadapter.cpp b/plugins/channelrx/demod802.15.4/ieee_802_15_4_demodwebapiadapter.cpp new file mode 100644 index 000000000..35b0f2238 --- /dev/null +++ b/plugins/channelrx/demod802.15.4/ieee_802_15_4_demodwebapiadapter.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 "ieee_802_15_4_demod.h" +#include "ieee_802_15_4_demodwebapiadapter.h" + +IEEE_802_15_4_DemodWebAPIAdapter::IEEE_802_15_4_DemodWebAPIAdapter() +{ +} + +IEEE_802_15_4_DemodWebAPIAdapter::~IEEE_802_15_4_DemodWebAPIAdapter() +{ +} + +int IEEE_802_15_4_DemodWebAPIAdapter::webapiSettingsGet( + SWGSDRangel::SWGChannelSettings& response, + QString& errorMessage) +{ + (void) errorMessage; + response.setIeee802154DemodSettings(new SWGSDRangel::SWGIEEE_802_15_4_DemodSettings()); + response.getIeee802154DemodSettings()->init(); + IEEE_802_15_4_Demod::webapiFormatChannelSettings(response, m_settings); + + return 200; +} + +int IEEE_802_15_4_DemodWebAPIAdapter::webapiSettingsPutPatch( + bool force, + const QStringList& channelSettingsKeys, + SWGSDRangel::SWGChannelSettings& response, + QString& errorMessage) +{ + (void) force; + (void) errorMessage; + IEEE_802_15_4_Demod::webapiUpdateChannelSettings(m_settings, channelSettingsKeys, response); + + return 200; +} diff --git a/plugins/channelrx/demod802.15.4/ieee_802_15_4_demodwebapiadapter.h b/plugins/channelrx/demod802.15.4/ieee_802_15_4_demodwebapiadapter.h new file mode 100644 index 000000000..8087a5ac3 --- /dev/null +++ b/plugins/channelrx/demod802.15.4/ieee_802_15_4_demodwebapiadapter.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_IEEE_802_15_4_DEMOD_WEBAPIADAPTER_H +#define INCLUDE_IEEE_802_15_4_DEMOD_WEBAPIADAPTER_H + +#include "channel/channelwebapiadapter.h" +#include "ieee_802_15_4_demodsettings.h" + +/** + * Standalone API adapter only for the settings + */ +class IEEE_802_15_4_DemodWebAPIAdapter : public ChannelWebAPIAdapter { +public: + IEEE_802_15_4_DemodWebAPIAdapter(); + virtual ~IEEE_802_15_4_DemodWebAPIAdapter(); + + 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: + IEEE_802_15_4_DemodSettings m_settings; +}; + +#endif // INCLUDE_IEEE_802_15_4_DEMOD_WEBAPIADAPTER_H diff --git a/plugins/channelrx/demod802.15.4/readme.md b/plugins/channelrx/demod802.15.4/readme.md new file mode 100644 index 000000000..b2ab1db12 --- /dev/null +++ b/plugins/channelrx/demod802.15.4/readme.md @@ -0,0 +1,202 @@ +

IEEE 802.15.4 demodulator plugin

+ +

Introduction

+ +This plugin can be used to demodulate IEEE 802.15.4 frames. The 802.15.4 PHY & MAC layers are used by networking protocols such as ZigBee, Thread, 6LoWPAN, WirelessHART and others. + +The demodulator supports the same PHYs as the [802.15.4 modulator](../../channeltx/mod802.15.4/readme.md): the BPSK PHYs (clause 13 of IEEE 802.15.4-2015) and the O-QPSK PHYs (clause 12), including the 2.4GHz O-QPSK PHY used by ZigBee and Thread. + +Received frames are displayed in a table, with the MAC header decoded. Frames can be forwarded via UDP, either as raw MAC frames or encapsulated in ZEP (ZigBee Encapsulation Protocol), which Wireshark can decode, or logged to a .csv or .pcap file. + +

Receiver

+ +All supported PHYs use DSSS (Direct Sequence Spread Spectrum), where each symbol (4 bits for O-QPSK, 1 bit for BPSK) is transmitted as a sequence of 32, 16 or 15 chips. + +The frequency tolerance of 802.15.4 devices is +/-40ppm, so two devices can be up to 80ppm apart: around +/-200kHz at 2.4GHz and +/-70kHz at 868/915MHz. The demodulator handles this, as well as clock offsets of 80ppm. + +When tested with the 802.15.4 modulator over a simulated AWGN channel with a frequency offset of 40ppm and clock offset of 20ppm, the packet error rate for a 20 octet PSDU (as used for the receiver sensitivity definition in 10.1.7 of the specification) was 1% at approximately the following Eb/N0: + +PHY | Both lanes | Coherent lane only | Non-coherent lane only +----------------------------|------------|--------------------|----------------------- +20kbps BPSK | 9dB | 9.5dB | 9.5dB +40kbps BPSK | 9.5dB | 9.5dB | 10dB +100kbps <1GHz O-QPSK | 6.5dB | 7dB | 8dB +250kbps <1GHz O-QPSK (Sine) | 7dB | 7dB | 8dB +250kbps <1GHz O-QPSK (RC) | 6dB | 6.5dB | 7.5dB +250kbps >2GHz O-QPSK | 7dB | 7dB | 7dB + +These were measured with 200 frames per 1dB step of Eb/N0, so are approximate. + +

Interface

+ +The top and bottom bars of the channel window are described [here](../../../sdrgui/channel/readme.md) + +![802.15.4 Demodulator plugin GUI](../../../doc/img/IEEE_802_15_4_Demod_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: Channel power

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

3: Level meter in dB

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

4: PHY

+ +Specifies the PHY (physical layer), which determines the bit rate, modulation and spreading. Each PHY is applicable only to specific frequency bands, as detailed below: + +Channel Page | Channels | Frequencies (MHz) | PHY | Bit rate (kbps) | Chip rate (kcps) | Modulation | Shaping +-------------|----------|--------------------|-----------------------------|-----------------|------------------|------------|--------- +0 | 0 | 868.3 | 20kbps BPSK | 20 | 300 | BPSK | RC r=1 +0 | 1-10 | 906, 908... 924 | 40kbps BPSK | 40 | 600 | BPSK | RC r=1 +0 | 11-26 | 2405, 2410... 2480 | 250kbps >2GHz O-QPSK | 250 | 2000 | O-QPSK | Sine +2 | 0 | 868.3 | 100kbps <1GHz O-QPSK | 100 | 400 | O-QPSK | Sine +2 | 1-10 | 906, 908... 924 | 250kbps <1GHz O-QPSK (Sine) | 250 | 1000 | O-QPSK | Sine +5 | 0-3 | 780, 782... 786 | 250kbps <1GHz O-QPSK (RC) | 250 | 1000 | O-QPSK | RC r=0.8 +11 | 0-13 | 2363... 2397 | 250kbps >2GHz O-QPSK | 250 | 2000 | O-QPSK | Sine + +Changing the PHY sets the RF bandwidth (7) and maximum frequency offset (8) to default values for the PHY. + +

5: CR - Chip rate

+ +Displays the chip rate for the selected PHY. + +

6: SPC - Samples per chip

+ +The number of samples per chip the demodulator works at. The channel sample rate, which is displayed to the right, is the chip rate multiplied by this value. +4 is a good choice. 2 gives a small loss of sensitivity, but halves the CPU usage. Larger values use more CPU without any real benefit. + +The device's sample rate needs to be at least the RF bandwidth, but doesn't need to be a multiple of the chip rate, as the signal is resampled. +So for the 2.4GHz PHY, a device sample rate of 4MSa/s or more is suitable. When the device sample rate is lower than the RF bandwidth, the RF bandwidth value will be displayed with a red background. + +

7: BW - RF Bandwidth

+ +Specifies the bandwidth of the channel filter applied to the received signal. + +

8: Max ΔF - Maximum frequency offset

+ +The maximum carrier frequency offset in kHz to search for when acquiring a frame. The default is 80ppm of the highest frequency the PHY is used at. +If the frequency offset of the transmitter is known to be smaller (E.g. after adjusting the channel frequency (1) by the ΔF displayed in the table), reducing this slightly reduces the CPU used per preamble detection. + +

9: TH - Detection threshold

+ +Sets the threshold for detecting a preamble. Lower values allow weaker signals to be detected, but increase the number of false detections, each of which uses some CPU while the preamble is verified. +The default is 0.05. + +

10: UDP

+ +When checked, received frames are forwarded to the specified UDP address (11) and port (12). + +

11: UDP address

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

12: UDP port

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

13: UDP format

+ +The format frames are forwarded in via UDP: + +* ZEP - Frames are encapsulated using ZigBee Encapsulation Protocol v2, which includes the channel number, LQI and a timestamp. Wireshark decodes ZEP on UDP port 17754. +* Raw - The MAC frame (PSDU), including the FCS. + +To view frames in Wireshark, set the UDP format to ZEP and the port to 17754, and capture on the loopback interface (which on Windows requires Npcap's loopback adapter). For ZigBee networks, you may need to enter the network key in Wireshark's ZigBee protocol preferences, to decrypt the NWK layer. + +

14: Frame type filter

+ +Display only frames of the selected type in the table (Beacon, Data, Ack, Command or Other). + +

15: PAN - PAN ID filter

+ +Entering a regular expression displays only frames where the source or destination PAN ID matches. PAN IDs are displayed as 0x followed by 4 hex digits. E.g. 0x1a62. + +

16: Addr - Address filter

+ +Entering a regular expression displays only frames where the source or destination address matches. Short addresses are displayed as 0x followed by 4 hex digits. +Extended addresses are displayed as 8 colon separated bytes, most significant byte first. E.g. 00:12:4b:00:01:02:03:04. + +

17: FCS - Show frames with invalid FCS

+ +When checked, frames with an invalid FCS (Frame Check Sequence - a CRC) are displayed in the table in red, logged and forwarded via UDP. When unchecked, only frames with a valid FCS are. + +

18: Use Date and Time from File

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

19: Start/stop Logging Frames to File

+ +When checked, writes all received frames to a file. If the filename has a .pcap extension, frames are written in PCAP format (with link type 195, IEEE 802.15.4 with FCS), which can be opened in Wireshark. Otherwise, a .csv file is written. + +

20: Log Filename

+ +Click to specify the name of the file which received frames 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 Frames from table

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

Received Frames Table

+ +The received frames table displays information about each frame received. + +![802.15.4 Demodulator received frames table](../../../doc/img/IEEE_802_15_4_Demod_frames.png) + +* Date/Time - The date and time the frame was received. +* Type - MAC frame type: Beacon, Data, Ack, Command, Multipurpose, Fragment or Extended. +* Seq - Sequence number. +* Dst PAN - Destination PAN ID. +* Dst Addr - Destination address. +* Src PAN - Source PAN ID. +* Src Addr - Source address. +* Info - Command name, security level, acknowledgement request (AR), frame pending (FP), frame version and information elements. +* Len - Length of the PSDU (MAC frame) in bytes, including the FCS. +* Payload - MAC payload as hex. This is encrypted if security is enabled. +* PSDU - The complete MAC frame as hex, including the FCS. +* FCS - Whether the FCS is valid. +* Power - Received power during the frame in dB. +* SNR - Estimated symbol signal to noise ratio (Es/N0) in dB, after despreading. Eb/N0 is 6dB less for the O-QPSK PHYs. +* LQI - Link quality indicator. The mean normalised correlation of the received symbols, from 0 to 1. +* ΔF - Estimated carrier frequency offset in Hz. + +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 an item in the table allows you to copy the value to the clipboard. + +

Waveforms

+ +The waveforms display shows signals within the demodulator, which may be useful for debugging. The available signals are: + +* IQ - The received signal, at the channel sample rate. +* MagSq - Magnitude squared of the received signal. +* Detect - Preamble detection metric, compared against the threshold (9). +* Correlation - Normalised correlation of the most recently decoded symbol. +* Chip - Phase corrected soft value of the last chip of the most recently decoded symbol. +* Phase - Tracked carrier phase / pi. +* State - 0 for searching, 1 for acquiring and 2 for receiving a frame. +* FCS - 1 after a frame with a valid FCS is received, -1 after a frame with an invalid FCS. + +

API

+ +Full details of the API can be found in the Swagger documentation. Below are a few examples: + +To set the PHY to 20kbps BPSK: + + curl -X PATCH "http://127.0.0.1:8091/sdrangel/deviceset/0/channel/0/settings" -d '{"channelType": "IEEE_802_15_4_Demod", "direction": 0, "IEEE_802_15_4_DemodSettings": { "phy": "20kbps BPSK" }}' + +To forward frames to Wireshark via ZEP: + + curl -X PATCH "http://127.0.0.1:8091/sdrangel/deviceset/0/channel/0/settings" -d '{"channelType": "IEEE_802_15_4_Demod", "direction": 0, "IEEE_802_15_4_DemodSettings": { "udpEnabled": 1, "udpAddress": "127.0.0.1", "udpPort": 17754, "udpFormat": 0 }}' + +To get the number of frames received: + + curl -X GET "http://127.0.0.1:8091/sdrangel/deviceset/0/channel/0/report" diff --git a/plugins/feature/mcpserver/mcpdocs.cpp b/plugins/feature/mcpserver/mcpdocs.cpp index 5164adbab..2a95cd710 100644 --- a/plugins/feature/mcpserver/mcpdocs.cpp +++ b/plugins/feature/mcpserver/mcpdocs.cpp @@ -404,6 +404,7 @@ const MCPDocs::Readme *MCPDocs::match(const QStringList& groups, const QString& // Plugins whose directory, id and title all differ static const QMap overrides = { {"ChannelAnalyzer", "chanalyzer"}, + {"IEEE_802_15_4_Demod", "demod802.15.4"}, {"IEEE_802_15_4_Mod", "mod802.15.4"}, }; diff --git a/sdrbase/CMakeLists.txt b/sdrbase/CMakeLists.txt index 48ae67509..6a799958a 100644 --- a/sdrbase/CMakeLists.txt +++ b/sdrbase/CMakeLists.txt @@ -243,6 +243,7 @@ set(sdrbase_SOURCES util/golay2312.cpp util/grb.cpp util/httpdownloadmanager.cpp + util/ieee_802_15_4.cpp util/interpolation.cpp util/jplhorizons.cpp util/kiwisdrlist.cpp @@ -514,6 +515,7 @@ set(sdrbase_HEADERS util/golay2312.h util/grb.h util/httpdownloadmanager.h + util/ieee_802_15_4.h util/incrementalarray.h util/incrementalvector.h util/interpolation.h diff --git a/sdrbase/resources/webapi.qrc b/sdrbase/resources/webapi.qrc index 9ab1ae0b4..7edc8baad 100644 --- a/sdrbase/resources/webapi.qrc +++ b/sdrbase/resources/webapi.qrc @@ -72,6 +72,7 @@ webapi/doc/swagger/include/GS232Controller.yaml webapi/doc/swagger/include/HackRF.yaml webapi/doc/swagger/include/HeatMap.yaml + webapi/doc/swagger/include/IEEE_802_15_4_Demod.yaml webapi/doc/swagger/include/IEEE_802_15_4_Mod.yaml webapi/doc/swagger/include/ILSDemod.yaml webapi/doc/swagger/include/Interferometer.yaml diff --git a/sdrbase/resources/webapi/doc/swagger/include/ChannelReport.yaml b/sdrbase/resources/webapi/doc/swagger/include/ChannelReport.yaml index 9ac0ab7c2..ecbfa4822 100644 --- a/sdrbase/resources/webapi/doc/swagger/include/ChannelReport.yaml +++ b/sdrbase/resources/webapi/doc/swagger/include/ChannelReport.yaml @@ -78,6 +78,8 @@ ChannelReport: EndOfTrainDemodReport: $ref: "/doc/swagger/include/EndOfTrainDemod.yaml#/EndOfTrainDemodReport" description: "End of train demod report data for Channel." + IEEE_802_15_4_DemodReport: + $ref: "/doc/swagger/include/IEEE_802_15_4_Demod.yaml#/IEEE_802_15_4_DemodReport" IEEE_802_15_4_ModReport: $ref: "/doc/swagger/include/IEEE_802_15_4_Mod.yaml#/IEEE_802_15_4_ModReport" description: "Ieee 802 15 4 mod 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 3de6d3cab..dfa26eaaf 100644 --- a/sdrbase/resources/webapi/doc/swagger/include/ChannelSettings.yaml +++ b/sdrbase/resources/webapi/doc/swagger/include/ChannelSettings.yaml @@ -129,6 +129,8 @@ ChannelSettings: InterferometerSettings: $ref: "/doc/swagger/include/Interferometer.yaml#/InterferometerSettings" description: "Interferometer settings configuration for Channel." + IEEE_802_15_4_DemodSettings: + $ref: "/doc/swagger/include/IEEE_802_15_4_Demod.yaml#/IEEE_802_15_4_DemodSettings" IEEE_802_15_4_ModSettings: $ref: "/doc/swagger/include/IEEE_802_15_4_Mod.yaml#/IEEE_802_15_4_ModSettings" description: "Ieee 802 15 4 mod settings configuration for Channel." diff --git a/sdrbase/resources/webapi/doc/swagger/include/IEEE_802_15_4_Demod.yaml b/sdrbase/resources/webapi/doc/swagger/include/IEEE_802_15_4_Demod.yaml new file mode 100644 index 000000000..f5e789ea2 --- /dev/null +++ b/sdrbase/resources/webapi/doc/swagger/include/IEEE_802_15_4_Demod.yaml @@ -0,0 +1,120 @@ +IEEE_802_15_4_DemodSettings: + description: IEEE_802_15_4_Demod + properties: + inputFrequencyOffset: + type: integer + format: int64 + description: "Frequency offset of the channel from the device center frequency in Hz." + phy: + type: string + description: > + PHY. One of: "20kbps BPSK", "40kbps BPSK", "100kbps <1GHz O-QPSK", + "250kbps <1GHz O-QPSK (Sine)", "250kbps <1GHz O-QPSK (RC)", "250kbps >2GHz O-QPSK" + rfBandwidth: + type: number + format: float + description: "RF bandwidth of the channel filter in Hz." + samplesPerChip: + type: integer + minimum: 2 + maximum: 16 + description: "Samples per chip. The channel sample rate is this multiplied by the chip rate." + maxFrequencyOffset: + type: number + format: float + description: "Maximum carrier frequency offset to search for during acquisition in Hz." + threshold: + type: number + format: float + minimum: 0 + maximum: 1 + description: "Preamble detection threshold." + showBadFCS: + type: integer + description: "Show frames with invalid FCS (1 for yes, 0 for no)." + filterFrameType: + type: integer + minimum: 0 + maximum: 5 + description: "Frame type filter for the GUI table: 0 - All, 1 - Beacon, 2 - Data, 3 - Ack, 4 - Command, 5 - Other." + filterPANID: + type: string + description: "Regular expression to filter frames by PAN ID in the GUI table." + filterAddress: + type: string + description: "Regular expression to filter frames by source or destination address in the GUI table." + udpEnabled: + type: integer + description: "Whether to forward received frames to specified UDP port (1 for yes, 0 for no)." + udpAddress: + type: string + description: "UDP address to forward received frames to." + udpPort: + type: integer + minimum: 1024 + maximum: 65535 + description: "UDP port to forward received frames to." + udpFormat: + type: integer + minimum: 0 + maximum: 1 + description: "Format of frames forwarded via UDP: 0 - ZEP (ZigBee Encapsulation Protocol v2), 1 - Raw MAC frame." + logFilename: + type: string + description: "Log filename. Use .pcap extension for PCAP format, otherwise CSV format is used." + logEnabled: + type: integer + description: "Whether to log received frames to a file (1 for yes, 0 for no)." + useFileTime: + type: integer + description: "Use date and time from file input device rather than the system clock (1 for yes, 0 for no)." + rgbColor: + type: integer + description: "Channel-marker colour as an ARGB integer." + title: + type: string + description: "Channel title shown in the GUI." + 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 + reverseAPIAddress: + type: string + description: "Address of the reverse API peer." + reverseAPIPort: + type: integer + description: "Port of the reverse API peer." + 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." + scopeConfig: + $ref: "/doc/swagger/include/GLScope.yaml#/GLScope" + description: "Oscilloscope-display configuration." + channelMarker: + $ref: "/doc/swagger/include/ChannelMarker.yaml#/ChannelMarker" + description: "Channel-marker display settings." + rollupState: + $ref: "/doc/swagger/include/RollupState.yaml#/RollupState" + description: "Saved expanded or collapsed state of the GUI sections." + +IEEE_802_15_4_DemodReport: + description: IEEE_802_15_4_Demod + 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." + framesOK: + type: integer + description: "Number of frames received with a valid FCS." + framesBadFCS: + type: integer + description: "Number of frames received with an invalid FCS." diff --git a/sdrbase/util/ieee_802_15_4.cpp b/sdrbase/util/ieee_802_15_4.cpp new file mode 100644 index 000000000..170c2aea8 --- /dev/null +++ b/sdrbase/util/ieee_802_15_4.cpp @@ -0,0 +1,717 @@ +/////////////////////////////////////////////////////////////////////////////////// +// 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 "util/crc.h" +#include "util/ieee_802_15_4.h" + +// Table 13-1 - Symbol-to-chip mapping for BPSK PHY (c0 first) +const uint8_t IEEE_802_15_4_PHY::m_chipsBPSK[2][15] = { + {1, 1, 1, 1, 0, 1, 0, 1, 1, 0, 0, 1, 0, 0, 0}, + {0, 0, 0, 0, 1, 0, 1, 0, 0, 1, 1, 0, 1, 1, 1} +}; + +// Table 12-2 - Symbol-to-chip mapping for the 780 MHz, 868 MHz and 915 MHz bands +const uint8_t IEEE_802_15_4_PHY::m_chipsSubGHzOQPSK[16][16] = { + {0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 1, 0, 1}, + {0, 1, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 1}, + {0, 1, 0, 1, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0}, + {1, 0, 0, 1, 0, 1, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0}, + {0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 1, 1, 1, 1, 0}, + {1, 0, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 1, 1, 1}, + {1, 1, 1, 0, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 1}, + {1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0}, + {0, 1, 1, 0, 1, 0, 1, 1, 0, 1, 1, 1, 0, 0, 0, 0}, + {0, 0, 0, 1, 1, 0, 1, 0, 1, 1, 0, 1, 1, 1, 0, 0}, + {0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 1, 1, 0, 1, 1, 1}, + {1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 1, 1, 0, 1}, + {0, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 1, 1}, + {1, 1, 0, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 1, 0}, + {1, 0, 1, 1, 0, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0}, + {1, 0, 1, 0, 1, 1, 0, 1, 1, 1, 0, 0, 0, 0, 0, 1}, +}; + +// Table 12-1 - Symbol-to-chip mapping for the 2450 MHz and 2380 MHz bands +const uint8_t IEEE_802_15_4_PHY::m_chips2450OQPSK[16][32] = { + {1, 1, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 1, 1, 1, 0}, + {1, 1, 1, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0}, + {0, 0, 1, 0, 1, 1, 1, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 0, 1, 0, 0, 1, 0}, + {0, 0, 1, 0, 0, 0, 1, 0, 1, 1, 1, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 0, 1}, + {0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 1, 1, 1, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1}, + {0, 0, 1, 1, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 1, 1, 1, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0}, + {1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 1, 1, 1, 0, 1, 1, 0, 1, 1, 0, 0, 1}, + {1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 1, 1, 1, 0, 1, 1, 0, 1}, + {1, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1}, + {1, 0, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 1, 1, 1}, + {0, 1, 1, 1, 1, 0, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1}, + {0, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 0}, + {0, 0, 0, 0, 0, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0, 1, 0, 1, 1, 0}, + {0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0, 1}, + {1, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0}, + {1, 1, 0, 0, 1, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 0, 0, 0} +}; + +IEEE_802_15_4_PHY::IEEE_802_15_4_PHY() : + m_bitRate(250000), + m_modulation(OQPSK), + m_subGHzBand(false), + m_pulseShaping(SINE), + m_beta(1.0f), + m_symbolSpan(6) +{ +} + +bool IEEE_802_15_4_PHY::fromString(const QString& phy) +{ + bool valid; + + // First part of phy string should give bitrate in kbps + float bitRate = phy.split("k")[0].toFloat(&valid) * 1000.0f; + + if (!valid) { + return false; + } + + if (phy.contains("BPSK")) + { + m_bitRate = bitRate; + m_subGHzBand = true; + m_modulation = BPSK; + m_pulseShaping = RC; + m_beta = 1.0f; + m_symbolSpan = 6; + } + else if (phy.contains("O-QPSK")) + { + m_bitRate = bitRate; + m_subGHzBand = phy.contains("<1"); + m_modulation = OQPSK; + + if (phy.contains("RC")) + { + m_pulseShaping = RC; + m_beta = 0.8f; + m_symbolSpan = 6; + } + else + { + m_pulseShaping = SINE; + } + } + else + { + return false; + } + + return true; +} + +QStringList IEEE_802_15_4_PHY::getPHYNames() +{ + return { + "20kbps BPSK", + "40kbps BPSK", + "100kbps <1GHz O-QPSK", + "250kbps <1GHz O-QPSK (Sine)", + "250kbps <1GHz O-QPSK (RC)", + "250kbps >2GHz O-QPSK" + }; +} + +QString IEEE_802_15_4_PHY::toString() const +{ + if (m_modulation == BPSK) + { + if (m_bitRate == 20000) { + return "20kbps BPSK"; + } else if (m_bitRate == 40000) { + return "40kbps BPSK"; + } + } + else if (m_subGHzBand) + { + if (m_bitRate == 100000) { + return "100kbps <1GHz O-QPSK"; + } else if ((m_bitRate == 250000) && (m_pulseShaping == SINE)) { + return "250kbps <1GHz O-QPSK (Sine)"; + } else if (m_bitRate == 250000) { + return "250kbps <1GHz O-QPSK (RC)"; + } + } + else if (m_bitRate == 250000) + { + return "250kbps >2GHz O-QPSK"; + } + + return ""; +} + +int IEEE_802_15_4_PHY::getChipsPerSymbol() const +{ + if (m_modulation == BPSK) { + return 15; + } else { + return m_subGHzBand ? 16 : 32; + } +} + +int IEEE_802_15_4_PHY::getBitsPerSymbol() const +{ + return m_modulation == BPSK ? 1 : 4; +} + +int IEEE_802_15_4_PHY::getChipRate() const +{ + return m_bitRate * getChipsPerSymbol() / getBitsPerSymbol(); +} + +int IEEE_802_15_4_PHY::getOccupiedBandwidth() const +{ + int chipRate = getChipRate(); + + if (m_pulseShaping == SINE) { + return (int) (1.5 * chipRate); + } else { + return (int) ((1.0 + m_beta) * chipRate); + } +} + +int IEEE_802_15_4_PHY::getChip(int symbol, int chipIdx) const +{ + if (m_modulation == BPSK) { + return m_chipsBPSK[symbol & 1][chipIdx]; + } else if (m_subGHzBand) { + return m_chipsSubGHzOQPSK[symbol & 0xf][chipIdx]; + } else { + return m_chips2450OQPSK[symbol & 0xf][chipIdx]; + } +} + +std::vector IEEE_802_15_4_PHY::getPulse(int samplesPerChip) const +{ + std::vector pulse; + + if (m_pulseShaping == SINE) + { + // Half-sine over two chips: p(t) = sin(pi*t/(2*Tc)), 0 <= t <= 2*Tc + pulse.resize(2 * samplesPerChip); + + for (int i = 0; i < 2 * samplesPerChip; i++) { + pulse[i] = (float) std::sin(M_PI * i / (2.0 * samplesPerChip)); + } + } + else + { + // Raised cosine, centred on the chip time, as used by RaisedCosine + int nTaps = m_symbolSpan * samplesPerChip + 1; + + if (!(nTaps & 1)) { + nTaps++; + } + + pulse.resize(nTaps); + + for (int i = 0; i < nTaps; i++) + { + double t = (i - (nTaps / 2)) / (double) samplesPerChip; + double denominator = 1.0 - std::pow(2.0 * m_beta * t, 2.0); + + if (std::abs(denominator) > 1e-9) + { + double sinc = (t == 0.0) ? 1.0 : std::sin(M_PI * t) / (M_PI * t); + pulse[i] = (float) (sinc * std::cos(M_PI * m_beta * t) / denominator); + } + else + { + pulse[i] = (float) (m_beta * std::sin(M_PI / (2.0 * m_beta)) / 2.0); + } + } + } + + return pulse; +} + +int IEEE_802_15_4_PHY::getPulseStartOffset(int samplesPerChip) const +{ + if (m_pulseShaping == SINE) + { + return 0; + } + else + { + int nTaps = m_symbolSpan * samplesPerChip + 1; + + if (!(nTaps & 1)) { + nTaps++; + } + + return -(nTaps / 2); + } +} + +IEEE_802_15_4_FrameDecoder::IEEE_802_15_4_FrameDecoder() : + m_valid(false), + m_frameControl(0), + m_frameType(Beacon), + m_securityEnabled(false), + m_framePending(false), + m_ackRequest(false), + m_panIdCompression(false), + m_seqNoSuppression(false), + m_iePresent(false), + m_destAddressMode(AddressNone), + m_frameVersion(0), + m_srcAddressMode(AddressNone), + m_hasSeqNo(false), + m_seqNo(0), + m_hasDestPANID(false), + m_destPANID(0), + m_destAddress(0), + m_hasSrcPANID(false), + m_srcPANID(0), + m_srcAddress(0), + m_securityLevel(0), + m_keyIdMode(0), + m_auxSecurityHeaderLength(0), + m_commandId(-1), + m_hasFCS(false), + m_fcs(0) +{ +} + +uint16_t IEEE_802_15_4_FrameDecoder::calcFCS(const uint8_t *data, int length) +{ + crc16itut crc; + crc.calculate(data, length); + return crc.get(); +} + +bool IEEE_802_15_4_FrameDecoder::decode(const QByteArray& psdu, bool hasFCS) +{ + const uint8_t *p = (const uint8_t *) psdu.data(); + int length = psdu.size(); + + m_valid = false; + m_ies.clear(); + m_payload.clear(); + m_commandId = -1; + m_hasFCS = hasFCS && (length >= 2); + + if (m_hasFCS) + { + m_fcs = p[length - 2] | (p[length - 1] << 8); + length -= 2; + } + + if (length < 1) { + return false; + } + + int idx = 0; + m_frameControl = p[idx++]; + m_frameType = (FrameType) (m_frameControl & 0x7); + + // Fragment frames have no frame control, and multipurpose frames have a different + // format which we don't decode further + if ((m_frameType == Fragment) || (m_frameType == Multipurpose) || (m_frameType == Extended) || (m_frameType == Reserved)) + { + m_payload = QByteArray((const char *) &p[idx], length - idx); + m_valid = true; + return true; + } + + if (length < 2) { + return false; + } + + m_frameControl |= p[idx++] << 8; + m_securityEnabled = (m_frameControl >> 3) & 1; + m_framePending = (m_frameControl >> 4) & 1; + m_ackRequest = (m_frameControl >> 5) & 1; + m_panIdCompression = (m_frameControl >> 6) & 1; + m_seqNoSuppression = (m_frameControl >> 8) & 1; + m_iePresent = (m_frameControl >> 9) & 1; + m_destAddressMode = (AddressMode) ((m_frameControl >> 10) & 3); + m_frameVersion = (m_frameControl >> 12) & 3; + m_srcAddressMode = (AddressMode) ((m_frameControl >> 14) & 3); + + if ((m_destAddressMode == AddressReserved) || (m_srcAddressMode == AddressReserved)) { + return false; + } + + m_hasSeqNo = !m_seqNoSuppression; + + if (m_hasSeqNo) + { + if (idx >= length) { + return false; + } + m_seqNo = p[idx++]; + } + + // Determine which PAN IDs are present - 7.2.1.5 + bool destPresent = m_destAddressMode != AddressNone; + bool srcPresent = m_srcAddressMode != AddressNone; + + if (m_frameVersion < 2) + { + m_hasDestPANID = destPresent; + m_hasSrcPANID = srcPresent && !(destPresent && m_panIdCompression); + } + else + { + // Table 7-2 + if (!destPresent && !srcPresent) + { + m_hasDestPANID = m_panIdCompression; + m_hasSrcPANID = false; + } + else if (destPresent && !srcPresent) + { + m_hasDestPANID = !m_panIdCompression; + m_hasSrcPANID = false; + } + else if (!destPresent && srcPresent) + { + m_hasDestPANID = false; + m_hasSrcPANID = !m_panIdCompression; + } + else if ((m_destAddressMode == AddressExtended) && (m_srcAddressMode == AddressExtended)) + { + m_hasDestPANID = !m_panIdCompression; + m_hasSrcPANID = false; + } + else + { + m_hasDestPANID = true; + m_hasSrcPANID = !m_panIdCompression; + } + } + + auto readAddress = [&](AddressMode mode, uint64_t& address) -> bool { + int bytes = mode == AddressShort ? 2 : (mode == AddressExtended ? 8 : 0); + + if (idx + bytes > length) { + return false; + } + + address = 0; + + for (int i = 0; i < bytes; i++) { + address |= ((uint64_t) p[idx++]) << (8 * i); + } + + return true; + }; + + uint64_t panId; + + if (m_hasDestPANID) + { + if (!readAddress(AddressShort, panId)) { + return false; + } + m_destPANID = (uint16_t) panId; + } + if (!readAddress(m_destAddressMode, m_destAddress)) { + return false; + } + if (m_hasSrcPANID) + { + if (!readAddress(AddressShort, panId)) { + return false; + } + m_srcPANID = (uint16_t) panId; + } + if (!readAddress(m_srcAddressMode, m_srcAddress)) { + return false; + } + + // Auxiliary security header - 9.4 + m_auxSecurityHeaderLength = 0; + + if (m_securityEnabled) + { + if (idx >= length) { + return false; + } + + uint8_t securityControl = p[idx]; + m_securityLevel = securityControl & 0x7; + m_keyIdMode = (securityControl >> 3) & 0x3; + bool frameCounterSuppression = (m_frameVersion >= 2) && ((securityControl >> 5) & 1); + static const int keyIdLengths[4] = {0, 1, 5, 9}; + + m_auxSecurityHeaderLength = 1 + (frameCounterSuppression ? 0 : 4) + keyIdLengths[m_keyIdMode]; + + if (idx + m_auxSecurityHeaderLength > length) { + return false; + } + + idx += m_auxSecurityHeaderLength; + } + + // Information elements - 7.4 + if (m_iePresent) + { + bool payloadIEs = false; + + // Header IEs + while (idx + 2 <= length) + { + uint16_t descriptor = p[idx] | (p[idx + 1] << 8); + idx += 2; + IE ie; + ie.m_header = true; + ie.m_length = descriptor & 0x7f; + ie.m_id = (descriptor >> 7) & 0xff; + + if (idx + ie.m_length > length) { + return false; + } + + idx += ie.m_length; + + if (ie.m_id == 0x7e) // Header Termination 1 - Payload IEs follow + { + payloadIEs = true; + break; + } + else if (ie.m_id == 0x7f) // Header Termination 2 - Payload follows + { + break; + } + + m_ies.append(ie); + } + + // Payload IEs are encrypted if security is enabled + if (payloadIEs && !m_securityEnabled) + { + while (idx + 2 <= length) + { + uint16_t descriptor = p[idx] | (p[idx + 1] << 8); + idx += 2; + IE ie; + ie.m_header = false; + ie.m_length = descriptor & 0x7ff; + ie.m_id = (descriptor >> 11) & 0xf; + + if (idx + ie.m_length > length) { + return false; + } + + idx += ie.m_length; + + if (ie.m_id == 0xf) { // Payload termination + break; + } + + m_ies.append(ie); + } + } + } + + if ((m_frameType == Command) && !m_securityEnabled && (idx < length)) { + m_commandId = p[idx]; + } + + m_payload = QByteArray((const char *) &p[idx], length - idx); + m_valid = true; + + return true; +} + +QString IEEE_802_15_4_FrameDecoder::frameTypeToString(FrameType type) +{ + switch (type) + { + case Beacon: + return "Beacon"; + case Data: + return "Data"; + case Ack: + return "Ack"; + case Command: + return "Command"; + case Multipurpose: + return "Multipurpose"; + case Fragment: + return "Fragment"; + case Extended: + return "Extended"; + default: + return "Reserved"; + } +} + +QString IEEE_802_15_4_FrameDecoder::commandToString(int commandId) +{ + // Table 7-49 + switch (commandId) + { + case 0x01: + return "Association Request"; + case 0x02: + return "Association Response"; + case 0x03: + return "Disassociation Notification"; + case 0x04: + return "Data Request"; + case 0x05: + return "PAN ID Conflict Notification"; + case 0x06: + return "Orphan Notification"; + case 0x07: + return "Beacon Request"; + case 0x08: + return "Coordinator Realignment"; + case 0x09: + return "GTS Request"; + case 0x0a: + return "TRLE Management Request"; + case 0x0b: + return "TRLE Management Response"; + case 0x13: + return "DSME Association Request"; + case 0x14: + return "DSME Association Response"; + case 0x15: + return "DSME GTS Request"; + case 0x16: + return "DSME GTS Response"; + case 0x17: + return "DSME GTS Notify"; + case 0x18: + return "DSME Information Request"; + case 0x19: + return "DSME Information Response"; + case 0x1a: + return "DSME Beacon Allocation Notification"; + case 0x1b: + return "DSME Beacon Collision Notification"; + case 0x1c: + return "DSME Link Report"; + case 0x20: + return "RIT Data Request"; + case 0x21: + return "DBS Request"; + case 0x22: + return "DBS Response"; + case 0x23: + return "RIT Data Response"; + case 0x24: + return "Vendor Specific"; + case 0x25: + return "SRM Request"; + case 0x26: + return "SRM Response"; + case 0x27: + return "SRM Report"; + case 0x28: + return "SRM Information"; + default: + return QString("Command 0x%1").arg(commandId, 2, 16, QChar('0')); + } +} + +QString IEEE_802_15_4_FrameDecoder::addressToString(AddressMode mode, uint64_t address) +{ + if (mode == AddressShort) + { + return QString("0x%1").arg(address, 4, 16, QChar('0')); + } + else if (mode == AddressExtended) + { + // Display MSB first, as Wireshark does + QStringList bytes; + + for (int i = 7; i >= 0; i--) { + bytes.append(QString("%1").arg((address >> (8 * i)) & 0xff, 2, 16, QChar('0'))); + } + + return bytes.join(":"); + } + else + { + return ""; + } +} + +QString IEEE_802_15_4_FrameDecoder::getFrameTypeString() const +{ + return frameTypeToString(m_frameType); +} + +QString IEEE_802_15_4_FrameDecoder::getDestPANIDString() const +{ + return m_hasDestPANID ? QString("0x%1").arg(m_destPANID, 4, 16, QChar('0')) : ""; +} + +QString IEEE_802_15_4_FrameDecoder::getDestAddressString() const +{ + return addressToString(m_destAddressMode, m_destAddress); +} + +QString IEEE_802_15_4_FrameDecoder::getSrcPANIDString() const +{ + return m_hasSrcPANID ? QString("0x%1").arg(m_srcPANID, 4, 16, QChar('0')) : ""; +} + +QString IEEE_802_15_4_FrameDecoder::getSrcAddressString() const +{ + return addressToString(m_srcAddressMode, m_srcAddress); +} + +QString IEEE_802_15_4_FrameDecoder::getCommandString() const +{ + return m_commandId >= 0 ? commandToString(m_commandId) : ""; +} + +QString IEEE_802_15_4_FrameDecoder::toString() const +{ + QStringList parts; + + if (!m_valid) { + return "Invalid frame"; + } + + parts.append(getFrameTypeString()); + + if (m_commandId >= 0) { + parts.append(getCommandString()); + } + if (m_securityEnabled) { + parts.append(QString("Secured (level %1)").arg(m_securityLevel)); + } + if (m_ackRequest) { + parts.append("AR"); + } + if (m_framePending) { + parts.append("FP"); + } + if (m_frameVersion > 0) { + parts.append(QString("v%1").arg(m_frameVersion)); + } + for (const auto& ie : m_ies) { + parts.append(QString("%1 IE 0x%2").arg(ie.m_header ? "Header" : "Payload").arg(ie.m_id, 2, 16, QChar('0'))); + } + + return parts.join(", "); +} diff --git a/sdrbase/util/ieee_802_15_4.h b/sdrbase/util/ieee_802_15_4.h new file mode 100644 index 000000000..93cc57277 --- /dev/null +++ b/sdrbase/util/ieee_802_15_4.h @@ -0,0 +1,165 @@ +/////////////////////////////////////////////////////////////////////////////////// +// 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_UTIL_IEEE_802_15_4_H +#define INCLUDE_UTIL_IEEE_802_15_4_H + +#include +#include + +#include +#include +#include +#include + +#include "export.h" + +// IEEE 802.15.4-2015 O-QPSK (clause 12) and BPSK (clause 13) PHYs +struct SDRBASE_API IEEE_802_15_4_PHY +{ + enum Modulation { + BPSK, + OQPSK + }; + + enum PulseShaping { + RC, + SINE + }; + + int m_bitRate; + Modulation m_modulation; + bool m_subGHzBand; + PulseShaping m_pulseShaping; + float m_beta; //!< Roll-off for RC pulse shaping + int m_symbolSpan; //!< Span of RC pulse in chips + + IEEE_802_15_4_PHY(); + + //! Set PHY from a string as returned by getPHYNames() + bool fromString(const QString& phy); + //! Full PHY name, as in getPHYNames(), or empty if not a standard PHY + QString toString() const; + //! Names of the supported PHYs, as used in the GUI + static QStringList getPHYNames(); + + int getChipsPerSymbol() const; + int getBitsPerSymbol() const; + int getNumberOfSymbols() const { return 1 << getBitsPerSymbol(); } + int getChipRate() const; + int getSymbolRate() const { return m_bitRate / getBitsPerSymbol(); } + //! Number of symbols in the preamble (4 octets of zeros) + int getPreambleSymbols() const { return 32 / getBitsPerSymbol(); } + //! Approximate occupied bandwidth (99%) + int getOccupiedBandwidth() const; + + //! Chip (0 or 1) for chip index chipIdx of the given symbol (data symbol for O-QPSK, differentially encoded bit for BPSK) + int getChip(int symbol, int chipIdx) const; + + //! Pulse shape used for a single chip, sampled at samplesPerChip. + //! Half-sine pulses span two chips and start at the chip time. RC pulses are centred on the chip time. + std::vector getPulse(int samplesPerChip) const; + //! Offset in samples from the chip time to the start of the pulse returned by getPulse() + int getPulseStartOffset(int samplesPerChip) const; + + static const uint8_t m_chipsBPSK[2][15]; + static const uint8_t m_chipsSubGHzOQPSK[16][16]; + static const uint8_t m_chips2450OQPSK[16][32]; +}; + +// Decode of a MAC frame (clause 7) +struct SDRBASE_API IEEE_802_15_4_FrameDecoder +{ + enum FrameType { + Beacon = 0, + Data = 1, + Ack = 2, + Command = 3, + Reserved = 4, + Multipurpose = 5, + Fragment = 6, + Extended = 7 + }; + + enum AddressMode { + AddressNone = 0, + AddressReserved = 1, + AddressShort = 2, + AddressExtended = 3 + }; + + struct IE { + bool m_header; //!< Header IE (true) or payload IE (false) + int m_id; //!< Element ID for header IEs, Group ID for payload IEs + int m_length; + }; + + bool m_valid; //!< Frame could be parsed + uint16_t m_frameControl; + FrameType m_frameType; + bool m_securityEnabled; + bool m_framePending; + bool m_ackRequest; + bool m_panIdCompression; + bool m_seqNoSuppression; + bool m_iePresent; + AddressMode m_destAddressMode; + int m_frameVersion; + AddressMode m_srcAddressMode; + + bool m_hasSeqNo; + uint8_t m_seqNo; + bool m_hasDestPANID; + uint16_t m_destPANID; + uint64_t m_destAddress; + bool m_hasSrcPANID; + uint16_t m_srcPANID; + uint64_t m_srcAddress; + + int m_securityLevel; + int m_keyIdMode; + int m_auxSecurityHeaderLength; + + QList m_ies; + int m_commandId; //!< -1 if not a command frame or encrypted + QByteArray m_payload; //!< MAC payload (excluding header, IEs and FCS) + bool m_hasFCS; + uint16_t m_fcs; + + IEEE_802_15_4_FrameDecoder(); + + //! Decode a PSDU (MPDU). If hasFCS is true, the last two bytes are the FCS + bool decode(const QByteArray& psdu, bool hasFCS = true); + + QString getFrameTypeString() const; + QString getDestPANIDString() const; + QString getDestAddressString() const; + QString getSrcPANIDString() const; + QString getSrcAddressString() const; + QString getCommandString() const; + //! Short human readable summary of the frame contents + QString toString() const; + + static QString frameTypeToString(FrameType type); + static QString commandToString(int commandId); + static QString addressToString(AddressMode mode, uint64_t address); + //! Calculate the 16-bit FCS (ITU-T CRC) of data + static uint16_t calcFCS(const uint8_t *data, int length); +}; + +#endif // INCLUDE_UTIL_IEEE_802_15_4_H diff --git a/sdrbase/webapi/webapirequestmapper.cpp b/sdrbase/webapi/webapirequestmapper.cpp index 55cb03394..758754315 100644 --- a/sdrbase/webapi/webapirequestmapper.cpp +++ b/sdrbase/webapi/webapirequestmapper.cpp @@ -5062,6 +5062,12 @@ bool WebAPIRequestMapper::getChannelSettings( channelSettings->getHeatMapSettings()->init(); channelSettings->getHeatMapSettings()->fromJsonObject(settingsJsonObject); } + else if (channelSettingsKey == "IEEE_802_15_4_DemodSettings") + { + channelSettings->setIeee802154DemodSettings(new SWGSDRangel::SWGIEEE_802_15_4_DemodSettings()); + channelSettings->getIeee802154DemodSettings()->init(); + channelSettings->getIeee802154DemodSettings()->fromJsonObject(settingsJsonObject); + } else if (channelSettingsKey == "IEEE_802_15_4_ModSettings") { channelSettings->setIeee802154ModSettings(new SWGSDRangel::SWGIEEE_802_15_4_ModSettings()); diff --git a/sdrbase/webapi/webapiutils.cpp b/sdrbase/webapi/webapiutils.cpp index c97922306..0681004b4 100644 --- a/sdrbase/webapi/webapiutils.cpp +++ b/sdrbase/webapi/webapiutils.cpp @@ -78,6 +78,7 @@ const QMap WebAPIUtils::m_channelURIToSettingsKey = { {"sdrangel.channeltx.modpacket", "PacketModSettings"}, {"sdrangel.channel.psk31mod", "PSK31ModSettings"}, {"sdrangel.channel.psk31demod", "PSK31DemodSettings"}, + {"sdrangel.channelrx.demod802.15.4", "IEEE_802_15_4_DemodSettings"}, {"sdrangel.channeltx.mod802.15.4", "IEEE_802_15_4_ModSettings"}, {"sdrangel.channel.radioclock", "RadioClockSettings"}, {"sdrangel.channel.radiosondedemod", "RadiosondeDemodSettings"}, @@ -198,6 +199,7 @@ const QMap WebAPIUtils::m_channelTypeToSettingsKey = { {"FreqScanner", "FreqScannerSettings"}, {"FreqTracker", "FreqTrackerSettings"}, {"HeatMap", "HeatMapSettings"}, + {"IEEE_802_15_4_Demod", "IEEE_802_15_4_DemodSettings"}, {"IEEE_802_15_4_Mod", "IEEE_802_15_4_ModSettings"}, {"M17Demod", "M17DemodSettings"}, {"M17Mod", "M17ModSettings"}, diff --git a/swagger/sdrangel/api/swagger/include/ChannelReport.yaml b/swagger/sdrangel/api/swagger/include/ChannelReport.yaml index 767ce72b7..9063bada9 100644 --- a/swagger/sdrangel/api/swagger/include/ChannelReport.yaml +++ b/swagger/sdrangel/api/swagger/include/ChannelReport.yaml @@ -78,6 +78,8 @@ ChannelReport: EndOfTrainDemodReport: $ref: "http://swgserver:8081/api/swagger/include/EndOfTrainDemod.yaml#/EndOfTrainDemodReport" description: "End of train demod report data for Channel." + IEEE_802_15_4_DemodReport: + $ref: "http://swgserver:8081/api/swagger/include/IEEE_802_15_4_Demod.yaml#/IEEE_802_15_4_DemodReport" IEEE_802_15_4_ModReport: $ref: "http://swgserver:8081/api/swagger/include/IEEE_802_15_4_Mod.yaml#/IEEE_802_15_4_ModReport" description: "Ieee 802 15 4 mod report data for Channel." diff --git a/swagger/sdrangel/api/swagger/include/ChannelSettings.yaml b/swagger/sdrangel/api/swagger/include/ChannelSettings.yaml index 0e680625e..866f2b598 100644 --- a/swagger/sdrangel/api/swagger/include/ChannelSettings.yaml +++ b/swagger/sdrangel/api/swagger/include/ChannelSettings.yaml @@ -129,6 +129,8 @@ ChannelSettings: InterferometerSettings: $ref: "http://swgserver:8081/api/swagger/include/Interferometer.yaml#/InterferometerSettings" description: "Interferometer settings configuration for Channel." + IEEE_802_15_4_DemodSettings: + $ref: "http://swgserver:8081/api/swagger/include/IEEE_802_15_4_Demod.yaml#/IEEE_802_15_4_DemodSettings" IEEE_802_15_4_ModSettings: $ref: "http://swgserver:8081/api/swagger/include/IEEE_802_15_4_Mod.yaml#/IEEE_802_15_4_ModSettings" description: "Ieee 802 15 4 mod settings configuration for Channel." diff --git a/swagger/sdrangel/api/swagger/include/IEEE_802_15_4_Demod.yaml b/swagger/sdrangel/api/swagger/include/IEEE_802_15_4_Demod.yaml new file mode 100644 index 000000000..514c40821 --- /dev/null +++ b/swagger/sdrangel/api/swagger/include/IEEE_802_15_4_Demod.yaml @@ -0,0 +1,120 @@ +IEEE_802_15_4_DemodSettings: + description: IEEE_802_15_4_Demod + properties: + inputFrequencyOffset: + type: integer + format: int64 + description: "Frequency offset of the channel from the device center frequency in Hz." + phy: + type: string + description: > + PHY. One of: "20kbps BPSK", "40kbps BPSK", "100kbps <1GHz O-QPSK", + "250kbps <1GHz O-QPSK (Sine)", "250kbps <1GHz O-QPSK (RC)", "250kbps >2GHz O-QPSK" + rfBandwidth: + type: number + format: float + description: "RF bandwidth of the channel filter in Hz." + samplesPerChip: + type: integer + minimum: 2 + maximum: 16 + description: "Samples per chip. The channel sample rate is this multiplied by the chip rate." + maxFrequencyOffset: + type: number + format: float + description: "Maximum carrier frequency offset to search for during acquisition in Hz." + threshold: + type: number + format: float + minimum: 0 + maximum: 1 + description: "Preamble detection threshold." + showBadFCS: + type: integer + description: "Show frames with invalid FCS (1 for yes, 0 for no)." + filterFrameType: + type: integer + minimum: 0 + maximum: 5 + description: "Frame type filter for the GUI table: 0 - All, 1 - Beacon, 2 - Data, 3 - Ack, 4 - Command, 5 - Other." + filterPANID: + type: string + description: "Regular expression to filter frames by PAN ID in the GUI table." + filterAddress: + type: string + description: "Regular expression to filter frames by source or destination address in the GUI table." + udpEnabled: + type: integer + description: "Whether to forward received frames to specified UDP port (1 for yes, 0 for no)." + udpAddress: + type: string + description: "UDP address to forward received frames to." + udpPort: + type: integer + minimum: 1024 + maximum: 65535 + description: "UDP port to forward received frames to." + udpFormat: + type: integer + minimum: 0 + maximum: 1 + description: "Format of frames forwarded via UDP: 0 - ZEP (ZigBee Encapsulation Protocol v2), 1 - Raw MAC frame." + logFilename: + type: string + description: "Log filename. Use .pcap extension for PCAP format, otherwise CSV format is used." + logEnabled: + type: integer + description: "Whether to log received frames to a file (1 for yes, 0 for no)." + useFileTime: + type: integer + description: "Use date and time from file input device rather than the system clock (1 for yes, 0 for no)." + rgbColor: + type: integer + description: "Channel-marker colour as an ARGB integer." + title: + type: string + description: "Channel title shown in the GUI." + 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 + reverseAPIAddress: + type: string + description: "Address of the reverse API peer." + reverseAPIPort: + type: integer + description: "Port of the reverse API peer." + 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." + scopeConfig: + $ref: "http://swgserver:8081/api/swagger/include/GLScope.yaml#/GLScope" + description: "Oscilloscope-display configuration." + channelMarker: + $ref: "http://swgserver:8081/api/swagger/include/ChannelMarker.yaml#/ChannelMarker" + description: "Channel-marker display settings." + rollupState: + $ref: "http://swgserver:8081/api/swagger/include/RollupState.yaml#/RollupState" + description: "Saved expanded or collapsed state of the GUI sections." + +IEEE_802_15_4_DemodReport: + description: IEEE_802_15_4_Demod + 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." + framesOK: + type: integer + description: "Number of frames received with a valid FCS." + framesBadFCS: + type: integer + description: "Number of frames received with an invalid FCS." diff --git a/swagger/sdrangel/code/qt5/client/SWGChannelReport.cpp b/swagger/sdrangel/code/qt5/client/SWGChannelReport.cpp index 28293b794..640ee8db9 100644 --- a/swagger/sdrangel/code/qt5/client/SWGChannelReport.cpp +++ b/swagger/sdrangel/code/qt5/client/SWGChannelReport.cpp @@ -80,6 +80,8 @@ SWGChannelReport::SWGChannelReport() { m_end_of_train_demod_report_isSet = false; ieee_802_15_4_mod_report = nullptr; m_ieee_802_15_4_mod_report_isSet = false; + ieee_802_15_4_demod_report = nullptr; + m_ieee_802_15_4_demod_report_isSet = false; file_sink_report = nullptr; m_file_sink_report_isSet = false; file_source_report = nullptr; @@ -220,6 +222,8 @@ SWGChannelReport::init() { m_end_of_train_demod_report_isSet = false; ieee_802_15_4_mod_report = new SWGIEEE_802_15_4_ModReport(); m_ieee_802_15_4_mod_report_isSet = false; + ieee_802_15_4_demod_report = new SWGIEEE_802_15_4_DemodReport(); + m_ieee_802_15_4_demod_report_isSet = false; file_sink_report = new SWGFileSinkReport(); m_file_sink_report_isSet = false; file_source_report = new SWGFileSourceReport(); @@ -380,6 +384,9 @@ SWGChannelReport::cleanup() { if(ieee_802_15_4_mod_report != nullptr) { delete ieee_802_15_4_mod_report; } + if(ieee_802_15_4_demod_report != nullptr) { + delete ieee_802_15_4_demod_report; + } if(file_sink_report != nullptr) { delete file_sink_report; } @@ -562,6 +569,8 @@ SWGChannelReport::fromJsonObject(QJsonObject &pJson) { ::SWGSDRangel::setValue(&ieee_802_15_4_mod_report, pJson["IEEE_802_15_4_ModReport"], "SWGIEEE_802_15_4_ModReport", "SWGIEEE_802_15_4_ModReport"); + ::SWGSDRangel::setValue(&ieee_802_15_4_demod_report, pJson["IEEE_802_15_4_DemodReport"], "SWGIEEE_802_15_4_DemodReport", "SWGIEEE_802_15_4_DemodReport"); + ::SWGSDRangel::setValue(&file_sink_report, pJson["FileSinkReport"], "SWGFileSinkReport", "SWGFileSinkReport"); ::SWGSDRangel::setValue(&file_source_report, pJson["FileSourceReport"], "SWGFileSourceReport", "SWGFileSourceReport"); @@ -735,6 +744,9 @@ SWGChannelReport::asJsonObject() { if((ieee_802_15_4_mod_report != nullptr) && (ieee_802_15_4_mod_report->isSet())){ toJsonValue(QString("IEEE_802_15_4_ModReport"), ieee_802_15_4_mod_report, obj, QString("SWGIEEE_802_15_4_ModReport")); } + if((ieee_802_15_4_demod_report != nullptr) && (ieee_802_15_4_demod_report->isSet())){ + toJsonValue(QString("IEEE_802_15_4_DemodReport"), ieee_802_15_4_demod_report, obj, QString("SWGIEEE_802_15_4_DemodReport")); + } if((file_sink_report != nullptr) && (file_sink_report->isSet())){ toJsonValue(QString("FileSinkReport"), file_sink_report, obj, QString("SWGFileSinkReport")); } @@ -1122,6 +1134,16 @@ SWGChannelReport::setIeee802154ModReport(SWGIEEE_802_15_4_ModReport* ieee_802_15 this->m_ieee_802_15_4_mod_report_isSet = true; } +SWGIEEE_802_15_4_DemodReport* +SWGChannelReport::getIeee802154DemodReport() { + return ieee_802_15_4_demod_report; +} +void +SWGChannelReport::setIeee802154DemodReport(SWGIEEE_802_15_4_DemodReport* ieee_802_15_4_demod_report) { + this->ieee_802_15_4_demod_report = ieee_802_15_4_demod_report; + this->m_ieee_802_15_4_demod_report_isSet = true; +} + SWGFileSinkReport* SWGChannelReport::getFileSinkReport() { return file_sink_report; @@ -1605,6 +1627,9 @@ SWGChannelReport::isSet(){ if(ieee_802_15_4_mod_report && ieee_802_15_4_mod_report->isSet()){ isObjectUpdated = true; break; } + if(ieee_802_15_4_demod_report && ieee_802_15_4_demod_report->isSet()){ + isObjectUpdated = true; break; + } if(file_sink_report && file_sink_report->isSet()){ isObjectUpdated = true; break; } diff --git a/swagger/sdrangel/code/qt5/client/SWGChannelReport.h b/swagger/sdrangel/code/qt5/client/SWGChannelReport.h index 5eef83a9d..27ec8f7fd 100644 --- a/swagger/sdrangel/code/qt5/client/SWGChannelReport.h +++ b/swagger/sdrangel/code/qt5/client/SWGChannelReport.h @@ -54,6 +54,7 @@ #include "SWGFreqTrackerReport.h" #include "SWGHeatMapReport.h" #include "SWGIEEE_802_15_4_ModReport.h" +#include "SWGIEEE_802_15_4_DemodReport.h" #include "SWGILSDemodReport.h" #include "SWGInmarsatDemodReport.h" #include "SWGM17DemodReport.h" @@ -183,6 +184,9 @@ public: SWGIEEE_802_15_4_ModReport* getIeee802154ModReport(); void setIeee802154ModReport(SWGIEEE_802_15_4_ModReport* ieee_802_15_4_mod_report); + SWGIEEE_802_15_4_DemodReport* getIeee802154DemodReport(); + void setIeee802154DemodReport(SWGIEEE_802_15_4_DemodReport* ieee_802_15_4_demod_report); + SWGFileSinkReport* getFileSinkReport(); void setFileSinkReport(SWGFileSinkReport* file_sink_report); @@ -384,6 +388,9 @@ private: SWGIEEE_802_15_4_ModReport* ieee_802_15_4_mod_report; bool m_ieee_802_15_4_mod_report_isSet; + SWGIEEE_802_15_4_DemodReport* ieee_802_15_4_demod_report; + bool m_ieee_802_15_4_demod_report_isSet; + SWGFileSinkReport* file_sink_report; bool m_file_sink_report_isSet; diff --git a/swagger/sdrangel/code/qt5/client/SWGChannelSettings.cpp b/swagger/sdrangel/code/qt5/client/SWGChannelSettings.cpp index a0ca06854..f9191efb6 100644 --- a/swagger/sdrangel/code/qt5/client/SWGChannelSettings.cpp +++ b/swagger/sdrangel/code/qt5/client/SWGChannelSettings.cpp @@ -114,6 +114,8 @@ SWGChannelSettings::SWGChannelSettings() { m_interferometer_settings_isSet = false; ieee_802_15_4_mod_settings = nullptr; m_ieee_802_15_4_mod_settings_isSet = false; + ieee_802_15_4_demod_settings = nullptr; + m_ieee_802_15_4_demod_settings_isSet = false; m17_demod_settings = nullptr; m_m17_demod_settings_isSet = false; m17_mod_settings = nullptr; @@ -276,6 +278,8 @@ SWGChannelSettings::init() { m_interferometer_settings_isSet = false; ieee_802_15_4_mod_settings = new SWGIEEE_802_15_4_ModSettings(); m_ieee_802_15_4_mod_settings_isSet = false; + ieee_802_15_4_demod_settings = new SWGIEEE_802_15_4_DemodSettings(); + m_ieee_802_15_4_demod_settings_isSet = false; m17_demod_settings = new SWGM17DemodSettings(); m_m17_demod_settings_isSet = false; m17_mod_settings = new SWGM17ModSettings(); @@ -471,6 +475,9 @@ SWGChannelSettings::cleanup() { if(ieee_802_15_4_mod_settings != nullptr) { delete ieee_802_15_4_mod_settings; } + if(ieee_802_15_4_demod_settings != nullptr) { + delete ieee_802_15_4_demod_settings; + } if(m17_demod_settings != nullptr) { delete m17_demod_settings; } @@ -669,6 +676,8 @@ SWGChannelSettings::fromJsonObject(QJsonObject &pJson) { ::SWGSDRangel::setValue(&ieee_802_15_4_mod_settings, pJson["IEEE_802_15_4_ModSettings"], "SWGIEEE_802_15_4_ModSettings", "SWGIEEE_802_15_4_ModSettings"); + ::SWGSDRangel::setValue(&ieee_802_15_4_demod_settings, pJson["IEEE_802_15_4_DemodSettings"], "SWGIEEE_802_15_4_DemodSettings", "SWGIEEE_802_15_4_DemodSettings"); + ::SWGSDRangel::setValue(&m17_demod_settings, pJson["M17DemodSettings"], "SWGM17DemodSettings", "SWGM17DemodSettings"); ::SWGSDRangel::setValue(&m17_mod_settings, pJson["M17ModSettings"], "SWGM17ModSettings", "SWGM17ModSettings"); @@ -881,6 +890,9 @@ SWGChannelSettings::asJsonObject() { if((ieee_802_15_4_mod_settings != nullptr) && (ieee_802_15_4_mod_settings->isSet())){ toJsonValue(QString("IEEE_802_15_4_ModSettings"), ieee_802_15_4_mod_settings, obj, QString("SWGIEEE_802_15_4_ModSettings")); } + if((ieee_802_15_4_demod_settings != nullptr) && (ieee_802_15_4_demod_settings->isSet())){ + toJsonValue(QString("IEEE_802_15_4_DemodSettings"), ieee_802_15_4_demod_settings, obj, QString("SWGIEEE_802_15_4_DemodSettings")); + } if((m17_demod_settings != nullptr) && (m17_demod_settings->isSet())){ toJsonValue(QString("M17DemodSettings"), m17_demod_settings, obj, QString("SWGM17DemodSettings")); } @@ -1420,6 +1432,16 @@ SWGChannelSettings::setIeee802154ModSettings(SWGIEEE_802_15_4_ModSettings* ieee_ this->m_ieee_802_15_4_mod_settings_isSet = true; } +SWGIEEE_802_15_4_DemodSettings* +SWGChannelSettings::getIeee802154DemodSettings() { + return ieee_802_15_4_demod_settings; +} +void +SWGChannelSettings::setIeee802154DemodSettings(SWGIEEE_802_15_4_DemodSettings* ieee_802_15_4_demod_settings) { + this->ieee_802_15_4_demod_settings = ieee_802_15_4_demod_settings; + this->m_ieee_802_15_4_demod_settings_isSet = true; +} + SWGM17DemodSettings* SWGChannelSettings::getM17DemodSettings() { return m17_demod_settings; @@ -1894,6 +1916,9 @@ SWGChannelSettings::isSet(){ if(ieee_802_15_4_mod_settings && ieee_802_15_4_mod_settings->isSet()){ isObjectUpdated = true; break; } + if(ieee_802_15_4_demod_settings && ieee_802_15_4_demod_settings->isSet()){ + isObjectUpdated = true; break; + } if(m17_demod_settings && m17_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 46c6d57c2..7da2e65fa 100644 --- a/swagger/sdrangel/code/qt5/client/SWGChannelSettings.h +++ b/swagger/sdrangel/code/qt5/client/SWGChannelSettings.h @@ -58,6 +58,7 @@ #include "SWGFreqTrackerSettings.h" #include "SWGHeatMapSettings.h" #include "SWGIEEE_802_15_4_ModSettings.h" +#include "SWGIEEE_802_15_4_DemodSettings.h" #include "SWGILSDemodSettings.h" #include "SWGInmarsatDemodSettings.h" #include "SWGInterferometerSettings.h" @@ -243,6 +244,9 @@ public: SWGIEEE_802_15_4_ModSettings* getIeee802154ModSettings(); void setIeee802154ModSettings(SWGIEEE_802_15_4_ModSettings* ieee_802_15_4_mod_settings); + SWGIEEE_802_15_4_DemodSettings* getIeee802154DemodSettings(); + void setIeee802154DemodSettings(SWGIEEE_802_15_4_DemodSettings* ieee_802_15_4_demod_settings); + SWGM17DemodSettings* getM17DemodSettings(); void setM17DemodSettings(SWGM17DemodSettings* m17_demod_settings); @@ -477,6 +481,9 @@ private: SWGIEEE_802_15_4_ModSettings* ieee_802_15_4_mod_settings; bool m_ieee_802_15_4_mod_settings_isSet; + SWGIEEE_802_15_4_DemodSettings* ieee_802_15_4_demod_settings; + bool m_ieee_802_15_4_demod_settings_isSet; + SWGM17DemodSettings* m17_demod_settings; bool m_m17_demod_settings_isSet; diff --git a/swagger/sdrangel/code/qt5/client/SWGIEEE_802_15_4_DemodReport.cpp b/swagger/sdrangel/code/qt5/client/SWGIEEE_802_15_4_DemodReport.cpp new file mode 100644 index 000000000..63b0d6005 --- /dev/null +++ b/swagger/sdrangel/code/qt5/client/SWGIEEE_802_15_4_DemodReport.cpp @@ -0,0 +1,178 @@ +/** + * 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 "SWGIEEE_802_15_4_DemodReport.h" + +#include "SWGHelpers.h" + +#include +#include +#include +#include + +namespace SWGSDRangel { + +SWGIEEE_802_15_4_DemodReport::SWGIEEE_802_15_4_DemodReport(QString* json) { + init(); + this->fromJson(*json); +} + +SWGIEEE_802_15_4_DemodReport::SWGIEEE_802_15_4_DemodReport() { + channel_power_db = 0.0f; + m_channel_power_db_isSet = false; + channel_sample_rate = 0; + m_channel_sample_rate_isSet = false; + frames_ok = 0; + m_frames_ok_isSet = false; + frames_bad_fcs = 0; + m_frames_bad_fcs_isSet = false; +} + +SWGIEEE_802_15_4_DemodReport::~SWGIEEE_802_15_4_DemodReport() { + this->cleanup(); +} + +void +SWGIEEE_802_15_4_DemodReport::init() { + channel_power_db = 0.0f; + m_channel_power_db_isSet = false; + channel_sample_rate = 0; + m_channel_sample_rate_isSet = false; + frames_ok = 0; + m_frames_ok_isSet = false; + frames_bad_fcs = 0; + m_frames_bad_fcs_isSet = false; +} + +void +SWGIEEE_802_15_4_DemodReport::cleanup() { + + + + +} + +SWGIEEE_802_15_4_DemodReport* +SWGIEEE_802_15_4_DemodReport::fromJson(QString &json) { + QByteArray array (json.toStdString().c_str()); + QJsonDocument doc = QJsonDocument::fromJson(array); + QJsonObject jsonObject = doc.object(); + this->fromJsonObject(jsonObject); + return this; +} + +void +SWGIEEE_802_15_4_DemodReport::fromJsonObject(QJsonObject &pJson) { + ::SWGSDRangel::setValue(&channel_power_db, pJson["channelPowerDB"], "float", ""); + + ::SWGSDRangel::setValue(&channel_sample_rate, pJson["channelSampleRate"], "qint32", ""); + + ::SWGSDRangel::setValue(&frames_ok, pJson["framesOK"], "qint32", ""); + + ::SWGSDRangel::setValue(&frames_bad_fcs, pJson["framesBadFCS"], "qint32", ""); + +} + +QString +SWGIEEE_802_15_4_DemodReport::asJson () +{ + QJsonObject* obj = this->asJsonObject(); + + QJsonDocument doc(*obj); + QByteArray bytes = doc.toJson(); + delete obj; + return QString(bytes); +} + +QJsonObject* +SWGIEEE_802_15_4_DemodReport::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_frames_ok_isSet){ + obj->insert("framesOK", QJsonValue(frames_ok)); + } + if(m_frames_bad_fcs_isSet){ + obj->insert("framesBadFCS", QJsonValue(frames_bad_fcs)); + } + + return obj; +} + +float +SWGIEEE_802_15_4_DemodReport::getChannelPowerDb() { + return channel_power_db; +} +void +SWGIEEE_802_15_4_DemodReport::setChannelPowerDb(float channel_power_db) { + this->channel_power_db = channel_power_db; + this->m_channel_power_db_isSet = true; +} + +qint32 +SWGIEEE_802_15_4_DemodReport::getChannelSampleRate() { + return channel_sample_rate; +} +void +SWGIEEE_802_15_4_DemodReport::setChannelSampleRate(qint32 channel_sample_rate) { + this->channel_sample_rate = channel_sample_rate; + this->m_channel_sample_rate_isSet = true; +} + +qint32 +SWGIEEE_802_15_4_DemodReport::getFramesOk() { + return frames_ok; +} +void +SWGIEEE_802_15_4_DemodReport::setFramesOk(qint32 frames_ok) { + this->frames_ok = frames_ok; + this->m_frames_ok_isSet = true; +} + +qint32 +SWGIEEE_802_15_4_DemodReport::getFramesBadFcs() { + return frames_bad_fcs; +} +void +SWGIEEE_802_15_4_DemodReport::setFramesBadFcs(qint32 frames_bad_fcs) { + this->frames_bad_fcs = frames_bad_fcs; + this->m_frames_bad_fcs_isSet = true; +} + + +bool +SWGIEEE_802_15_4_DemodReport::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_frames_ok_isSet){ + isObjectUpdated = true; break; + } + if(m_frames_bad_fcs_isSet){ + isObjectUpdated = true; break; + } + }while(false); + return isObjectUpdated; +} +} + diff --git a/swagger/sdrangel/code/qt5/client/SWGIEEE_802_15_4_DemodReport.h b/swagger/sdrangel/code/qt5/client/SWGIEEE_802_15_4_DemodReport.h new file mode 100644 index 000000000..0ef2b702f --- /dev/null +++ b/swagger/sdrangel/code/qt5/client/SWGIEEE_802_15_4_DemodReport.h @@ -0,0 +1,77 @@ +/** + * 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. + */ + + +/* + * SWGIEEE_802_15_4_DemodReport.h + * + * IEEE_802_15_4_Demod + */ + +#ifndef SWGIEEE_802_15_4_DemodReport_H_ +#define SWGIEEE_802_15_4_DemodReport_H_ + +#include + + + +#include "SWGObject.h" +#include "export.h" + +namespace SWGSDRangel { + +class SWG_API SWGIEEE_802_15_4_DemodReport: public SWGObject { +public: + SWGIEEE_802_15_4_DemodReport(); + SWGIEEE_802_15_4_DemodReport(QString* json); + virtual ~SWGIEEE_802_15_4_DemodReport(); + void init(); + void cleanup(); + + virtual QString asJson () override; + virtual QJsonObject* asJsonObject() override; + virtual void fromJsonObject(QJsonObject &json) override; + virtual SWGIEEE_802_15_4_DemodReport* fromJson(QString &jsonString) override; + + float getChannelPowerDb(); + void setChannelPowerDb(float channel_power_db); + + qint32 getChannelSampleRate(); + void setChannelSampleRate(qint32 channel_sample_rate); + + qint32 getFramesOk(); + void setFramesOk(qint32 frames_ok); + + qint32 getFramesBadFcs(); + void setFramesBadFcs(qint32 frames_bad_fcs); + + + 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 frames_ok; + bool m_frames_ok_isSet; + + qint32 frames_bad_fcs; + bool m_frames_bad_fcs_isSet; + +}; + +} + +#endif /* SWGIEEE_802_15_4_DemodReport_H_ */ diff --git a/swagger/sdrangel/code/qt5/client/SWGIEEE_802_15_4_DemodSettings.cpp b/swagger/sdrangel/code/qt5/client/SWGIEEE_802_15_4_DemodSettings.cpp new file mode 100644 index 000000000..8d967a977 --- /dev/null +++ b/swagger/sdrangel/code/qt5/client/SWGIEEE_802_15_4_DemodSettings.cpp @@ -0,0 +1,750 @@ +/** + * 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 "SWGIEEE_802_15_4_DemodSettings.h" + +#include "SWGHelpers.h" + +#include +#include +#include +#include + +namespace SWGSDRangel { + +SWGIEEE_802_15_4_DemodSettings::SWGIEEE_802_15_4_DemodSettings(QString* json) { + init(); + this->fromJson(*json); +} + +SWGIEEE_802_15_4_DemodSettings::SWGIEEE_802_15_4_DemodSettings() { + input_frequency_offset = 0L; + m_input_frequency_offset_isSet = false; + phy = nullptr; + m_phy_isSet = false; + rf_bandwidth = 0.0f; + m_rf_bandwidth_isSet = false; + samples_per_chip = 0; + m_samples_per_chip_isSet = false; + max_frequency_offset = 0.0f; + m_max_frequency_offset_isSet = false; + threshold = 0.0f; + m_threshold_isSet = false; + show_bad_fcs = 0; + m_show_bad_fcs_isSet = false; + filter_frame_type = 0; + m_filter_frame_type_isSet = false; + filter_panid = nullptr; + m_filter_panid_isSet = false; + filter_address = nullptr; + m_filter_address_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; + udp_format = 0; + m_udp_format_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; + scope_config = nullptr; + m_scope_config_isSet = false; + channel_marker = nullptr; + m_channel_marker_isSet = false; + rollup_state = nullptr; + m_rollup_state_isSet = false; +} + +SWGIEEE_802_15_4_DemodSettings::~SWGIEEE_802_15_4_DemodSettings() { + this->cleanup(); +} + +void +SWGIEEE_802_15_4_DemodSettings::init() { + input_frequency_offset = 0L; + m_input_frequency_offset_isSet = false; + phy = new QString(""); + m_phy_isSet = false; + rf_bandwidth = 0.0f; + m_rf_bandwidth_isSet = false; + samples_per_chip = 0; + m_samples_per_chip_isSet = false; + max_frequency_offset = 0.0f; + m_max_frequency_offset_isSet = false; + threshold = 0.0f; + m_threshold_isSet = false; + show_bad_fcs = 0; + m_show_bad_fcs_isSet = false; + filter_frame_type = 0; + m_filter_frame_type_isSet = false; + filter_panid = new QString(""); + m_filter_panid_isSet = false; + filter_address = new QString(""); + m_filter_address_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; + udp_format = 0; + m_udp_format_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; + scope_config = new SWGGLScope(); + m_scope_config_isSet = false; + channel_marker = new SWGChannelMarker(); + m_channel_marker_isSet = false; + rollup_state = new SWGRollupState(); + m_rollup_state_isSet = false; +} + +void +SWGIEEE_802_15_4_DemodSettings::cleanup() { + + if(phy != nullptr) { + delete phy; + } + + + + + + + if(filter_panid != nullptr) { + delete filter_panid; + } + if(filter_address != nullptr) { + delete filter_address; + } + + 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(scope_config != nullptr) { + delete scope_config; + } + if(channel_marker != nullptr) { + delete channel_marker; + } + if(rollup_state != nullptr) { + delete rollup_state; + } +} + +SWGIEEE_802_15_4_DemodSettings* +SWGIEEE_802_15_4_DemodSettings::fromJson(QString &json) { + QByteArray array (json.toStdString().c_str()); + QJsonDocument doc = QJsonDocument::fromJson(array); + QJsonObject jsonObject = doc.object(); + this->fromJsonObject(jsonObject); + return this; +} + +void +SWGIEEE_802_15_4_DemodSettings::fromJsonObject(QJsonObject &pJson) { + ::SWGSDRangel::setValue(&input_frequency_offset, pJson["inputFrequencyOffset"], "qint64", ""); + + ::SWGSDRangel::setValue(&phy, pJson["phy"], "QString", "QString"); + + ::SWGSDRangel::setValue(&rf_bandwidth, pJson["rfBandwidth"], "float", ""); + + ::SWGSDRangel::setValue(&samples_per_chip, pJson["samplesPerChip"], "qint32", ""); + + ::SWGSDRangel::setValue(&max_frequency_offset, pJson["maxFrequencyOffset"], "float", ""); + + ::SWGSDRangel::setValue(&threshold, pJson["threshold"], "float", ""); + + ::SWGSDRangel::setValue(&show_bad_fcs, pJson["showBadFCS"], "qint32", ""); + + ::SWGSDRangel::setValue(&filter_frame_type, pJson["filterFrameType"], "qint32", ""); + + ::SWGSDRangel::setValue(&filter_panid, pJson["filterPANID"], "QString", "QString"); + + ::SWGSDRangel::setValue(&filter_address, pJson["filterAddress"], "QString", "QString"); + + ::SWGSDRangel::setValue(&udp_enabled, pJson["udpEnabled"], "qint32", ""); + + ::SWGSDRangel::setValue(&udp_address, pJson["udpAddress"], "QString", "QString"); + + ::SWGSDRangel::setValue(&udp_port, pJson["udpPort"], "qint32", ""); + + ::SWGSDRangel::setValue(&udp_format, pJson["udpFormat"], "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(&scope_config, pJson["scopeConfig"], "SWGGLScope", "SWGGLScope"); + + ::SWGSDRangel::setValue(&channel_marker, pJson["channelMarker"], "SWGChannelMarker", "SWGChannelMarker"); + + ::SWGSDRangel::setValue(&rollup_state, pJson["rollupState"], "SWGRollupState", "SWGRollupState"); + +} + +QString +SWGIEEE_802_15_4_DemodSettings::asJson () +{ + QJsonObject* obj = this->asJsonObject(); + + QJsonDocument doc(*obj); + QByteArray bytes = doc.toJson(); + delete obj; + return QString(bytes); +} + +QJsonObject* +SWGIEEE_802_15_4_DemodSettings::asJsonObject() { + QJsonObject* obj = new QJsonObject(); + if(m_input_frequency_offset_isSet){ + obj->insert("inputFrequencyOffset", QJsonValue(input_frequency_offset)); + } + if(phy != nullptr && *phy != QString("")){ + toJsonValue(QString("phy"), phy, obj, QString("QString")); + } + if(m_rf_bandwidth_isSet){ + obj->insert("rfBandwidth", QJsonValue(rf_bandwidth)); + } + if(m_samples_per_chip_isSet){ + obj->insert("samplesPerChip", QJsonValue(samples_per_chip)); + } + if(m_max_frequency_offset_isSet){ + obj->insert("maxFrequencyOffset", QJsonValue(max_frequency_offset)); + } + if(m_threshold_isSet){ + obj->insert("threshold", QJsonValue(threshold)); + } + if(m_show_bad_fcs_isSet){ + obj->insert("showBadFCS", QJsonValue(show_bad_fcs)); + } + if(m_filter_frame_type_isSet){ + obj->insert("filterFrameType", QJsonValue(filter_frame_type)); + } + if(filter_panid != nullptr && *filter_panid != QString("")){ + toJsonValue(QString("filterPANID"), filter_panid, obj, QString("QString")); + } + if(filter_address != nullptr && *filter_address != QString("")){ + toJsonValue(QString("filterAddress"), filter_address, obj, QString("QString")); + } + 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(m_udp_format_isSet){ + obj->insert("udpFormat", QJsonValue(udp_format)); + } + 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((scope_config != nullptr) && (scope_config->isSet())){ + toJsonValue(QString("scopeConfig"), scope_config, obj, QString("SWGGLScope")); + } + 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 +SWGIEEE_802_15_4_DemodSettings::getInputFrequencyOffset() { + return input_frequency_offset; +} +void +SWGIEEE_802_15_4_DemodSettings::setInputFrequencyOffset(qint64 input_frequency_offset) { + this->input_frequency_offset = input_frequency_offset; + this->m_input_frequency_offset_isSet = true; +} + +QString* +SWGIEEE_802_15_4_DemodSettings::getPhy() { + return phy; +} +void +SWGIEEE_802_15_4_DemodSettings::setPhy(QString* phy) { + this->phy = phy; + this->m_phy_isSet = true; +} + +float +SWGIEEE_802_15_4_DemodSettings::getRfBandwidth() { + return rf_bandwidth; +} +void +SWGIEEE_802_15_4_DemodSettings::setRfBandwidth(float rf_bandwidth) { + this->rf_bandwidth = rf_bandwidth; + this->m_rf_bandwidth_isSet = true; +} + +qint32 +SWGIEEE_802_15_4_DemodSettings::getSamplesPerChip() { + return samples_per_chip; +} +void +SWGIEEE_802_15_4_DemodSettings::setSamplesPerChip(qint32 samples_per_chip) { + this->samples_per_chip = samples_per_chip; + this->m_samples_per_chip_isSet = true; +} + +float +SWGIEEE_802_15_4_DemodSettings::getMaxFrequencyOffset() { + return max_frequency_offset; +} +void +SWGIEEE_802_15_4_DemodSettings::setMaxFrequencyOffset(float max_frequency_offset) { + this->max_frequency_offset = max_frequency_offset; + this->m_max_frequency_offset_isSet = true; +} + +float +SWGIEEE_802_15_4_DemodSettings::getThreshold() { + return threshold; +} +void +SWGIEEE_802_15_4_DemodSettings::setThreshold(float threshold) { + this->threshold = threshold; + this->m_threshold_isSet = true; +} + +qint32 +SWGIEEE_802_15_4_DemodSettings::getShowBadFcs() { + return show_bad_fcs; +} +void +SWGIEEE_802_15_4_DemodSettings::setShowBadFcs(qint32 show_bad_fcs) { + this->show_bad_fcs = show_bad_fcs; + this->m_show_bad_fcs_isSet = true; +} + +qint32 +SWGIEEE_802_15_4_DemodSettings::getFilterFrameType() { + return filter_frame_type; +} +void +SWGIEEE_802_15_4_DemodSettings::setFilterFrameType(qint32 filter_frame_type) { + this->filter_frame_type = filter_frame_type; + this->m_filter_frame_type_isSet = true; +} + +QString* +SWGIEEE_802_15_4_DemodSettings::getFilterPanid() { + return filter_panid; +} +void +SWGIEEE_802_15_4_DemodSettings::setFilterPanid(QString* filter_panid) { + this->filter_panid = filter_panid; + this->m_filter_panid_isSet = true; +} + +QString* +SWGIEEE_802_15_4_DemodSettings::getFilterAddress() { + return filter_address; +} +void +SWGIEEE_802_15_4_DemodSettings::setFilterAddress(QString* filter_address) { + this->filter_address = filter_address; + this->m_filter_address_isSet = true; +} + +qint32 +SWGIEEE_802_15_4_DemodSettings::getUdpEnabled() { + return udp_enabled; +} +void +SWGIEEE_802_15_4_DemodSettings::setUdpEnabled(qint32 udp_enabled) { + this->udp_enabled = udp_enabled; + this->m_udp_enabled_isSet = true; +} + +QString* +SWGIEEE_802_15_4_DemodSettings::getUdpAddress() { + return udp_address; +} +void +SWGIEEE_802_15_4_DemodSettings::setUdpAddress(QString* udp_address) { + this->udp_address = udp_address; + this->m_udp_address_isSet = true; +} + +qint32 +SWGIEEE_802_15_4_DemodSettings::getUdpPort() { + return udp_port; +} +void +SWGIEEE_802_15_4_DemodSettings::setUdpPort(qint32 udp_port) { + this->udp_port = udp_port; + this->m_udp_port_isSet = true; +} + +qint32 +SWGIEEE_802_15_4_DemodSettings::getUdpFormat() { + return udp_format; +} +void +SWGIEEE_802_15_4_DemodSettings::setUdpFormat(qint32 udp_format) { + this->udp_format = udp_format; + this->m_udp_format_isSet = true; +} + +QString* +SWGIEEE_802_15_4_DemodSettings::getLogFilename() { + return log_filename; +} +void +SWGIEEE_802_15_4_DemodSettings::setLogFilename(QString* log_filename) { + this->log_filename = log_filename; + this->m_log_filename_isSet = true; +} + +qint32 +SWGIEEE_802_15_4_DemodSettings::getLogEnabled() { + return log_enabled; +} +void +SWGIEEE_802_15_4_DemodSettings::setLogEnabled(qint32 log_enabled) { + this->log_enabled = log_enabled; + this->m_log_enabled_isSet = true; +} + +qint32 +SWGIEEE_802_15_4_DemodSettings::getUseFileTime() { + return use_file_time; +} +void +SWGIEEE_802_15_4_DemodSettings::setUseFileTime(qint32 use_file_time) { + this->use_file_time = use_file_time; + this->m_use_file_time_isSet = true; +} + +qint32 +SWGIEEE_802_15_4_DemodSettings::getRgbColor() { + return rgb_color; +} +void +SWGIEEE_802_15_4_DemodSettings::setRgbColor(qint32 rgb_color) { + this->rgb_color = rgb_color; + this->m_rgb_color_isSet = true; +} + +QString* +SWGIEEE_802_15_4_DemodSettings::getTitle() { + return title; +} +void +SWGIEEE_802_15_4_DemodSettings::setTitle(QString* title) { + this->title = title; + this->m_title_isSet = true; +} + +qint32 +SWGIEEE_802_15_4_DemodSettings::getStreamIndex() { + return stream_index; +} +void +SWGIEEE_802_15_4_DemodSettings::setStreamIndex(qint32 stream_index) { + this->stream_index = stream_index; + this->m_stream_index_isSet = true; +} + +qint32 +SWGIEEE_802_15_4_DemodSettings::getUseReverseApi() { + return use_reverse_api; +} +void +SWGIEEE_802_15_4_DemodSettings::setUseReverseApi(qint32 use_reverse_api) { + this->use_reverse_api = use_reverse_api; + this->m_use_reverse_api_isSet = true; +} + +QString* +SWGIEEE_802_15_4_DemodSettings::getReverseApiAddress() { + return reverse_api_address; +} +void +SWGIEEE_802_15_4_DemodSettings::setReverseApiAddress(QString* reverse_api_address) { + this->reverse_api_address = reverse_api_address; + this->m_reverse_api_address_isSet = true; +} + +qint32 +SWGIEEE_802_15_4_DemodSettings::getReverseApiPort() { + return reverse_api_port; +} +void +SWGIEEE_802_15_4_DemodSettings::setReverseApiPort(qint32 reverse_api_port) { + this->reverse_api_port = reverse_api_port; + this->m_reverse_api_port_isSet = true; +} + +qint32 +SWGIEEE_802_15_4_DemodSettings::getReverseApiDeviceIndex() { + return reverse_api_device_index; +} +void +SWGIEEE_802_15_4_DemodSettings::setReverseApiDeviceIndex(qint32 reverse_api_device_index) { + this->reverse_api_device_index = reverse_api_device_index; + this->m_reverse_api_device_index_isSet = true; +} + +qint32 +SWGIEEE_802_15_4_DemodSettings::getReverseApiChannelIndex() { + return reverse_api_channel_index; +} +void +SWGIEEE_802_15_4_DemodSettings::setReverseApiChannelIndex(qint32 reverse_api_channel_index) { + this->reverse_api_channel_index = reverse_api_channel_index; + this->m_reverse_api_channel_index_isSet = true; +} + +SWGGLScope* +SWGIEEE_802_15_4_DemodSettings::getScopeConfig() { + return scope_config; +} +void +SWGIEEE_802_15_4_DemodSettings::setScopeConfig(SWGGLScope* scope_config) { + this->scope_config = scope_config; + this->m_scope_config_isSet = true; +} + +SWGChannelMarker* +SWGIEEE_802_15_4_DemodSettings::getChannelMarker() { + return channel_marker; +} +void +SWGIEEE_802_15_4_DemodSettings::setChannelMarker(SWGChannelMarker* channel_marker) { + this->channel_marker = channel_marker; + this->m_channel_marker_isSet = true; +} + +SWGRollupState* +SWGIEEE_802_15_4_DemodSettings::getRollupState() { + return rollup_state; +} +void +SWGIEEE_802_15_4_DemodSettings::setRollupState(SWGRollupState* rollup_state) { + this->rollup_state = rollup_state; + this->m_rollup_state_isSet = true; +} + + +bool +SWGIEEE_802_15_4_DemodSettings::isSet(){ + bool isObjectUpdated = false; + do{ + if(m_input_frequency_offset_isSet){ + isObjectUpdated = true; break; + } + if(phy && *phy != QString("")){ + isObjectUpdated = true; break; + } + if(m_rf_bandwidth_isSet){ + isObjectUpdated = true; break; + } + if(m_samples_per_chip_isSet){ + isObjectUpdated = true; break; + } + if(m_max_frequency_offset_isSet){ + isObjectUpdated = true; break; + } + if(m_threshold_isSet){ + isObjectUpdated = true; break; + } + if(m_show_bad_fcs_isSet){ + isObjectUpdated = true; break; + } + if(m_filter_frame_type_isSet){ + isObjectUpdated = true; break; + } + if(filter_panid && *filter_panid != QString("")){ + isObjectUpdated = true; break; + } + if(filter_address && *filter_address != QString("")){ + 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(m_udp_format_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(scope_config && scope_config->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/SWGIEEE_802_15_4_DemodSettings.h b/swagger/sdrangel/code/qt5/client/SWGIEEE_802_15_4_DemodSettings.h new file mode 100644 index 000000000..f0a4d5565 --- /dev/null +++ b/swagger/sdrangel/code/qt5/client/SWGIEEE_802_15_4_DemodSettings.h @@ -0,0 +1,225 @@ +/** + * 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. + */ + + +/* + * SWGIEEE_802_15_4_DemodSettings.h + * + * IEEE_802_15_4_Demod + */ + +#ifndef SWGIEEE_802_15_4_DemodSettings_H_ +#define SWGIEEE_802_15_4_DemodSettings_H_ + +#include + + +#include "SWGChannelMarker.h" +#include "SWGGLScope.h" +#include "SWGRollupState.h" +#include + +#include "SWGObject.h" +#include "export.h" + +namespace SWGSDRangel { + +class SWG_API SWGIEEE_802_15_4_DemodSettings: public SWGObject { +public: + SWGIEEE_802_15_4_DemodSettings(); + SWGIEEE_802_15_4_DemodSettings(QString* json); + virtual ~SWGIEEE_802_15_4_DemodSettings(); + void init(); + void cleanup(); + + virtual QString asJson () override; + virtual QJsonObject* asJsonObject() override; + virtual void fromJsonObject(QJsonObject &json) override; + virtual SWGIEEE_802_15_4_DemodSettings* fromJson(QString &jsonString) override; + + qint64 getInputFrequencyOffset(); + void setInputFrequencyOffset(qint64 input_frequency_offset); + + QString* getPhy(); + void setPhy(QString* phy); + + float getRfBandwidth(); + void setRfBandwidth(float rf_bandwidth); + + qint32 getSamplesPerChip(); + void setSamplesPerChip(qint32 samples_per_chip); + + float getMaxFrequencyOffset(); + void setMaxFrequencyOffset(float max_frequency_offset); + + float getThreshold(); + void setThreshold(float threshold); + + qint32 getShowBadFcs(); + void setShowBadFcs(qint32 show_bad_fcs); + + qint32 getFilterFrameType(); + void setFilterFrameType(qint32 filter_frame_type); + + QString* getFilterPanid(); + void setFilterPanid(QString* filter_panid); + + QString* getFilterAddress(); + void setFilterAddress(QString* filter_address); + + qint32 getUdpEnabled(); + void setUdpEnabled(qint32 udp_enabled); + + QString* getUdpAddress(); + void setUdpAddress(QString* udp_address); + + qint32 getUdpPort(); + void setUdpPort(qint32 udp_port); + + qint32 getUdpFormat(); + void setUdpFormat(qint32 udp_format); + + 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); + + SWGGLScope* getScopeConfig(); + void setScopeConfig(SWGGLScope* scope_config); + + 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; + + QString* phy; + bool m_phy_isSet; + + float rf_bandwidth; + bool m_rf_bandwidth_isSet; + + qint32 samples_per_chip; + bool m_samples_per_chip_isSet; + + float max_frequency_offset; + bool m_max_frequency_offset_isSet; + + float threshold; + bool m_threshold_isSet; + + qint32 show_bad_fcs; + bool m_show_bad_fcs_isSet; + + qint32 filter_frame_type; + bool m_filter_frame_type_isSet; + + QString* filter_panid; + bool m_filter_panid_isSet; + + QString* filter_address; + bool m_filter_address_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; + + qint32 udp_format; + bool m_udp_format_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; + + SWGGLScope* scope_config; + bool m_scope_config_isSet; + + SWGChannelMarker* channel_marker; + bool m_channel_marker_isSet; + + SWGRollupState* rollup_state; + bool m_rollup_state_isSet; + +}; + +} + +#endif /* SWGIEEE_802_15_4_DemodSettings_H_ */ diff --git a/swagger/sdrangel/code/qt5/client/SWGModelFactory.h b/swagger/sdrangel/code/qt5/client/SWGModelFactory.h index 671b00a29..c7d28d421 100644 --- a/swagger/sdrangel/code/qt5/client/SWGModelFactory.h +++ b/swagger/sdrangel/code/qt5/client/SWGModelFactory.h @@ -216,7 +216,9 @@ #include "SWGHeatMapSettings.h" #include "SWGIEEE_802_15_4_ModActions.h" #include "SWGIEEE_802_15_4_ModReport.h" +#include "SWGIEEE_802_15_4_DemodReport.h" #include "SWGIEEE_802_15_4_ModSettings.h" +#include "SWGIEEE_802_15_4_DemodSettings.h" #include "SWGILSDemodReport.h" #include "SWGILSDemodSettings.h" #include "SWGInmarsatDemodReport.h" @@ -1461,11 +1463,21 @@ namespace SWGSDRangel { obj->init(); return obj; } + if(QString("SWGIEEE_802_15_4_DemodReport").compare(type) == 0) { + SWGIEEE_802_15_4_DemodReport *obj = new SWGIEEE_802_15_4_DemodReport(); + obj->init(); + return obj; + } if(QString("SWGIEEE_802_15_4_ModSettings").compare(type) == 0) { SWGIEEE_802_15_4_ModSettings *obj = new SWGIEEE_802_15_4_ModSettings(); obj->init(); return obj; } + if(QString("SWGIEEE_802_15_4_DemodSettings").compare(type) == 0) { + SWGIEEE_802_15_4_DemodSettings *obj = new SWGIEEE_802_15_4_DemodSettings(); + obj->init(); + return obj; + } if(QString("SWGILSDemodReport").compare(type) == 0) { SWGILSDemodReport *obj = new SWGILSDemodReport(); obj->init();