diff --git a/CMakeLists.txt b/CMakeLists.txt index 22d05a8ce..fcd324caf 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -93,6 +93,7 @@ option(ENABLE_CHANNELRX_DEMODILS "Enable channelrx demodils 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) +option(ENABLE_CHANNELRX_ENDOFTRAIN "Enable channelrx end-of-train plugin" ON) # Channel Tx enablers option(ENABLE_CHANNELTX "Enable channeltx plugins" ON) diff --git a/doc/img/EndOfTrainDemod_plugin.png b/doc/img/EndOfTrainDemod_plugin.png new file mode 100644 index 000000000..915e0e525 Binary files /dev/null and b/doc/img/EndOfTrainDemod_plugin.png differ diff --git a/plugins/channelrx/CMakeLists.txt b/plugins/channelrx/CMakeLists.txt index c2b2ae395..5c5b43911 100644 --- a/plugins/channelrx/CMakeLists.txt +++ b/plugins/channelrx/CMakeLists.txt @@ -1,5 +1,9 @@ project(demod) +if (ENABLE_CHANNELRX_ENDOFTRAIN) + add_subdirectory(demodendoftrain) +endif() + if (ENABLE_CHANNELRX_FREQSCANNER) add_subdirectory(freqscanner) endif() diff --git a/plugins/channelrx/demodendoftrain/CMakeLists.txt b/plugins/channelrx/demodendoftrain/CMakeLists.txt new file mode 100644 index 000000000..f3d901783 --- /dev/null +++ b/plugins/channelrx/demodendoftrain/CMakeLists.txt @@ -0,0 +1,65 @@ +project(demodendoftrain) + +set(demodendoftrain_SOURCES + endoftraindemod.cpp + endoftraindemodsettings.cpp + endoftraindemodbaseband.cpp + endoftraindemodsink.cpp + endoftraindemodplugin.cpp + endoftraindemodwebapiadapter.cpp + endoftrainpacket.cpp +) + +set(demodendoftrain_HEADERS + endoftraindemod.h + endoftraindemodsettings.h + endoftraindemodbaseband.h + endoftraindemodsink.h + endoftraindemodplugin.h + endoftraindemodwebapiadapter.h + endoftrainpacket.h +) + +include_directories( + ${CMAKE_SOURCE_DIR}/swagger/sdrangel/code/qt5/client +) + +if(NOT SERVER_MODE) + set(demodendoftrain_SOURCES + ${demodendoftrain_SOURCES} + endoftraindemodgui.cpp + endoftraindemodgui.ui + ) + set(demodendoftrain_HEADERS + ${demodendoftrain_HEADERS} + endoftraindemodgui.h + ) + + set(TARGET_NAME demodendoftrain) + set(TARGET_LIB "Qt::Widgets") + set(TARGET_LIB_GUI "sdrgui") + set(INSTALL_FOLDER ${INSTALL_PLUGINS_DIR}) +else() + set(TARGET_NAME demodendoftrainsrv) + set(TARGET_LIB "") + set(TARGET_LIB_GUI "") + set(INSTALL_FOLDER ${INSTALL_PLUGINSSRV_DIR}) +endif() + +add_library(${TARGET_NAME} SHARED + ${demodendoftrain_SOURCES} +) + +target_link_libraries(${TARGET_NAME} + Qt::Core + ${TARGET_LIB} + sdrbase + ${TARGET_LIB_GUI} +) + +install(TARGETS ${TARGET_NAME} DESTINATION ${INSTALL_FOLDER}) + +# Install debug symbols +if (WIN32) + install(FILES $ CONFIGURATIONS Debug RelWithDebInfo DESTINATION ${INSTALL_FOLDER} ) +endif() diff --git a/plugins/channelrx/demodendoftrain/endoftraindemod.cpp b/plugins/channelrx/demodendoftrain/endoftraindemod.cpp new file mode 100644 index 000000000..9d88cac71 --- /dev/null +++ b/plugins/channelrx/demodendoftrain/endoftraindemod.cpp @@ -0,0 +1,671 @@ +/////////////////////////////////////////////////////////////////////////////////// +// Copyright (C) 2021-2022 Edouard Griffiths, F4EXB // +// Copyright (C) 2021-2024 Jon Beniston, M7RCE // +// // +// This program is free software; you can redistribute it and/or modify // +// it under the terms of the GNU General Public License as published by // +// the Free Software Foundation as version 3 of the License, or // +// (at your option) any later version. // +// // +// This program is distributed in the hope that it will be useful, // +// but WITHOUT ANY WARRANTY; without even the implied warranty of // +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // +// GNU General Public License V3 for more details. // +// // +// You should have received a copy of the GNU General Public License // +// along with this program. If not, see . // +/////////////////////////////////////////////////////////////////////////////////// + +#include "endoftraindemod.h" +#include "endoftrainpacket.h" + +#include +#include +#include +#include +#include + +#include "SWGChannelSettings.h" +#include "SWGWorkspaceInfo.h" +#include "SWGEndOfTrainDemodSettings.h" +#include "SWGChannelReport.h" + +#include "dsp/dspengine.h" +#include "dsp/dspcommands.h" +#include "device/deviceapi.h" +#include "settings/serializable.h" +#include "util/db.h" +#include "maincore.h" + +MESSAGE_CLASS_DEFINITION(EndOfTrainDemod::MsgConfigureEndOfTrainDemod, Message) + +const char * const EndOfTrainDemod::m_channelIdURI = "sdrangel.channel.endoftraindemod"; +const char * const EndOfTrainDemod::m_channelId = "EndOfTrainDemod"; + +EndOfTrainDemod::EndOfTrainDemod(DeviceAPI *deviceAPI) : + ChannelAPI(m_channelIdURI, ChannelAPI::StreamSingleSink), + m_deviceAPI(deviceAPI), + m_basebandSampleRate(0) +{ + setObjectName(m_channelId); + + m_basebandSink = new EndOfTrainDemodBaseband(this); + m_basebandSink->setMessageQueueToChannel(getInputMessageQueue()); + m_basebandSink->setChannel(this); + m_basebandSink->moveToThread(&m_thread); + + applySettings(m_settings, QStringList(), true); + + m_deviceAPI->addChannelSink(this); + m_deviceAPI->addChannelSinkAPI(this); + + m_networkManager = new QNetworkAccessManager(); + QObject::connect( + m_networkManager, + &QNetworkAccessManager::finished, + this, + &EndOfTrainDemod::networkManagerFinished + ); + QObject::connect( + this, + &ChannelAPI::indexInDeviceSetChanged, + this, + &EndOfTrainDemod::handleIndexInDeviceSetChanged + ); +} + +EndOfTrainDemod::~EndOfTrainDemod() +{ + qDebug("EndOfTrainDemod::~EndOfTrainDemod"); + QObject::disconnect( + m_networkManager, + &QNetworkAccessManager::finished, + this, + &EndOfTrainDemod::networkManagerFinished + ); + delete m_networkManager; + m_deviceAPI->removeChannelSinkAPI(this); + m_deviceAPI->removeChannelSink(this); + + if (m_basebandSink->isRunning()) { + stop(); + } + + delete m_basebandSink; +} + +void EndOfTrainDemod::setDeviceAPI(DeviceAPI *deviceAPI) +{ + if (deviceAPI != m_deviceAPI) + { + m_deviceAPI->removeChannelSinkAPI(this); + m_deviceAPI->removeChannelSink(this); + m_deviceAPI = deviceAPI; + m_deviceAPI->addChannelSink(this); + m_deviceAPI->addChannelSinkAPI(this); + } +} + +uint32_t EndOfTrainDemod::getNumberOfDeviceStreams() const +{ + return m_deviceAPI->getNbSourceStreams(); +} + +void EndOfTrainDemod::feed(const SampleVector::const_iterator& begin, const SampleVector::const_iterator& end, bool firstOfBurst) +{ + (void) firstOfBurst; + m_basebandSink->feed(begin, end); +} + +void EndOfTrainDemod::start() +{ + qDebug("EndOfTrainDemod::start"); + + m_basebandSink->reset(); + m_basebandSink->startWork(); + m_thread.start(); + + DSPSignalNotification *dspMsg = new DSPSignalNotification(m_basebandSampleRate, m_centerFrequency); + m_basebandSink->getInputMessageQueue()->push(dspMsg); + + EndOfTrainDemodBaseband::MsgConfigureEndOfTrainDemodBaseband *msg = EndOfTrainDemodBaseband::MsgConfigureEndOfTrainDemodBaseband::create(m_settings, QStringList(), true); + m_basebandSink->getInputMessageQueue()->push(msg); +} + +void EndOfTrainDemod::stop() +{ + qDebug("EndOfTrainDemod::stop"); + m_basebandSink->stopWork(); + m_thread.quit(); + m_thread.wait(); +} + +bool EndOfTrainDemod::handleMessage(const Message& cmd) +{ + if (MsgConfigureEndOfTrainDemod::match(cmd)) + { + MsgConfigureEndOfTrainDemod& cfg = (MsgConfigureEndOfTrainDemod&) cmd; + qDebug() << "EndOfTrainDemod::handleMessage: MsgConfigureEndOfTrainDemod"; + applySettings(cfg.getSettings(), cfg.getSettingsKeys(), 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() << "EndOfTrainDemod::handleMessage: DSPSignalNotification"; + m_basebandSink->getInputMessageQueue()->push(rep); + // Forward to GUI if any + if (m_guiMessageQueue) { + m_guiMessageQueue->push(new DSPSignalNotification(notif)); + } + + return true; + } + else if (MainCore::MsgPacket::match(cmd)) + { + // Forward to GUI + MainCore::MsgPacket& report = (MainCore::MsgPacket&)cmd; + if (getMessageQueueToGUI()) + { + MainCore::MsgPacket *msg = new MainCore::MsgPacket(report); + getMessageQueueToGUI()->push(msg); + } + + // Forward via UDP + if (m_settings.m_udpEnabled) + { + qDebug() << "Forwarding to " << m_settings.m_udpAddress << ":" << m_settings.m_udpPort; + m_udpSocket.writeDatagram(report.getPacket().data(), report.getPacket().size(), + QHostAddress(m_settings.m_udpAddress), m_settings.m_udpPort); + } + + // Write to log file + if (m_logFile.isOpen()) + { + EndOfTrainPacket packet; + + if (packet.decode(report.getPacket())) + { + m_logStream << report.getDateTime().date().toString() << "," + << report.getDateTime().time().toString() << "," + << report.getPacket().toHex() << "," + << packet.m_chainingBits << "," + << packet.m_batteryCondition << "," + << packet.m_type << "," + << packet.m_address << "," + << packet.m_pressure << "," + << packet.m_batteryCharge << "," + << packet.m_discretionary << "," + << packet.m_valveCircuitStatus << "," + << packet.m_confirmation << "," + << packet.m_turbine << "," + << packet.m_markerLightBatteryCondition << "," + << packet.m_markerLightStatus << "," + << packet.m_crcValid << "\n"; + } + else + { + m_logStream << report.getDateTime().date().toString() << "," + << report.getDateTime().time().toString() << "," + << report.getPacket().toHex() << "\n"; + } + } + + return true; + } + else if (MainCore::MsgChannelDemodQuery::match(cmd)) + { + qDebug() << "EndOfTrainDemod::handleMessage: MsgChannelDemodQuery"; + sendSampleRateToDemodAnalyzer(); + + return true; + } + else + { + return false; + } +} + +ScopeVis *EndOfTrainDemod::getScopeSink() +{ + return m_basebandSink->getScopeSink(); +} + +void EndOfTrainDemod::setCenterFrequency(qint64 frequency) +{ + EndOfTrainDemodSettings settings = m_settings; + settings.m_inputFrequencyOffset = frequency; + applySettings(settings, {"inputFrequencyOffset"}, false); + + if (m_guiMessageQueue) // forward to GUI if any + { + MsgConfigureEndOfTrainDemod *msgToGUI = MsgConfigureEndOfTrainDemod::create(settings, {"inputFrequencyOffset"}, false); + m_guiMessageQueue->push(msgToGUI); + } +} + +void EndOfTrainDemod::applySettings(const EndOfTrainDemodSettings& settings, const QStringList& settingsKeys, bool force) +{ + qDebug() << "EndOfTrainDemod::applySettings:" + << settings.getDebugString(settingsKeys, force) + << " force: " << force; + + if (settingsKeys.contains("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); + } + } + + EndOfTrainDemodBaseband::MsgConfigureEndOfTrainDemodBaseband *msg = EndOfTrainDemodBaseband::MsgConfigureEndOfTrainDemodBaseband::create(settings, settingsKeys, force); + m_basebandSink->getInputMessageQueue()->push(msg); + + if (settings.m_useReverseAPI) + { + bool fullUpdate = (settingsKeys.contains("useReverseAPI") && settings.m_useReverseAPI) || + settingsKeys.contains("reverseAPIAddress") || + settingsKeys.contains("reverseAPIPort") || + settingsKeys.contains("reverseAPIDeviceIndex") || + settingsKeys.contains("reverseAPIChannelIndex"); + webapiReverseSendSettings(settingsKeys, settings, fullUpdate || force); + } + + if (settingsKeys.contains("logEnabled") + || settingsKeys.contains("logFilename") + || force) + { + if (m_logFile.isOpen()) + { + m_logStream.flush(); + m_logFile.close(); + } + if (settings.m_logEnabled && !settings.m_logFilename.isEmpty()) + { + m_logFile.setFileName(settings.m_logFilename); + if (m_logFile.open(QIODevice::WriteOnly | QIODevice::Append | QIODevice::Text)) + { + qDebug() << "EndOfTrainDemod::applySettings - Logging to: " << settings.m_logFilename; + bool newFile = m_logFile.size() == 0; + m_logStream.setDevice(&m_logFile); + if (newFile) + { + // Write header + m_logStream << "Date,Time,Data,Chaining Bits,Battery Condition,Message Type,Address,Pressure,Battery Charge,Discretionary,Valve Circuit Status,Confidence Indicator,Turbine,Motion,Marker Battery Light Condition,Marker Light Status, Arm Status,CRC Valid\n"; + } + } + else + { + qDebug() << "EndOfTrainDemod::applySettings - Unable to open log file: " << settings.m_logFilename; + } + } + } + + if (force) { + m_settings = settings; + } else { + m_settings.applySettings(settingsKeys, settings); + } +} + +void EndOfTrainDemod::sendSampleRateToDemodAnalyzer() +{ + QList pipes; + MainCore::instance()->getMessagePipes().getMessagePipes(this, "reportdemod", pipes); + + if (pipes.size() > 0) + { + for (const auto& pipe : pipes) + { + MessageQueue *messageQueue = qobject_cast(pipe->m_element); + MainCore::MsgChannelDemodReport *msg = MainCore::MsgChannelDemodReport::create( + this, + EndOfTrainDemodSettings::CHANNEL_SAMPLE_RATE + ); + messageQueue->push(msg); + } + } +} + +QByteArray EndOfTrainDemod::serialize() const +{ + return m_settings.serialize(); +} + +bool EndOfTrainDemod::deserialize(const QByteArray& data) +{ + if (m_settings.deserialize(data)) + { + MsgConfigureEndOfTrainDemod *msg = MsgConfigureEndOfTrainDemod::create(m_settings, QStringList(), true); + m_inputMessageQueue.push(msg); + return true; + } + else + { + m_settings.resetToDefaults(); + MsgConfigureEndOfTrainDemod *msg = MsgConfigureEndOfTrainDemod::create(m_settings, QStringList(), true); + m_inputMessageQueue.push(msg); + return false; + } +} + +int EndOfTrainDemod::webapiSettingsGet( + SWGSDRangel::SWGChannelSettings& response, + QString& errorMessage) +{ + (void) errorMessage; + response.setEndOfTrainDemodSettings(new SWGSDRangel::SWGEndOfTrainDemodSettings()); + response.getEndOfTrainDemodSettings()->init(); + webapiFormatChannelSettings(response, m_settings); + return 200; +} + +int EndOfTrainDemod::webapiWorkspaceGet( + SWGSDRangel::SWGWorkspaceInfo& response, + QString& errorMessage) +{ + (void) errorMessage; + response.setIndex(m_settings.m_workspaceIndex); + return 200; +} + +int EndOfTrainDemod::webapiSettingsPutPatch( + bool force, + const QStringList& channelSettingsKeys, + SWGSDRangel::SWGChannelSettings& response, + QString& errorMessage) +{ + (void) errorMessage; + EndOfTrainDemodSettings settings = m_settings; + webapiUpdateChannelSettings(settings, channelSettingsKeys, response); + + MsgConfigureEndOfTrainDemod *msg = MsgConfigureEndOfTrainDemod::create(settings, channelSettingsKeys, force); + m_inputMessageQueue.push(msg); + + qDebug("EndOfTrainDemod::webapiSettingsPutPatch: forward to GUI: %p", m_guiMessageQueue); + if (m_guiMessageQueue) // forward to GUI if any + { + MsgConfigureEndOfTrainDemod *msgToGUI = MsgConfigureEndOfTrainDemod::create(settings, channelSettingsKeys, force); + m_guiMessageQueue->push(msgToGUI); + } + + webapiFormatChannelSettings(response, settings); + + return 200; +} + +int EndOfTrainDemod::webapiReportGet( + SWGSDRangel::SWGChannelReport& response, + QString& errorMessage) +{ + (void) errorMessage; + response.setEndOfTrainDemodReport(new SWGSDRangel::SWGEndOfTrainDemodReport()); + response.getEndOfTrainDemodReport()->init(); + webapiFormatChannelReport(response); + return 200; +} + +void EndOfTrainDemod::webapiUpdateChannelSettings( + EndOfTrainDemodSettings& settings, + const QStringList& channelSettingsKeys, + SWGSDRangel::SWGChannelSettings& response) +{ + if (channelSettingsKeys.contains("inputFrequencyOffset")) { + settings.m_inputFrequencyOffset = response.getEndOfTrainDemodSettings()->getInputFrequencyOffset(); + } + if (channelSettingsKeys.contains("fmDeviation")) { + settings.m_fmDeviation = response.getEndOfTrainDemodSettings()->getFmDeviation(); + } + if (channelSettingsKeys.contains("rfBandwidth")) { + settings.m_rfBandwidth = response.getEndOfTrainDemodSettings()->getRfBandwidth(); + } + if (channelSettingsKeys.contains("udpEnabled")) { + settings.m_udpEnabled = response.getEndOfTrainDemodSettings()->getUdpEnabled(); + } + if (channelSettingsKeys.contains("udpAddress")) { + settings.m_udpAddress = *response.getEndOfTrainDemodSettings()->getUdpAddress(); + } + if (channelSettingsKeys.contains("udpPort")) { + settings.m_udpPort = response.getEndOfTrainDemodSettings()->getUdpPort(); + } + if (channelSettingsKeys.contains("logFilename")) { + settings.m_logFilename = *response.getAdsbDemodSettings()->getLogFilename(); + } + if (channelSettingsKeys.contains("logEnabled")) { + settings.m_logEnabled = response.getAdsbDemodSettings()->getLogEnabled(); + } + if (channelSettingsKeys.contains("rgbColor")) { + settings.m_rgbColor = response.getEndOfTrainDemodSettings()->getRgbColor(); + } + if (channelSettingsKeys.contains("title")) { + settings.m_title = *response.getEndOfTrainDemodSettings()->getTitle(); + } + if (channelSettingsKeys.contains("streamIndex")) { + settings.m_streamIndex = response.getEndOfTrainDemodSettings()->getStreamIndex(); + } + if (channelSettingsKeys.contains("useReverseAPI")) { + settings.m_useReverseAPI = response.getEndOfTrainDemodSettings()->getUseReverseApi() != 0; + } + if (channelSettingsKeys.contains("reverseAPIAddress")) { + settings.m_reverseAPIAddress = *response.getEndOfTrainDemodSettings()->getReverseApiAddress(); + } + if (channelSettingsKeys.contains("reverseAPIPort")) { + settings.m_reverseAPIPort = response.getEndOfTrainDemodSettings()->getReverseApiPort(); + } + if (channelSettingsKeys.contains("reverseAPIDeviceIndex")) { + settings.m_reverseAPIDeviceIndex = response.getEndOfTrainDemodSettings()->getReverseApiDeviceIndex(); + } + if (channelSettingsKeys.contains("reverseAPIChannelIndex")) { + settings.m_reverseAPIChannelIndex = response.getEndOfTrainDemodSettings()->getReverseApiChannelIndex(); + } + if (settings.m_channelMarker && channelSettingsKeys.contains("channelMarker")) { + settings.m_channelMarker->updateFrom(channelSettingsKeys, response.getEndOfTrainDemodSettings()->getChannelMarker()); + } + if (settings.m_rollupState && channelSettingsKeys.contains("rollupState")) { + settings.m_rollupState->updateFrom(channelSettingsKeys, response.getEndOfTrainDemodSettings()->getRollupState()); + } +} + +void EndOfTrainDemod::webapiFormatChannelSettings(SWGSDRangel::SWGChannelSettings& response, const EndOfTrainDemodSettings& settings) +{ + response.getEndOfTrainDemodSettings()->setFmDeviation(settings.m_fmDeviation); + response.getEndOfTrainDemodSettings()->setInputFrequencyOffset(settings.m_inputFrequencyOffset); + response.getEndOfTrainDemodSettings()->setRfBandwidth(settings.m_rfBandwidth); + response.getEndOfTrainDemodSettings()->setUdpEnabled(settings.m_udpEnabled); + response.getEndOfTrainDemodSettings()->setUdpAddress(new QString(settings.m_udpAddress)); + response.getEndOfTrainDemodSettings()->setUdpPort(settings.m_udpPort); + response.getEndOfTrainDemodSettings()->setLogFilename(new QString(settings.m_logFilename)); + response.getEndOfTrainDemodSettings()->setLogEnabled(settings.m_logEnabled); + + response.getEndOfTrainDemodSettings()->setRgbColor(settings.m_rgbColor); + if (response.getEndOfTrainDemodSettings()->getTitle()) { + *response.getEndOfTrainDemodSettings()->getTitle() = settings.m_title; + } else { + response.getEndOfTrainDemodSettings()->setTitle(new QString(settings.m_title)); + } + + response.getEndOfTrainDemodSettings()->setStreamIndex(settings.m_streamIndex); + response.getEndOfTrainDemodSettings()->setUseReverseApi(settings.m_useReverseAPI ? 1 : 0); + + if (response.getEndOfTrainDemodSettings()->getReverseApiAddress()) { + *response.getEndOfTrainDemodSettings()->getReverseApiAddress() = settings.m_reverseAPIAddress; + } else { + response.getEndOfTrainDemodSettings()->setReverseApiAddress(new QString(settings.m_reverseAPIAddress)); + } + + response.getEndOfTrainDemodSettings()->setReverseApiPort(settings.m_reverseAPIPort); + response.getEndOfTrainDemodSettings()->setReverseApiDeviceIndex(settings.m_reverseAPIDeviceIndex); + response.getEndOfTrainDemodSettings()->setReverseApiChannelIndex(settings.m_reverseAPIChannelIndex); + + if (settings.m_channelMarker) + { + if (response.getEndOfTrainDemodSettings()->getChannelMarker()) + { + settings.m_channelMarker->formatTo(response.getEndOfTrainDemodSettings()->getChannelMarker()); + } + else + { + SWGSDRangel::SWGChannelMarker *swgChannelMarker = new SWGSDRangel::SWGChannelMarker(); + settings.m_channelMarker->formatTo(swgChannelMarker); + response.getEndOfTrainDemodSettings()->setChannelMarker(swgChannelMarker); + } + } + + if (settings.m_rollupState) + { + if (response.getEndOfTrainDemodSettings()->getRollupState()) + { + settings.m_rollupState->formatTo(response.getEndOfTrainDemodSettings()->getRollupState()); + } + else + { + SWGSDRangel::SWGRollupState *swgRollupState = new SWGSDRangel::SWGRollupState(); + settings.m_rollupState->formatTo(swgRollupState); + response.getEndOfTrainDemodSettings()->setRollupState(swgRollupState); + } + } +} + +void EndOfTrainDemod::webapiFormatChannelReport(SWGSDRangel::SWGChannelReport& response) +{ + double magsqAvg, magsqPeak; + int nbMagsqSamples; + getMagSqLevels(magsqAvg, magsqPeak, nbMagsqSamples); + + response.getEndOfTrainDemodReport()->setChannelPowerDb(CalcDb::dbPower(magsqAvg)); + response.getEndOfTrainDemodReport()->setChannelSampleRate(m_basebandSink->getChannelSampleRate()); +} + +void EndOfTrainDemod::webapiReverseSendSettings(const QStringList& channelSettingsKeys, const EndOfTrainDemodSettings& 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 EndOfTrainDemod::webapiFormatChannelSettings( + const QStringList& channelSettingsKeys, + SWGSDRangel::SWGChannelSettings *swgChannelSettings, + const EndOfTrainDemodSettings& settings, + bool force +) +{ + swgChannelSettings->setDirection(0); // Single sink (Rx) + swgChannelSettings->setOriginatorChannelIndex(getIndexInDeviceSet()); + swgChannelSettings->setOriginatorDeviceSetIndex(getDeviceSetIndex()); + swgChannelSettings->setChannelType(new QString("EndOfTrainDemod")); + swgChannelSettings->setEndOfTrainDemodSettings(new SWGSDRangel::SWGEndOfTrainDemodSettings()); + SWGSDRangel::SWGEndOfTrainDemodSettings *swgEndOfTrainDemodSettings = swgChannelSettings->getEndOfTrainDemodSettings(); + + // transfer data that has been modified. When force is on transfer all data except reverse API data + + if (channelSettingsKeys.contains("fmDeviation") || force) { + swgEndOfTrainDemodSettings->setFmDeviation(settings.m_fmDeviation); + } + if (channelSettingsKeys.contains("inputFrequencyOffset") || force) { + swgEndOfTrainDemodSettings->setInputFrequencyOffset(settings.m_inputFrequencyOffset); + } + if (channelSettingsKeys.contains("rfBandwidth") || force) { + swgEndOfTrainDemodSettings->setRfBandwidth(settings.m_rfBandwidth); + } + if (channelSettingsKeys.contains("udpEnabled") || force) { + swgEndOfTrainDemodSettings->setUdpEnabled(settings.m_udpEnabled); + } + if (channelSettingsKeys.contains("udpAddress") || force) { + swgEndOfTrainDemodSettings->setUdpAddress(new QString(settings.m_udpAddress)); + } + if (channelSettingsKeys.contains("udpPort") || force) { + swgEndOfTrainDemodSettings->setUdpPort(settings.m_udpPort); + } + if (channelSettingsKeys.contains("logFilename") || force) { + swgEndOfTrainDemodSettings->setLogFilename(new QString(settings.m_logFilename)); + } + if (channelSettingsKeys.contains("logEnabled") || force) { + swgEndOfTrainDemodSettings->setLogEnabled(settings.m_logEnabled); + } + if (channelSettingsKeys.contains("rgbColor") || force) { + swgEndOfTrainDemodSettings->setRgbColor(settings.m_rgbColor); + } + if (channelSettingsKeys.contains("title") || force) { + swgEndOfTrainDemodSettings->setTitle(new QString(settings.m_title)); + } + if (channelSettingsKeys.contains("streamIndex") || force) { + swgEndOfTrainDemodSettings->setStreamIndex(settings.m_streamIndex); + } + + if (settings.m_channelMarker && (channelSettingsKeys.contains("channelMarker") || force)) + { + SWGSDRangel::SWGChannelMarker *swgChannelMarker = new SWGSDRangel::SWGChannelMarker(); + settings.m_channelMarker->formatTo(swgChannelMarker); + swgEndOfTrainDemodSettings->setChannelMarker(swgChannelMarker); + } + + if (settings.m_rollupState && (channelSettingsKeys.contains("rollupState") || force)) + { + SWGSDRangel::SWGRollupState *swgRollupState = new SWGSDRangel::SWGRollupState(); + settings.m_rollupState->formatTo(swgRollupState); + swgEndOfTrainDemodSettings->setRollupState(swgRollupState); + } +} + +void EndOfTrainDemod::networkManagerFinished(QNetworkReply *reply) +{ + QNetworkReply::NetworkError replyError = reply->error(); + + if (replyError) + { + qWarning() << "EndOfTrainDemod::networkManagerFinished:" + << " error(" << (int) replyError + << "): " << replyError + << ": " << reply->errorString(); + } + else + { + QString answer = reply->readAll(); + answer.chop(1); // remove last \n + qDebug("EndOfTrainDemod::networkManagerFinished: reply:\n%s", answer.toStdString().c_str()); + } + + reply->deleteLater(); +} + +void EndOfTrainDemod::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); +} diff --git a/plugins/channelrx/demodendoftrain/endoftraindemod.h b/plugins/channelrx/demodendoftrain/endoftraindemod.h new file mode 100644 index 000000000..a3d294403 --- /dev/null +++ b/plugins/channelrx/demodendoftrain/endoftraindemod.h @@ -0,0 +1,182 @@ +/////////////////////////////////////////////////////////////////////////////////// +// Copyright (C) 2012 maintech GmbH, Otto-Hahn-Str. 15, 97204 Hoechberg, Germany // +// written by Christian Daniel // +// Copyright (C) 2014-2015 John Greb // +// Copyright (C) 2015-2022 Edouard Griffiths, F4EXB // +// Copyright (C) 2020-2024 Jon Beniston, M7RCE // +// Copyright (C) 2020 Kacper Michajłow // +// // +// 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_ENDOFTRAINDEMOD_H +#define INCLUDE_ENDOFTRAINDEMOD_H + +#include +#include +#include +#include +#include + +#include "dsp/basebandsamplesink.h" +#include "channel/channelapi.h" +#include "util/message.h" + +#include "endoftraindemodbaseband.h" +#include "endoftraindemodsettings.h" + +class QNetworkAccessManager; +class QNetworkReply; +class QThread; +class DeviceAPI; +class ScopeVis; + +class EndOfTrainDemod : public BasebandSampleSink, public ChannelAPI { +public: + class MsgConfigureEndOfTrainDemod : public Message { + MESSAGE_CLASS_DECLARATION + + public: + const EndOfTrainDemodSettings& getSettings() const { return m_settings; } + const QStringList& getSettingsKeys() const { return m_settingsKeys; } + bool getForce() const { return m_force; } + + static MsgConfigureEndOfTrainDemod* create(const EndOfTrainDemodSettings& settings, const QStringList& settingsKeys, bool force) + { + return new MsgConfigureEndOfTrainDemod(settings, settingsKeys, force); + } + + private: + EndOfTrainDemodSettings m_settings; + QStringList m_settingsKeys; + bool m_force; + + MsgConfigureEndOfTrainDemod(const EndOfTrainDemodSettings& settings, const QStringList& settingsKeys, bool force) : + Message(), + m_settings(settings), + m_settingsKeys(settingsKeys), + m_force(force) + { } + }; + + EndOfTrainDemod(DeviceAPI *deviceAPI); + virtual ~EndOfTrainDemod(); + 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; } + 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 EndOfTrainDemodSettings& settings); + + static void webapiUpdateChannelSettings( + EndOfTrainDemodSettings& 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); + } +/* void setMessageQueueToGUI(MessageQueue* queue) override { + ChannelAPI::setMessageQueueToGUI(queue); + m_basebandSink->setMessageQueueToGUI(queue); + }*/ + + uint32_t getNumberOfDeviceStreams() const; + + static const char * const m_channelIdURI; + static const char * const m_channelId; + +private: + DeviceAPI *m_deviceAPI; + QThread m_thread; + EndOfTrainDemodBaseband* m_basebandSink; + EndOfTrainDemodSettings m_settings; + int m_basebandSampleRate; //!< stored from device message used when starting baseband sink + qint64 m_centerFrequency; + QUdpSocket m_udpSocket; + QFile m_logFile; + QTextStream m_logStream; + + QNetworkAccessManager *m_networkManager; + QNetworkRequest m_networkRequest; + + virtual bool handleMessage(const Message& cmd); + void applySettings(const EndOfTrainDemodSettings& settings, const QStringList& settingsKeys, bool force = false); + void sendSampleRateToDemodAnalyzer(); + void webapiReverseSendSettings(const QStringList& channelSettingsKeys, const EndOfTrainDemodSettings& settings, bool force); + void webapiFormatChannelSettings( + const QStringList& channelSettingsKeys, + SWGSDRangel::SWGChannelSettings *swgChannelSettings, + const EndOfTrainDemodSettings& settings, + bool force + ); + void webapiFormatChannelReport(SWGSDRangel::SWGChannelReport& response); + +private slots: + void networkManagerFinished(QNetworkReply *reply); + void handleIndexInDeviceSetChanged(int index); + +}; + +#endif // INCLUDE_ENDOFTRAINDEMOD_H diff --git a/plugins/channelrx/demodendoftrain/endoftraindemodbaseband.cpp b/plugins/channelrx/demodendoftrain/endoftraindemodbaseband.cpp new file mode 100644 index 000000000..b00b09614 --- /dev/null +++ b/plugins/channelrx/demodendoftrain/endoftraindemodbaseband.cpp @@ -0,0 +1,186 @@ +/////////////////////////////////////////////////////////////////////////////////// +// Copyright (C) 2019-2021 Edouard Griffiths, F4EXB // +// Copyright (C) 2020-2024 Jon Beniston, M7RCE // +// Copyright (C) 2022 Jiří Pinkava // +// // +// This program is free software; you can redistribute it and/or modify // +// it under the terms of the GNU General Public License as published by // +// the Free Software Foundation as version 3 of the License, or // +// (at your option) any later version. // +// // +// This program is distributed in the hope that it will be useful, // +// but WITHOUT ANY WARRANTY; without even the implied warranty of // +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // +// GNU General Public License V3 for more details. // +// // +// You should have received a copy of the GNU General Public License // +// along with this program. If not, see . // +/////////////////////////////////////////////////////////////////////////////////// + +#include + +#include "dsp/dspengine.h" +#include "dsp/dspcommands.h" +#include "dsp/downchannelizer.h" + +#include "endoftraindemodbaseband.h" + +MESSAGE_CLASS_DEFINITION(EndOfTrainDemodBaseband::MsgConfigureEndOfTrainDemodBaseband, Message) + +EndOfTrainDemodBaseband::EndOfTrainDemodBaseband(EndOfTrainDemod *endoftrainDemod) : + m_sink(endoftrainDemod), + m_running(false) +{ + qDebug("EndOfTrainDemodBaseband::EndOfTrainDemodBaseband"); + + m_scopeSink.setNbStreams(EndOfTrainDemodSettings::m_scopeStreams); + m_sink.setScopeSink(&m_scopeSink); + m_sampleFifo.setSize(SampleSinkFifo::getSizePolicy(48000)); + m_channelizer = new DownChannelizer(&m_sink); +} + +EndOfTrainDemodBaseband::~EndOfTrainDemodBaseband() +{ + m_inputMessageQueue.clear(); + + delete m_channelizer; +} + +void EndOfTrainDemodBaseband::reset() +{ + QMutexLocker mutexLocker(&m_mutex); + m_inputMessageQueue.clear(); + m_sampleFifo.reset(); +} + +void EndOfTrainDemodBaseband::startWork() +{ + QMutexLocker mutexLocker(&m_mutex); + QObject::connect( + &m_sampleFifo, + &SampleSinkFifo::dataReady, + this, + &EndOfTrainDemodBaseband::handleData, + Qt::QueuedConnection + ); + connect(&m_inputMessageQueue, SIGNAL(messageEnqueued()), this, SLOT(handleInputMessages())); + m_running = true; +} + +void EndOfTrainDemodBaseband::stopWork() +{ + QMutexLocker mutexLocker(&m_mutex); + disconnect(&m_inputMessageQueue, SIGNAL(messageEnqueued()), this, SLOT(handleInputMessages())); + QObject::disconnect( + &m_sampleFifo, + &SampleSinkFifo::dataReady, + this, + &EndOfTrainDemodBaseband::handleData + ); + m_running = false; +} + +void EndOfTrainDemodBaseband::setChannel(ChannelAPI *channel) +{ + m_sink.setChannel(channel); +} + +void EndOfTrainDemodBaseband::feed(const SampleVector::const_iterator& begin, const SampleVector::const_iterator& end) +{ + m_sampleFifo.write(begin, end); +} + +void EndOfTrainDemodBaseband::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 EndOfTrainDemodBaseband::handleInputMessages() +{ + Message* message; + + while ((message = m_inputMessageQueue.pop()) != nullptr) + { + if (handleMessage(*message)) { + delete message; + } + } +} + +bool EndOfTrainDemodBaseband::handleMessage(const Message& cmd) +{ + if (MsgConfigureEndOfTrainDemodBaseband::match(cmd)) + { + QMutexLocker mutexLocker(&m_mutex); + MsgConfigureEndOfTrainDemodBaseband& cfg = (MsgConfigureEndOfTrainDemodBaseband&) cmd; + qDebug() << "EndOfTrainDemodBaseband::handleMessage: MsgConfigureEndOfTrainDemodBaseband"; + + applySettings(cfg.getSettings(), cfg.getSettingsKeys(), cfg.getForce()); + + return true; + } + else if (DSPSignalNotification::match(cmd)) + { + QMutexLocker mutexLocker(&m_mutex); + DSPSignalNotification& notif = (DSPSignalNotification&) cmd; + qDebug() << "EndOfTrainDemodBaseband::handleMessage: DSPSignalNotification: basebandSampleRate: " << notif.getSampleRate(); + setBasebandSampleRate(notif.getSampleRate()); + m_sampleFifo.setSize(SampleSinkFifo::getSizePolicy(notif.getSampleRate())); + + return true; + } + else + { + return false; + } +} + +void EndOfTrainDemodBaseband::applySettings(const EndOfTrainDemodSettings& settings, const QStringList& settingsKeys, bool force) +{ + if (settingsKeys.contains("inputFrequencyOffset") || force) + { + m_channelizer->setChannelization(EndOfTrainDemodSettings::CHANNEL_SAMPLE_RATE, settings.m_inputFrequencyOffset); + m_sink.applyChannelSettings(m_channelizer->getChannelSampleRate(), m_channelizer->getChannelFrequencyOffset()); + } + + m_sink.applySettings(settings, settingsKeys, force); + + if (force) { + m_settings = settings; + } else { + m_settings.applySettings(settingsKeys, settings); + } +} + +int EndOfTrainDemodBaseband::getChannelSampleRate() const +{ + return m_channelizer->getChannelSampleRate(); +} + +void EndOfTrainDemodBaseband::setBasebandSampleRate(int sampleRate) +{ + m_channelizer->setBasebandSampleRate(sampleRate); + m_sink.applyChannelSettings(m_channelizer->getChannelSampleRate(), m_channelizer->getChannelFrequencyOffset()); +} diff --git a/plugins/channelrx/demodendoftrain/endoftraindemodbaseband.h b/plugins/channelrx/demodendoftrain/endoftraindemodbaseband.h new file mode 100644 index 000000000..33727fa59 --- /dev/null +++ b/plugins/channelrx/demodendoftrain/endoftraindemodbaseband.h @@ -0,0 +1,105 @@ +/////////////////////////////////////////////////////////////////////////////////// +// Copyright (C) 2019-2022 Edouard Griffiths, F4EXB // +// Copyright (C) 2020-2024 Jon Beniston, M7RCE // +// Copyright (C) 2022 Jiří Pinkava // +// // +// 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_ENDOFTRAINDEMODBASEBAND_H +#define INCLUDE_ENDOFTRAINDEMODBASEBAND_H + +#include +#include + +#include "dsp/samplesinkfifo.h" +#include "dsp/scopevis.h" +#include "util/message.h" +#include "util/messagequeue.h" + +#include "endoftraindemodsink.h" + +class DownChannelizer; +class ChannelAPI; +class EndOfTrainDemod; +class ScopeVis; + +class EndOfTrainDemodBaseband : public QObject +{ + Q_OBJECT +public: + class MsgConfigureEndOfTrainDemodBaseband : public Message { + MESSAGE_CLASS_DECLARATION + + public: + const EndOfTrainDemodSettings& getSettings() const { return m_settings; } + const QStringList& getSettingsKeys() const { return m_settingsKeys; } + bool getForce() const { return m_force; } + + static MsgConfigureEndOfTrainDemodBaseband* create(const EndOfTrainDemodSettings& settings, const QStringList& settingsKeys, bool force) + { + return new MsgConfigureEndOfTrainDemodBaseband(settings, settingsKeys, force); + } + + private: + EndOfTrainDemodSettings m_settings; + QStringList m_settingsKeys; + bool m_force; + + MsgConfigureEndOfTrainDemodBaseband(const EndOfTrainDemodSettings& settings, const QStringList& settingsKeys, bool force) : + Message(), + m_settings(settings), + m_settingsKeys(settingsKeys), + m_force(force) + { } + }; + + EndOfTrainDemodBaseband(EndOfTrainDemod *endoftrainDemod); + ~EndOfTrainDemodBaseband(); + 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); + ScopeVis *getScopeSink() { return &m_scopeSink; } + 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); } + +private: + SampleSinkFifo m_sampleFifo; + DownChannelizer *m_channelizer; + EndOfTrainDemodSink m_sink; + MessageQueue m_inputMessageQueue; //!< Queue for asynchronous inbound communication + EndOfTrainDemodSettings m_settings; + ScopeVis m_scopeSink; + bool m_running; + QRecursiveMutex m_mutex; + + bool handleMessage(const Message& cmd); + void applySettings(const EndOfTrainDemodSettings& settings, const QStringList& settingsKeys, bool force = false); + +private slots: + void handleInputMessages(); + void handleData(); //!< Handle data when samples have to be processed +}; + +#endif // INCLUDE_ENDOFTRAINDEMODBASEBAND_H diff --git a/plugins/channelrx/demodendoftrain/endoftraindemodgui.cpp b/plugins/channelrx/demodendoftrain/endoftraindemodgui.cpp new file mode 100644 index 000000000..0567b742b --- /dev/null +++ b/plugins/channelrx/demodendoftrain/endoftraindemodgui.cpp @@ -0,0 +1,760 @@ +/////////////////////////////////////////////////////////////////////////////////// +// Copyright (C) 2021-2024 Jon Beniston, M7RCE // +// Copyright (C) 2021-2022 Edouard Griffiths, F4EXB // +// // +// 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 "endoftraindemodgui.h" +#include "endoftrainpacket.h" + +#include "device/deviceuiset.h" +#include "dsp/dspengine.h" +#include "dsp/dspcommands.h" +#include "ui_endoftraindemodgui.h" +#include "plugin/pluginapi.h" +#include "util/simpleserializer.h" +#include "util/csv.h" +#include "util/db.h" +#include "util/units.h" +#include "gui/basicchannelsettingsdialog.h" +#include "gui/devicestreamselectiondialog.h" +#include "dsp/dspengine.h" +#include "dsp/glscopesettings.h" +#include "gui/crightclickenabler.h" +#include "gui/dialogpositioner.h" +#include "channel/channelwebapiutils.h" +#include "maincore.h" + +#include "endoftraindemod.h" +#include "endoftraindemodsink.h" + +void EndOfTrainDemodGUI::resizeTable() +{ + // Fill table with a row of dummy data that will size the columns nicely + // Trailing spaces are for sort arrow + int row = ui->packets->rowCount(); + ui->packets->setRowCount(row + 1); + ui->packets->setItem(row, PACKETS_COL_DATE, new QTableWidgetItem("Frid Apr 15 2016-")); + ui->packets->setItem(row, PACKETS_COL_TIME, new QTableWidgetItem("10:17:00")); + ui->packets->setItem(row, PACKETS_COL_BATTERY_CONDITION, new QTableWidgetItem("Very low")); + ui->packets->setItem(row, PACKETS_COL_TYPE, new QTableWidgetItem("7-")); + ui->packets->setItem(row, PACKETS_COL_ADDRESS, new QTableWidgetItem("65535-")); + ui->packets->setItem(row, PACKETS_COL_PRESSURE, new QTableWidgetItem("PID-")); + ui->packets->setItem(row, PACKETS_COL_BATTERY_CHARGE, new QTableWidgetItem("100.0%")); + ui->packets->setItem(row, PACKETS_COL_ARM_STATUS, new QTableWidgetItem("Normal")); + ui->packets->setItem(row, PACKETS_COL_CRC, new QTableWidgetItem("123456-15-")); + ui->packets->setItem(row, PACKETS_COL_DATA_HEX, new QTableWidgetItem("88888888888888888888")); + ui->packets->resizeColumnsToContents(); + ui->packets->removeRow(row); +} + +// Columns in table reordered +void EndOfTrainDemodGUI::endoftrains_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 EndOfTrainDemodGUI::endoftrains_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 EndOfTrainDemodGUI::columnSelectMenu(QPoint pos) +{ + menu->popup(ui->packets->horizontalHeader()->viewport()->mapToGlobal(pos)); +} + +// Hide/show column when menu selected +void EndOfTrainDemodGUI::columnSelectMenuChecked(bool checked) +{ + (void) checked; + + QAction* action = qobject_cast(sender()); + if (action != nullptr) + { + int idx = action->data().toInt(nullptr); + ui->packets->setColumnHidden(idx, !action->isChecked()); + } +} + +// Create column select menu item +QAction *EndOfTrainDemodGUI::createCheckableItem(QString &text, int idx, bool checked) +{ + QAction *action = new QAction(text, this); + action->setCheckable(true); + action->setChecked(checked); + action->setData(QVariant(idx)); + connect(action, SIGNAL(triggered()), this, SLOT(columnSelectMenuChecked())); + return action; +} + +EndOfTrainDemodGUI* EndOfTrainDemodGUI::create(PluginAPI* pluginAPI, DeviceUISet *deviceUISet, BasebandSampleSink *rxChannel) +{ + EndOfTrainDemodGUI* gui = new EndOfTrainDemodGUI(pluginAPI, deviceUISet, rxChannel); + return gui; +} + +void EndOfTrainDemodGUI::destroy() +{ + delete this; +} + +void EndOfTrainDemodGUI::resetToDefaults() +{ + m_settings.resetToDefaults(); + displaySettings(); + applyAllSettings(); +} + +QByteArray EndOfTrainDemodGUI::serialize() const +{ + return m_settings.serialize(); +} + +bool EndOfTrainDemodGUI::deserialize(const QByteArray& data) +{ + if(m_settings.deserialize(data)) + { + displaySettings(); + applyAllSettings(); + return true; + } + else + { + resetToDefaults(); + return false; + } +} + +// Add row to table +void EndOfTrainDemodGUI::packetReceived(const QByteArray& packetData, const QDateTime& dateTime) +{ + EndOfTrainPacket packet; + + if (packet.decode(packetData)) + { + // Is scroll bar at bottom + QScrollBar *sb = ui->packets->verticalScrollBar(); + bool scrollToBottom = sb->value() == sb->maximum(); + + ui->packets->setSortingEnabled(false); + int row = ui->packets->rowCount(); + ui->packets->setRowCount(row + 1); + + QTableWidgetItem *dateItem = new QTableWidgetItem(); + QTableWidgetItem *timeItem = new QTableWidgetItem(); + QTableWidgetItem *chainingBitsItem = new QTableWidgetItem(); + QTableWidgetItem *batteryConditionItem = new QTableWidgetItem(); + QTableWidgetItem *typeItem = new QTableWidgetItem(); + QTableWidgetItem *addressItem = new QTableWidgetItem(); + QTableWidgetItem *pressureItem = new QTableWidgetItem(); + QTableWidgetItem *batteryChargeItem = new QTableWidgetItem(); + QTableWidgetItem *discretionaryItem = new QTableWidgetItem(); + QTableWidgetItem *valveCircuitStatusItem = new QTableWidgetItem(); + QTableWidgetItem *confIndItem = new QTableWidgetItem(); + QTableWidgetItem *turbineItem = new QTableWidgetItem(); + QTableWidgetItem *motionItem = new QTableWidgetItem(); + QTableWidgetItem *markerBatteryLightConditionItem = new QTableWidgetItem(); + QTableWidgetItem *markerLightStatusItem = new QTableWidgetItem(); + QTableWidgetItem *armStatusItem = new QTableWidgetItem(); + QTableWidgetItem *crcItem = new QTableWidgetItem(); + QTableWidgetItem *dataHexItem = new QTableWidgetItem(); + ui->packets->setItem(row, PACKETS_COL_DATE, dateItem); + ui->packets->setItem(row, PACKETS_COL_TIME, timeItem); + ui->packets->setItem(row, PACKETS_COL_CHAINING_BITS, chainingBitsItem); + ui->packets->setItem(row, PACKETS_COL_BATTERY_CONDITION, batteryConditionItem); + ui->packets->setItem(row, PACKETS_COL_TYPE, typeItem); + ui->packets->setItem(row, PACKETS_COL_ADDRESS, addressItem); + ui->packets->setItem(row, PACKETS_COL_PRESSURE, pressureItem); + ui->packets->setItem(row, PACKETS_COL_BATTERY_CHARGE, batteryChargeItem); + ui->packets->setItem(row, PACKETS_COL_DISCRETIONARY, discretionaryItem); + ui->packets->setItem(row, PACKETS_COL_VALVE_CIRCUIT_STATUS, valveCircuitStatusItem); + ui->packets->setItem(row, PACKETS_COL_CONF_IND, confIndItem); + ui->packets->setItem(row, PACKETS_COL_TURBINE, turbineItem); + ui->packets->setItem(row, PACKETS_COL_MOTION, motionItem); + ui->packets->setItem(row, PACKETS_COL_MARKER_BATTERY, markerBatteryLightConditionItem); + ui->packets->setItem(row, PACKETS_COL_MARKER_LIGHT, markerLightStatusItem); + ui->packets->setItem(row, PACKETS_COL_ARM_STATUS, armStatusItem); + ui->packets->setItem(row, PACKETS_COL_CRC, crcItem); + ui->packets->setItem(row, PACKETS_COL_DATA_HEX, dataHexItem); + dateItem->setText(dateTime.date().toString()); + timeItem->setText(dateTime.time().toString()); + chainingBitsItem->setText(QString::number(packet.m_chainingBits)); + batteryConditionItem->setText(packet.getBatteryCondition()); + typeItem->setText(packet.getMessageType()); + addressItem->setText(QString::number(packet.m_address)); + pressureItem->setText(QString::number(packet.m_pressure)); + batteryChargeItem->setText(QString("%1%").arg(packet.getBatteryChargePercent(), 0, 'f', 1)); + discretionaryItem->setCheckState(packet.m_discretionary ? Qt::Checked : Qt::Unchecked); + valveCircuitStatusItem->setText(packet.getValveCircuitStatus()); + confIndItem->setCheckState(packet.m_confirmation ? Qt::Checked : Qt::Unchecked); + turbineItem->setCheckState(packet.m_turbine ? Qt::Checked : Qt::Unchecked); + motionItem->setCheckState(packet.m_motion ? Qt::Checked : Qt::Unchecked); + markerBatteryLightConditionItem->setText(packet.getMarkerLightBatteryCondition()); + markerLightStatusItem->setText(packet.getMarkerLightStatus()); + armStatusItem->setText(packet.getArmStatus()); + crcItem->setCheckState(packet.m_crcValid ? Qt::Checked : Qt::Unchecked); + dataHexItem->setText(packet.m_dataHex); + filterRow(row); + ui->packets->setSortingEnabled(true); + if (scrollToBottom) { + ui->packets->scrollToBottom(); + } + } + else + { + qDebug() << "EndOfTrainDemodGUI::packetReceived: Unsupported packet: " << packetData; + } +} + +bool EndOfTrainDemodGUI::handleMessage(const Message& message) +{ + if (EndOfTrainDemod::MsgConfigureEndOfTrainDemod::match(message)) + { + qDebug("EndOfTrainDemodGUI::handleMessage: EndOfTrainDemod::MsgConfigureEndOfTrainDemod"); + const EndOfTrainDemod::MsgConfigureEndOfTrainDemod& cfg = (EndOfTrainDemod::MsgConfigureEndOfTrainDemod&) message; + m_settings = cfg.getSettings(); + blockApplySettings(true); + ui->scopeGUI->updateSettings(); + m_channelMarker.updateSettings(static_cast(m_settings.m_channelMarker)); + displaySettings(); + blockApplySettings(false); + return true; + } + else if (DSPSignalNotification::match(message)) + { + DSPSignalNotification& notif = (DSPSignalNotification&) message; + m_deviceCenterFrequency = notif.getCenterFrequency(); + m_basebandSampleRate = notif.getSampleRate(); + ui->deltaFrequency->setValueRange(false, 7, -m_basebandSampleRate/2, m_basebandSampleRate/2); + ui->deltaFrequencyLabel->setToolTip(tr("Range %1 %L2 Hz").arg(QChar(0xB1)).arg(m_basebandSampleRate/2)); + updateAbsoluteCenterFrequency(); + return true; + } + else if (MainCore::MsgPacket::match(message)) + { + MainCore::MsgPacket& report = (MainCore::MsgPacket&) message; + packetReceived(report.getPacket(), report.getDateTime()); + return true; + } + + return false; +} + +void EndOfTrainDemodGUI::handleInputMessages() +{ + Message* message; + + while ((message = getInputMessageQueue()->pop()) != 0) + { + if (handleMessage(*message)) + { + delete message; + } + } +} + +void EndOfTrainDemodGUI::channelMarkerChangedByCursor() +{ + ui->deltaFrequency->setValue(m_channelMarker.getCenterFrequency()); + m_settings.m_inputFrequencyOffset = m_channelMarker.getCenterFrequency(); + applySetting("inputFrequencyOffset"); +} + +void EndOfTrainDemodGUI::channelMarkerHighlightedByCursor() +{ + setHighlighted(m_channelMarker.getHighlighted()); +} + +void EndOfTrainDemodGUI::on_deltaFrequency_changed(qint64 value) +{ + m_channelMarker.setCenterFrequency(value); + m_settings.m_inputFrequencyOffset = m_channelMarker.getCenterFrequency(); + updateAbsoluteCenterFrequency(); + applySetting("inputFrequencyOffset"); +} + +void EndOfTrainDemodGUI::on_rfBW_valueChanged(int value) +{ + float bw = value * 100.0f; + ui->rfBWText->setText(QString("%1k").arg(value / 10.0, 0, 'f', 1)); + m_channelMarker.setBandwidth(bw); + m_settings.m_rfBandwidth = bw; + applySetting("rfBandwidth"); +} + +void EndOfTrainDemodGUI::on_fmDev_valueChanged(int value) +{ + ui->fmDevText->setText(QString("%1k").arg(value / 10.0, 0, 'f', 1)); + m_settings.m_fmDeviation = value * 100.0; + applySetting("fmDeviation"); +} + +void EndOfTrainDemodGUI::on_filterFrom_editingFinished() +{ + m_settings.m_filterFrom = ui->filterFrom->text(); + filter(); + applySetting("filterFrom"); +} + +void EndOfTrainDemodGUI::on_clearTable_clicked() +{ + ui->packets->setRowCount(0); +} + +void EndOfTrainDemodGUI::on_udpEnabled_clicked(bool checked) +{ + m_settings.m_udpEnabled = checked; + applySetting("udpEnabled"); +} + +void EndOfTrainDemodGUI::on_udpAddress_editingFinished() +{ + m_settings.m_udpAddress = ui->udpAddress->text(); + applySetting("udpAddress"); +} + +void EndOfTrainDemodGUI::on_udpPort_editingFinished() +{ + m_settings.m_udpPort = ui->udpPort->text().toInt(); + applySetting("udpPort"); +} + +void EndOfTrainDemodGUI::filterRow(int row) +{ + bool hidden = false; + if (m_settings.m_filterFrom != "") + { + QRegExp re(m_settings.m_filterFrom); + QTableWidgetItem *fromItem = ui->packets->item(row, PACKETS_COL_ADDRESS); + if (!re.exactMatch(fromItem->text())) + hidden = true; + } + ui->packets->setRowHidden(row, hidden); +} + +void EndOfTrainDemodGUI::filter() +{ + for (int i = 0; i < ui->packets->rowCount(); i++) + { + filterRow(i); + } +} + +void EndOfTrainDemodGUI::onWidgetRolled(QWidget* widget, bool rollDown) +{ + (void) widget; + (void) rollDown; + + getRollupContents()->saveState(m_rollupState); + applySetting("rollupState"); +} + +void EndOfTrainDemodGUI::onMenuDialogCalled(const QPoint &p) +{ + if (m_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_endoftrainDemod->getNumberOfDeviceStreams()); + dialog.setStreamIndex(m_settings.m_streamIndex); + } + + dialog.move(p); + new DialogPositioner(&dialog, false); + dialog.exec(); + + m_settings.m_rgbColor = m_channelMarker.getColor().rgb(); + m_settings.m_title = m_channelMarker.getTitle(); + m_settings.m_useReverseAPI = dialog.useReverseAPI(); + m_settings.m_reverseAPIAddress = dialog.getReverseAPIAddress(); + m_settings.m_reverseAPIPort = dialog.getReverseAPIPort(); + m_settings.m_reverseAPIDeviceIndex = dialog.getReverseAPIDeviceIndex(); + m_settings.m_reverseAPIChannelIndex = dialog.getReverseAPIChannelIndex(); + + setWindowTitle(m_settings.m_title); + setTitle(m_channelMarker.getTitle()); + setTitleColor(m_settings.m_rgbColor); + + QStringList settingsKeys({ + "rgbColor", + "title", + "useReverseAPI", + "reverseAPIAddress", + "reverseAPIPort", + "reverseAPIDeviceIndex", + "reverseAPIChannelIndex" + }); + + if (m_deviceUISet->m_deviceMIMOEngine) + { + m_settings.m_streamIndex = dialog.getSelectedStreamIndex(); + m_channelMarker.clearStreamIndexes(); + m_channelMarker.addStreamIndex(m_settings.m_streamIndex); + updateIndexLabel(); + } + + applySettings(settingsKeys); + } + + resetContextMenuType(); +} + +EndOfTrainDemodGUI::EndOfTrainDemodGUI(PluginAPI* pluginAPI, DeviceUISet *deviceUISet, BasebandSampleSink *rxChannel, QWidget* parent) : + ChannelGUI(parent), + ui(new Ui::EndOfTrainDemodGUI), + m_pluginAPI(pluginAPI), + m_deviceUISet(deviceUISet), + m_channelMarker(this), + m_deviceCenterFrequency(0), + m_doApplySettings(true), + m_tickCount(0) +{ + setAttribute(Qt::WA_DeleteOnClose, true); + m_helpURL = "plugins/channelrx/demodendoftrain/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_endoftrainDemod = reinterpret_cast(rxChannel); + m_endoftrainDemod->setMessageQueueToGUI(getInputMessageQueue()); + + connect(&MainCore::instance()->getMasterTimer(), SIGNAL(timeout()), this, SLOT(tick())); // 50 ms + + m_scopeVis = m_endoftrainDemod->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", "FM demod", "f0Filt", "f1Filt", "diff", "sample", "bit", "gotSOP"})); + + // 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 + + m_scopeVis->setLiveRate(EndOfTrainDemodSettings::CHANNEL_SAMPLE_RATE); + //m_scopeVis->setFreeRun(false); // FIXME: add method rather than call m_scopeVis->configure() + + ui->deltaFrequencyLabel->setText(QString("%1f").arg(QChar(0x94, 0x03))); + ui->deltaFrequency->setColorMapper(ColorMapper(ColorMapper::GrayGold)); + ui->deltaFrequency->setValueRange(false, 7, -9999999, 9999999); + ui->channelPowerMeter->setColorTheme(LevelMeterSignalDB::ColorGreenAndBlue); + + m_channelMarker.blockSignals(true); + m_channelMarker.setColor(Qt::yellow); + m_channelMarker.setBandwidth(m_settings.m_rfBandwidth); + m_channelMarker.setCenterFrequency(m_settings.m_inputFrequencyOffset); + m_channelMarker.setTitle("End Of Train Demodulator"); + m_channelMarker.blockSignals(false); + m_channelMarker.setVisible(true); // activate signal on the last setting only + + setTitleColor(m_channelMarker.getColor()); + m_settings.setChannelMarker(&m_channelMarker); + m_settings.setRollupState(&m_rollupState); + + m_deviceUISet->addChannelMarker(&m_channelMarker); + + connect(&m_channelMarker, SIGNAL(changedByCursor()), this, SLOT(channelMarkerChangedByCursor())); + connect(&m_channelMarker, SIGNAL(highlightedByCursor()), this, SLOT(channelMarkerHighlightedByCursor())); + connect(getInputMessageQueue(), SIGNAL(messageEnqueued()), this, SLOT(handleInputMessages())); + + // Resize the table using dummy data + resizeTable(); + // Allow user to reorder columns + ui->packets->horizontalHeader()->setSectionsMovable(true); + // Allow user to sort table by clicking on headers + ui->packets->setSortingEnabled(true); + // Add context menu to allow hiding/showing of columns + menu = new QMenu(ui->packets); + for (int i = 0; i < ui->packets->horizontalHeader()->count(); i++) + { + QString text = ui->packets->horizontalHeaderItem(i)->text(); + menu->addAction(createCheckableItem(text, i, true)); + } + ui->packets->horizontalHeader()->setContextMenuPolicy(Qt::CustomContextMenu); + connect(ui->packets->horizontalHeader(), SIGNAL(customContextMenuRequested(QPoint)), SLOT(columnSelectMenu(QPoint))); + // Get signals when columns change + connect(ui->packets->horizontalHeader(), SIGNAL(sectionMoved(int, int, int)), SLOT(endoftrains_sectionMoved(int, int, int))); + connect(ui->packets->horizontalHeader(), SIGNAL(sectionResized(int, int, int)), SLOT(endoftrains_sectionResized(int, int, int))); + + displaySettings(); + makeUIConnections(); + applyAllSettings(); + m_resizer.enableChildMouseTracking(); +} + +EndOfTrainDemodGUI::~EndOfTrainDemodGUI() +{ + delete ui; +} + +void EndOfTrainDemodGUI::blockApplySettings(bool block) +{ + m_doApplySettings = !block; +} + +void EndOfTrainDemodGUI::applySetting(const QString& settingsKey) +{ + applySettings({settingsKey}); +} + +void EndOfTrainDemodGUI::applySettings(const QStringList& settingsKeys, bool force) +{ + m_settingsKeys.append(settingsKeys); + if (m_doApplySettings) + { + EndOfTrainDemod::MsgConfigureEndOfTrainDemod* message = EndOfTrainDemod::MsgConfigureEndOfTrainDemod::create(m_settings, m_settingsKeys, force); + m_endoftrainDemod->getInputMessageQueue()->push(message); + m_settingsKeys.clear(); + } +} + +void EndOfTrainDemodGUI::applyAllSettings() +{ + applySettings(QStringList(), true); +} + +void EndOfTrainDemodGUI::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); + + ui->deltaFrequency->setValue(m_channelMarker.getCenterFrequency()); + + ui->rfBWText->setText(QString("%1k").arg(m_settings.m_rfBandwidth / 1000.0, 0, 'f', 1)); + ui->rfBW->setValue(m_settings.m_rfBandwidth / 100.0); + + ui->fmDevText->setText(QString("%1k").arg(m_settings.m_fmDeviation / 1000.0, 0, 'f', 1)); + ui->fmDev->setValue(m_settings.m_fmDeviation / 100.0); + + updateIndexLabel(); + + ui->filterFrom->setText(m_settings.m_filterFrom); + + ui->udpEnabled->setChecked(m_settings.m_udpEnabled); + ui->udpAddress->setText(m_settings.m_udpAddress); + ui->udpPort->setText(QString::number(m_settings.m_udpPort)); + + ui->logFilename->setToolTip(QString(".csv log filename: %1").arg(m_settings.m_logFilename)); + ui->logEnable->setChecked(m_settings.m_logEnabled); + + // Order and size columns + QHeaderView *header = ui->packets->horizontalHeader(); + for (int i = 0; i < ENDOFTRAINDEMOD_COLUMNS; i++) + { + bool hidden = m_settings.m_columnSizes[i] == 0; + header->setSectionHidden(i, hidden); + menu->actions().at(i)->setChecked(!hidden); + if (m_settings.m_columnSizes[i] > 0) + ui->packets->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 EndOfTrainDemodGUI::leaveEvent(QEvent* event) +{ + m_channelMarker.setHighlighted(false); + ChannelGUI::leaveEvent(event); +} + +void EndOfTrainDemodGUI::enterEvent(EnterEventType* event) +{ + m_channelMarker.setHighlighted(true); + ChannelGUI::enterEvent(event); +} + +void EndOfTrainDemodGUI::tick() +{ + double magsqAvg, magsqPeak; + int nbMagsqSamples; + m_endoftrainDemod->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 EndOfTrainDemodGUI::on_logEnable_clicked(bool checked) +{ + m_settings.m_logEnabled = checked; + applySetting("logEnabled"); +} + +void EndOfTrainDemodGUI::on_logFilename_clicked() +{ + // Get filename to save to + QFileDialog fileDialog(nullptr, "Select file to log received frames to", "", "*.csv"); + fileDialog.setAcceptMode(QFileDialog::AcceptSave); + if (fileDialog.exec()) + { + QStringList fileNames = fileDialog.selectedFiles(); + if (fileNames.size() > 0) + { + m_settings.m_logFilename = fileNames[0]; + ui->logFilename->setToolTip(QString(".csv log filename: %1").arg(m_settings.m_logFilename)); + applySetting("logFilename"); + } + } +} + +// Read .csv log and process as received frames +void EndOfTrainDemodGUI::on_logOpen_clicked() +{ + QFileDialog fileDialog(nullptr, "Select .csv log file to read", "", "*.csv"); + if (fileDialog.exec()) + { + QStringList fileNames = fileDialog.selectedFiles(); + if (fileNames.size() > 0) + { + QFile file(fileNames[0]); + if (file.open(QIODevice::ReadOnly | QIODevice::Text)) + { + QTextStream in(&file); + QString error; + QHash colIndexes = CSV::readHeader(in, {"Date", "Time", "Data"}, error); + if (error.isEmpty()) + { + int dateCol = colIndexes.value("Date"); + int timeCol = colIndexes.value("Time"); + int dataCol = colIndexes.value("Data"); + int maxCol = std::max({dateCol, timeCol, dataCol}); + + QMessageBox dialog(this); + dialog.setText("Reading packet data"); + dialog.addButton(QMessageBox::Cancel); + dialog.show(); + QApplication::processEvents(); + int count = 0; + bool cancelled = false; + QStringList cols; + while (!cancelled && CSV::readRow(in, &cols)) + { + if (cols.size() > maxCol) + { + QDate date = QDate::fromString(cols[dateCol]); + QTime time = QTime::fromString(cols[timeCol]); + QDateTime dateTime(date, time); + QByteArray bytes = QByteArray::fromHex(cols[dataCol].toLatin1()); + packetReceived(bytes, dateTime); + if (count % 1000 == 0) + { + QApplication::processEvents(); + if (dialog.clickedButton()) { + cancelled = true; + } + } + count++; + } + } + dialog.close(); + } + else + { + QMessageBox::critical(this, "End-Of-Train Demod", error); + } + } + else + { + QMessageBox::critical(this, "End-Of-Train Demod", QString("Failed to open file %1").arg(fileNames[0])); + } + } + } +} + +void EndOfTrainDemodGUI::makeUIConnections() +{ + QObject::connect(ui->deltaFrequency, &ValueDialZ::changed, this, &EndOfTrainDemodGUI::on_deltaFrequency_changed); + QObject::connect(ui->rfBW, &QSlider::valueChanged, this, &EndOfTrainDemodGUI::on_rfBW_valueChanged); + QObject::connect(ui->fmDev, &QSlider::valueChanged, this, &EndOfTrainDemodGUI::on_fmDev_valueChanged); + QObject::connect(ui->filterFrom, &QLineEdit::editingFinished, this, &EndOfTrainDemodGUI::on_filterFrom_editingFinished); + QObject::connect(ui->clearTable, &QPushButton::clicked, this, &EndOfTrainDemodGUI::on_clearTable_clicked); + QObject::connect(ui->udpEnabled, &QCheckBox::clicked, this, &EndOfTrainDemodGUI::on_udpEnabled_clicked); + QObject::connect(ui->udpAddress, &QLineEdit::editingFinished, this, &EndOfTrainDemodGUI::on_udpAddress_editingFinished); + QObject::connect(ui->udpPort, &QLineEdit::editingFinished, this, &EndOfTrainDemodGUI::on_udpPort_editingFinished); + QObject::connect(ui->logEnable, &ButtonSwitch::clicked, this, &EndOfTrainDemodGUI::on_logEnable_clicked); + QObject::connect(ui->logFilename, &QToolButton::clicked, this, &EndOfTrainDemodGUI::on_logFilename_clicked); + QObject::connect(ui->logOpen, &QToolButton::clicked, this, &EndOfTrainDemodGUI::on_logOpen_clicked); +} + +void EndOfTrainDemodGUI::updateAbsoluteCenterFrequency() +{ + setStatusFrequency(m_deviceCenterFrequency + m_settings.m_inputFrequencyOffset); +} diff --git a/plugins/channelrx/demodendoftrain/endoftraindemodgui.h b/plugins/channelrx/demodendoftrain/endoftraindemodgui.h new file mode 100644 index 000000000..30f3827e9 --- /dev/null +++ b/plugins/channelrx/demodendoftrain/endoftraindemodgui.h @@ -0,0 +1,152 @@ +/////////////////////////////////////////////////////////////////////////////////// +// Copyright (C) 2020-2024 Jon Beniston, M7RCE // +// Copyright (C) 2020, 2022 Edouard Griffiths, F4EXB // +// // +// 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_ENDOFTRAINDEMODGUI_H +#define INCLUDE_ENDOFTRAINDEMODGUI_H + +#include + +#include "channel/channelgui.h" +#include "dsp/channelmarker.h" +#include "util/messagequeue.h" +#include "settings/rollupstate.h" +#include "endoftraindemodsettings.h" + +class PluginAPI; +class DeviceUISet; +class BasebandSampleSink; +class ScopeVis; +class EndOfTrainDemod; +class EndOfTrainDemodGUI; + +namespace Ui { + class EndOfTrainDemodGUI; +} +class EndOfTrainDemodGUI; + +class EndOfTrainDemodGUI : public ChannelGUI { + Q_OBJECT + +public: + static EndOfTrainDemodGUI* 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::EndOfTrainDemodGUI* ui; + PluginAPI* m_pluginAPI; + DeviceUISet* m_deviceUISet; + ChannelMarker m_channelMarker; + RollupState m_rollupState; + EndOfTrainDemodSettings m_settings; + QStringList m_settingsKeys; + qint64 m_deviceCenterFrequency; + bool m_doApplySettings; + ScopeVis* m_scopeVis; + + EndOfTrainDemod* m_endoftrainDemod; + int m_basebandSampleRate; + uint32_t m_tickCount; + MessageQueue m_inputMessageQueue; + + QMenu *menu; // Column select context menu + + explicit EndOfTrainDemodGUI(PluginAPI* pluginAPI, DeviceUISet *deviceUISet, BasebandSampleSink *rxChannel, QWidget* parent = 0); + virtual ~EndOfTrainDemodGUI(); + + void blockApplySettings(bool block); + void applySetting(const QString& settingsKey); + void applySettings(const QStringList& settingsKeys, bool force = false); + void applyAllSettings(); + void displaySettings(); + void packetReceived(const QByteArray& packet, const QDateTime& dateTime); + bool handleMessage(const Message& message); + void makeUIConnections(); + void updateAbsoluteCenterFrequency(); + + void leaveEvent(QEvent*); + void enterEvent(EnterEventType*); + + void resizeTable(); + QAction *createCheckableItem(QString& text, int idx, bool checked); + + enum EndOfTrainCol { + PACKETS_COL_DATE, + PACKETS_COL_TIME, + PACKETS_COL_CHAINING_BITS, + PACKETS_COL_BATTERY_CONDITION, + PACKETS_COL_TYPE, + PACKETS_COL_ADDRESS, + PACKETS_COL_PRESSURE, + PACKETS_COL_BATTERY_CHARGE, + PACKETS_COL_DISCRETIONARY, + PACKETS_COL_VALVE_CIRCUIT_STATUS, + PACKETS_COL_CONF_IND, + PACKETS_COL_TURBINE, + PACKETS_COL_MOTION, + PACKETS_COL_MARKER_BATTERY, + PACKETS_COL_MARKER_LIGHT, + PACKETS_COL_ARM_STATUS, + PACKETS_COL_CRC, + PACKETS_COL_DATA_HEX + }; + +private slots: + void on_deltaFrequency_changed(qint64 value); + void on_rfBW_valueChanged(int index); + void on_fmDev_valueChanged(int value); + void on_filterFrom_editingFinished(); + void on_clearTable_clicked(); + void on_udpEnabled_clicked(bool checked); + void on_udpAddress_editingFinished(); + void on_udpPort_editingFinished(); + void on_logEnable_clicked(bool checked=false); + void on_logFilename_clicked(); + void on_logOpen_clicked(); + void filterRow(int row); + void filter(); + void endoftrains_sectionMoved(int logicalIndex, int oldVisualIndex, int newVisualIndex); + void endoftrains_sectionResized(int logicalIndex, int oldSize, int newSize); + void columnSelectMenu(QPoint pos); + void columnSelectMenuChecked(bool checked = false); + void onWidgetRolled(QWidget* widget, bool rollDown); + void onMenuDialogCalled(const QPoint& p); + void handleInputMessages(); + void tick(); +}; + +#endif // INCLUDE_ENDOFTRAINDEMODGUI_H diff --git a/plugins/channelrx/demodendoftrain/endoftraindemodgui.ui b/plugins/channelrx/demodendoftrain/endoftraindemodgui.ui new file mode 100644 index 000000000..e70556983 --- /dev/null +++ b/plugins/channelrx/demodendoftrain/endoftraindemodgui.ui @@ -0,0 +1,854 @@ + + + EndOfTrainDemodGUI + + + + 0 + 0 + 398 + 806 + + + + + 0 + 0 + + + + + 352 + 0 + + + + + Liberation Sans + 9 + + + + Qt::StrongFocus + + + EndOfTrain Demodulator + + + + + 0 + 0 + 390 + 151 + + + + + 350 + 0 + + + + Settings + + + + 3 + + + 2 + + + 2 + + + 2 + + + 2 + + + + + 2 + + + + + + 16 + 0 + + + + Df + + + + + + + + 0 + 0 + + + + + 32 + 16 + + + + + Liberation Mono + 12 + + + + PointingHandCursor + + + Qt::StrongFocus + + + Demod shift frequency from center in Hz + + + + + + + Hz + + + + + + + Qt::Vertical + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + + Channel power + + + Qt::RightToLeft + + + 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::Horizontal + + + + + + + + + BW + + + + + + + + 0 + 0 + + + + + 0 + 0 + + + + RF bandwidth + + + 10 + + + 400 + + + 1 + + + 100 + + + Qt::Horizontal + + + + + + + + 30 + 0 + + + + 10.0k + + + Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter + + + + + + + Qt::Vertical + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + Qt::Vertical + + + + + + + Dev + + + + + + + + 0 + 0 + + + + + 0 + 0 + + + + Frequency deviation + + + 10 + + + 60 + + + 1 + + + 50 + + + Qt::Horizontal + + + + + + + + 30 + 0 + + + + 5.0k + + + Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter + + + + + + + + + Qt::Horizontal + + + + + + + + + UDP + + + + + + + Send endoftrains via UDP + + + Qt::RightToLeft + + + + + + + + + + + 120 + 0 + + + + Qt::ClickFocus + + + Destination UDP address + + + 000.000.000.000 + + + 127.0.0.1 + + + + + + + : + + + Qt::AlignCenter + + + + + + + + 50 + 0 + + + + + 50 + 16777215 + + + + Qt::ClickFocus + + + Destination UDP port + + + 00000 + + + 9998 + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + + Qt::Horizontal + + + + + + + + + Filter Address + + + + + + + Display only packets where the address matches the specified regular expression + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + 24 + 16777215 + + + + Start/stop logging of received packets to .csv file + + + + + + + :/record_off.png:/record_off.png + + + + + + + Set log .csv filename + + + ... + + + + :/save.png:/save.png + + + false + + + + + + + Read data from .csv log file + + + ... + + + + :/load.png:/load.png + + + false + + + + + + + Clear endoftrains from table + + + + + + + :/bin.png:/bin.png + + + + + + + + + + + 0 + 170 + 391 + 261 + + + + + 0 + 0 + + + + Received Packets + + + + 2 + + + 3 + + + 3 + + + 3 + + + 3 + + + + + + + + QAbstractItemView::NoEditTriggers + + + + Date + + + Date packet was received + + + + + Time + + + Time packet was received + + + + + Chain + + + + + Battery + + + Battery condition + + + + + Type + + + Message type + + + + + Address + + + Unit address + + + + + Pressure (PSIG) + + + Brake pipe pressure in Pounds per Square Inch Gauge (PSIG) + + + + + Charge (%) + + + Battery charge in % + + + + + Disc + + + Discretionary bit used for varying data by different vendors + + + + + Valve + + + Valve circuit status + + + + + Conf + + + Confirmation + + + + + Turbine + + + + + Motion + + + Motion detected + + + + + Light Batt + + + Market light battery condtion + + + + + Light + + + Marker light status (on / off) + + + + + Arm Status + + + + + CRC + + + Indicates if calculated CRC matches received CRC + + + + + Hex + + + Packet hex data + + + + + + + + + + 10 + 440 + 716 + 341 + + + + + 714 + 0 + + + + Waveforms + + + + 2 + + + 3 + + + 3 + + + 3 + + + 3 + + + + + + 200 + 250 + + + + + Liberation Mono + 8 + + + + + + + + + + + + + ButtonSwitch + QToolButton +
gui/buttonswitch.h
+
+ + ValueDialZ + QWidget +
gui/valuedialz.h
+ 1 +
+ + RollupContents + QWidget +
gui/rollupcontents.h
+ 1 +
+ + LevelMeterSignalDB + QWidget +
gui/levelmeter.h
+ 1 +
+ + GLScope + QWidget +
gui/glscope.h
+ 1 +
+ + GLScopeGUI + QWidget +
gui/glscopegui.h
+ 1 +
+
+ + packets + + + + + +
diff --git a/plugins/channelrx/demodendoftrain/endoftraindemodplugin.cpp b/plugins/channelrx/demodendoftrain/endoftraindemodplugin.cpp new file mode 100644 index 000000000..e8b9377f6 --- /dev/null +++ b/plugins/channelrx/demodendoftrain/endoftraindemodplugin.cpp @@ -0,0 +1,96 @@ +/////////////////////////////////////////////////////////////////////////////////// +// Copyright (C) 2012 maintech GmbH, Otto-Hahn-Str. 15, 97204 Hoechberg, Germany // +// written by Christian Daniel // +// Copyright (C) 2015-2022 Edouard Griffiths, F4EXB // +// Copyright (C) 2019 Davide Gerhard // +// Copyright (C) 2020-2024 Jon Beniston, M7RCE // +// Copyright (C) 2020 Kacper Michajłow // +// // +// 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 "endoftraindemodgui.h" +#endif +#include "endoftraindemod.h" +#include "endoftraindemodwebapiadapter.h" +#include "endoftraindemodplugin.h" + +const PluginDescriptor EndOfTrainDemodPlugin::m_pluginDescriptor = { + EndOfTrainDemod::m_channelId, + QStringLiteral("End-of-Train Demodulator"), + QStringLiteral("7.19.0"), + QStringLiteral("(c) Jon Beniston, M7RCE"), + QStringLiteral("https://github.com/f4exb/sdrangel"), + true, + QStringLiteral("https://github.com/f4exb/sdrangel") +}; + +EndOfTrainDemodPlugin::EndOfTrainDemodPlugin(QObject* parent) : + QObject(parent), + m_pluginAPI(0) +{ +} + +const PluginDescriptor& EndOfTrainDemodPlugin::getPluginDescriptor() const +{ + return m_pluginDescriptor; +} + +void EndOfTrainDemodPlugin::initPlugin(PluginAPI* pluginAPI) +{ + m_pluginAPI = pluginAPI; + + m_pluginAPI->registerRxChannel(EndOfTrainDemod::m_channelIdURI, EndOfTrainDemod::m_channelId, this); +} + +void EndOfTrainDemodPlugin::createRxChannel(DeviceAPI *deviceAPI, BasebandSampleSink **bs, ChannelAPI **cs) const +{ + if (bs || cs) + { + EndOfTrainDemod *instance = new EndOfTrainDemod(deviceAPI); + + if (bs) { + *bs = instance; + } + + if (cs) { + *cs = instance; + } + } +} + +#ifdef SERVER_MODE +ChannelGUI* EndOfTrainDemodPlugin::createRxChannelGUI( + DeviceUISet *deviceUISet, + BasebandSampleSink *rxChannel) const +{ + (void) deviceUISet; + (void) rxChannel; + return 0; +} +#else +ChannelGUI* EndOfTrainDemodPlugin::createRxChannelGUI(DeviceUISet *deviceUISet, BasebandSampleSink *rxChannel) const +{ + return EndOfTrainDemodGUI::create(m_pluginAPI, deviceUISet, rxChannel); +} +#endif + +ChannelWebAPIAdapter* EndOfTrainDemodPlugin::createChannelWebAPIAdapter() const +{ + return new EndOfTrainDemodWebAPIAdapter(); +} diff --git a/plugins/channelrx/demodendoftrain/endoftraindemodplugin.h b/plugins/channelrx/demodendoftrain/endoftraindemodplugin.h new file mode 100644 index 000000000..66b9180a0 --- /dev/null +++ b/plugins/channelrx/demodendoftrain/endoftraindemodplugin.h @@ -0,0 +1,52 @@ +/////////////////////////////////////////////////////////////////////////////////// +// Copyright (C) 2012 maintech GmbH, Otto-Hahn-Str. 15, 97204 Hoechberg, Germany // +// written by Christian Daniel // +// Copyright (C) 2015-2020 Edouard Griffiths, F4EXB // +// Copyright (C) 2015 John Greb // +// Copyright (C) 2020-2024 Jon Beniston, M7RCE // +// // +// This program is free software; you can redistribute it and/or modify // +// it under the terms of the GNU General Public License as published by // +// the Free Software Foundation as version 3 of the License, or // +// (at your option) any later version. // +// // +// This program is distributed in the hope that it will be useful, // +// but WITHOUT ANY WARRANTY; without even the implied warranty of // +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // +// GNU General Public License V3 for more details. // +// // +// You should have received a copy of the GNU General Public License // +// along with this program. If not, see . // +/////////////////////////////////////////////////////////////////////////////////// + +#ifndef INCLUDE_ENDOFTRAINDEMODPLUGIN_H +#define INCLUDE_ENDOFTRAINDEMODPLUGIN_H + +#include +#include "plugin/plugininterface.h" + +class DeviceUISet; +class BasebandSampleSink; + +class EndOfTrainDemodPlugin : public QObject, PluginInterface { + Q_OBJECT + Q_INTERFACES(PluginInterface) + Q_PLUGIN_METADATA(IID "sdrangel.channel.endoftraindemod") + +public: + explicit EndOfTrainDemodPlugin(QObject* parent = NULL); + + const PluginDescriptor& getPluginDescriptor() const; + void initPlugin(PluginAPI* pluginAPI); + + virtual void createRxChannel(DeviceAPI *deviceAPI, BasebandSampleSink **bs, ChannelAPI **cs) const; + virtual ChannelGUI* createRxChannelGUI(DeviceUISet *deviceUISet, BasebandSampleSink *rxChannel) const; + virtual ChannelWebAPIAdapter* createChannelWebAPIAdapter() const; + +private: + static const PluginDescriptor m_pluginDescriptor; + + PluginAPI* m_pluginAPI; +}; + +#endif // INCLUDE_ENDOFTRAINDEMODPLUGIN_H diff --git a/plugins/channelrx/demodendoftrain/endoftraindemodsettings.cpp b/plugins/channelrx/demodendoftrain/endoftraindemodsettings.cpp new file mode 100644 index 000000000..f03af32b3 --- /dev/null +++ b/plugins/channelrx/demodendoftrain/endoftraindemodsettings.cpp @@ -0,0 +1,319 @@ +/////////////////////////////////////////////////////////////////////////////////// +// Copyright (C) 2012 maintech GmbH, Otto-Hahn-Str. 15, 97204 Hoechberg, Germany // +// written by Christian Daniel // +// Copyright (C) 2015-2022 Edouard Griffiths, F4EXB // +// Copyright (C) 2020-2024 Jon Beniston, M7RCE // +// // +// This program is free software; you can redistribute it and/or modify // +// it under the terms of the GNU General Public License as published by // +// the Free Software Foundation as version 3 of the License, or // +// (at your option) any later version. // +// // +// This program is distributed in the hope that it will be useful, // +// but WITHOUT ANY WARRANTY; without even the implied warranty of // +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // +// GNU General Public License V3 for more details. // +// // +// You should have received a copy of the GNU General Public License // +// along with this program. If not, see . // +/////////////////////////////////////////////////////////////////////////////////// + +#include + +#include "util/simpleserializer.h" +#include "settings/serializable.h" +#include "endoftraindemodsettings.h" + +EndOfTrainDemodSettings::EndOfTrainDemodSettings() : + m_channelMarker(nullptr), + m_rollupState(nullptr) +{ + for (int i = 0; i < ENDOFTRAINDEMOD_COLUMNS; i++) + { + m_columnIndexes.append(i); + m_columnSizes.append(-1); + } + resetToDefaults(); +} + +void EndOfTrainDemodSettings::resetToDefaults() +{ + m_inputFrequencyOffset = 0; + m_rfBandwidth = 20000.0f; + m_fmDeviation = 3000.0f; + m_filterFrom = ""; + m_udpEnabled = false; + m_udpAddress = "127.0.0.1"; + m_udpPort = 9999; + m_logFilename = "endoftrain_log.csv"; + m_logEnabled = false; + + m_rgbColor = QColor(0, 105, 2).rgb(); + m_title = "End-of-Train 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 < ENDOFTRAINDEMOD_COLUMNS; i++) + { + m_columnIndexes[i] = i; + m_columnSizes[i] = -1; // Autosize + } +} + +QByteArray EndOfTrainDemodSettings::serialize() const +{ + SimpleSerializer s(1); + + s.writeS32(1, m_inputFrequencyOffset); + s.writeFloat(2, m_rfBandwidth); + s.writeFloat(3, m_fmDeviation); + s.writeString(4, m_filterFrom); + s.writeBool(5, m_udpEnabled); + s.writeString(6, m_udpAddress); + s.writeU32(7, m_udpPort); + s.writeString(8, m_logFilename); + s.writeBool(9, m_logEnabled); + + 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_rollupState) { + s.writeBlob(29, m_rollupState->serialize()); + } + s.writeS32(30, m_workspaceIndex); + s.writeBlob(31, m_geometryBytes); + s.writeBool(32, m_hidden); + + s.writeList(33, m_columnIndexes); + s.writeList(34, m_columnSizes); + + return s.final(); +} + +bool EndOfTrainDemodSettings::deserialize(const QByteArray& data) +{ + SimpleDeserializer d(data); + + if(!d.isValid()) + { + resetToDefaults(); + return false; + } + + if(d.getVersion() == 1) + { + QByteArray bytetmp; + uint32_t utmp; + QString strtmp; + + d.readS32(1, &m_inputFrequencyOffset, 0); + d.readFloat(2, &m_rfBandwidth, 20000.0f); + d.readFloat(3, &m_fmDeviation, 3000.0f); + d.readString(4, &m_filterFrom, ""); + d.readBool(5, &m_udpEnabled); + d.readString(6, &m_udpAddress); + d.readU32(7, &utmp); + if ((utmp > 1023) && (utmp < 65535)) { + m_udpPort = utmp; + } else { + m_udpPort = 9999; + } + d.readString(8, &m_logFilename, "endoftrain_log.csv"); + d.readBool(9, &m_logEnabled, false); + + d.readU32(20, &m_rgbColor, QColor(0, 105, 2).rgb()); + d.readString(21, &m_title, "End-of-Train 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_rollupState) + { + d.readBlob(29, &bytetmp); + m_rollupState->deserialize(bytetmp); + } + + d.readS32(30, &m_workspaceIndex, 0); + d.readBlob(31, &m_geometryBytes); + d.readBool(32, &m_hidden, false); + + d.readList(33, &m_columnIndexes); + d.readList(34, &m_columnSizes); + + return true; + } + else + { + resetToDefaults(); + return false; + } +} + +void EndOfTrainDemodSettings::applySettings(const QStringList& settingsKeys, const EndOfTrainDemodSettings& settings) +{ + if (settingsKeys.contains("inputFrequencyOffset")) { + m_inputFrequencyOffset = settings.m_inputFrequencyOffset; + } + if (settingsKeys.contains("rfBandwidth")) { + m_rfBandwidth = settings.m_rfBandwidth; + } + if (settingsKeys.contains("fmDeviation")) { + m_fmDeviation = settings.m_fmDeviation; + } + if (settingsKeys.contains("filterFrom")) { + m_filterFrom = settings.m_filterFrom; + } + if (settingsKeys.contains("udpEnabled")) { + m_udpEnabled = settings.m_udpEnabled; + } + if (settingsKeys.contains("udpAddress")) { + m_udpAddress = settings.m_udpAddress; + } + if (settingsKeys.contains("udpPort")) { + m_udpPort = settings.m_udpPort; + } + if (settingsKeys.contains("logFilename")) { + m_logFilename = settings.m_logFilename; + } + if (settingsKeys.contains("logEnabledpPort")) { + m_logEnabled = settings.m_logEnabled; + } + 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("hidden")) { + m_hidden = settings.m_hidden; + } + if (settingsKeys.contains("columnIndexes")) { + m_columnIndexes = settings.m_columnIndexes; + } + if (settingsKeys.contains("columnSizes")) { + m_columnSizes = settings.m_columnSizes; + } +} + +QString EndOfTrainDemodSettings::getDebugString(const QStringList& settingsKeys, bool force) const +{ + std::ostringstream ostr; + + if (settingsKeys.contains("inputFrequencyOffset") || force) { + ostr << " m_inputFrequencyOffset: " << m_inputFrequencyOffset; + } + if (settingsKeys.contains("rfBandwidth")) { + ostr << " m_rfBandwidth: " << m_rfBandwidth; + } + if (settingsKeys.contains("fmDeviation")) { + ostr << " m_fmDeviation: " << m_fmDeviation; + } + if (settingsKeys.contains("filterFrom")) { + ostr << " m_filterFrom: " << m_filterFrom.toStdString(); + } + if (settingsKeys.contains("udpEnabled")) { + ostr << " m_udpEnabled: " << m_udpEnabled; + } + if (settingsKeys.contains("udpAddress")) { + ostr << " m_udpAddress: " << m_udpAddress.toStdString(); + } + if (settingsKeys.contains("udpPort")) { + ostr << " m_udpPort: " << m_udpPort; + } + if (settingsKeys.contains("logFilename")) { + ostr << " m_logFilename: " << m_logFilename.toStdString(); + } + if (settingsKeys.contains("logEnabledpPort")) { + ostr << " m_logEnabled: " << m_logEnabled; + } + 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; + } + if (settingsKeys.contains("columnIndexes") || force) { + // Don't display + } + if (settingsKeys.contains("columnSizes") || force) { + // Don't display + } + + return QString(ostr.str().c_str()); +} diff --git a/plugins/channelrx/demodendoftrain/endoftraindemodsettings.h b/plugins/channelrx/demodendoftrain/endoftraindemodsettings.h new file mode 100644 index 000000000..a2d1545fd --- /dev/null +++ b/plugins/channelrx/demodendoftrain/endoftraindemodsettings.h @@ -0,0 +1,78 @@ +/////////////////////////////////////////////////////////////////////////////////// +// Copyright (C) 2012 maintech GmbH, Otto-Hahn-Str. 15, 97204 Hoechberg, Germany // +// written by Christian Daniel // +// Copyright (C) 2015-2019, 2021-2022 Edouard Griffiths, F4EXB // +// Copyright (C) 2021-2024 Jon Beniston, M7RCE // +// // +// This program is free software; you can redistribute it and/or modify // +// it under the terms of the GNU General Public License as published by // +// the Free Software Foundation as version 3 of the License, or // +// (at your option) any later version. // +// // +// This program is distributed in the hope that it will be useful, // +// but WITHOUT ANY WARRANTY; without even the implied warranty of // +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // +// GNU General Public License V3 for more details. // +// // +// You should have received a copy of the GNU General Public License // +// along with this program. If not, see . // +/////////////////////////////////////////////////////////////////////////////////// + +#ifndef INCLUDE_ENDOFTRAINDEMODSETTINGS_H +#define INCLUDE_ENDOFTRAINDEMODSETTINGS_H + +#include +#include + +#include "dsp/dsptypes.h" + +class Serializable; + +// Number of columns in the table +#define ENDOFTRAINDEMOD_COLUMNS 18 + +struct EndOfTrainDemodSettings +{ + qint32 m_inputFrequencyOffset; + Real m_rfBandwidth; + Real m_fmDeviation; + QString m_filterFrom; + bool m_udpEnabled; + QString m_udpAddress; + uint16_t m_udpPort; + QString m_logFilename; + bool m_logEnabled; + + quint32 m_rgbColor; + QString m_title; + Serializable *m_channelMarker; + int m_streamIndex; //!< MIMO channel. Not relevant when connected to SI (single Rx). + bool m_useReverseAPI; + QString m_reverseAPIAddress; + uint16_t m_reverseAPIPort; + uint16_t m_reverseAPIDeviceIndex; + uint16_t m_reverseAPIChannelIndex; + + Serializable *m_rollupState; + int m_workspaceIndex; + QByteArray m_geometryBytes; + bool m_hidden; + + QList m_columnIndexes; //!< How the columns are ordered in the table + QList m_columnSizes; //!< Size of the columns in the table + + static const int CHANNEL_SAMPLE_RATE = 48000; // Must be integer multiple of baud rate + static const int BAUD_RATE = 1200; + static const int m_scopeStreams = 9; + + EndOfTrainDemodSettings(); + void resetToDefaults(); + void setChannelMarker(Serializable *channelMarker) { m_channelMarker = channelMarker; } + void setRollupState(Serializable *rollupState) { m_rollupState = rollupState; } + QByteArray serialize() const; + bool deserialize(const QByteArray& data); + void applySettings(const QStringList& settingsKeys, const EndOfTrainDemodSettings& settings); + QString getDebugString(const QStringList& settingsKeys, bool force = false) const; +}; + +#endif /* INCLUDE_ENDOFTRAINDEMODSETTINGS_H */ diff --git a/plugins/channelrx/demodendoftrain/endoftraindemodsink.cpp b/plugins/channelrx/demodendoftrain/endoftraindemodsink.cpp new file mode 100644 index 000000000..2c73c8f08 --- /dev/null +++ b/plugins/channelrx/demodendoftrain/endoftraindemodsink.cpp @@ -0,0 +1,348 @@ +/////////////////////////////////////////////////////////////////////////////////// +// Copyright (C) 2021-2024 Jon Beniston, M7RCE // +// Copyright (C) 2021-2022 Edouard Griffiths, F4EXB // +// // +// This program is free software; you can redistribute it and/or modify // +// it under the terms of the GNU General Public License as published by // +// the Free Software Foundation as version 3 of the License, or // +// (at your option) any later version. // +// // +// This program is distributed in the hope that it will be useful, // +// but WITHOUT ANY WARRANTY; without even the implied warranty of // +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // +// GNU General Public License V3 for more details. // +// // +// You should have received a copy of the GNU General Public License // +// along with this program. If not, see . // +/////////////////////////////////////////////////////////////////////////////////// + +#include + +#include "dsp/dspengine.h" +#include "dsp/datafifo.h" +#include "util/db.h" +#include "maincore.h" + +#include "endoftraindemod.h" +#include "endoftraindemodsink.h" + +EndOfTrainDemodSink::EndOfTrainDemodSink(EndOfTrainDemod *endoftrainDemod) : + m_scopeSink(nullptr), + m_endoftrainDemod(endoftrainDemod), + m_channelSampleRate(EndOfTrainDemodSettings::CHANNEL_SAMPLE_RATE), + m_channelFrequencyOffset(0), + m_magsqSum(0.0f), + m_magsqPeak(0.0f), + m_magsqCount(0), + m_messageQueueToChannel(nullptr), + m_f1(nullptr), + m_f0(nullptr), + m_corrBuf(nullptr), + m_corrIdx(0), + m_corrCnt(0), + m_sampleBufferIndex(0) +{ + m_magsq = 0.0; + + m_demodBuffer.resize(1<<12); + m_demodBufferFill = 0; + for (int i = 0; i < EndOfTrainDemodSettings::m_scopeStreams; i++) { + m_sampleBuffer[i].resize(m_sampleBufferSize); + } + + applySettings(m_settings, QStringList(), true); + applyChannelSettings(m_channelSampleRate, m_channelFrequencyOffset, true); +} + +EndOfTrainDemodSink::~EndOfTrainDemodSink() +{ + delete[] m_f1; + delete[] m_f0; + delete[] m_corrBuf; +} + +void EndOfTrainDemodSink::sampleToScope(Complex sample, Real s1, Real s2, Real s3, Real s4, Real s5, Real s6, Real s7, Real s8) +{ + if (m_scopeSink) + { + m_sampleBuffer[0][m_sampleBufferIndex] = sample; + m_sampleBuffer[1][m_sampleBufferIndex] = Complex(s1, 0.0f); + m_sampleBuffer[2][m_sampleBufferIndex] = Complex(s2, 0.0f); + m_sampleBuffer[3][m_sampleBufferIndex] = Complex(s3, 0.0f); + m_sampleBuffer[4][m_sampleBufferIndex] = Complex(s4, 0.0f); + m_sampleBuffer[5][m_sampleBufferIndex] = Complex(s5, 0.0f); + m_sampleBuffer[6][m_sampleBufferIndex] = Complex(s6, 0.0f); + m_sampleBuffer[7][m_sampleBufferIndex] = Complex(s7, 0.0f); + m_sampleBuffer[8][m_sampleBufferIndex] = Complex(s8, 0.0f); + m_sampleBufferIndex++; + if (m_sampleBufferIndex == m_sampleBufferSize) + { + std::vector vbegin; + + for (int i = 0; i < EndOfTrainDemodSettings::m_scopeStreams; i++) { + vbegin.push_back(m_sampleBuffer[i].begin()); + } + + m_scopeSink->feed(vbegin, m_sampleBufferSize); + m_sampleBufferIndex = 0; + } + } +} + +void EndOfTrainDemodSink::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 EndOfTrainDemodSink::processOneSample(Complex &ci) +{ + Complex ca; + + // FM demodulation + double magsqRaw; + Real deviation; + Real fmDemod = m_phaseDiscri.phaseDiscriminatorDelta(ci, magsqRaw, deviation); + + // Calculate average and peak levels for level meter + Real magsq = magsqRaw / (SDR_RX_SCALED*SDR_RX_SCALED); + m_movingAverage(magsq); + m_magsq = m_movingAverage.asDouble(); + m_magsqSum += magsq; + if (magsq > m_magsqPeak) + { + m_magsqPeak = magsq; + } + m_magsqCount++; + + Real f0Filt = 0.0f; + Real f1Filt = 0.0f; + float diff = 0.0; + int sample = 0; + int bit = 0; + + m_corrBuf[m_corrIdx] = fmDemod; + if (m_corrCnt >= m_correlationLength) + { + // Correlate with 1200 + 1800 baud complex exponentials + Complex corrF0 = 0.0f; + Complex corrF1 = 0.0f; + for (int i = 0; i < m_correlationLength; i++) + { + int j = m_corrIdx - i; + if (j < 0) + j += m_correlationLength; + corrF0 += m_f0[i] * m_corrBuf[j]; + corrF1 += m_f1[i] * m_corrBuf[j]; + } + m_corrCnt--; // Avoid overflow in increment below + + // Low pass filter, to minimize changes above the baud rate + f0Filt = m_lowpassF0.filter(std::abs(corrF0)); + f1Filt = m_lowpassF1.filter(std::abs(corrF1)); + + // Determine which is the closest match and then quantise to 1 or -1 + diff = f1Filt - f0Filt; + sample = diff >= 0.0f ? 1 : 0; + + // Look for edge + if (sample != m_samplePrev) + { + m_syncCount = EndOfTrainDemodSettings::CHANNEL_SAMPLE_RATE/EndOfTrainDemodSettings::BAUD_RATE/2; + } + else + { + m_syncCount--; + if (m_syncCount <= 0) + { + bit = sample; + + // Store in shift reg - LSB first + m_bits |= bit << m_bitCount; + + m_bitCount++; + + if (!m_gotSOP) + { + if (m_bitCount >= 17) + { + // Look for frame sync + if ((m_bits & 0x1ffff) == 0x91D5) + { + // Start of packet + m_gotSOP = true; + m_bits = 0; + m_bitCount = 0; + m_byteCount = 0; + } + else + { + m_bitCount--; + m_bits >>= 1; + } + } + } + else + { + if (m_bitCount == 8) + { + if (m_byteCount == 8) + { + QByteArray rxPacket((char *)m_bytes, m_byteCount); + //qDebug() << "RX: " << rxPacket.toHex(); + if (getMessageQueueToChannel()) + { + MainCore::MsgPacket *msg = MainCore::MsgPacket::create(m_endoftrainDemod, rxPacket, QDateTime::currentDateTime()); + getMessageQueueToChannel()->push(msg); + } + // Reset state to start receiving next packet + m_gotSOP = false; + m_bits = 0; + m_bitCount = 0; + m_byteCount = 0; + } + else + { + m_bytes[m_byteCount] = m_bits; + m_byteCount++; + } + m_bits = 0; + m_bitCount = 0; + } + } + m_syncCount = EndOfTrainDemodSettings::CHANNEL_SAMPLE_RATE/EndOfTrainDemodSettings::BAUD_RATE; + } + } + m_samplePrev = sample; + } + m_corrIdx = (m_corrIdx + 1) % m_correlationLength; + m_corrCnt++; + + // Select signals to feed to scope + sampleToScope(ci / SDR_RX_SCALEF, magsq, fmDemod, f0Filt, f1Filt, diff, sample, bit, m_gotSOP); + + // Send demod signal to Demod Analzyer feature + m_demodBuffer[m_demodBufferFill++] = fmDemod * std::numeric_limits::max(); + + if (m_demodBufferFill >= m_demodBuffer.size()) + { + QList dataPipes; + MainCore::instance()->getDataPipes().getDataPipes(m_channel, "demod", dataPipes); + + if (dataPipes.size() > 0) + { + QList::iterator it = dataPipes.begin(); + + for (; it != dataPipes.end(); ++it) + { + DataFifo *fifo = qobject_cast((*it)->m_element); + + if (fifo) { + fifo->write((quint8*) &m_demodBuffer[0], m_demodBuffer.size() * sizeof(qint16), DataFifo::DataTypeI16); + } + } + } + + m_demodBufferFill = 0; + } +} + +void EndOfTrainDemodSink::applyChannelSettings(int channelSampleRate, int channelFrequencyOffset, bool force) +{ + qDebug() << "EndOfTrainDemodSink::applyChannelSettings:" + << " channelSampleRate: " << channelSampleRate + << " channelFrequencyOffset: " << channelFrequencyOffset; + + if ((m_channelFrequencyOffset != channelFrequencyOffset) || + (m_channelSampleRate != channelSampleRate) || force) + { + m_nco.setFreq(-channelFrequencyOffset, channelSampleRate); + } + + if ((m_channelSampleRate != channelSampleRate) || force) + { + m_interpolator.create(16, channelSampleRate, m_settings.m_rfBandwidth / 2.2); + m_interpolatorDistance = (Real) channelSampleRate / (Real) EndOfTrainDemodSettings::CHANNEL_SAMPLE_RATE; + m_interpolatorDistanceRemain = m_interpolatorDistance; + } + + m_channelSampleRate = channelSampleRate; + m_channelFrequencyOffset = channelFrequencyOffset; +} + +void EndOfTrainDemodSink::applySettings(const EndOfTrainDemodSettings& settings, const QStringList& settingsKeys, bool force) +{ + qDebug() << "EndOfTrainDemodSink::applySettings:" + << settings.getDebugString(settingsKeys, force) + << " force: " << force; + + if (settingsKeys.contains("rfBandwidth") || force) + { + m_interpolator.create(16, m_channelSampleRate, settings.m_rfBandwidth / 2.2); + m_interpolatorDistance = (Real) m_channelSampleRate / (Real) EndOfTrainDemodSettings::CHANNEL_SAMPLE_RATE; + m_interpolatorDistanceRemain = m_interpolatorDistance; + } + if (settingsKeys.contains("fmDeviation") || force) + { + m_phaseDiscri.setFMScaling(EndOfTrainDemodSettings::CHANNEL_SAMPLE_RATE / (2.0f * settings.m_fmDeviation)); + } + + if (force) + { + delete[] m_f1; + delete[] m_f0; + delete[] m_corrBuf; + m_correlationLength = EndOfTrainDemodSettings::CHANNEL_SAMPLE_RATE/EndOfTrainDemodSettings::BAUD_RATE; + m_f1 = new Complex[m_correlationLength](); + m_f0 = new Complex[m_correlationLength](); + m_corrBuf = new Complex[m_correlationLength](); + m_corrIdx = 0; + m_corrCnt = 0; + Real f0 = 0.0f; + Real f1 = 0.0f; + for (int i = 0; i < m_correlationLength; i++) + { + m_f0[i] = Complex(cos(f0), sin(f0)); + m_f1[i] = Complex(cos(f1), sin(f1)); + f0 += 2.0f*(Real)M_PI*1800.0f/EndOfTrainDemodSettings::CHANNEL_SAMPLE_RATE; + f1 += 2.0f*(Real)M_PI*1200.0f/EndOfTrainDemodSettings::CHANNEL_SAMPLE_RATE; + } + + m_lowpassF1.create(301, EndOfTrainDemodSettings::CHANNEL_SAMPLE_RATE, EndOfTrainDemodSettings::BAUD_RATE * 1.1f); + m_lowpassF0.create(301, EndOfTrainDemodSettings::CHANNEL_SAMPLE_RATE, EndOfTrainDemodSettings::BAUD_RATE * 1.1f); + m_samplePrev = 0; + m_syncCount = 0; + m_bits = 0; + m_bitCount = 0; + m_gotSOP = false; + m_byteCount = 0; + } + + if (force) { + m_settings = settings; + } else { + m_settings.applySettings(settingsKeys, settings); + } +} diff --git a/plugins/channelrx/demodendoftrain/endoftraindemodsink.h b/plugins/channelrx/demodendoftrain/endoftraindemodsink.h new file mode 100644 index 000000000..869fb6a43 --- /dev/null +++ b/plugins/channelrx/demodendoftrain/endoftraindemodsink.h @@ -0,0 +1,138 @@ +/////////////////////////////////////////////////////////////////////////////////// +// Copyright (C) 2019-2021 Edouard Griffiths, F4EXB // +// Copyright (C) 2020-2024 Jon Beniston, M7RCE // +// Copyright (C) 2020 Kacper Michajłow // +// // +// 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_ENDOFTRAINDEMODSINK_H +#define INCLUDE_ENDOFTRAINDEMODSINK_H + +#include + +#include "dsp/channelsamplesink.h" +#include "dsp/phasediscri.h" +#include "dsp/nco.h" +#include "dsp/interpolator.h" +#include "dsp/firfilter.h" +#include "util/movingaverage.h" +#include "util/messagequeue.h" + +#include "endoftraindemodsettings.h" + +class ChannelAPI; +class EndOfTrainDemod; +class ScopeVis; + +class EndOfTrainDemodSink : public ChannelSampleSink { +public: + EndOfTrainDemodSink(EndOfTrainDemod *endoftrainDemod); + ~EndOfTrainDemodSink(); + + 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 EndOfTrainDemodSettings& settings, const QStringList& settingsKeys, 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; // Scope GUI to display baseband waveform + EndOfTrainDemod *m_endoftrainDemod; + EndOfTrainDemodSettings m_settings; + ChannelAPI *m_channel; + int m_channelSampleRate; + int m_channelFrequencyOffset; + + 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; + + PhaseDiscriminators m_phaseDiscri; + + int m_correlationLength; + Complex *m_f1; + Complex *m_f0; + Complex *m_corrBuf; + int m_corrIdx; + int m_corrCnt; + + Lowpass m_lowpassF1; + Lowpass m_lowpassF0; + + int m_samplePrev; + int m_syncCount; + quint32 m_bits; + int m_bitCount; + bool m_gotSOP; + unsigned char m_bytes[8]; + int m_byteCount; + + QVector m_demodBuffer; + int m_demodBufferFill; + + ComplexVector m_sampleBuffer[EndOfTrainDemodSettings::m_scopeStreams]; + static const int m_sampleBufferSize = EndOfTrainDemodSettings::CHANNEL_SAMPLE_RATE / 20; + int m_sampleBufferIndex; + + void processOneSample(Complex &ci); + MessageQueue *getMessageQueueToChannel() { return m_messageQueueToChannel; } + void sampleToScope(Complex sample, Real s1, Real s2, Real s3, Real s4, Real s5, Real s6, Real s7, Real s8); +}; + +#endif // INCLUDE_ENDOFTRAINDEMODSINK_H diff --git a/plugins/channelrx/demodendoftrain/endoftraindemodwebapiadapter.cpp b/plugins/channelrx/demodendoftrain/endoftraindemodwebapiadapter.cpp new file mode 100644 index 000000000..626d1543d --- /dev/null +++ b/plugins/channelrx/demodendoftrain/endoftraindemodwebapiadapter.cpp @@ -0,0 +1,54 @@ +/////////////////////////////////////////////////////////////////////////////////// +// Copyright (C) 2012 maintech GmbH, Otto-Hahn-Str. 15, 97204 Hoechberg, Germany // +// written by Christian Daniel // +// Copyright (C) 2015-2020 Edouard Griffiths, F4EXB // +// Copyright (C) 2021-2024 Jon Beniston, M7RCE // +// // +// This program is free software; you can redistribute it and/or modify // +// it under the terms of the GNU General Public License as published by // +// the Free Software Foundation as version 3 of the License, or // +// (at your option) any later version. // +// // +// This program is distributed in the hope that it will be useful, // +// but WITHOUT ANY WARRANTY; without even the implied warranty of // +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // +// GNU General Public License V3 for more details. // +// // +// You should have received a copy of the GNU General Public License // +// along with this program. If not, see . // +/////////////////////////////////////////////////////////////////////////////////// + +#include "SWGChannelSettings.h" +#include "endoftraindemod.h" +#include "endoftraindemodwebapiadapter.h" + +EndOfTrainDemodWebAPIAdapter::EndOfTrainDemodWebAPIAdapter() +{} + +EndOfTrainDemodWebAPIAdapter::~EndOfTrainDemodWebAPIAdapter() +{} + +int EndOfTrainDemodWebAPIAdapter::webapiSettingsGet( + SWGSDRangel::SWGChannelSettings& response, + QString& errorMessage) +{ + (void) errorMessage; + response.setEndOfTrainDemodSettings(new SWGSDRangel::SWGEndOfTrainDemodSettings()); + response.getEndOfTrainDemodSettings()->init(); + EndOfTrainDemod::webapiFormatChannelSettings(response, m_settings); + + return 200; +} + +int EndOfTrainDemodWebAPIAdapter::webapiSettingsPutPatch( + bool force, + const QStringList& channelSettingsKeys, + SWGSDRangel::SWGChannelSettings& response, + QString& errorMessage) +{ + (void) force; + (void) errorMessage; + EndOfTrainDemod::webapiUpdateChannelSettings(m_settings, channelSettingsKeys, response); + + return 200; +} diff --git a/plugins/channelrx/demodendoftrain/endoftraindemodwebapiadapter.h b/plugins/channelrx/demodendoftrain/endoftraindemodwebapiadapter.h new file mode 100644 index 000000000..ad903189e --- /dev/null +++ b/plugins/channelrx/demodendoftrain/endoftraindemodwebapiadapter.h @@ -0,0 +1,50 @@ +/////////////////////////////////////////////////////////////////////////////////// +// Copyright (C) 2019 Edouard Griffiths, F4EXB // +// Copyright (C) 2020-2024 Jon Beniston, M7RCE // +// // +// This program is free software; you can redistribute it and/or modify // +// it under the terms of the GNU General Public License as published by // +// the Free Software Foundation as version 3 of the License, or // +// (at your option) any later version. // +// // +// This program is distributed in the hope that it will be useful, // +// but WITHOUT ANY WARRANTY; without even the implied warranty of // +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // +// GNU General Public License V3 for more details. // +// // +// You should have received a copy of the GNU General Public License // +// along with this program. If not, see . // +/////////////////////////////////////////////////////////////////////////////////// + +#ifndef INCLUDE_ENDOFTRAINDEMOD_WEBAPIADAPTER_H +#define INCLUDE_ENDOFTRAINDEMOD_WEBAPIADAPTER_H + +#include "channel/channelwebapiadapter.h" +#include "endoftraindemodsettings.h" + +/** + * Standalone API adapter only for the settings + */ +class EndOfTrainDemodWebAPIAdapter : public ChannelWebAPIAdapter { +public: + EndOfTrainDemodWebAPIAdapter(); + virtual ~EndOfTrainDemodWebAPIAdapter(); + + 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: + EndOfTrainDemodSettings m_settings; +}; + +#endif // INCLUDE_ENDOFTRAINDEMOD_WEBAPIADAPTER_H diff --git a/plugins/channelrx/demodendoftrain/endoftrainpacket.cpp b/plugins/channelrx/demodendoftrain/endoftrainpacket.cpp new file mode 100644 index 000000000..38e3c1c31 --- /dev/null +++ b/plugins/channelrx/demodendoftrain/endoftrainpacket.cpp @@ -0,0 +1,99 @@ +/////////////////////////////////////////////////////////////////////////////////// +// Copyright (C) 2024 Jon Beniston, M7RCE // +// Copyright (C) 2018 Eric Reuter // +// // +// 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 "endoftrainpacket.h" + +#include "util/crc.h" + +// Reverse order of bits +static quint32 reverse(quint32 x) +{ + x = (((x & 0xaaaaaaaa) >> 1) | ((x & 0x55555555) << 1)); + x = (((x & 0xcccccccc) >> 2) | ((x & 0x33333333) << 2)); + x = (((x & 0xf0f0f0f0) >> 4) | ((x & 0x0f0f0f0f) << 4)); + x = (((x & 0xff00ff00) >> 8) | ((x & 0x00ff00ff) << 8)); + return((x >> 16) | (x << 16)); +} + +// Reverse order of bits, for specified number of bits +static quint32 reverseBits(quint32 x, int bits) +{ + return reverse(x) >> (32-bits); +} + +// Decode end-of-train packet +// Defined in: +// AAR MSRP (Manual of Standards and Recommended Practices) - Section K Part II Locomotive Electronics and Train Consist System Architecture - S-9152 End of Train Communication +// but not readily available, so see: +// https://patents.google.com/patent/US5374015A/en +// https://rdso.indianrailways.gov.in/uploads/files/TC0156_15_02_2022.pdf + +bool EndOfTrainPacket::decode(const QByteArray& packet) +{ + //qDebug() << packet.toHex(); + + if (packet.size() != 8) { + return false; + } + + m_chainingBits = packet[0] & 0x3; + + m_batteryCondition = (packet[0] >> 2) & 0x3; + + m_type = (packet[0] >> 4) & 0x7; + + m_address = ((packet[2] & 0xff) << 9) | ((packet[1] & 0xff) << 1) | ((packet[0] >> 7) & 0x1); + + m_pressure = packet[3] & 0x7f; + + m_discretionary = (packet[3] >> 7) & 1; + + m_batteryCharge = packet[4] & 0x7f; + + m_valveCircuitStatus = (packet[4] >> 7) & 1; + + m_confirmation = packet[5] & 1; + m_turbine = (packet[5] >> 1) & 1; + m_motion = (packet[5] >> 2) & 1; + m_markerLightBatteryCondition = (packet[5] >> 3) & 1; + m_markerLightStatus = (packet[5] >> 4) & 1; + + // Calculate and compare CRC + + crc crc18(18, 0x39A0F, true, 0, 0x2b770); + + // 45-bits are protected + crc18.calculate(packet[5] & 0x1f, 5); + crc18.calculate(packet[4] & 0xff, 8); + crc18.calculate(packet[3] & 0xff, 8); + crc18.calculate(packet[2] & 0xff, 8); + crc18.calculate(packet[1] & 0xff, 8); + crc18.calculate(packet[0] & 0xff, 8); + + m_crc = ((packet[7] & 0xff) << 11) | ((packet[6] & 0xff) << 3) | ((packet[5] >> 5) & 0x7); + m_crcCalculated = reverseBits(crc18.get(), 18); + m_crcValid = m_crc == m_crcCalculated; + + if (crc18.get() != m_crc) { + qDebug() << "CRC Mismatch: " << QString::number(crc18.get(), 16) << QString::number(m_crc, 16); + } + + m_dataHex = QString(packet.toHex()); + + return m_crcValid; +} diff --git a/plugins/channelrx/demodendoftrain/endoftrainpacket.h b/plugins/channelrx/demodendoftrain/endoftrainpacket.h new file mode 100644 index 000000000..07aa7caa4 --- /dev/null +++ b/plugins/channelrx/demodendoftrain/endoftrainpacket.h @@ -0,0 +1,98 @@ +/////////////////////////////////////////////////////////////////////////////////// +// Copyright (C) 2024 Jon Beniston, M7RCE // +// Copyright (C) 2018 Eric Reuter // +// // +// 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_ENDOFTRAINPACKET_H +#define INCLUDE_ENDOFTRAINPACKET_H + +#include +#include +#include + +struct EndOfTrainPacket { + + int m_chainingBits; + int m_batteryCondition; // Device battery status + int m_type; // Message type identifier + int m_address; // EOT unit address + int m_pressure; // Rear brake pressure PSIG + int m_batteryCharge; // Battery charge + bool m_discretionary; // Used differently by different vendors + bool m_valveCircuitStatus; + bool m_confirmation; + bool m_turbine; + bool m_motion; // Whether train is in motion + bool m_markerLightBatteryCondition; // Condition of marker light battery + bool m_markerLightStatus; // Whether light is on or off + quint32 m_crc; + quint32 m_crcCalculated; + bool m_crcValid; + + QString m_dataHex; + + bool decode(const QByteArray& packet); + + QString getMessageType() const + { + return QString::number(m_type); + } + + QString getBatteryCondition() const + { + const QStringList batteryConditions = {"N/A", "Very Low", "Low", "OK"}; + return batteryConditions[m_batteryCondition]; + } + + QString getValveCircuitStatus() const + { + return m_valveCircuitStatus ? "OK" : "Fail"; + } + + QString getMarkerLightBatteryCondition() const + { + return m_markerLightBatteryCondition ? "Low" : "Ok"; + } + + QString getMarkerLightStatus() const + { + return m_markerLightStatus ? "On" : "Off"; + } + + float getBatteryChargePercent() const + { + return 100.0f * m_batteryCharge / 127.0f; + } + + QString getArmStatus() const + { + if (m_type == 7) + { + if (m_confirmation == 0) { + return "Arming"; + } else { + return "Armed"; + } + } + else + { + return "Normal"; + } + } + +}; + +#endif // INCLUDE_ENDOFTRAINPACKET_H diff --git a/plugins/channelrx/demodendoftrain/readme.md b/plugins/channelrx/demodendoftrain/readme.md new file mode 100644 index 000000000..4c955feee --- /dev/null +++ b/plugins/channelrx/demodendoftrain/readme.md @@ -0,0 +1,100 @@ +

End-of-Train Demodulator Plugin

+ +

Introduction

+ +This plugin can be used to demodulate End-of-Train packets. These are packets transmitted by an [End-of-Train Device](https://en.wikipedia.org/wiki/End-of-train_device), +that can be found on some trains. +It transmits information about whether motion is detected, brake pressue, whether the marker light is on and battery information. + +* Frequency: 457.9375 MHz (North America, India), 477.7 MHz (Australia) and 450.2625 MHz (New Zealand). +* Modulation: FSK, 1800Hz space, 1200 mark, +-3kHz deviation. +* Baud rate: 1200 baud. + +The End-of-train packet specification is defined in: +AAR Manual of Standards and Recommended Practices - S-9152 End of Train Communication - Section K Part II Locomotive Electronics and Train Consist System Architecture. +If anyone has a copy, please get in touch. + +

Interface

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

+ +This specifies the bandwidth of a LPF that is applied to the input signal to limit the RF bandwidth. + +

5: Frequency deviation

+ +Adjusts the expected frequency deviation in 0.1 kHz steps from 1 to 6 kHz. Typical value is 3 kHz. + +

6: Filter Address

+ +Entering a regular expression in the field displays only packets where the unit address matches the regular expression. + +

7: UDP

+ +When checked, received packets are forwarded to the specified UDP address (8) and port (9). + +

8: UDP address

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

9: UDP port

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

10: Start/stop Logging Packets to .csv File

+ +When checked, writes all received packets to a .csv file. The filename is specified by (11). + +

11: .csv Log Filename

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

12: Read Data from .csv File

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

13: Clear table

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

Received Packets Table

+ +The received packets table displays the contents of the packets that have been received. Only packets with valid CRCs are displayed. + +* Date - Date the packet was received. +* Time - Time the packet was received. +* Battery condition - Whether the battery charge is OK, low, very low or not monitored (N/A). +* Type - Message type identifier. +* Address - Unit address, which uniquely identifies the end-of-train unit. +* Pressure - Brake pipe pressure in Pounds per Square Inch Gauge (PSIG). +* Charge - Battery charge in percent. +* Disc - Discretionary bit that is used for varying data by different vendors. +* Valve - Valve circuit status (Ok or Fail). +* Conf - Confirmation indicator. +* Turbine - Air tubine equiped. +* Motion - Whether motion is detected (i.e. is the rear of the train is moving). +* Light Batt - Marker light battery condition (Ok or Low). +* Light - Marker light status (On or off). +* CRC - Whether the calculated CRC matches the received CRC. +* Hex - The packet data displayed as hexadecimal. + +

Attribution

+ +Based on code and reverse engineering by Eric Reuter diff --git a/plugins/feature/demodanalyzer/demodanalyzersettings.cpp b/plugins/feature/demodanalyzer/demodanalyzersettings.cpp index 0883fe7f7..ea35ed453 100644 --- a/plugins/feature/demodanalyzer/demodanalyzersettings.cpp +++ b/plugins/feature/demodanalyzer/demodanalyzersettings.cpp @@ -33,6 +33,7 @@ const QStringList DemodAnalyzerSettings::m_channelTypes = { QStringLiteral("BFMDemod"), QStringLiteral("DABDemod"), QStringLiteral("DSDDemod"), + QStringLiteral("EndOfTrainDemod"), QStringLiteral("FT8Demod"), QStringLiteral("M17Demod"), QStringLiteral("M17Mmod"), @@ -57,6 +58,7 @@ const QStringList DemodAnalyzerSettings::m_channelURIs = { QStringLiteral("sdrangel.channel.bfm"), QStringLiteral("sdrangel.channel.dabdemod"), QStringLiteral("sdrangel.channel.dsddemod"), + QStringLiteral("sdrangel.channel.endoftraindemod"), QStringLiteral("sdrangel.channel.ft8demod"), QStringLiteral("sdrangel.channel.m17demod"), QStringLiteral("sdrangel.channeltx.modm17"), diff --git a/sdrbase/util/crc.cpp b/sdrbase/util/crc.cpp index 63655cf2c..876f24d9d 100644 --- a/sdrbase/util/crc.cpp +++ b/sdrbase/util/crc.cpp @@ -44,7 +44,7 @@ void crc::calculate(uint32_t data, int data_bits) { mask = (1 << m_poly_bits) - 1; msb = 1 << (m_poly_bits - 1); - tmp = m_crc ^ (data << (m_poly_bits - 8)); + tmp = m_crc ^ (data << (m_poly_bits - data_bits)); for (i = 0; i < data_bits; i++) { if (tmp & msb) diff --git a/sdrbase/webapi/webapirequestmapper.cpp b/sdrbase/webapi/webapirequestmapper.cpp index 675faa6af..dad19b7b7 100644 --- a/sdrbase/webapi/webapirequestmapper.cpp +++ b/sdrbase/webapi/webapirequestmapper.cpp @@ -4526,6 +4526,12 @@ bool WebAPIRequestMapper::getChannelSettings( channelSettings->getDsdDemodSettings()->init(); channelSettings->getDsdDemodSettings()->fromJsonObject(settingsJsonObject); } + else if (channelSettingsKey == "EndOfTrainDemodSettings") + { + channelSettings->setEndOfTrainDemodSettings(new SWGSDRangel::SWGEndOfTrainDemodSettings()); + channelSettings->getEndOfTrainDemodSettings()->init(); + channelSettings->getEndOfTrainDemodSettings()->fromJsonObject(settingsJsonObject); + } else if (channelSettingsKey == "FileSinkSettings") { channelSettings->setFileSinkSettings(new SWGSDRangel::SWGFileSinkSettings()); @@ -5523,6 +5529,7 @@ void WebAPIRequestMapper::resetChannelSettings(SWGSDRangel::SWGChannelSettings& channelSettings.setDatvModSettings(nullptr); channelSettings.setDabDemodSettings(nullptr); channelSettings.setDsdDemodSettings(nullptr); + channelSettings.setEndOfTrainDemodSettings(nullptr); channelSettings.setFreqScannerSettings(nullptr); channelSettings.setFreqTrackerSettings(nullptr); channelSettings.setHeatMapSettings(nullptr); @@ -5567,6 +5574,7 @@ void WebAPIRequestMapper::resetChannelReport(SWGSDRangel::SWGChannelReport& chan channelReport.setBfmDemodReport(nullptr); channelReport.setDatvModReport(nullptr); channelReport.setDsdDemodReport(nullptr); + channelReport.setEndOfTrainDemodReport(nullptr); channelReport.setFreqScannerReport(nullptr); channelReport.setFreqTrackerReport(nullptr); channelReport.setHeatMapReport(nullptr); diff --git a/sdrbase/webapi/webapiutils.cpp b/sdrbase/webapi/webapiutils.cpp index d0a524330..24537a8b3 100644 --- a/sdrbase/webapi/webapiutils.cpp +++ b/sdrbase/webapi/webapiutils.cpp @@ -43,6 +43,7 @@ const QMap WebAPIUtils::m_channelURIToSettingsKey = { {"sdrangel.channel.doa2", "DOA2Settings"}, {"sdrangel.channel.dscdemod", "DSCDemodSettings"}, {"sdrangel.channel.dsddemod", "DSDDemodSettings"}, + {"sdrangel.channel.endoftraindemod", "EndOfTrainDemodSettings"}, {"sdrangel.channel.filesink", "FileSinkSettings"}, {"sdrangel.channeltx.filesource", "FileSourceSettings"}, {"sdrangel.channel.freedvdemod", "FreeDVDemodSettings"}, @@ -165,6 +166,7 @@ const QMap WebAPIUtils::m_channelTypeToSettingsKey = { {"DOA2", "DOA2Settings"}, {"DSCDemod", "DSCDemodSettings"}, {"DSDDemod", "DSDDemodSettings"}, + {"EndOfTrainDemod", "EndOfTrainDemodSettings"}, {"FileSink", "FileSinkSettings"}, {"FileSource", "FileSourceSettings"}, {"FreeDVDemod", "FreeDVDemodSettings"},