Browse Source

meshtastic: consolidate LoRa/Meshtastic demod, auto-profile, decode tree, and dechirp replay improvements

chirpmodem-v8.0.0
Alejandro Aleman 9 months ago
parent
commit
40ea5d096f
  1. 2
      CMakeLists.txt
  2. 6
      plugins/channelrx/CMakeLists.txt
  3. 90
      plugins/channelrx/demodmeshtastic/CMakeLists.txt
  4. 1457
      plugins/channelrx/demodmeshtastic/meshtasticdemod.cpp
  5. 228
      plugins/channelrx/demodmeshtastic/meshtasticdemod.h
  6. 190
      plugins/channelrx/demodmeshtastic/meshtasticdemodbaseband.cpp
  7. 89
      plugins/channelrx/demodmeshtastic/meshtasticdemodbaseband.h
  8. 504
      plugins/channelrx/demodmeshtastic/meshtasticdemoddecoder.cpp
  9. 106
      plugins/channelrx/demodmeshtastic/meshtasticdemoddecoder.h
  10. 32
      plugins/channelrx/demodmeshtastic/meshtasticdemoddecoderascii.cpp
  11. 32
      plugins/channelrx/demodmeshtastic/meshtasticdemoddecoderascii.h
  12. 187
      plugins/channelrx/demodmeshtastic/meshtasticdemoddecoderft.cpp
  13. 64
      plugins/channelrx/demodmeshtastic/meshtasticdemoddecoderft.h
  14. 682
      plugins/channelrx/demodmeshtastic/meshtasticdemoddecoderlora.cpp
  15. 483
      plugins/channelrx/demodmeshtastic/meshtasticdemoddecoderlora.h
  16. 67
      plugins/channelrx/demodmeshtastic/meshtasticdemoddecodertty.cpp
  17. 44
      plugins/channelrx/demodmeshtastic/meshtasticdemoddecodertty.h
  18. 3522
      plugins/channelrx/demodmeshtastic/meshtasticdemodgui.cpp
  19. 251
      plugins/channelrx/demodmeshtastic/meshtasticdemodgui.h
  20. 1286
      plugins/channelrx/demodmeshtastic/meshtasticdemodgui.ui
  21. 27
      plugins/channelrx/demodmeshtastic/meshtasticdemodmsg.cpp
  22. 534
      plugins/channelrx/demodmeshtastic/meshtasticdemodmsg.h
  23. 400
      plugins/channelrx/demodmeshtastic/meshtasticdemodsettings.cpp
  24. 111
      plugins/channelrx/demodmeshtastic/meshtasticdemodsettings.h
  25. 1972
      plugins/channelrx/demodmeshtastic/meshtasticdemodsink.cpp
  26. 258
      plugins/channelrx/demodmeshtastic/meshtasticdemodsink.h
  27. 52
      plugins/channelrx/demodmeshtastic/meshtasticdemodwebapiadapter.cpp
  28. 49
      plugins/channelrx/demodmeshtastic/meshtasticdemodwebapiadapter.h
  29. 88
      plugins/channelrx/demodmeshtastic/meshtasticplugin.cpp
  30. 50
      plugins/channelrx/demodmeshtastic/meshtasticplugin.h
  31. 384
      plugins/channelrx/demodmeshtastic/readme.md
  32. 4
      plugins/channeltx/CMakeLists.txt
  33. 90
      plugins/channeltx/modmeshtastic/CMakeLists.txt
  34. 1089
      plugins/channeltx/modmeshtastic/meshtasticmod.cpp
  35. 206
      plugins/channeltx/modmeshtastic/meshtasticmod.h
  36. 201
      plugins/channeltx/modmeshtastic/meshtasticmodbaseband.cpp
  37. 120
      plugins/channeltx/modmeshtastic/meshtasticmodbaseband.h
  38. 181
      plugins/channeltx/modmeshtastic/meshtasticmodencoder.cpp
  39. 57
      plugins/channeltx/modmeshtastic/meshtasticmodencoder.h
  40. 30
      plugins/channeltx/modmeshtastic/meshtasticmodencoderascii.cpp
  41. 32
      plugins/channeltx/modmeshtastic/meshtasticmodencoderascii.h
  42. 246
      plugins/channeltx/modmeshtastic/meshtasticmodencoderft.cpp
  43. 49
      plugins/channeltx/modmeshtastic/meshtasticmodencoderft.h
  44. 148
      plugins/channeltx/modmeshtastic/meshtasticmodencoderlora.cpp
  45. 274
      plugins/channeltx/modmeshtastic/meshtasticmodencoderlora.h
  46. 133
      plugins/channeltx/modmeshtastic/meshtasticmodencodertty.cpp
  47. 44
      plugins/channeltx/modmeshtastic/meshtasticmodencodertty.h
  48. 880
      plugins/channeltx/modmeshtastic/meshtasticmodgui.cpp
  49. 135
      plugins/channeltx/modmeshtastic/meshtasticmodgui.h
  50. 1260
      plugins/channeltx/modmeshtastic/meshtasticmodgui.ui
  51. 96
      plugins/channeltx/modmeshtastic/meshtasticmodplugin.cpp
  52. 51
      plugins/channeltx/modmeshtastic/meshtasticmodplugin.h
  53. 492
      plugins/channeltx/modmeshtastic/meshtasticmodsettings.cpp
  54. 123
      plugins/channeltx/modmeshtastic/meshtasticmodsettings.h
  55. 410
      plugins/channeltx/modmeshtastic/meshtasticmodsource.cpp
  56. 112
      plugins/channeltx/modmeshtastic/meshtasticmodsource.h
  57. 52
      plugins/channeltx/modmeshtastic/meshtasticmodwebapiadapter.cpp
  58. 49
      plugins/channeltx/modmeshtastic/meshtasticmodwebapiadapter.h
  59. 272
      plugins/channeltx/modmeshtastic/readme.md
  60. 2167
      plugins/meshtasticcommon/meshtasticpacket.cpp
  61. 90
      plugins/meshtasticcommon/meshtasticpacket.h
  62. 18
      plugins/samplesource/fileinput/fileinput.cpp
  63. 5
      plugins/samplesource/remotetcpinput/remotetcpinput.cpp
  64. 27
      plugins/samplesource/remotetcpinput/remotetcpinputgui.cpp
  65. 76
      sdrbase/channel/channelwebapiutils.cpp
  66. 8
      sdrbase/channel/channelwebapiutils.h
  67. 2
      sdrbase/webapi/webapiutils.cpp

2
CMakeLists.txt

@ -133,6 +133,7 @@ option(ENABLE_CHANNELRX_DEMODM17 "Enable channelrx demodm17 plugin" ON) @@ -133,6 +133,7 @@ option(ENABLE_CHANNELRX_DEMODM17 "Enable channelrx demodm17 plugin" ON)
option(ENABLE_CHANNELRX_FILESINK "Enable channelrx filesink plugin" ON)
option(ENABLE_CHANNELRX_DEMODFREEDV "Enable channelrx demodfreedv plugin" ON)
option(ENABLE_CHANNELRX_DEMODCHIRPCHAT "Enable channelrx demodchirpchat plugin" ON)
option(ENABLE_CHANNELRX_DEMODMESHTASTIC "Enable channelrx demodmeshtastic plugin" ON)
option(ENABLE_CHANNELRX_REMOTESINK "Enable channelrx remotesink plugin" ON)
option(ENABLE_CHANNELRX_REMOTETCPSINK "Enable channelrx remotetcpsink plugin" ON)
option(ENABLE_CHANNELRX_DEMODSSB "Enable channelrx demodssb plugin" ON)
@ -171,6 +172,7 @@ option(ENABLE_CHANNELTX_MODPACKET "Enable channeltx modpacket plugin" ON) @@ -171,6 +172,7 @@ option(ENABLE_CHANNELTX_MODPACKET "Enable channeltx modpacket plugin" ON)
option(ENABLE_CHANNELTX_MODSSB "Enable channeltx modssb plugin" ON)
option(ENABLE_CHANNELTX_UDPSOURCE "Enable channeltx udpsource plugin" ON)
option(ENABLE_CHANNELTX_MODCHIRPCHAT "Enable channeltx modchirpchat plugin" ON)
option(ENABLE_CHANNELTX_MODMESHTASTIC "Enable channeltx modmeshtastic plugin" ON)
option(ENABLE_CHANNELTX_MODWFM "Enable channeltx modwfm plugin" ON)
option(ENABLE_CHANNELTX_MODATV "Enable channeltx modatv plugin" ON)
option(ENABLE_CHANNELTX_MOD802.15.4 "Enable channeltx mod802.15.4 plugin" ON)

6
plugins/channelrx/CMakeLists.txt

@ -85,6 +85,12 @@ else() @@ -85,6 +85,12 @@ else()
message(STATUS "Not building demodchirpchat (ENABLE_CHANNELRX_DEMODCHIRPCHAT=${ENABLE_CHANNELRX_DEMODCHIRPCHAT})")
endif()
if (ENABLE_CHANNELRX_DEMODMESHTASTIC)
add_subdirectory(demodmeshtastic)
else()
message(STATUS "Not building demodmeshtastic (ENABLE_CHANNELRX_DEMODMESHTASTIC=${ENABLE_CHANNELRX_DEMODMESHTASTIC})")
endif()
if (ENABLE_CHANNELRX_DEMODVOR)
add_subdirectory(demodvor)
else()

90
plugins/channelrx/demodmeshtastic/CMakeLists.txt

@ -0,0 +1,90 @@ @@ -0,0 +1,90 @@
project(meshtastic)
if (FT8_SUPPORT)
set(meshtastic_FT8_LIB ft8)
set(meshtastic_FT8_INCLUDE ${CMAKE_SOURCE_DIR}/ft8)
endif()
set(meshtastic_SOURCES
meshtasticdemod.cpp
meshtasticdemodsettings.cpp
meshtasticdemodsink.cpp
meshtasticdemodbaseband.cpp
meshtasticplugin.cpp
meshtasticdemoddecoder.cpp
meshtasticdemoddecodertty.cpp
meshtasticdemoddecoderascii.cpp
meshtasticdemoddecoderlora.cpp
meshtasticdemoddecoderft.cpp
meshtasticdemodmsg.cpp
${CMAKE_SOURCE_DIR}/plugins/meshtasticcommon/meshtasticpacket.cpp
)
set(meshtastic_HEADERS
meshtasticdemod.h
meshtasticdemodsettings.h
meshtasticdemodsink.h
meshtasticdemodbaseband.h
meshtasticdemoddecoder.h
meshtasticdemoddecodertty.h
meshtasticdemoddecoderascii.h
meshtasticdemoddecoderlora.h
meshtasticdemoddecoderft.h
meshtasticdemodmsg.h
meshtasticplugin.h
)
include_directories(
${CMAKE_SOURCE_DIR}/swagger/sdrangel/code/qt5/client
${meshtastic_FT8_INCLUDE}
${CMAKE_SOURCE_DIR}/plugins/meshtasticcommon
)
if(NOT SERVER_MODE)
set(meshtastic_SOURCES
${meshtastic_SOURCES}
meshtasticdemodgui.cpp
meshtasticdemodgui.ui
)
set(meshtastic_HEADERS
${meshtastic_HEADERS}
meshtasticdemodgui.h
)
set(TARGET_NAME ${PLUGINS_PREFIX}demodmeshtastic)
set(TARGET_LIB "Qt::Widgets")
set(TARGET_LIB_GUI "sdrgui")
set(INSTALL_FOLDER ${INSTALL_PLUGINS_DIR})
else()
set(TARGET_NAME ${PLUGINSSRV_PREFIX}demodmeshtasticsrv)
set(TARGET_LIB "")
set(TARGET_LIB_GUI "")
set(INSTALL_FOLDER ${INSTALL_PLUGINSSRV_DIR})
endif()
if(NOT Qt6_FOUND)
add_library(${TARGET_NAME} ${meshtastic_SOURCES})
else()
qt_add_plugin(${TARGET_NAME} CLASS_NAME MeshtasticPlugin ${meshtastic_SOURCES})
endif()
if(NOT BUILD_SHARED_LIBS)
set_property(GLOBAL APPEND PROPERTY STATIC_PLUGINS_PROPERTY ${TARGET_NAME})
endif()
target_link_libraries(${TARGET_NAME} PRIVATE
Qt::Core
${TARGET_LIB}
sdrbase
${TARGET_LIB_GUI}
swagger
${meshtastic_FT8_LIB}
)
install(TARGETS ${TARGET_NAME} DESTINATION ${INSTALL_FOLDER})
# Install debug symbols
if (WIN32)
install(FILES $<TARGET_PROPERTY:${TARGET_NAME},RUNTIME_OUTPUT_DIRECTORY>/${TARGET_NAME}stripped.pdb CONFIGURATIONS Release DESTINATION ${INSTALL_FOLDER} RENAME ${TARGET_NAME}.pdb )
install(FILES $<TARGET_PDB_FILE:${TARGET_NAME}> CONFIGURATIONS Debug RelWithDebInfo DESTINATION ${INSTALL_FOLDER} )
endif()

1457
plugins/channelrx/demodmeshtastic/meshtasticdemod.cpp

File diff suppressed because it is too large Load Diff

228
plugins/channelrx/demodmeshtastic/meshtasticdemod.h

@ -0,0 +1,228 @@ @@ -0,0 +1,228 @@
///////////////////////////////////////////////////////////////////////////////////
// Copyright (C) 2012 maintech GmbH, Otto-Hahn-Str. 15, 97204 Hoechberg, Germany //
// written by Christian Daniel //
// Copyright (C) 2015-2017, 2019-2020, 2022 Edouard Griffiths, F4EXB <f4exb06@gmail.com> //
// Copyright (C) 2015 John Greb <hexameron@spam.no> //
// Copyright (C) 2020 Kacper Michajłow <kasper93@gmail.com> //
// (C) 2015 John Greb //
// (C) 2020 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 <http://www.gnu.org/licenses/>. //
///////////////////////////////////////////////////////////////////////////////////
#ifndef INCLUDE_MESHTASTICDEMOD_H
#define INCLUDE_MESHTASTICDEMOD_H
#include <vector>
#include <QNetworkRequest>
#include "dsp/basebandsamplesink.h"
#include "dsp/spectrumvis.h"
#include "channel/channelapi.h"
#include "util/message.h"
#include "util/udpsinkutil.h"
#include "meshtasticdemodbaseband.h"
class QNetworkAccessManager;
class QNetworkReply;
class DeviceAPI;
class QThread;
class ObjectPipe;
class MeshtasticDemodDecoder;
namespace Meshtastic { struct TxRadioSettings; }
class MeshtasticDemod : public BasebandSampleSink, public ChannelAPI {
public:
class MsgConfigureMeshtasticDemod : public Message {
MESSAGE_CLASS_DECLARATION
public:
const MeshtasticDemodSettings& getSettings() const { return m_settings; }
bool getForce() const { return m_force; }
static MsgConfigureMeshtasticDemod* create(const MeshtasticDemodSettings& settings, bool force)
{
return new MsgConfigureMeshtasticDemod(settings, force);
}
private:
MeshtasticDemodSettings m_settings;
bool m_force;
MsgConfigureMeshtasticDemod(const MeshtasticDemodSettings& settings, bool force) :
Message(),
m_settings(settings),
m_force(force)
{ }
};
MeshtasticDemod(DeviceAPI* deviceAPI);
virtual ~MeshtasticDemod();
virtual void destroy() { delete this; }
virtual void setDeviceAPI(DeviceAPI *deviceAPI);
virtual DeviceAPI *getDeviceAPI() { return m_deviceAPI; }
SpectrumVis *getSpectrumVis() { return &m_spectrumVis; }
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 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 MeshtasticDemodSettings& settings);
static void webapiUpdateChannelSettings(
MeshtasticDemodSettings& settings,
const QStringList& channelSettingsKeys,
SWGSDRangel::SWGChannelSettings& response);
bool getDemodActive() const;
double getCurrentNoiseLevel() const;
double getTotalPower() const;
uint32_t getNumberOfDeviceStreams() const;
static const char* const m_channelIdURI;
static const char* const m_channelId;
private:
struct PipelineConfig
{
int id = -1;
QString name;
QString presetName;
MeshtasticDemodSettings settings;
};
struct PipelineRuntime
{
int id = -1;
QString name;
QString presetName;
MeshtasticDemodSettings settings;
QThread *basebandThread = nullptr;
QThread *decoderThread = nullptr;
MeshtasticDemodBaseband *basebandSink = nullptr;
MeshtasticDemodDecoder *decoder = nullptr;
};
DeviceAPI *m_deviceAPI;
std::vector<PipelineRuntime> m_pipelines;
bool m_running;
MeshtasticDemodSettings m_settings;
SpectrumVis m_spectrumVis;
int m_basebandSampleRate; //!< stored from device message used when starting baseband sink
qint64 m_basebandCenterFrequency;
bool m_haveBasebandCenterFrequency;
float m_lastMsgSignalDb;
float m_lastMsgNoiseDb;
int m_lastMsgSyncWord;
int m_lastMsgPacketLength;
int m_lastMsgNbParityBits;
bool m_lastMsgHasCRC;
int m_lastMsgNbSymbols;
int m_lastMsgNbCodewords;
bool m_lastMsgEarlyEOM;
bool m_lastMsgHeaderCRC;
int m_lastMsgHeaderParityStatus;
bool m_lastMsgPayloadCRC;
int m_lastMsgPayloadParityStatus;
QString m_lastMsgTimestamp;
QString m_lastMsgString;
QByteArray m_lastMsgBytes;
UDPSinkUtil<uint8_t> m_udpSink;
QNetworkAccessManager *m_networkManager;
QNetworkRequest m_networkRequest;
virtual bool handleMessage(const Message& cmd);
void applySettings(const MeshtasticDemodSettings& settings, bool force = false);
std::vector<PipelineConfig> buildPipelineConfigs(const MeshtasticDemodSettings& settings) const;
MeshtasticDemodSettings makePipelineSettingsFromMeshRadio(
const MeshtasticDemodSettings& baseSettings,
const QString& presetName,
const Meshtastic::TxRadioSettings& meshRadio,
qint64 selectedPresetFrequencyHz,
bool haveSelectedPresetFrequency
) const;
int findBandwidthIndexForHz(int bandwidthHz) const;
void startPipelines(const std::vector<PipelineConfig>& configs);
void stopPipelines();
void applyPipelineRuntimeSettings(PipelineRuntime& runtime, const MeshtasticDemodSettings& settings, bool force);
bool pipelineLayoutMatches(const std::vector<PipelineConfig>& configs) const;
void syncPipelinesWithSettings(const MeshtasticDemodSettings& settings, bool force);
void webapiFormatChannelReport(SWGSDRangel::SWGChannelReport& response);
void webapiReverseSendSettings(QList<QString>& channelSettingsKeys, const MeshtasticDemodSettings& settings, bool force);
void sendChannelSettings(
const QList<ObjectPipe*>& pipes,
QList<QString>& channelSettingsKeys,
const MeshtasticDemodSettings& settings,
bool force
);
void webapiFormatChannelSettings(
QList<QString>& channelSettingsKeys,
SWGSDRangel::SWGChannelSettings *swgChannelSettings,
const MeshtasticDemodSettings& settings,
bool force
);
private slots:
void networkManagerFinished(QNetworkReply *reply);
void handleIndexInDeviceSetChanged(int index);
};
#endif // INCLUDE_MESHTASTICDEMOD_H

190
plugins/channelrx/demodmeshtastic/meshtasticdemodbaseband.cpp

@ -0,0 +1,190 @@ @@ -0,0 +1,190 @@
///////////////////////////////////////////////////////////////////////////////////
// Copyright (C) 2019-2020, 2022 Edouard Griffiths, F4EXB <f4exb06@gmail.com> //
// Copyright (C) 2022 Jiří Pinkava <jiri.pinkava@rossum.ai> //
// //
// This program is free software; you can redistribute it and/or modify //
// it under the terms of the GNU General Public License as published by //
// the Free Software Foundation as version 3 of the License, or //
// (at your option) any later version. //
// //
// This program is distributed in the hope that it will be useful, //
// but WITHOUT ANY WARRANTY; without even the implied warranty of //
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //
// GNU General Public License V3 for more details. //
// //
// You should have received a copy of the GNU General Public License //
// along with this program. If not, see <http://www.gnu.org/licenses/>. //
///////////////////////////////////////////////////////////////////////////////////
#include <QDebug>
#include "dsp/dspcommands.h"
#include "dsp/downchannelizer.h"
#include "meshtasticdemodbaseband.h"
#include "meshtasticdemodmsg.h"
MESSAGE_CLASS_DEFINITION(MeshtasticDemodBaseband::MsgConfigureMeshtasticDemodBaseband, Message)
MeshtasticDemodBaseband::MeshtasticDemodBaseband() :
m_channelizer(&m_sink)
{
m_sampleFifo.setSize(SampleSinkFifo::getSizePolicy(48000));
qDebug("MeshtasticDemodBaseband::MeshtasticDemodBaseband");
QObject::connect(
&m_sampleFifo,
&SampleSinkFifo::dataReady,
this,
&MeshtasticDemodBaseband::handleData,
Qt::QueuedConnection
);
connect(&m_inputMessageQueue, SIGNAL(messageEnqueued()), this, SLOT(handleInputMessages()));
}
MeshtasticDemodBaseband::~MeshtasticDemodBaseband()
{
}
void MeshtasticDemodBaseband::reset()
{
QMutexLocker mutexLocker(&m_mutex);
m_sampleFifo.reset();
}
void MeshtasticDemodBaseband::feed(const SampleVector::const_iterator& begin, const SampleVector::const_iterator& end)
{
m_sampleFifo.write(begin, end);
}
void MeshtasticDemodBaseband::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 MeshtasticDemodBaseband::handleInputMessages()
{
Message* message;
while ((message = m_inputMessageQueue.pop()) != nullptr)
{
if (handleMessage(*message)) {
delete message;
}
}
}
bool MeshtasticDemodBaseband::handleMessage(const Message& cmd)
{
if (MsgConfigureMeshtasticDemodBaseband::match(cmd))
{
QMutexLocker mutexLocker(&m_mutex);
MsgConfigureMeshtasticDemodBaseband& cfg = (MsgConfigureMeshtasticDemodBaseband&) cmd;
qDebug() << "MeshtasticDemodBaseband::handleMessage: MsgConfigureMeshtasticDemodBaseband";
applySettings(cfg.getSettings(), cfg.getForce());
return true;
}
else if (DSPSignalNotification::match(cmd))
{
QMutexLocker mutexLocker(&m_mutex);
DSPSignalNotification& notif = (DSPSignalNotification&) cmd;
qDebug() << "MeshtasticDemodBaseband::handleMessage: DSPSignalNotification:"
<< " basebandSampleRate:" << notif.getSampleRate()
<< " centerFrequency:" << notif.getCenterFrequency();
m_sampleFifo.setSize(SampleSinkFifo::getSizePolicy(notif.getSampleRate()));
m_channelizer.setBasebandSampleRate(notif.getSampleRate());
m_sink.setDeviceCenterFrequency(notif.getCenterFrequency());
m_sink.applyChannelSettings(
m_channelizer.getChannelSampleRate(),
MeshtasticDemodSettings::bandwidths[m_settings.m_bandwidthIndex],
m_channelizer.getChannelFrequencyOffset()
);
return true;
}
else if (MeshtasticDemodMsg::MsgLoRaHeaderFeedback::match(cmd))
{
QMutexLocker mutexLocker(&m_mutex);
MeshtasticDemodMsg::MsgLoRaHeaderFeedback& feedback = (MeshtasticDemodMsg::MsgLoRaHeaderFeedback&) cmd;
qDebug("MeshtasticDemodBaseband::handleMessage: header feedback frameId=%u valid=%d expected=%u",
feedback.getFrameId(), feedback.isValid() ? 1 : 0, feedback.getExpectedSymbols());
m_sink.applyLoRaHeaderFeedback(
feedback.getFrameId(),
feedback.isValid(),
feedback.getHasCRC(),
feedback.getNbParityBits(),
feedback.getPacketLength(),
feedback.getLdro(),
feedback.getExpectedSymbols(),
feedback.getHeaderParityStatus(),
feedback.getHeaderCRCStatus()
);
return true;
}
else
{
return false;
}
}
void MeshtasticDemodBaseband::applySettings(const MeshtasticDemodSettings& settings, bool force)
{
if ((settings.m_bandwidthIndex != m_settings.m_bandwidthIndex)
|| (settings.m_inputFrequencyOffset != m_settings.m_inputFrequencyOffset) || force)
{
m_channelizer.setChannelization(
MeshtasticDemodSettings::bandwidths[settings.m_bandwidthIndex]*MeshtasticDemodSettings::oversampling,
settings.m_inputFrequencyOffset
);
m_sink.applyChannelSettings(
m_channelizer.getChannelSampleRate(),
MeshtasticDemodSettings::bandwidths[settings.m_bandwidthIndex],
m_channelizer.getChannelFrequencyOffset()
);
}
m_sink.applySettings(settings, force);
m_settings = settings;
}
int MeshtasticDemodBaseband::getChannelSampleRate() const
{
return m_channelizer.getChannelSampleRate();
}
void MeshtasticDemodBaseband::setBasebandSampleRate(int sampleRate)
{
m_channelizer.setBasebandSampleRate(sampleRate);
m_sink.applyChannelSettings(
m_channelizer.getChannelSampleRate(),
MeshtasticDemodSettings::bandwidths[m_settings.m_bandwidthIndex],
m_channelizer.getChannelFrequencyOffset()
);
}

89
plugins/channelrx/demodmeshtastic/meshtasticdemodbaseband.h

@ -0,0 +1,89 @@ @@ -0,0 +1,89 @@
///////////////////////////////////////////////////////////////////////////////////
// Copyright (C) 2019-2020, 2022 Edouard Griffiths, F4EXB <f4exb06@gmail.com> //
// Copyright (C) 2022 Jiří Pinkava <jiri.pinkava@rossum.ai> //
// //
// This program is free software; you can redistribute it and/or modify //
// it under the terms of the GNU General Public License as published by //
// the Free Software Foundation as version 3 of the License, or //
// (at your option) any later version. //
// //
// This program is distributed in the hope that it will be useful, //
// but WITHOUT ANY WARRANTY; without even the implied warranty of //
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //
// GNU General Public License V3 for more details. //
// //
// You should have received a copy of the GNU General Public License //
// along with this program. If not, see <http://www.gnu.org/licenses/>. //
///////////////////////////////////////////////////////////////////////////////////
#ifndef INCLUDE_MESHTASTICDEMODBASEBAND_H
#define INCLUDE_MESHTASTICDEMODBASEBAND_H
#include <QObject>
#include <QRecursiveMutex>
#include "dsp/samplesinkfifo.h"
#include "dsp/downchannelizer.h"
#include "util/message.h"
#include "util/messagequeue.h"
#include "meshtasticdemodsink.h"
class MeshtasticDemodBaseband : public QObject
{
Q_OBJECT
public:
class MsgConfigureMeshtasticDemodBaseband : public Message {
MESSAGE_CLASS_DECLARATION
public:
const MeshtasticDemodSettings& getSettings() const { return m_settings; }
bool getForce() const { return m_force; }
static MsgConfigureMeshtasticDemodBaseband* create(const MeshtasticDemodSettings& settings, bool force)
{
return new MsgConfigureMeshtasticDemodBaseband(settings, force);
}
private:
MeshtasticDemodSettings m_settings;
bool m_force;
MsgConfigureMeshtasticDemodBaseband(const MeshtasticDemodSettings& settings, bool force) :
Message(),
m_settings(settings),
m_force(force)
{ }
};
MeshtasticDemodBaseband();
~MeshtasticDemodBaseband();
void reset();
void feed(const SampleVector::const_iterator& begin, const SampleVector::const_iterator& end);
MessageQueue *getInputMessageQueue() { return &m_inputMessageQueue; } //!< Get the queue for asynchronous inbound communication
int getChannelSampleRate() const;
bool getDemodActive() const { return m_sink.getDemodActive(); }
double getCurrentNoiseLevel() const { return m_sink.getCurrentNoiseLevel(); }
double getTotalPower() const { return m_sink.getTotalPower(); }
void setBasebandSampleRate(int sampleRate);
void setDecoderMessageQueue(MessageQueue *messageQueue) { m_sink.setDecoderMessageQueue(messageQueue); }
void setSpectrumSink(BasebandSampleSink* spectrumSink) { m_sink.setSpectrumSink(spectrumSink); }
void setFifoLabel(const QString& label) { m_sampleFifo.setLabel(label); }
private:
SampleSinkFifo m_sampleFifo;
DownChannelizer m_channelizer;
MeshtasticDemodSink m_sink;
MessageQueue m_inputMessageQueue; //!< Queue for asynchronous inbound communication
MeshtasticDemodSettings m_settings;
QRecursiveMutex m_mutex;
bool handleMessage(const Message& cmd);
void applySettings(const MeshtasticDemodSettings& settings, bool force = false);
private slots:
void handleInputMessages();
void handleData(); //!< Handle data when samples have to be processed
};
#endif // INCLUDE_MESHTASTICDEMODBASEBAND_H

504
plugins/channelrx/demodmeshtastic/meshtasticdemoddecoder.cpp

@ -0,0 +1,504 @@ @@ -0,0 +1,504 @@
///////////////////////////////////////////////////////////////////////////////////
// Copyright (C) 2020 Edouard Griffiths, F4EXB <f4exb06@gmail.com> //
// //
// This program is free software; you can redistribute it and/or modify //
// it under the terms of the GNU General Public License as published by //
// the Free Software Foundation as version 3 of the License, or //
// (at your option) any later version. //
// //
// This program is distributed in the hope that it will be useful, //
// but WITHOUT ANY WARRANTY; without even the implied warranty of //
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //
// GNU General Public License V3 for more details. //
// //
// You should have received a copy of the GNU General Public License //
// along with this program. If not, see <http://www.gnu.org/licenses/>. //
///////////////////////////////////////////////////////////////////////////////////
#include <QTime>
#include <algorithm>
#include <cmath>
#include "meshtasticdemoddecoder.h"
#include "meshtasticdemoddecodertty.h"
#include "meshtasticdemoddecoderascii.h"
#include "meshtasticdemoddecoderlora.h"
#include "meshtasticdemoddecoderft.h"
#include "meshtasticdemodmsg.h"
MeshtasticDemodDecoder::MeshtasticDemodDecoder() :
m_codingScheme(MeshtasticDemodSettings::CodingTTY),
m_spreadFactor(0U),
m_deBits(0U),
m_nbSymbolBits(5),
m_nbParityBits(1),
m_hasCRC(true),
m_hasHeader(true),
m_packetLength(0U),
m_loRaBandwidth(250000U),
m_nbSymbols(0U),
m_nbCodewords(0U),
m_earlyEOM(false),
m_headerParityStatus((int) MeshtasticDemodSettings::ParityUndefined),
m_headerCRCStatus(false),
m_payloadParityStatus((int) MeshtasticDemodSettings::ParityUndefined),
m_payloadCRCStatus(false),
m_pipelineId(-1),
m_outputMessageQueue(nullptr),
m_headerFeedbackMessageQueue(nullptr)
{
connect(&m_inputMessageQueue, SIGNAL(messageEnqueued()), this, SLOT(handleInputMessages()));
}
MeshtasticDemodDecoder::~MeshtasticDemodDecoder()
{}
void MeshtasticDemodDecoder::setNbSymbolBits(unsigned int spreadFactor, unsigned int deBits)
{
m_spreadFactor = spreadFactor;
if (deBits >= spreadFactor) {
m_deBits = m_spreadFactor - 1;
} else {
m_deBits = deBits;
}
m_nbSymbolBits = m_spreadFactor - m_deBits;
}
void MeshtasticDemodDecoder::decodeSymbols(const std::vector<unsigned short>& symbols, QString& str)
{
switch(m_codingScheme)
{
case MeshtasticDemodSettings::CodingTTY:
if (m_nbSymbolBits == 5) {
MeshtasticDemodDecoderTTY::decodeSymbols(symbols, str);
}
break;
case MeshtasticDemodSettings::CodingASCII:
if (m_nbSymbolBits == 7) {
MeshtasticDemodDecoderASCII::decodeSymbols(symbols, str);
}
break;
default:
break;
}
}
void MeshtasticDemodDecoder::decodeSymbols(const std::vector<unsigned short>& symbols, QByteArray& bytes)
{
switch(m_codingScheme)
{
case MeshtasticDemodSettings::CodingLoRa:
if (m_nbSymbolBits >= 5)
{
unsigned int headerNbSymbolBits;
if (m_hasHeader && (m_spreadFactor > 2U)) {
headerNbSymbolBits = m_spreadFactor - 2U;
} else {
headerNbSymbolBits = m_nbSymbolBits;
}
MeshtasticDemodDecoderLoRa::decodeBytes(
bytes,
symbols,
m_nbSymbolBits,
headerNbSymbolBits,
m_hasHeader,
m_hasCRC,
m_nbParityBits,
m_packetLength,
m_earlyEOM,
m_headerParityStatus,
m_headerCRCStatus,
m_payloadParityStatus,
m_payloadCRCStatus
);
MeshtasticDemodDecoderLoRa::getCodingMetrics(
m_nbSymbolBits,
headerNbSymbolBits,
m_nbParityBits,
m_packetLength,
m_hasHeader,
m_hasCRC,
m_nbSymbols,
m_nbCodewords
);
}
break;
default:
break;
}
}
void MeshtasticDemodDecoder::decodeSymbols( //!< For FT coding scheme
const std::vector<std::vector<float>>& mags, // vector of symbols magnitudes
int nbSymbolBits, //!< number of bits per symbol
std::string& msg, //!< formatted message
std::string& call1, //!< 1st callsign or shorthand
std::string& call2, //!< 2nd callsign
std::string& loc, //!< locator, report or shorthand
bool& reply //!< true if message is a reply report
)
{
if (m_codingScheme != MeshtasticDemodSettings::CodingFT) {
return;
}
MeshtasticDemodDecoderFT::decodeSymbols(
mags,
nbSymbolBits,
msg,
call1,
call2,
loc,
reply,
m_payloadParityStatus,
m_payloadCRCStatus
);
}
bool MeshtasticDemodDecoder::handleMessage(const Message& cmd)
{
if (MeshtasticDemodMsg::MsgLoRaHeaderProbe::match(cmd))
{
MeshtasticDemodMsg::MsgLoRaHeaderProbe& msg = (MeshtasticDemodMsg::MsgLoRaHeaderProbe&) cmd;
const std::vector<unsigned short>& symbols = msg.getSymbols();
bool hasCRC = msg.getHasCRC();
unsigned int nbParityBits = m_nbParityBits;
unsigned int packetLength = m_packetLength;
int headerParityStatus = (int) MeshtasticDemodSettings::ParityUndefined;
bool headerCRCStatus = false;
bool ldro = false;
unsigned int expectedSymbols = 0U;
bool valid = false;
if (symbols.size() >= 8U && msg.getHasHeader())
{
MeshtasticDemodDecoderLoRa::decodeHeader(
symbols,
msg.getHeaderNbSymbolBits(),
hasCRC,
nbParityBits,
packetLength,
headerParityStatus,
headerCRCStatus
);
if (headerCRCStatus && (packetLength > 0U) && (nbParityBits >= 1U) && (nbParityBits <= 4U))
{
const unsigned int spreadFactor = msg.getSpreadFactor();
const unsigned int bandwidth = msg.getBandwidth() > 0U ? msg.getBandwidth() : m_loRaBandwidth;
ldro = ((1U << spreadFactor) * 1000.0 / static_cast<double>(std::max(1U, bandwidth))) > 16.0;
const int denom = static_cast<int>(spreadFactor) - (ldro ? 2 : 0);
if (denom > 0)
{
const int numerator =
2 * static_cast<int>(packetLength)
- static_cast<int>(spreadFactor)
+ 2
+ 5 // explicit header path (!impl_head)
+ (hasCRC ? 4 : 0);
const int payloadBlocks = std::max(0, static_cast<int>(std::ceil(static_cast<double>(numerator) / static_cast<double>(denom))));
expectedSymbols = 8U + static_cast<unsigned int>(payloadBlocks) * (4U + nbParityBits);
valid = expectedSymbols >= 8U;
}
}
}
if (m_headerFeedbackMessageQueue)
{
MeshtasticDemodMsg::MsgLoRaHeaderFeedback *feedback = MeshtasticDemodMsg::MsgLoRaHeaderFeedback::create(
msg.getFrameId(),
valid,
hasCRC,
nbParityBits,
packetLength,
ldro,
expectedSymbols,
headerParityStatus,
headerCRCStatus
);
m_headerFeedbackMessageQueue->push(feedback);
qDebug("MeshtasticDemodDecoder::handleMessage: header probe frameId=%u valid=%d len=%u CR=%u expected=%u",
msg.getFrameId(), valid ? 1 : 0, packetLength, nbParityBits, expectedSymbols);
}
return true;
}
else if (MeshtasticDemodMsg::MsgDecodeSymbols::match(cmd))
{
qDebug("MeshtasticDemodDecoder::handleMessage: MsgDecodeSymbols");
MeshtasticDemodMsg::MsgDecodeSymbols& msg = (MeshtasticDemodMsg::MsgDecodeSymbols&) cmd;
float msgSignalDb = msg.getSingalDb();
float msgNoiseDb = msg.getNoiseDb();
unsigned int msgSyncWord = msg.getSyncWord();
QDateTime dt = QDateTime::currentDateTime();
QString msgTimestamp = dt.toString(Qt::ISODateWithMs);
if (m_codingScheme == MeshtasticDemodSettings::CodingLoRa)
{
QByteArray msgBytes;
const std::vector<std::vector<float>>& msgMags = msg.getMagnitudes();
const bool canSoftDecode = !msgMags.empty()
&& (msgMags.size() >= msg.getSymbols().size())
&& (m_spreadFactor >= 5U)
&& (m_loRaBandwidth > 0U);
struct LoRaDecodeState
{
QByteArray bytes;
bool hasCRC;
unsigned int nbParityBits;
unsigned int packetLength;
unsigned int nbSymbols;
unsigned int nbCodewords;
bool earlyEOM;
int headerParityStatus;
bool headerCRCStatus;
int payloadParityStatus;
bool payloadCRCStatus;
};
auto captureLoRaState = [this](const QByteArray& bytes) -> LoRaDecodeState {
LoRaDecodeState s;
s.bytes = bytes;
s.hasCRC = m_hasCRC;
s.nbParityBits = m_nbParityBits;
s.packetLength = m_packetLength;
s.nbSymbols = m_nbSymbols;
s.nbCodewords = m_nbCodewords;
s.earlyEOM = m_earlyEOM;
s.headerParityStatus = m_headerParityStatus;
s.headerCRCStatus = m_headerCRCStatus;
s.payloadParityStatus = m_payloadParityStatus;
s.payloadCRCStatus = m_payloadCRCStatus;
return s;
};
auto restoreLoRaState = [this, &msgBytes](const LoRaDecodeState& s) {
msgBytes = s.bytes;
m_hasCRC = s.hasCRC;
m_nbParityBits = s.nbParityBits;
m_packetLength = s.packetLength;
m_nbSymbols = s.nbSymbols;
m_nbCodewords = s.nbCodewords;
m_earlyEOM = s.earlyEOM;
m_headerParityStatus = s.headerParityStatus;
m_headerCRCStatus = s.headerCRCStatus;
m_payloadParityStatus = s.payloadParityStatus;
m_payloadCRCStatus = s.payloadCRCStatus;
};
if (canSoftDecode)
{
unsigned int headerNbSymbolBits;
if (m_hasHeader && (m_spreadFactor > 2U)) {
headerNbSymbolBits = m_spreadFactor - 2U;
} else {
headerNbSymbolBits = m_nbSymbolBits;
}
MeshtasticDemodDecoderLoRa::decodeBytesSoft(
msgBytes,
msgMags,
msg.getSymbols(),
m_spreadFactor,
m_loRaBandwidth,
m_nbSymbolBits,
headerNbSymbolBits,
m_hasHeader,
m_hasCRC,
m_nbParityBits,
m_packetLength,
m_earlyEOM,
m_headerParityStatus,
m_headerCRCStatus,
m_payloadParityStatus,
m_payloadCRCStatus
);
MeshtasticDemodDecoderLoRa::getCodingMetrics(
m_nbSymbolBits,
headerNbSymbolBits,
m_nbParityBits,
m_packetLength,
m_hasHeader,
m_hasCRC,
m_nbSymbols,
m_nbCodewords
);
const LoRaDecodeState softState = captureLoRaState(msgBytes);
// Soft path is canonical for gr-lora_sdr, but if this approximation misses CRC
// on noisy captures, retry hard decode once and keep whichever path validates.
if (m_hasCRC && !m_payloadCRCStatus)
{
QByteArray hardBytes;
decodeSymbols(msg.getSymbols(), hardBytes); // hard path updates decoder state
const LoRaDecodeState hardState = captureLoRaState(hardBytes);
if (hardState.payloadCRCStatus) {
restoreLoRaState(hardState);
} else {
restoreLoRaState(softState);
}
}
}
else
{
decodeSymbols(msg.getSymbols(), msgBytes);
}
if (m_hasCRC && !m_payloadCRCStatus && (m_spreadFactor >= 5U))
{
const LoRaDecodeState baseState = captureLoRaState(msgBytes);
const unsigned int headerNbSymbolBits = (m_hasHeader && (m_spreadFactor > 2U))
? (m_spreadFactor - 2U)
: m_nbSymbolBits;
bool recovered = false;
for (int delta : {-1, 1})
{
std::vector<unsigned short> shifted = msg.getSymbols();
for (size_t i = 0; i < shifted.size(); i++)
{
const bool isHeader = m_hasHeader && (i < 8U);
const unsigned int bits = isHeader ? headerNbSymbolBits : m_nbSymbolBits;
const unsigned int mod = 1U << std::max(1U, bits);
const int s = static_cast<int>(shifted[i]);
const int v = (s + delta) % static_cast<int>(mod);
shifted[i] = static_cast<unsigned short>(v < 0 ? (v + static_cast<int>(mod)) : v);
}
QByteArray shiftedBytes;
decodeSymbols(shifted, shiftedBytes); // hard-path decode with adjusted symbol indices
const LoRaDecodeState shiftedState = captureLoRaState(shiftedBytes);
if (shiftedState.payloadCRCStatus)
{
restoreLoRaState(shiftedState);
recovered = true;
break;
}
}
if (!recovered) {
restoreLoRaState(baseState);
}
}
qDebug(
"MeshtasticDemodDecoder::handleMessage: decode symbols=%zu bytes=%lld earlyEOM=%d hCRC=%d pCRC=%d hParity=%d pParity=%d",
msg.getSymbols().size(),
static_cast<long long>(msgBytes.size()),
m_earlyEOM ? 1 : 0,
m_headerCRCStatus ? 1 : 0,
m_payloadCRCStatus ? 1 : 0,
m_headerParityStatus,
m_payloadParityStatus
);
if (m_outputMessageQueue)
{
qDebug(
"MeshtasticDemodDecoder::handleMessage: push report ts=%s bytes=%lld pCRC=%d",
qPrintable(msgTimestamp),
static_cast<long long>(msgBytes.size()),
m_payloadCRCStatus ? 1 : 0
);
MeshtasticDemodMsg::MsgReportDecodeBytes *outputMsg = MeshtasticDemodMsg::MsgReportDecodeBytes::create(msgBytes);
outputMsg->setFrameId(msg.getFrameId());
outputMsg->setSyncWord(msgSyncWord);
outputMsg->setSignalDb(msgSignalDb);
outputMsg->setNoiseDb(msgNoiseDb);
outputMsg->setMsgTimestamp(msgTimestamp);
outputMsg->setPacketSize(getPacketLength());
outputMsg->setNbParityBits(getNbParityBits());
outputMsg->setHasCRC(getHasCRC());
outputMsg->setNbSymbols(getNbSymbols());
outputMsg->setNbCodewords(getNbCodewords());
outputMsg->setEarlyEOM(getEarlyEOM());
outputMsg->setHeaderParityStatus(getHeaderParityStatus());
outputMsg->setHeaderCRCStatus(getHeaderCRCStatus());
outputMsg->setPayloadParityStatus(getPayloadParityStatus());
outputMsg->setPayloadCRCStatus(getPayloadCRCStatus());
outputMsg->setPipelineMetadata(m_pipelineId, m_pipelineName, m_pipelinePreset);
outputMsg->setDechirpedSpectrum(msg.getDechirpedSpectrum());
m_outputMessageQueue->push(outputMsg);
}
}
else if (m_codingScheme == MeshtasticDemodSettings::CodingFT)
{
std::string fmsg, call1, call2, loc;
bool reply;
decodeSymbols(
msg.getMagnitudes(),
m_nbSymbolBits,
fmsg,
call1,
call2,
loc,
reply
);
if (m_outputMessageQueue)
{
MeshtasticDemodMsg::MsgReportDecodeFT *outputMsg = MeshtasticDemodMsg::MsgReportDecodeFT::create();
outputMsg->setSyncWord(msgSyncWord);
outputMsg->setSignalDb(msgSignalDb);
outputMsg->setNoiseDb(msgNoiseDb);
outputMsg->setMsgTimestamp(msgTimestamp);
outputMsg->setMessage(QString(fmsg.c_str()));
outputMsg->setCall1(QString(call1.c_str()));
outputMsg->setCall2(QString(call2.c_str()));
outputMsg->setLoc(QString(loc.c_str()));
outputMsg->setReply(reply);
outputMsg->setPayloadParityStatus(getPayloadParityStatus());
outputMsg->setPayloadCRCStatus(getPayloadCRCStatus());
outputMsg->setPipelineMetadata(m_pipelineId, m_pipelineName, m_pipelinePreset);
m_outputMessageQueue->push(outputMsg);
}
}
else
{
QString msgString;
decodeSymbols(msg.getSymbols(), msgString);
if (m_outputMessageQueue)
{
MeshtasticDemodMsg::MsgReportDecodeString *outputMsg = MeshtasticDemodMsg::MsgReportDecodeString::create(msgString);
outputMsg->setFrameId(msg.getFrameId());
outputMsg->setSyncWord(msgSyncWord);
outputMsg->setSignalDb(msgSignalDb);
outputMsg->setNoiseDb(msgNoiseDb);
outputMsg->setMsgTimestamp(msgTimestamp);
outputMsg->setPipelineMetadata(m_pipelineId, m_pipelineName, m_pipelinePreset);
m_outputMessageQueue->push(outputMsg);
}
}
return true;
}
return false;
}
void MeshtasticDemodDecoder::handleInputMessages()
{
Message* message;
while ((message = m_inputMessageQueue.pop()) != nullptr)
{
if (handleMessage(*message)) {
delete message;
}
}
}

106
plugins/channelrx/demodmeshtastic/meshtasticdemoddecoder.h

@ -0,0 +1,106 @@ @@ -0,0 +1,106 @@
///////////////////////////////////////////////////////////////////////////////////
// Copyright (C) 2012 maintech GmbH, Otto-Hahn-Str. 15, 97204 Hoechberg, Germany //
// written by Christian Daniel //
// Copyright (C) 2016-2020 Edouard Griffiths, F4EXB <f4exb06@gmail.com> //
// //
// This program is free software; you can redistribute it and/or modify //
// it under the terms of the GNU General Public License as published by //
// the Free Software Foundation as version 3 of the License, or //
// (at your option) any later version. //
// //
// This program is distributed in the hope that it will be useful, //
// but WITHOUT ANY WARRANTY; without even the implied warranty of //
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //
// GNU General Public License V3 for more details. //
// //
// You should have received a copy of the GNU General Public License //
// along with this program. If not, see <http://www.gnu.org/licenses/>. //
///////////////////////////////////////////////////////////////////////////////////
#ifndef INCLUDE_MESHTASTICDEMODDECODER_H
#define INCLUDE_MESHTASTICDEMODDECODER_H
#include <vector>
#include <QObject>
#include "util/messagequeue.h"
#include "meshtasticdemodsettings.h"
class MeshtasticDemodDecoder : public QObject
{
Q_OBJECT
public:
MeshtasticDemodDecoder();
~MeshtasticDemodDecoder();
void setCodingScheme(MeshtasticDemodSettings::CodingScheme codingScheme) { m_codingScheme = codingScheme; }
void setNbSymbolBits(unsigned int spreadFactor, unsigned int deBits);
void setLoRaParityBits(unsigned int parityBits) { m_nbParityBits = parityBits; }
void setLoRaHasHeader(bool hasHeader) { m_hasHeader = hasHeader; }
void setLoRaHasCRC(bool hasCRC) { m_hasCRC = hasCRC; }
void setLoRaPacketLength(unsigned int packetLength) { m_packetLength = packetLength; }
void setLoRaBandwidth(unsigned int bandwidth) { m_loRaBandwidth = bandwidth; }
void setPipelineMetadata(int pipelineId, const QString& pipelineName, const QString& pipelinePreset)
{
m_pipelineId = pipelineId;
m_pipelineName = pipelineName;
m_pipelinePreset = pipelinePreset;
}
MessageQueue *getInputMessageQueue() { return &m_inputMessageQueue; }
void setOutputMessageQueue(MessageQueue *messageQueue) { m_outputMessageQueue = messageQueue; }
void setHeaderFeedbackMessageQueue(MessageQueue *messageQueue) { m_headerFeedbackMessageQueue = messageQueue; }
private:
bool handleMessage(const Message& cmd);
void decodeSymbols(const std::vector<unsigned short>& symbols, QString& str); //!< For ASCII and TTY
void decodeSymbols(const std::vector<unsigned short>& symbols, QByteArray& bytes); //!< For raw bytes (original LoRa)
void decodeSymbols( //!< For FT coding scheme
const std::vector<std::vector<float>>& mags, // vector of symbols magnitudes
int nbSymbolBits, //!< number of bits per symbol
std::string& msg, //!< formatted message
std::string& call1, //!< 1st callsign or shorthand
std::string& call2, //!< 2nd callsign
std::string& loc, //!< locator, report or shorthand
bool& reply //!< true if message is a reply report
);
unsigned int getNbParityBits() const { return m_nbParityBits; }
unsigned int getPacketLength() const { return m_packetLength; }
bool getHasCRC() const { return m_hasCRC; }
unsigned int getNbSymbols() const { return m_nbSymbols; }
unsigned int getNbCodewords() const { return m_nbCodewords; }
bool getEarlyEOM() const { return m_earlyEOM; }
int getHeaderParityStatus() const { return m_headerParityStatus; }
bool getHeaderCRCStatus() const { return m_headerCRCStatus; }
int getPayloadParityStatus() const { return m_payloadParityStatus; }
bool getPayloadCRCStatus() const { return m_payloadCRCStatus; }
MeshtasticDemodSettings::CodingScheme m_codingScheme;
unsigned int m_spreadFactor;
unsigned int m_deBits;
unsigned int m_nbSymbolBits;
// LoRa attributes
unsigned int m_nbParityBits; //!< 1 to 4 Hamming FEC bits for 4 payload bits
bool m_hasCRC;
bool m_hasHeader;
unsigned int m_packetLength;
unsigned int m_loRaBandwidth;
unsigned int m_nbSymbols; //!< Number of encoded symbols: this is only dependent of nbSymbolBits, nbParityBits, packetLength, hasHeader and hasCRC
unsigned int m_nbCodewords; //!< Number of encoded codewords: this is only dependent of nbSymbolBits, nbParityBits, packetLength, hasHeader and hasCRC
bool m_earlyEOM;
int m_headerParityStatus;
bool m_headerCRCStatus;
int m_payloadParityStatus;
bool m_payloadCRCStatus;
int m_pipelineId;
QString m_pipelineName;
QString m_pipelinePreset;
MessageQueue m_inputMessageQueue;
MessageQueue *m_outputMessageQueue;
MessageQueue *m_headerFeedbackMessageQueue;
private slots:
void handleInputMessages();
};
#endif // INCLUDE_MESHTASTICDEMODDECODER_H

32
plugins/channelrx/demodmeshtastic/meshtasticdemoddecoderascii.cpp

@ -0,0 +1,32 @@ @@ -0,0 +1,32 @@
///////////////////////////////////////////////////////////////////////////////////
// Copyright (C) 2012 maintech GmbH, Otto-Hahn-Str. 15, 97204 Hoechberg, Germany //
// written by Christian Daniel //
// Copyright (C) 2015-2020 Edouard Griffiths, F4EXB <f4exb06@gmail.com> //
// //
// This program is free software; you can redistribute it and/or modify //
// it under the terms of the GNU General Public License as published by //
// the Free Software Foundation as version 3 of the License, or //
// (at your option) any later version. //
// //
// This program is distributed in the hope that it will be useful, //
// but WITHOUT ANY WARRANTY; without even the implied warranty of //
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //
// GNU General Public License V3 for more details. //
// //
// You should have received a copy of the GNU General Public License //
// along with this program. If not, see <http://www.gnu.org/licenses/>. //
///////////////////////////////////////////////////////////////////////////////////
#include "meshtasticdemoddecoderascii.h"
void MeshtasticDemodDecoderASCII::decodeSymbols(const std::vector<unsigned short>& symbols, QString& str)
{
std::vector<unsigned short>::const_iterator it = symbols.begin();
QByteArray bytes;
for (; it != symbols.end(); ++it) {
bytes.push_back(*it & 0x7F);
}
str = QString(bytes.toStdString().c_str());
}

32
plugins/channelrx/demodmeshtastic/meshtasticdemoddecoderascii.h

@ -0,0 +1,32 @@ @@ -0,0 +1,32 @@
///////////////////////////////////////////////////////////////////////////////////
// Copyright (C) 2012 maintech GmbH, Otto-Hahn-Str. 15, 97204 Hoechberg, Germany //
// written by Christian Daniel //
// Copyright (C) 2015-2020 Edouard Griffiths, F4EXB <f4exb06@gmail.com> //
// //
// This program is free software; you can redistribute it and/or modify //
// it under the terms of the GNU General Public License as published by //
// the Free Software Foundation as version 3 of the License, or //
// (at your option) any later version. //
// //
// This program is distributed in the hope that it will be useful, //
// but WITHOUT ANY WARRANTY; without even the implied warranty of //
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //
// GNU General Public License V3 for more details. //
// //
// You should have received a copy of the GNU General Public License //
// along with this program. If not, see <http://www.gnu.org/licenses/>. //
///////////////////////////////////////////////////////////////////////////////////
#ifndef INCLUDE_MESHTASTICDEMODDECODERASCII_H
#define INCLUDE_MESHTASTICDEMODDECODERASCII_H
#include <vector>
#include <QString>
class MeshtasticDemodDecoderASCII
{
public:
static void decodeSymbols(const std::vector<unsigned short>& symbols, QString& str);
};
#endif // INCLUDE_MESHTASTICDEMODDECODERASCII_H

187
plugins/channelrx/demodmeshtastic/meshtasticdemoddecoderft.cpp

@ -0,0 +1,187 @@ @@ -0,0 +1,187 @@
///////////////////////////////////////////////////////////////////////////////////
// Copyright (C) 2024 Edouard Griffiths, F4EXB <f4exb06@gmail.com> //
// //
// This program is free software; you can redistribute it and/or modify //
// it under the terms of the GNU General Public License as published by //
// the Free Software Foundation as version 3 of the License, or //
// (at your option) any later version. //
// //
// This program is distributed in the hope that it will be useful, //
// but WITHOUT ANY WARRANTY; without even the implied warranty of //
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //
// GNU General Public License V3 for more details. //
// //
// You should have received a copy of the GNU General Public License //
// along with this program. If not, see <http://www.gnu.org/licenses/>. //
///////////////////////////////////////////////////////////////////////////////////
#include "meshtasticdemodsettings.h"
#include "meshtasticdemoddecoderft.h"
#ifndef HAS_FT8
void MeshtasticDemodDecoderFT::decodeSymbols(
const std::vector<std::vector<float>>& mags, // vector of symbols magnitudes
int nbSymbolBits, //!< number of bits per symbol
QString& msg, //!< formatted message
QString& call1, //!< 1st callsign or shorthand
QString& call2, //!< 2nd callsign
QString& loc, //!< locator, report or shorthand
bool& reply //!< true if message is a reply report
)
{
qWarning("MeshtasticDemodDecoderFT::decodeSymbols: not implemented");
}
#else
#include "ft8.h"
#include "packing.h"
void MeshtasticDemodDecoderFT::decodeSymbols(
const std::vector<std::vector<float>>& mags, // vector of symbols magnitudes
int nbSymbolBits, //!< number of bits per symbol
std::string& msg, //!< formatted message
std::string& call1, //!< 1st callsign or shorthand
std::string& call2, //!< 2nd callsign
std::string& loc, //!< locator, report or shorthand
bool& reply, //!< true if message is a reply report
int& payloadParityStatus,
bool& payloadCRCStatus
)
{
if (mags.size()*nbSymbolBits < 174)
{
qWarning("MeshtasticDemodDecoderFT::decodeSymbols: insufficient number of symbols for FT payload");
return;
}
FT8::FT8Params params;
int r174[174];
std::string comments;
payloadParityStatus = (int) MeshtasticDemodSettings::ParityOK;
payloadCRCStatus = false;
std::vector<std::vector<float>> magsp = mags;
qDebug("MeshtasticDemodDecoderFT::decodeSymbols: try decode with symbol shift 0");
int res = decodeWithShift(params, magsp, nbSymbolBits, r174, comments);
if (res == 0)
{
std::vector<std::vector<float>> magsn = mags;
int shiftcount = 0;
while ((res == 0) && (shiftcount < 7))
{
qDebug("MeshtasticDemodDecoderFT::decodeSymbols: try decode with symbol shift %d", shiftcount + 1);
res = decodeWithShift(params, magsp, nbSymbolBits, r174, comments, 1);
if (res == 0)
{
qDebug("MeshtasticDemodDecoderFT::decodeSymbols: try decode with symbol shift -%d", shiftcount + 1);
res = decodeWithShift(params, magsn, nbSymbolBits, r174, comments, -1);
}
shiftcount++;
}
}
if (res == 0)
{
if (comments == "LDPC fail")
{
qWarning("MeshtasticDemodDecoderFT::decodeSymbols: LDPC failed");
payloadParityStatus = (int) MeshtasticDemodSettings::ParityError;
}
else if (comments == "OSD fail")
{
qWarning("MeshtasticDemodDecoderFT::decodeSymbols: OSD failed");
payloadParityStatus = (int) MeshtasticDemodSettings::ParityError;
}
else if (comments == "CRC fail")
{
qWarning("MeshtasticDemodDecoderFT::decodeSymbols: CRC failed");
}
else
{
qWarning("MeshtasticDemodDecoderFT::decodeSymbols: decode failed for unknown reason");
payloadParityStatus = (int) MeshtasticDemodSettings::ParityUndefined;
}
return;
}
payloadCRCStatus = true;
FT8::Packing packing;
std::string msgType;
msg = packing.unpack(r174, call1, call2, loc, msgType);
reply = false;
if ((msgType == "0.3") || (msgType == "0.3")) {
reply = r174[56] != 0;
}
if ((msgType == "1") || (msgType == "2")) {
reply = r174[58] != 0;
}
if ((msgType == "3")) {
reply = r174[57] != 0;
}
if ((msgType == "5")) {
reply = r174[34] != 0;
}
}
int MeshtasticDemodDecoderFT::decodeWithShift(
FT8::FT8Params& params,
std::vector<std::vector<float>>& mags,
int nbSymbolBits,
int *r174,
std::string& comments,
int shift
)
{
if (shift > 0)
{
for (unsigned int si = 0; si < mags.size(); si++)
{
for (int bini = (1<<nbSymbolBits) - 1; bini > 0; bini--)
{
float x = mags[si][bini - 1];
mags[si][bini - 1] = mags[si][bini];
mags[si][bini] = x;
}
}
}
if (shift < 0)
{
for (unsigned int si = 0; si < mags.size(); si++)
{
for (int bini = 0; bini < (1<<nbSymbolBits) - 1; bini++)
{
float x = mags[si][bini + 1];
mags[si][bini + 1] = mags[si][bini];
mags[si][bini] = x;
}
}
}
float *lls = new float[mags.size()*nbSymbolBits]; // bits log likelihoods (>0 for 0, <0 for 1)
std::fill(lls, lls+mags.size()*nbSymbolBits, 0.0);
FT8::FT8::soft_decode_mags(params, mags, nbSymbolBits, lls);
deinterleave174(lls);
int ret = FT8::FT8::decode(lls, r174, params, 0, comments);
delete[] lls;
return ret;
}
void MeshtasticDemodDecoderFT::deinterleave174(float ll174[])
{
// 174 = 2*3*29
float t174[174];
std::copy(ll174, ll174+174, t174);
for (int i = 0; i < 174; i++) {
ll174[i] = t174[(i%6)*29 + (i%29)];
}
}
#endif // HAS_FT8

64
plugins/channelrx/demodmeshtastic/meshtasticdemoddecoderft.h

@ -0,0 +1,64 @@ @@ -0,0 +1,64 @@
///////////////////////////////////////////////////////////////////////////////////
// Copyright (C) 2024 Edouard Griffiths, F4EXB <f4exb06@gmail.com> //
// //
// This program is free software; you can redistribute it and/or modify //
// it under the terms of the GNU General Public License as published by //
// the Free Software Foundation as version 3 of the License, or //
// (at your option) any later version. //
// //
// This program is distributed in the hope that it will be useful, //
// but WITHOUT ANY WARRANTY; without even the implied warranty of //
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //
// GNU General Public License V3 for more details. //
// //
// You should have received a copy of the GNU General Public License //
// along with this program. If not, see <http://www.gnu.org/licenses/>. //
///////////////////////////////////////////////////////////////////////////////////
#ifndef INCLUDE_MESHTASTICDEMODDECODERFT_H
#define INCLUDE_MESHTASTICDEMODDECODERFT_H
#include <vector>
#include <string>
namespace FT8 {
class FT8Params;
}
class MeshtasticDemodDecoderFT
{
public:
enum ParityStatus
{
ParityUndefined,
ParityError,
ParityCorrected,
ParityOK
};
static void decodeSymbols(
const std::vector<std::vector<float>>& mags, // vector of symbols magnitudes
int nbSymbolBits, //!< number of bits per symbol
std::string& msg, //!< formatted message
std::string& call1, //!< 1st callsign or shorthand
std::string& call2, //!< 2nd callsign
std::string& loc, //!< locator, report or shorthand
bool& reply, //!< true if message is a reply report
int& payloadParityStatus,
bool& payloadCRCStatus
);
private:
static int decodeWithShift(
FT8::FT8Params& params,
std::vector<std::vector<float>>& mags,
int nbSymbolBits,
int *r174,
std::string& comments,
int shift = 0
);
static void deinterleave174(float ll174[]);
};
#endif

682
plugins/channelrx/demodmeshtastic/meshtasticdemoddecoderlora.cpp

@ -0,0 +1,682 @@ @@ -0,0 +1,682 @@
///////////////////////////////////////////////////////////////////////////////////
// Copyright (C) 2020 Edouard Griffiths, F4EXB <f4exb06@gmail.com> //
// //
// Inspired by: https://github.com/myriadrf/LoRa-SDR //
// //
// This program is free software; you can redistribute it and/or modify //
// it under the terms of the GNU General Public License as published by //
// the Free Software Foundation as version 3 of the License, or //
// (at your option) any later version. //
// //
// This program is distributed in the hope that it will be useful, //
// but WITHOUT ANY WARRANTY; without even the implied warranty of //
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //
// GNU General Public License V3 for more details. //
// //
// You should have received a copy of the GNU General Public License //
// along with this program. If not, see <http://www.gnu.org/licenses/>. //
///////////////////////////////////////////////////////////////////////////////////
#include <algorithm>
#include "meshtasticdemodsettings.h"
#include "meshtasticdemoddecoderlora.h"
void MeshtasticDemodDecoderLoRa::decodeHeader(
const std::vector<unsigned short>& inSymbols,
unsigned int headerNbSymbolBits,
bool& hasCRC,
unsigned int& nbParityBits,
unsigned int& packetLength,
int& headerParityStatus,
bool& headerCRCStatus
)
{
// with header (H: header 8-bit codeword P: payload-8 bit codeword):
// nbSymbolBits = 5 |H|H|H|H|H| codewords => 8 symbols (always) : static headerSymbols = 8
// nbSymbolBits = 7 |H|H|H|H|H|P|P|
// without header (P: payload 8-bit codeword):
// nbSymbolBits = 5 |P|P|P|P|P| codewords => 8 symbols (always)
// nbSymbolBits = 7 |P|P|P|P|P|P|P|
// Actual header is always represented with 5 8-bit codewords : static headerCodewords = 5
// These 8-bit codewords are encoded with Hamming(4,8) FEC : static headerParityBits = 4
std::vector<uint16_t> symbols(headerSymbols);
std::copy(inSymbols.begin(), inSymbols.begin() + headerSymbols, symbols.begin());
//gray encode
for (auto &sym : symbols) {
sym = binaryToGray16(sym);
}
std::vector<uint8_t> codewords(headerNbSymbolBits);
// Header symbols de-interleave thus headerSymbols (8) symbols into nbSymbolBits (5..12) codewords using header FEC (4/8)
diagonalDeinterleaveSx(symbols.data(), headerSymbols, codewords.data(), headerNbSymbolBits, headerParityBits);
bool error = false;
bool bad = false;
uint8_t bytes[3];
// decode actual header inside 8-bit codewords header with 4/8 FEC (5 first codewords)
bytes[0] = decodeHamming84sx(codewords[1], error, bad) & 0xf;
bytes[0] |= decodeHamming84sx(codewords[0], error, bad) << 4; // length
bytes[1] = decodeHamming84sx(codewords[2], error, bad) & 0xf; // coding rate and crc enable
bytes[2] = decodeHamming84sx(codewords[4], error, bad) & 0xf;
bytes[2] |= decodeHamming84sx(codewords[3], error, bad) << 4; // checksum
bytes[2] ^= headerChecksum(bytes);
if (bad)
{
headerParityStatus = (int) MeshtasticDemodSettings::ParityError;
}
else
{
if (error) {
headerParityStatus = (int) MeshtasticDemodSettings::ParityCorrected;
} else {
headerParityStatus = (int) MeshtasticDemodSettings::ParityOK;
}
if (((bytes[2] & 0x1F) != 0) || (bytes[0] == 0)) {
headerCRCStatus = false;
} else {
headerCRCStatus = true;
}
}
hasCRC = (bytes[1] & 1) != 0;
nbParityBits = (bytes[1] >> 1) & 0x7;
packetLength = bytes[0];
}
void MeshtasticDemodDecoderLoRa::decodeBytes(
QByteArray& inBytes,
const std::vector<unsigned short>& inSymbols,
unsigned int payloadNbSymbolBits,
unsigned int headerNbSymbolBits,
bool hasHeader,
bool& hasCRC,
unsigned int& nbParityBits,
unsigned int& packetLength,
bool& earlyEOM,
int& headerParityStatus,
bool& headerCRCStatus,
int& payloadParityStatus,
bool& payloadCRCStatus
)
{
payloadCRCStatus = false;
// need at least a header (8 symbols of 8 bit codewords) whether an actual header is sent or not
if (inSymbols.size() < headerSymbols)
{
qDebug("MeshtasticDemodDecoderLoRa::decodeBytes: need at least %u symbols for header", headerSymbols);
earlyEOM = true;
return;
}
else
{
earlyEOM = false;
}
if (hasHeader)
{
if (headerNbSymbolBits < headerCodewords)
{
qDebug("MeshtasticDemodDecoderLoRa::decodeBytes: invalid header symbol bits: %u", headerNbSymbolBits);
earlyEOM = true;
headerCRCStatus = false;
return;
}
decodeHeader(
inSymbols,
headerNbSymbolBits,
hasCRC,
nbParityBits,
packetLength,
headerParityStatus,
headerCRCStatus
);
// Match gr-lora_sdr behavior: on explicit-header checksum failure,
// do not continue payload decoding for this frame attempt.
if (!headerCRCStatus)
{
earlyEOM = true;
return;
}
}
qDebug("MeshtasticDemodDecoderLoRa::decodeBytes: crc: %s nbParityBits: %u packetLength: %u payloadSFbits: %u headerSFbits: %u",
hasCRC ? "on": "off", nbParityBits, packetLength, payloadNbSymbolBits, headerNbSymbolBits);
if (nbParityBits > 4)
{
qDebug("MeshtasticDemodDecoderLoRa::decodeBytes: invalid parity bits in header: %u", nbParityBits);
earlyEOM = true;
headerCRCStatus = false;
return;
}
const unsigned int payloadBlockSymbols = 4 + nbParityBits;
unsigned int numSymbols = 0;
unsigned int numCodewords = 0;
if (hasHeader)
{
const unsigned int payloadSymbols = inSymbols.size() > headerSymbols
? static_cast<unsigned int>(inSymbols.size() - headerSymbols)
: 0U;
const unsigned int payloadBlocks = payloadSymbols / payloadBlockSymbols;
numSymbols = headerSymbols + payloadBlocks * payloadBlockSymbols;
numCodewords = headerNbSymbolBits + payloadBlocks * payloadNbSymbolBits;
}
else
{
const unsigned int payloadBlocks = static_cast<unsigned int>(inSymbols.size()) / payloadBlockSymbols;
numSymbols = payloadBlocks * payloadBlockSymbols;
numCodewords = payloadBlocks * payloadNbSymbolBits;
}
if (numSymbols < headerSymbols)
{
earlyEOM = true;
return;
}
std::vector<uint16_t> symbols(numSymbols);
std::copy_n(inSymbols.begin(), numSymbols, symbols.begin());
//gray encode, when SF > PPM, depad the LSBs with rounding
for (auto &sym : symbols) {
sym = binaryToGray16(sym);
}
std::vector<uint8_t> codewords(numCodewords);
// deinterleave / dewhiten the symbols into codewords
unsigned int sOfs = 0;
unsigned int cOfs = 0;
// The first 8 LoRa symbols are always protected with 4/8 FEC.
// In explicit-header mode this first block is interleaved over SF-2 bits
// (header + first payload nibbles), while the remaining payload uses the
// configured payload symbol width.
if (hasHeader)
{
diagonalDeinterleaveSx(symbols.data(), headerSymbols, codewords.data(), headerNbSymbolBits, headerParityBits);
cOfs = headerNbSymbolBits;
sOfs = headerSymbols;
if (numSymbols > sOfs)
{
diagonalDeinterleaveSx(symbols.data() + sOfs, numSymbols - sOfs, codewords.data() + cOfs, payloadNbSymbolBits, nbParityBits);
}
}
else
{
diagonalDeinterleaveSx(symbols.data(), numSymbols, codewords.data(), payloadNbSymbolBits, nbParityBits);
}
// Now we have nbSymbolBits 8-bit codewords (4/8 FEC) possibly containing the actual header followed by the rest of payload codewords with their own FEC (4/5..4/8)
std::vector<uint8_t> bytes((codewords.size()+1) / 2);
unsigned int dOfs = 0;
cOfs = 0;
// Payload byte count plus optional outer CRC bytes; include header bytes
// only for explicit-header mode.
unsigned int dataLength = packetLength + (hasCRC ? 2 : 0);
if (hasHeader) {
dataLength += 3;
}
if (hasHeader)
{
cOfs = headerCodewords;
dOfs = 6;
}
else
{
cOfs = 0;
dOfs = 0;
}
if (dataLength > bytes.size())
{
qDebug("MeshtasticDemodDecoderLoRa::decodeBytes: not enough data %lu vs %u", bytes.size(), dataLength);
earlyEOM = true;
return;
}
// decode the rest of the payload inside 8-bit codewords header with 4/8 FEC
bool error = false;
bool bad = false;
const unsigned int firstBlockCodewords = hasHeader ? headerNbSymbolBits : payloadNbSymbolBits;
for (; cOfs < firstBlockCodewords; cOfs++, dOfs++)
{
if (dOfs % 2 == 1) {
bytes[dOfs/2] |= decodeHamming84sx(codewords[cOfs], error, bad) << 4;
} else {
bytes[dOfs/2] = decodeHamming84sx(codewords[cOfs], error, bad) & 0xf;
}
}
if (dOfs % 2 == 1) // decode the start of the payload codewords with their own FEC when not on an even boundary
{
if (nbParityBits == 1) {
bytes[dOfs/2] |= checkParity54(codewords[cOfs++], error) << 4;
} else if (nbParityBits == 2) {
bytes[dOfs/2] |= checkParity64(codewords[cOfs++], error) << 4;
} else if (nbParityBits == 3){
bytes[dOfs/2] |= decodeHamming74sx(codewords[cOfs++], error) << 4;
} else if (nbParityBits == 4){
bytes[dOfs/2] |= decodeHamming84sx(codewords[cOfs++], error, bad) << 4;
} else {
bytes[dOfs/2] |= codewords[cOfs++] << 4;
}
dOfs++;
}
dOfs /= 2;
// decode the rest of the payload codewords with their own FEC
if (nbParityBits == 1)
{
for (unsigned int i = dOfs; i < dataLength; i++)
{
bytes[i] = checkParity54(codewords[cOfs++],error);
bytes[i] |= checkParity54(codewords[cOfs++], error) << 4;
}
}
else if (nbParityBits == 2)
{
for (unsigned int i = dOfs; i < dataLength; i++)
{
bytes[i] = checkParity64(codewords[cOfs++], error);
bytes[i] |= checkParity64(codewords[cOfs++],error) << 4;
}
}
else if (nbParityBits == 3)
{
for (unsigned int i = dOfs; i < dataLength; i++)
{
bytes[i] = decodeHamming74sx(codewords[cOfs++], error) & 0xf;
bytes[i] |= decodeHamming74sx(codewords[cOfs++], error) << 4;
}
}
else if (nbParityBits == 4)
{
for (unsigned int i = dOfs; i < dataLength; i++)
{
bytes[i] = decodeHamming84sx(codewords[cOfs++], error, bad) & 0xf;
bytes[i] |= decodeHamming84sx(codewords[cOfs++], error, bad) << 4;
}
}
else
{
for (unsigned int i = dOfs; i < dataLength; i++)
{
bytes[i] = codewords[cOfs++] & 0xf;
bytes[i] |= codewords[cOfs++] << 4;
}
}
// LoRa payload dewhitening is applied after FEC decode and excludes the CRC bytes.
const unsigned int payloadByteOfs = hasHeader ? 3U : 0U;
if (packetLength > 0U && (payloadByteOfs + packetLength) <= bytes.size()) {
dewhitenPayloadBytes(bytes.data() + payloadByteOfs, packetLength);
}
if (bad) {
payloadParityStatus = (int) MeshtasticDemodSettings::ParityError;
} else if (error) {
payloadParityStatus = (int) MeshtasticDemodSettings::ParityCorrected;
} else {
payloadParityStatus = (int) MeshtasticDemodSettings::ParityOK;
}
// finalization:
// adjust offsets dpending on header and CRC presence
// compute and verify payload CRC if present
if (hasHeader)
{
dOfs = 3; // skip header
dataLength -= 3; // remove header
if (hasCRC) // always compute crc if present skipping the header
{
if ((packetLength >= 2U) && ((dOfs + packetLength + 2U) <= bytes.size()))
{
// Match gr-lora_sdr crc_verif:
// crc16(first pay_len-2 bytes) XOR last 2 bytes inside payload
// compare against trailing CRC bytes.
uint16_t crc = crc16gr(bytes.data() + dOfs, packetLength - 2U);
crc = static_cast<uint16_t>(crc ^ static_cast<uint8_t>(bytes[dOfs + packetLength - 1U]));
crc = static_cast<uint16_t>(crc ^ (static_cast<uint16_t>(static_cast<uint8_t>(bytes[dOfs + packetLength - 2U])) << 8));
const uint16_t packetCRC = static_cast<uint16_t>(static_cast<uint8_t>(bytes[dOfs + packetLength]))
| (static_cast<uint16_t>(static_cast<uint8_t>(bytes[dOfs + packetLength + 1U])) << 8);
payloadCRCStatus = (crc == packetCRC);
}
else
{
payloadCRCStatus = false;
}
}
else
{
payloadCRCStatus = true;
}
}
else
{
dOfs = 0; // no header to skip
if (hasCRC)
{
if ((packetLength >= 2U) && ((packetLength + 2U) <= bytes.size()))
{
uint16_t crc = crc16gr(bytes.data(), packetLength - 2U);
crc = static_cast<uint16_t>(crc ^ static_cast<uint8_t>(bytes[packetLength - 1U]));
crc = static_cast<uint16_t>(crc ^ (static_cast<uint16_t>(static_cast<uint8_t>(bytes[packetLength - 2U])) << 8));
const uint16_t packetCRC = static_cast<uint16_t>(static_cast<uint8_t>(bytes[packetLength]))
| (static_cast<uint16_t>(static_cast<uint8_t>(bytes[packetLength + 1U])) << 8);
payloadCRCStatus = (crc == packetCRC);
}
else
{
payloadCRCStatus = false;
}
}
else
{
payloadCRCStatus = true;
}
}
inBytes.resize(packetLength);
std::copy(bytes.data() + dOfs, bytes.data() + dOfs + packetLength, inBytes.data());
}
void MeshtasticDemodDecoderLoRa::decodeBytesSoft(
QByteArray& inBytes,
const std::vector<std::vector<float>>& inMagnitudes,
const std::vector<unsigned short>& inSymbols,
unsigned int spreadFactor,
unsigned int bandwidth,
unsigned int payloadNbSymbolBits,
unsigned int headerNbSymbolBits,
bool hasHeader,
bool& hasCRC,
unsigned int& nbParityBits,
unsigned int& packetLength,
bool& earlyEOM,
int& headerParityStatus,
bool& headerCRCStatus,
int& payloadParityStatus,
bool& payloadCRCStatus
)
{
payloadCRCStatus = false;
payloadParityStatus = (int) MeshtasticDemodSettings::ParityUndefined;
if (inSymbols.size() < headerSymbols)
{
earlyEOM = true;
return;
}
else
{
earlyEOM = false;
}
if (hasHeader)
{
if (headerNbSymbolBits < headerCodewords)
{
earlyEOM = true;
headerCRCStatus = false;
return;
}
decodeHeader(
inSymbols,
headerNbSymbolBits,
hasCRC,
nbParityBits,
packetLength,
headerParityStatus,
headerCRCStatus
);
if (!headerCRCStatus)
{
earlyEOM = true;
return;
}
}
if ((nbParityBits < 1U) || (nbParityBits > 4U))
{
earlyEOM = true;
headerCRCStatus = false;
return;
}
const unsigned int payloadBlockSymbols = 4U + nbParityBits;
unsigned int numSymbols = 0U;
if (hasHeader)
{
const unsigned int payloadSymbols = inSymbols.size() > headerSymbols
? static_cast<unsigned int>(inSymbols.size() - headerSymbols)
: 0U;
const unsigned int payloadBlocks = payloadSymbols / payloadBlockSymbols;
numSymbols = headerSymbols + payloadBlocks * payloadBlockSymbols;
}
else
{
const unsigned int payloadBlocks = static_cast<unsigned int>(inSymbols.size()) / payloadBlockSymbols;
numSymbols = payloadBlocks * payloadBlockSymbols;
}
if ((numSymbols < headerSymbols) || (inMagnitudes.size() < numSymbols))
{
earlyEOM = true;
return;
}
const unsigned int N = 1U << spreadFactor;
const bool ldro = ((1U << spreadFactor) * 1000.0 / static_cast<double>(std::max(1U, bandwidth))) > 16.0;
std::vector<std::vector<float>> llrs(numSymbols, std::vector<float>(spreadFactor, 0.0f));
for (unsigned int symIdx = 0; symIdx < numSymbols; symIdx++)
{
const std::vector<float>& mags = inMagnitudes[symIdx];
if (mags.size() < N)
{
earlyEOM = true;
return;
}
const bool isHeaderSym = hasHeader && (symIdx < headerSymbols);
const bool ldroSym = (!isHeaderSym) && ldro;
const unsigned int symbolDiv = (isHeaderSym || ldroSym) ? 4U : 1U;
for (unsigned int bit = 0; bit < spreadFactor; bit++)
{
float maxX1 = std::numeric_limits<float>::lowest();
float maxX0 = std::numeric_limits<float>::lowest();
for (unsigned int n = 0; n < N; n++)
{
unsigned int s = static_cast<unsigned int>(modInt(static_cast<int>(n) - 1, static_cast<int>(N)));
s /= symbolDiv;
s = s ^ (s >> 1U);
const float v = mags[n];
if ((s & (1U << bit)) != 0U) {
maxX1 = std::max(maxX1, v);
} else {
maxX0 = std::max(maxX0, v);
}
}
if (!std::isfinite(maxX1)) { maxX1 = 0.0f; }
if (!std::isfinite(maxX0)) { maxX0 = 0.0f; }
llrs[symIdx][spreadFactor - 1U - bit] = maxX1 - maxX0;
}
}
auto decodeSoftBlock = [&llrs, spreadFactor](unsigned int symOfs, unsigned int cwLen, unsigned int sfApp, unsigned int crApp, std::vector<uint8_t>& nibbles) {
if (sfApp == 0U) {
return false;
}
std::vector<std::vector<float>> interBin(cwLen, std::vector<float>(sfApp, 0.0f));
std::vector<std::vector<float>> deinterBin(sfApp, std::vector<float>(cwLen, 0.0f));
for (unsigned int i = 0; i < cwLen; i++)
{
const std::vector<float>& symLlr = llrs[symOfs + i];
const unsigned int start = (spreadFactor > sfApp) ? (spreadFactor - sfApp) : 0U;
for (unsigned int j = 0; j < sfApp; j++) {
interBin[i][j] = symLlr[start + j];
}
}
for (unsigned int i = 0; i < cwLen; i++)
{
for (unsigned int j = 0; j < sfApp; j++)
{
const unsigned int row = static_cast<unsigned int>(modInt(static_cast<int>(i) - static_cast<int>(j) - 1, static_cast<int>(sfApp)));
deinterBin[row][i] = interBin[i][j];
}
}
for (unsigned int row = 0; row < sfApp; row++) {
nibbles.push_back(decodeCodewordSoft(deinterBin[row], crApp));
}
return true;
};
std::vector<uint8_t> nibbles;
nibbles.reserve((packetLength + (hasCRC ? 2U : 0U) * 2U) + 16U);
unsigned int symOfs = 0U;
if (hasHeader)
{
if (symOfs + headerSymbols > numSymbols) {
earlyEOM = true;
return;
}
if (!decodeSoftBlock(symOfs, 8U, headerNbSymbolBits, 4U, nibbles)) {
earlyEOM = true;
return;
}
symOfs += headerSymbols;
}
while (symOfs + payloadBlockSymbols <= numSymbols)
{
if (!decodeSoftBlock(symOfs, payloadBlockSymbols, payloadNbSymbolBits, nbParityBits, nibbles)) {
earlyEOM = true;
return;
}
symOfs += payloadBlockSymbols;
}
const unsigned int dataByteLen = packetLength + (hasCRC ? 2U : 0U);
const unsigned int nibbleOfs = hasHeader ? 5U : 0U;
const unsigned int neededNibbles = nibbleOfs + dataByteLen * 2U;
if (nibbles.size() < neededNibbles)
{
earlyEOM = true;
return;
}
std::vector<uint8_t> bytes(dataByteLen, 0U);
for (unsigned int i = 0; i < dataByteLen; i++)
{
const uint8_t low = nibbles[nibbleOfs + i * 2U] & 0x0FU;
const uint8_t high = nibbles[nibbleOfs + i * 2U + 1U] & 0x0FU;
bytes[i] = static_cast<uint8_t>(low | (high << 4));
}
if (packetLength > 0U) {
dewhitenPayloadBytes(bytes.data(), packetLength);
}
if (hasCRC)
{
if ((packetLength >= 2U) && (dataByteLen >= packetLength + 2U))
{
uint16_t crc = crc16gr(bytes.data(), packetLength - 2U);
crc = static_cast<uint16_t>(crc ^ bytes[packetLength - 1U]);
crc = static_cast<uint16_t>(crc ^ (static_cast<uint16_t>(bytes[packetLength - 2U]) << 8));
const uint16_t packetCRC = static_cast<uint16_t>(bytes[packetLength])
| (static_cast<uint16_t>(bytes[packetLength + 1U]) << 8);
payloadCRCStatus = (crc == packetCRC);
}
else
{
payloadCRCStatus = false;
}
}
else
{
payloadCRCStatus = true;
}
inBytes.resize(packetLength);
std::copy(bytes.begin(), bytes.begin() + packetLength, inBytes.begin());
}
void MeshtasticDemodDecoderLoRa::getCodingMetrics(
unsigned int payloadNbSymbolBits,
unsigned int headerNbSymbolBits,
unsigned int nbParityBits,
unsigned int packetLength,
bool hasHeader,
bool hasCRC,
unsigned int& numSymbols,
unsigned int& numCodewords
)
{
if (hasHeader)
{
const unsigned int payloadNibbles = (packetLength + (hasCRC ? 2 : 0)) * 2;
const unsigned int firstPayloadNibbles = headerNbSymbolBits > headerCodewords ? (headerNbSymbolBits - headerCodewords) : 0;
const unsigned int remainingPayloadNibbles = payloadNibbles > firstPayloadNibbles ? (payloadNibbles - firstPayloadNibbles) : 0;
const unsigned int payloadBlocks = remainingPayloadNibbles > 0 ? roundUp(remainingPayloadNibbles, payloadNbSymbolBits) / payloadNbSymbolBits : 0;
numCodewords = headerNbSymbolBits + payloadBlocks * payloadNbSymbolBits;
numSymbols = headerSymbols + payloadBlocks * (4 + nbParityBits);
}
else
{
numCodewords = roundUp((packetLength + (hasCRC ? 2 : 0)) * 2, payloadNbSymbolBits);
numSymbols = headerSymbols + (numCodewords / payloadNbSymbolBits - 1) * (4 + nbParityBits);
}
}

483
plugins/channelrx/demodmeshtastic/meshtasticdemoddecoderlora.h

@ -0,0 +1,483 @@ @@ -0,0 +1,483 @@
///////////////////////////////////////////////////////////////////////////////////
// Copyright (C) 2020 Edouard Griffiths, F4EXB <f4exb06@gmail.com> //
// //
// Inspired by: https://github.com/myriadrf/LoRa-SDR //
// //
// This program is free software; you can redistribute it and/or modify //
// it under the terms of the GNU General Public License as published by //
// the Free Software Foundation as version 3 of the License, or //
// (at your option) any later version. //
// //
// This program is distributed in the hope that it will be useful, //
// but WITHOUT ANY WARRANTY; without even the implied warranty of //
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //
// GNU General Public License V3 for more details. //
// //
// You should have received a copy of the GNU General Public License //
// along with this program. If not, see <http://www.gnu.org/licenses/>. //
///////////////////////////////////////////////////////////////////////////////////
#ifndef INCLUDE_MESHTASTICDEMODDECODERLORA_H
#define INCLUDE_MESHTASTICDEMODDECODERLORA_H
#include <cmath>
#include <limits>
#include <vector>
#include <QByteArray>
class MeshtasticDemodDecoderLoRa
{
public:
static void decodeBytes(
QByteArray& bytes,
const std::vector<unsigned short>& inSymbols,
unsigned int payloadNbSymbolBits,
unsigned int headerNbSymbolBits,
bool hasHeader,
bool& hasCRC,
unsigned int& nbParityBits,
unsigned int& packetLength,
bool& earlyEOM,
int& headerParityStatus,
bool& headerCRCStatus,
int& payloadParityStatus,
bool& payloadCRCStatus
);
static void decodeBytesSoft(
QByteArray& bytes,
const std::vector<std::vector<float>>& inMagnitudes,
const std::vector<unsigned short>& inSymbols,
unsigned int spreadFactor,
unsigned int bandwidth,
unsigned int payloadNbSymbolBits,
unsigned int headerNbSymbolBits,
bool hasHeader,
bool& hasCRC,
unsigned int& nbParityBits,
unsigned int& packetLength,
bool& earlyEOM,
int& headerParityStatus,
bool& headerCRCStatus,
int& payloadParityStatus,
bool& payloadCRCStatus
);
static void getCodingMetrics(
unsigned int payloadNbSymbolBits,
unsigned int headerNbSymbolBits,
unsigned int nbParityBits,
unsigned int packetLength,
bool hasHeader,
bool hasCRC,
unsigned int& numSymbols,
unsigned int& numCodewords
);
static void decodeHeader(
const std::vector<unsigned short>& inSymbols,
unsigned int headerNbSymbolBits,
bool& hasCRC,
unsigned int& nbParityBits,
unsigned int& packetLength,
int& headerParityStatus,
bool& headerCRCStatus
);
private:
static constexpr unsigned int headerParityBits = 4;
static constexpr unsigned int headerSymbols = 8;
static constexpr unsigned int headerCodewords = 5;
/***********************************************************************
* Round functions
**********************************************************************/
static inline unsigned roundUp(unsigned num, unsigned factor)
{
return ((num + factor - 1) / factor) * factor;
}
/***********************************************************************
* https://en.wikipedia.org/wiki/Gray_code
**********************************************************************/
/*
* This function converts an unsigned binary
* number to reflected binary Gray code.
*
* The operator >> is shift right. The operator ^ is exclusive or.
*/
static inline unsigned short binaryToGray16(unsigned short num)
{
return num ^ (num >> 1);
}
static inline int modInt(int a, int b)
{
if (b <= 0) {
return 0;
}
return (a % b + b) % b;
}
/***********************************************************************
* Diagonal deinterleaver
**********************************************************************/
static inline void diagonalDeinterleaveSx(
const uint16_t *symbols,
const unsigned int numSymbols,
uint8_t *codewords,
const unsigned int nbSymbolBits,
const unsigned int nbParityBits)
{
const int cwLen = 4 + static_cast<int>(nbParityBits);
for (unsigned int x = 0; x < numSymbols / (4 + nbParityBits); x++)
{
const unsigned int cwOff = x*nbSymbolBits;
const unsigned int symOff = x*(4U + nbParityBits);
for (int i = 0; i < cwLen; i++)
{
const uint16_t sym = symbols[symOff + i];
for (int j = 0; j < static_cast<int>(nbSymbolBits); j++)
{
const uint8_t bit = (sym >> (static_cast<int>(nbSymbolBits) - 1 - j)) & 0x1;
const int row = ((i - j - 1) % static_cast<int>(nbSymbolBits) + static_cast<int>(nbSymbolBits)) % static_cast<int>(nbSymbolBits);
codewords[cwOff + static_cast<unsigned int>(row)] |= (bit << (cwLen - 1 - i));
}
}
}
}
/***********************************************************************
* Dewhitening sequence used by LoRa payload bytes.
* Matches the sequence used by gr-lora_sdr.
**********************************************************************/
static constexpr uint8_t s_whiteningSeq[] = {
0xFF, 0xFE, 0xFC, 0xF8, 0xF0, 0xE1, 0xC2, 0x85, 0x0B, 0x17, 0x2F, 0x5E, 0xBC, 0x78, 0xF1, 0xE3,
0xC6, 0x8D, 0x1A, 0x34, 0x68, 0xD0, 0xA0, 0x40, 0x80, 0x01, 0x02, 0x04, 0x08, 0x11, 0x23, 0x47,
0x8E, 0x1C, 0x38, 0x71, 0xE2, 0xC4, 0x89, 0x12, 0x25, 0x4B, 0x97, 0x2E, 0x5C, 0xB8, 0x70, 0xE0,
0xC0, 0x81, 0x03, 0x06, 0x0C, 0x19, 0x32, 0x64, 0xC9, 0x92, 0x24, 0x49, 0x93, 0x26, 0x4D, 0x9B,
0x37, 0x6E, 0xDC, 0xB9, 0x72, 0xE4, 0xC8, 0x90, 0x20, 0x41, 0x82, 0x05, 0x0A, 0x15, 0x2B, 0x56,
0xAD, 0x5B, 0xB6, 0x6D, 0xDA, 0xB5, 0x6B, 0xD6, 0xAC, 0x59, 0xB2, 0x65, 0xCB, 0x96, 0x2C, 0x58,
0xB0, 0x61, 0xC3, 0x87, 0x0F, 0x1F, 0x3E, 0x7D, 0xFB, 0xF6, 0xED, 0xDB, 0xB7, 0x6F, 0xDE, 0xBD,
0x7A, 0xF5, 0xEB, 0xD7, 0xAE, 0x5D, 0xBA, 0x74, 0xE8, 0xD1, 0xA2, 0x44, 0x88, 0x10, 0x21, 0x43,
0x86, 0x0D, 0x1B, 0x36, 0x6C, 0xD8, 0xB1, 0x63, 0xC7, 0x8F, 0x1E, 0x3C, 0x79, 0xF3, 0xE7, 0xCE,
0x9C, 0x39, 0x73, 0xE6, 0xCC, 0x98, 0x31, 0x62, 0xC5, 0x8B, 0x16, 0x2D, 0x5A, 0xB4, 0x69, 0xD2,
0xA4, 0x48, 0x91, 0x22, 0x45, 0x8A, 0x14, 0x29, 0x52, 0xA5, 0x4A, 0x95, 0x2A, 0x54, 0xA9, 0x53,
0xA7, 0x4E, 0x9D, 0x3B, 0x77, 0xEE, 0xDD, 0xBB, 0x76, 0xEC, 0xD9, 0xB3, 0x67, 0xCF, 0x9E, 0x3D,
0x7B, 0xF7, 0xEF, 0xDF, 0xBF, 0x7E, 0xFD, 0xFA, 0xF4, 0xE9, 0xD3, 0xA6, 0x4C, 0x99, 0x33, 0x66,
0xCD, 0x9A, 0x35, 0x6A, 0xD4, 0xA8, 0x51, 0xA3, 0x46, 0x8C, 0x18, 0x30, 0x60, 0xC1, 0x83, 0x07,
0x0E, 0x1D, 0x3A, 0x75, 0xEA, 0xD5, 0xAA, 0x55, 0xAB, 0x57, 0xAF, 0x5F, 0xBE, 0x7C, 0xF9, 0xF2,
0xE5, 0xCA, 0x94, 0x28, 0x50, 0xA1, 0x42, 0x84, 0x09, 0x13, 0x27, 0x4F, 0x9F, 0x3F, 0x7F
};
static inline void dewhitenPayloadBytes(uint8_t* payload, unsigned int length)
{
const unsigned int whiteningSize = static_cast<unsigned int>(sizeof(s_whiteningSeq) / sizeof(s_whiteningSeq[0]));
for (unsigned int i = 0; i < length; ++i) {
payload[i] ^= s_whiteningSeq[i % whiteningSize];
}
}
/***********************************************************************
* Canonical gr-lora_sdr hard-decision codeword decoder.
* crApp is the LoRa coding-rate parity bits count in [1..4].
**********************************************************************/
static inline unsigned char decodeCodewordHard(const unsigned char b, unsigned int crApp, bool &error, bool &bad)
{
if ((crApp < 1U) || (crApp > 4U)) {
bad = true;
return b & 0xF;
}
const unsigned int cwLen = 4U + crApp;
bool codeword[8] = {false, false, false, false, false, false, false, false};
for (unsigned int i = 0; i < cwLen; i++) {
codeword[i] = ((b >> (cwLen - 1U - i)) & 0x1U) != 0U;
}
// hamming_dec nibble ordering: {codeword[3], codeword[2], codeword[1], codeword[0]}.
uint8_t nibbleBits[4] = {
static_cast<uint8_t>(codeword[3]),
static_cast<uint8_t>(codeword[2]),
static_cast<uint8_t>(codeword[1]),
static_cast<uint8_t>(codeword[0])
};
switch (crApp)
{
case 4:
{
int ones = 0;
for (unsigned int i = 0; i < cwLen; i++) {
ones += codeword[i] ? 1 : 0;
}
if ((ones % 2) == 0) {
break; // do not correct even-weight patterns
}
// fall through to crApp=3 syndrome logic
}
// no break
case 3:
{
const bool s0 = codeword[0] ^ codeword[1] ^ codeword[2] ^ codeword[4];
const bool s1 = codeword[1] ^ codeword[2] ^ codeword[3] ^ codeword[5];
const bool s2 = codeword[0] ^ codeword[1] ^ codeword[3] ^ codeword[6];
const int syndrome = static_cast<int>(s0) + (static_cast<int>(s1) << 1) + (static_cast<int>(s2) << 2);
if (syndrome != 0) {
error = true;
}
switch (syndrome)
{
case 5: nibbleBits[3] ^= 0x1U; break;
case 7: nibbleBits[2] ^= 0x1U; break;
case 3: nibbleBits[1] ^= 0x1U; break;
case 6: nibbleBits[0] ^= 0x1U; break;
default: break;
}
break;
}
case 2:
{
const bool s0 = codeword[0] ^ codeword[1] ^ codeword[2] ^ codeword[4];
const bool s1 = codeword[1] ^ codeword[2] ^ codeword[3] ^ codeword[5];
if (s0 || s1) {
error = true;
}
break;
}
case 1:
default:
{
int ones = 0;
for (unsigned int i = 0; i < cwLen; i++) {
ones += codeword[i] ? 1 : 0;
}
if ((ones % 2) == 0) {
error = true;
}
break;
}
}
bad = false;
return static_cast<unsigned char>((nibbleBits[0] << 3) | (nibbleBits[1] << 2) | (nibbleBits[2] << 1) | nibbleBits[3]);
}
static inline unsigned char decodeCodewordSoft(const std::vector<float>& codewordLLR, unsigned int crApp)
{
static const unsigned char cwLUT[16] = {
0, 23, 45, 58, 78, 89, 99, 116,
139, 156, 166, 177, 197, 210, 232, 255
};
static const unsigned char cwLUTCr5[16] = {
0, 24, 40, 48, 72, 80, 96, 120,
136, 144, 160, 184, 192, 216, 232, 240
};
if ((crApp < 1U) || (crApp > 4U)) {
return 0;
}
const unsigned int cwLen = 4U + crApp;
const unsigned char *lut = (crApp == 1U) ? cwLUTCr5 : cwLUT;
float bestScore = std::numeric_limits<float>::lowest();
unsigned int bestIdx = 0U;
for (unsigned int n = 0; n < 16U; n++)
{
const unsigned char cw = static_cast<unsigned char>(lut[n] >> (8U - cwLen));
float score = 0.0f;
for (unsigned int j = 0; j < cwLen; j++)
{
const bool bit = ((cw >> (cwLen - 1U - j)) & 0x1U) != 0U;
const float v = std::fabs(codewordLLR[j]);
score += (((bit && (codewordLLR[j] > 0.0f)) || (!bit && (codewordLLR[j] < 0.0f))) ? v : -v);
}
if (score > bestScore) {
bestScore = score;
bestIdx = n;
}
}
const unsigned char dataNibbleSoft = static_cast<unsigned char>(cwLUT[bestIdx] >> 4);
return static_cast<unsigned char>(
(((dataNibbleSoft & 0x1U) != 0U) << 3) |
(((dataNibbleSoft & 0x2U) != 0U) << 2) |
(((dataNibbleSoft & 0x4U) != 0U) << 1) |
((dataNibbleSoft & 0x8U) != 0U)
);
}
/***********************************************************************
* Decode 8 bits into a 4 bit word with single bit correction.
* Set error to true when a parity error was detected.
**********************************************************************/
static inline unsigned char decodeHamming84sx(const unsigned char b, bool &error, bool &bad)
{
return decodeCodewordHard(b, 4U, error, bad);
}
/***********************************************************************
* Simple 8-bit checksum routine
**********************************************************************/
static inline uint8_t checksum8(const uint8_t *p, const size_t len)
{
uint8_t acc = 0;
for (size_t i = 0; i < len; i++)
{
acc = (acc >> 1) + ((acc & 0x1) << 7); //rotate
acc += p[i]; //add
}
return acc;
}
static inline uint8_t headerChecksum(const uint8_t *h)
{
auto a0 = (h[0] >> 4) & 0x1;
auto a1 = (h[0] >> 5) & 0x1;
auto a2 = (h[0] >> 6) & 0x1;
auto a3 = (h[0] >> 7) & 0x1;
auto b0 = (h[0] >> 0) & 0x1;
auto b1 = (h[0] >> 1) & 0x1;
auto b2 = (h[0] >> 2) & 0x1;
auto b3 = (h[0] >> 3) & 0x1;
auto c0 = (h[1] >> 0) & 0x1;
auto c1 = (h[1] >> 1) & 0x1;
auto c2 = (h[1] >> 2) & 0x1;
auto c3 = (h[1] >> 3) & 0x1;
uint8_t res;
res = (a0 ^ a1 ^ a2 ^ a3) << 4;
res |= (a3 ^ b1 ^ b2 ^ b3 ^ c0) << 3;
res |= (a2 ^ b0 ^ b3 ^ c1 ^ c3) << 2;
res |= (a1 ^ b0 ^ b2 ^ c0 ^ c1 ^ c2) << 1;
res |= a0 ^ b1 ^ c0 ^ c1 ^ c2 ^ c3;
return res;
}
/***********************************************************************
* Check parity for 5/4 code.
* return true if parity is valid.
**********************************************************************/
static inline unsigned char checkParity54(const unsigned char b, bool &error)
{
bool bad = false;
return decodeCodewordHard(b, 1U, error, bad);
}
/***********************************************************************
* Check parity for 6/4 code.
* return true if parity is valid.
**********************************************************************/
static inline unsigned char checkParity64(const unsigned char b, bool &error)
{
bool bad = false;
return decodeCodewordHard(b, 2U, error, bad);
}
/***********************************************************************
* Decode 7 bits into a 4 bit word with single bit correction.
* Non standard version used in sx1272.
* Set error to true when a parity error was detected
* Non correctable errors are indistinguishable from single or no errors
* therefore no 'bad' variable is proposed
**********************************************************************/
static inline unsigned char decodeHamming74sx(const unsigned char b, bool &error)
{
bool bad = false;
return decodeCodewordHard(b, 3U, error, bad);
}
/***********************************************************************
* CRC reverse engineered from Sx1272 data stream.
* Modified CCITT crc with masking of the output with an 8bit lfsr
**********************************************************************/
static inline uint16_t crc16sx(uint16_t crc, const uint16_t poly)
{
for (int i = 0; i < 8; i++)
{
if (crc & 0x8000) {
crc = (crc << 1) ^ poly;
} else {
crc <<= 1;
}
}
return crc;
}
static inline uint8_t xsum8(uint8_t t)
{
t ^= t >> 4;
t ^= t >> 2;
t ^= t >> 1;
return (t & 1);
}
static inline uint16_t sx1272DataChecksum(const uint8_t *data, int length)
{
uint16_t res = 0;
uint8_t v = 0xff;
uint16_t crc = 0;
for (int i = 0; i < length; i++)
{
crc = crc16sx(res, 0x1021);
v = xsum8(v & 0xB8) | (v << 1);
res = crc ^ data[i];
}
res ^= v;
v = xsum8(v & 0xB8) | (v << 1);
res ^= v << 8;
return res;
}
/**
* CRC routine used by gr-lora_sdr crc_verif block.
*/
static inline uint16_t crc16gr(const uint8_t *data, unsigned int length)
{
uint16_t crc = 0x0000;
for (unsigned int i = 0; i < length; i++)
{
uint8_t b = data[i];
for (unsigned char j = 0; j < 8; j++)
{
if ((((crc & 0x8000) >> 8) ^ (b & 0x80)) != 0) {
crc = static_cast<uint16_t>((crc << 1) ^ 0x1021);
} else {
crc = static_cast<uint16_t>(crc << 1);
}
b <<= 1;
}
}
return crc;
}
};
#endif // INCLUDE_MESHTASTICDEMODDECODERLORA_H

67
plugins/channelrx/demodmeshtastic/meshtasticdemoddecodertty.cpp

@ -0,0 +1,67 @@ @@ -0,0 +1,67 @@
///////////////////////////////////////////////////////////////////////////////////
// Copyright (C) 2020 Edouard Griffiths, F4EXB <f4exb06@gmail.com> //
// //
// This program is free software; you can redistribute it and/or modify //
// it under the terms of the GNU General Public License as published by //
// the Free Software Foundation as version 3 of the License, or //
// (at your option) any later version. //
// //
// This program is distributed in the hope that it will be useful, //
// but WITHOUT ANY WARRANTY; without even the implied warranty of //
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //
// GNU General Public License V3 for more details. //
// //
// You should have received a copy of the GNU General Public License //
// along with this program. If not, see <http://www.gnu.org/licenses/>. //
///////////////////////////////////////////////////////////////////////////////////
#include "meshtasticdemoddecodertty.h"
const char MeshtasticDemodDecoderTTY::ttyLetters[32] = {
'_', 'E', '\n', 'A', ' ', 'S', 'I', 'U',
'\r', 'D', 'R', 'J', 'N', 'F', 'C', 'K',
'T', 'Z', 'L', 'W', 'H', 'Y', 'P', 'Q',
'O', 'B', 'G', ' ', 'M', 'X', 'V', ' '
};
const char MeshtasticDemodDecoderTTY::ttyFigures[32] = { // U.S. standard
'_', '3', '\n', '-', ' ', '\a', '8', '7',
'\r', '$', '4', '\'', ',', '!', ':', '(',
'5', '"', ')', '2', '#', '6', '0', '1',
'9', '?', '&', ' ', '.', '/', ';', ' '
};
void MeshtasticDemodDecoderTTY::decodeSymbols(const std::vector<unsigned short>& symbols, QString& str)
{
std::vector<unsigned short>::const_iterator it = symbols.begin();
QByteArray bytes;
TTYState ttyState = TTYLetters;
for (; it != symbols.end(); ++it)
{
char ttyChar = *it & 0x1F;
if (ttyChar == lettersTag) {
ttyState = TTYLetters;
} else if (ttyChar == figuresTag) {
ttyState = TTYFigures;
}
else
{
signed char asciiChar = -1;
if (ttyState == TTYLetters) {
asciiChar = ttyLetters[(int) ttyChar];
} else if (ttyState == TTYFigures) {
asciiChar = ttyFigures[(int) ttyChar];
}
if (asciiChar >= 0) {
bytes.push_back(asciiChar);
}
}
}
str = QString(bytes.toStdString().c_str());
}

44
plugins/channelrx/demodmeshtastic/meshtasticdemoddecodertty.h

@ -0,0 +1,44 @@ @@ -0,0 +1,44 @@
///////////////////////////////////////////////////////////////////////////////////
// Copyright (C) 2012 maintech GmbH, Otto-Hahn-Str. 15, 97204 Hoechberg, Germany //
// written by Christian Daniel //
// Copyright (C) 2015-2020 Edouard Griffiths, F4EXB <f4exb06@gmail.com> //
// //
// This program is free software; you can redistribute it and/or modify //
// it under the terms of the GNU General Public License as published by //
// the Free Software Foundation as version 3 of the License, or //
// (at your option) any later version. //
// //
// This program is distributed in the hope that it will be useful, //
// but WITHOUT ANY WARRANTY; without even the implied warranty of //
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //
// GNU General Public License V3 for more details. //
// //
// You should have received a copy of the GNU General Public License //
// along with this program. If not, see <http://www.gnu.org/licenses/>. //
///////////////////////////////////////////////////////////////////////////////////
#ifndef INCLUDE_MESHTASTICDEMODDECODERTTY_H
#define INCLUDE_MESHTASTICDEMODDECODERTTY_H
#include <vector>
#include <QString>
class MeshtasticDemodDecoderTTY
{
public:
static void decodeSymbols(const std::vector<unsigned short>& symbols, QString& str);
private:
enum TTYState
{
TTYLetters,
TTYFigures
};
static const char ttyLetters[32];
static const char ttyFigures[32];
static const char lettersTag = 0x1f;
static const char figuresTag = 0x1b;
};
#endif // INCLUDE_MESHTASTICDEMODDECODERTTY_H

3522
plugins/channelrx/demodmeshtastic/meshtasticdemodgui.cpp

File diff suppressed because it is too large Load Diff

251
plugins/channelrx/demodmeshtastic/meshtasticdemodgui.h

@ -0,0 +1,251 @@ @@ -0,0 +1,251 @@
///////////////////////////////////////////////////////////////////////////////////
// Copyright (C) 2012 maintech GmbH, Otto-Hahn-Str. 15, 97204 Hoechberg, Germany //
// written by Christian Daniel //
// Copyright (C) 2014 John Greb <hexameron@spam.no> //
// Copyright (C) 2015-2020, 2022 Edouard Griffiths, F4EXB <f4exb06@gmail.com> //
// //
// This program is free software; you can redistribute it and/or modify //
// it under the terms of the GNU General Public License as published by //
// the Free Software Foundation as version 3 of the License, or //
// (at your option) any later version. //
// //
// This program is distributed in the hope that it will be useful, //
// but WITHOUT ANY WARRANTY; without even the implied warranty of //
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //
// GNU General Public License V3 for more details. //
// //
// You should have received a copy of the GNU General Public License //
// along with this program. If not, see <http://www.gnu.org/licenses/>. //
///////////////////////////////////////////////////////////////////////////////////
#ifndef INCLUDE_MESHTASTICDEMODGUI_H
#define INCLUDE_MESHTASTICDEMODGUI_H
#include "channel/channelgui.h"
#include "dsp/channelmarker.h"
#include "util/messagequeue.h"
#include "settings/rollupstate.h"
#include <vector>
#include <QMap>
#include <QVector>
#include "meshtasticdemodsettings.h"
class PluginAPI;
class DeviceUISet;
class MeshtasticDemod;
class SpectrumVis;
class BasebandSampleSink;
class QComboBox;
class QCheckBox;
class QPushButton;
class QTabWidget;
class QPlainTextEdit;
class QTreeWidget;
class QTreeWidgetItem;
namespace MeshtasticDemodMsg { class MsgReportDecodeBytes; }
namespace Ui {
class MeshtasticDemodGUI;
}
class MeshtasticDemodGUI : public ChannelGUI {
Q_OBJECT
public:
static MeshtasticDemodGUI* create(PluginAPI* pluginAPI, DeviceUISet *deviceAPI, 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; }
private slots:
void channelMarkerChangedByCursor();
void on_deltaFrequency_changed(qint64 value);
void on_BW_valueChanged(int value);
void on_Spread_valueChanged(int value);
void on_deBits_valueChanged(int value);
void on_fftWindow_currentIndexChanged(int index);
void on_preambleChirps_valueChanged(int value);
void on_scheme_currentIndexChanged(int index);
void on_mute_toggled(bool checked);
void on_clear_clicked(bool checked);
void on_eomSquelch_valueChanged(int value);
void on_messageLength_valueChanged(int value);
void on_messageLengthAuto_stateChanged(int state);
void on_header_stateChanged(int state);
void on_fecParity_valueChanged(int value);
void on_crc_stateChanged(int state);
void on_packetLength_valueChanged(int value);
void on_udpSend_stateChanged(int state);
void on_udpAddress_editingFinished();
void on_udpPort_editingFinished();
void on_invertRamps_stateChanged(int state);
void on_meshRegion_currentIndexChanged(int index);
void on_meshPreset_currentIndexChanged(int index);
void on_meshChannel_currentIndexChanged(int index);
void on_meshApply_clicked(bool checked);
void on_meshKeys_clicked(bool checked);
void on_meshAutoSampleRate_toggled(bool checked);
void on_meshAutoLock_clicked(bool checked);
void onWidgetRolled(QWidget* widget, bool rollDown);
void onMenuDialogCalled(const QPoint& p);
void channelMarkerHighlightedByCursor();
void handleInputMessages();
void onPipelineTreeSelectionChanged();
void tick();
private:
Ui::MeshtasticDemodGUI* ui;
PluginAPI* m_pluginAPI;
DeviceUISet* m_deviceUISet;
ChannelMarker m_channelMarker;
RollupState m_rollupState;
MeshtasticDemodSettings m_settings;
qint64 m_deviceCenterFrequency;
int m_basebandSampleRate;
bool m_doApplySettings;
MeshtasticDemod* m_chirpChatDemod;
SpectrumVis* m_spectrumVis;
QComboBox* m_meshRegionCombo;
QComboBox* m_meshPresetCombo;
QComboBox* m_meshChannelCombo;
QPushButton* m_meshApplyButton;
QPushButton* m_meshKeysButton;
QPushButton* m_meshAutoLockButton;
QPushButton* m_dechirpLiveFollowButton;
QCheckBox* m_meshAutoSampleRateCheck;
struct PipelineView
{
QWidget *tabWidget = nullptr;
QPlainTextEdit *logText = nullptr;
QTreeWidget *treeWidget = nullptr;
};
QTabWidget *m_pipelineTabs;
QMap<int, PipelineView> m_pipelineViews;
bool m_meshControlsUpdating;
struct MeshAutoLockCandidate {
int inputOffsetHz;
bool invertRamps;
int deBits;
double score;
int samples;
double sourceScore;
int sourceSamples;
int syncWordZeroCount;
int headerParityOkOrFixCount;
int headerCRCCount;
int payloadCRCCount;
int earlyEOMCount;
};
QVector<MeshAutoLockCandidate> m_meshAutoLockCandidates;
bool m_meshAutoLockActive;
int m_meshAutoLockCandidateIndex;
qint64 m_meshAutoLockCandidateStartMs;
int m_meshAutoLockObservedSamplesForCandidate;
int m_meshAutoLockObservedSourceSamplesForCandidate;
int m_meshAutoLockTotalDecodeSamples;
bool m_meshAutoLockTrafficSeen;
int m_meshAutoLockActivityTicks;
qint64 m_meshAutoLockArmStartMs;
int m_meshAutoLockBaseOffsetHz;
bool m_meshAutoLockBaseInvert;
int m_meshAutoLockBaseDeBits;
bool m_remoteTcpReconnectAutoApplyPending;
int m_remoteTcpReconnectAutoApplyWaitTicks;
bool m_remoteTcpLastRunningState;
struct DechirpSnapshot
{
int fftSize = 0;
std::vector<std::vector<float>> lines;
};
QMap<QString, DechirpSnapshot> m_dechirpSnapshots;
QVector<QString> m_dechirpSnapshotOrder;
bool m_dechirpInspectionActive;
QString m_dechirpSelectedMessageKey;
QString m_replayPendingMessageKey;
bool m_replayPendingHasSelection;
bool m_replaySelectionQueued;
QMap<QString, QString> m_pipelineMessageKeyByBase;
QMap<QString, QVector<QString>> m_pipelinePendingMessageKeysByBase;
quint64 m_pipelineMessageSequence;
MessageQueue m_inputMessageQueue;
unsigned int m_tickCount;
explicit MeshtasticDemodGUI(PluginAPI* pluginAPI, DeviceUISet *deviceUISet, BasebandSampleSink *rxChannel, QWidget* parent = 0);
virtual ~MeshtasticDemodGUI();
void blockApplySettings(bool block);
void applySettings(bool force = false);
void displaySettings();
void updateControlAvailabilityHints();
void displaySquelch();
void setBandwidths();
void showLoRaMessage(const Message& message); //!< For LoRa coding scheme
void showTextMessage(const Message& message); //!< For TTY and ASCII
void showFTMessage(const Message& message); //!< For FT coding scheme
void setupPipelineViews();
PipelineView& ensurePipelineView(int pipelineId, const QString& pipelineName);
void clearPipelineViews();
void appendPipelineLogLine(int pipelineId, const QString& pipelineName, const QString& line);
void appendPipelineStatusLine(int pipelineId, const QString& pipelineName, const QString& status);
void appendPipelineBytes(int pipelineId, const QString& pipelineName, const QByteArray& bytes);
void appendPipelineTreeFields(
int pipelineId,
const QString& pipelineName,
const QString& messageTitle,
const QVector<QPair<QString, QString>>& fields,
const QString& messageKey
);
void displayText(const QString& text);
void displayBytes(const QByteArray& bytes);
void displayStatus(const QString& status);
void displayLoRaStatus(int headerParityStatus, bool headerCRCStatus, int payloadParityStatus, bool payloadCRCStatus);
void displayFTStatus(int payloadParityStatus, bool payloadCRCStatus);
QString getParityStr(int parityStatus);
void resetLoRaStatus();
bool handleMessage(const Message& message);
void makeUIConnections();
void updateAbsoluteCenterFrequency();
void setupMeshtasticAutoProfileControls();
void rebuildMeshtasticChannelOptions();
bool retuneDeviceToFrequency(qint64 centerFrequencyHz);
bool autoTuneDeviceSampleRateForBandwidth(int bandwidthHz, QString& summary);
int findBandwidthIndex(int bandwidthHz) const;
void applyMeshtasticProfileFromSelection();
void editMeshtasticKeys();
void startMeshAutoLock();
void stopMeshAutoLock(bool keepBestCandidate);
void applyMeshAutoLockCandidate(const MeshAutoLockCandidate& candidate, bool applySettingsNow);
void handleMeshAutoLockObservation(const MeshtasticDemodMsg::MsgReportDecodeBytes& msg);
void handleMeshAutoLockSourceObservation();
void advanceMeshAutoLock();
QString buildPipelineMessageBaseKey(int pipelineId, uint32_t frameId, const QString& timestamp) const;
QString allocatePipelineMessageKey(const QString& baseKey);
QString resolvePipelineMessageKey(const QString& baseKey) const;
void consumePipelineMessageKey(const QString& baseKey, const QString& key);
void rememberLoRaDechirpSnapshot(const MeshtasticDemodMsg::MsgReportDecodeBytes& msg, const QString& messageKey);
void setDechirpInspectionMode(bool enabled);
void updateDechirpModeUI();
void queueReplayForTree(QTreeWidget *treeWidget);
void processQueuedReplay();
void hardResetDechirpDisplayBuffers();
void clearTreeMessageKeyReferences(const QString& messageKey);
void replayDechirpSnapshot(const DechirpSnapshot& snapshot);
};
#endif // INCLUDE_MESHTASTICDEMODGUI_H

1286
plugins/channelrx/demodmeshtastic/meshtasticdemodgui.ui

File diff suppressed because it is too large Load Diff

27
plugins/channelrx/demodmeshtastic/meshtasticdemodmsg.cpp

@ -0,0 +1,27 @@ @@ -0,0 +1,27 @@
///////////////////////////////////////////////////////////////////////////////////
// Copyright (C) 2012 maintech GmbH, Otto-Hahn-Str. 15, 97204 Hoechberg, Germany //
// written by Christian Daniel //
// Copyright (C) 2015-2020 Edouard Griffiths, F4EXB <f4exb06@gmail.com> //
// //
// This program is free software; you can redistribute it and/or modify //
// it under the terms of the GNU General Public License as published by //
// the Free Software Foundation as version 3 of the License, or //
// (at your option) any later version. //
// //
// This program is distributed in the hope that it will be useful, //
// but WITHOUT ANY WARRANTY; without even the implied warranty of //
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //
// GNU General Public License V3 for more details. //
// //
// You should have received a copy of the GNU General Public License //
// along with this program. If not, see <http://www.gnu.org/licenses/>. //
///////////////////////////////////////////////////////////////////////////////////
#include "meshtasticdemodmsg.h"
MESSAGE_CLASS_DEFINITION(MeshtasticDemodMsg::MsgDecodeSymbols, Message)
MESSAGE_CLASS_DEFINITION(MeshtasticDemodMsg::MsgLoRaHeaderProbe, Message)
MESSAGE_CLASS_DEFINITION(MeshtasticDemodMsg::MsgLoRaHeaderFeedback, Message)
MESSAGE_CLASS_DEFINITION(MeshtasticDemodMsg::MsgReportDecodeBytes, Message)
MESSAGE_CLASS_DEFINITION(MeshtasticDemodMsg::MsgReportDecodeString, Message)
MESSAGE_CLASS_DEFINITION(MeshtasticDemodMsg::MsgReportDecodeFT, Message)

534
plugins/channelrx/demodmeshtastic/meshtasticdemodmsg.h

@ -0,0 +1,534 @@ @@ -0,0 +1,534 @@
///////////////////////////////////////////////////////////////////////////////////
// Copyright (C) 2020 Edouard Griffiths, F4EXB <f4exb06@gmail.com> //
// //
// This program is free software; you can redistribute it and/or modify //
// it under the terms of the GNU General Public License as published by //
// the Free Software Foundation as version 3 of the License, or //
// (at your option) any later version. //
// //
// This program is distributed in the hope that it will be useful, //
// but WITHOUT ANY WARRANTY; without even the implied warranty of //
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //
// GNU General Public License V3 for more details. //
// //
// You should have received a copy of the GNU General Public License //
// along with this program. If not, see <http://www.gnu.org/licenses/>. //
///////////////////////////////////////////////////////////////////////////////////
#ifndef INCLUDE_MESHTASTICDEMODMSG_H
#define INCLUDE_MESHTASTICDEMODMSG_H
#include <vector>
#include <QObject>
#include <QPair>
#include <QVector>
#include "util/message.h"
#include "meshtasticdemodsettings.h"
namespace MeshtasticDemodMsg
{
class MsgDecodeSymbols : public Message {
MESSAGE_CLASS_DECLARATION
public:
const std::vector<unsigned short>& getSymbols() const { return m_symbols; }
const std::vector<std::vector<float>>& getMagnitudes() const { return m_magnitudes; }
const std::vector<std::vector<float>>& getDechirpedSpectrum() const { return m_dechirpedSpectrum; }
uint32_t getFrameId() const { return m_frameId; }
unsigned int getSyncWord() const { return m_syncWord; }
float getSingalDb() const { return m_signalDb; }
float getNoiseDb() const { return m_noiseDb; }
void pushBackSymbol(unsigned short symbol) {
m_symbols.push_back(symbol);
}
void popSymbol() {
m_symbols.pop_back();
}
void setSyncWord(unsigned char syncWord) {
m_syncWord = syncWord;
}
void setSignalDb(float db) {
m_signalDb = db;
}
void setNoiseDb(float db) {
m_noiseDb = db;
}
void setFrameId(uint32_t frameId) {
m_frameId = frameId;
}
void pushBackMagnitudes(const std::vector<float>& magnitudes) {
m_magnitudes.push_back(magnitudes);
}
void pushBackDechirpedSpectrumLine(const std::vector<float>& spectrumLine) {
m_dechirpedSpectrum.push_back(spectrumLine);
}
static MsgDecodeSymbols* create() {
return new MsgDecodeSymbols();
}
static MsgDecodeSymbols* create(const std::vector<unsigned short> symbols) {
return new MsgDecodeSymbols(symbols);
}
private:
std::vector<unsigned short> m_symbols;
std::vector<std::vector<float>> m_magnitudes;
std::vector<std::vector<float>> m_dechirpedSpectrum;
uint32_t m_frameId;
unsigned int m_syncWord;
float m_signalDb;
float m_noiseDb;
MsgDecodeSymbols() : //!< create an empty message
Message(),
m_frameId(0),
m_syncWord(0),
m_signalDb(0.0),
m_noiseDb(0.0)
{}
MsgDecodeSymbols(const std::vector<unsigned short> symbols) : //!< create a message with symbols copy
Message(),
m_frameId(0),
m_syncWord(0),
m_signalDb(0.0),
m_noiseDb(0.0)
{ m_symbols = symbols; }
};
class MsgLoRaHeaderProbe : public Message {
MESSAGE_CLASS_DECLARATION
public:
uint32_t getFrameId() const { return m_frameId; }
const std::vector<unsigned short>& getSymbols() const { return m_symbols; }
unsigned int getPayloadNbSymbolBits() const { return m_payloadNbSymbolBits; }
unsigned int getHeaderNbSymbolBits() const { return m_headerNbSymbolBits; }
unsigned int getSpreadFactor() const { return m_spreadFactor; }
unsigned int getBandwidth() const { return m_bandwidth; }
bool getHasHeader() const { return m_hasHeader; }
bool getHasCRC() const { return m_hasCRC; }
static MsgLoRaHeaderProbe* create(
uint32_t frameId,
const std::vector<unsigned short>& symbols,
unsigned int payloadNbSymbolBits,
unsigned int headerNbSymbolBits,
unsigned int spreadFactor,
unsigned int bandwidth,
bool hasHeader,
bool hasCRC
) {
return new MsgLoRaHeaderProbe(
frameId,
symbols,
payloadNbSymbolBits,
headerNbSymbolBits,
spreadFactor,
bandwidth,
hasHeader,
hasCRC
);
}
private:
uint32_t m_frameId;
std::vector<unsigned short> m_symbols;
unsigned int m_payloadNbSymbolBits;
unsigned int m_headerNbSymbolBits;
unsigned int m_spreadFactor;
unsigned int m_bandwidth;
bool m_hasHeader;
bool m_hasCRC;
MsgLoRaHeaderProbe(
uint32_t frameId,
const std::vector<unsigned short>& symbols,
unsigned int payloadNbSymbolBits,
unsigned int headerNbSymbolBits,
unsigned int spreadFactor,
unsigned int bandwidth,
bool hasHeader,
bool hasCRC
) :
Message(),
m_frameId(frameId),
m_symbols(symbols),
m_payloadNbSymbolBits(payloadNbSymbolBits),
m_headerNbSymbolBits(headerNbSymbolBits),
m_spreadFactor(spreadFactor),
m_bandwidth(bandwidth),
m_hasHeader(hasHeader),
m_hasCRC(hasCRC)
{}
};
class MsgLoRaHeaderFeedback : public Message {
MESSAGE_CLASS_DECLARATION
public:
uint32_t getFrameId() const { return m_frameId; }
bool isValid() const { return m_valid; }
bool getHasCRC() const { return m_hasCRC; }
unsigned int getNbParityBits() const { return m_nbParityBits; }
unsigned int getPacketLength() const { return m_packetLength; }
bool getLdro() const { return m_ldro; }
unsigned int getExpectedSymbols() const { return m_expectedSymbols; }
int getHeaderParityStatus() const { return m_headerParityStatus; }
bool getHeaderCRCStatus() const { return m_headerCRCStatus; }
static MsgLoRaHeaderFeedback* create(
uint32_t frameId,
bool valid,
bool hasCRC,
unsigned int nbParityBits,
unsigned int packetLength,
bool ldro,
unsigned int expectedSymbols,
int headerParityStatus,
bool headerCRCStatus
) {
return new MsgLoRaHeaderFeedback(
frameId,
valid,
hasCRC,
nbParityBits,
packetLength,
ldro,
expectedSymbols,
headerParityStatus,
headerCRCStatus
);
}
private:
uint32_t m_frameId;
bool m_valid;
bool m_hasCRC;
unsigned int m_nbParityBits;
unsigned int m_packetLength;
bool m_ldro;
unsigned int m_expectedSymbols;
int m_headerParityStatus;
bool m_headerCRCStatus;
MsgLoRaHeaderFeedback(
uint32_t frameId,
bool valid,
bool hasCRC,
unsigned int nbParityBits,
unsigned int packetLength,
bool ldro,
unsigned int expectedSymbols,
int headerParityStatus,
bool headerCRCStatus
) :
Message(),
m_frameId(frameId),
m_valid(valid),
m_hasCRC(hasCRC),
m_nbParityBits(nbParityBits),
m_packetLength(packetLength),
m_ldro(ldro),
m_expectedSymbols(expectedSymbols),
m_headerParityStatus(headerParityStatus),
m_headerCRCStatus(headerCRCStatus)
{}
};
class MsgReportDecodeBytes : public Message {
MESSAGE_CLASS_DECLARATION
public:
const QByteArray& getBytes() const { return m_bytes; }
uint32_t getFrameId() const { return m_frameId; }
unsigned int getSyncWord() const { return m_syncWord; }
float getSingalDb() const { return m_signalDb; }
float getNoiseDb() const { return m_noiseDb; }
const QString& getMsgTimestamp() const { return m_msgTimestamp; }
unsigned int getPacketSize() const { return m_packetSize; }
unsigned int getNbParityBits() const { return m_nbParityBits; }
unsigned int getNbSymbols() const { return m_nbSymbols; }
unsigned int getNbCodewords() const { return m_nbCodewords; }
bool getHasCRC() const { return m_hasCRC; }
bool getEarlyEOM() const { return m_earlyEOM; }
int getHeaderParityStatus() const { return m_headerParityStatus; }
bool getHeaderCRCStatus() const { return m_headerCRCStatus; }
int getPayloadParityStatus() const { return m_payloadParityStatus; }
bool getPayloadCRCStatus() const { return m_payloadCRCStatus; }
int getPipelineId() const { return m_pipelineId; }
const QString& getPipelineName() const { return m_pipelineName; }
const QString& getPipelinePreset() const { return m_pipelinePreset; }
const std::vector<std::vector<float>>& getDechirpedSpectrum() const { return m_dechirpedSpectrum; }
static MsgReportDecodeBytes* create(const QByteArray& bytes) {
return new MsgReportDecodeBytes(bytes);
}
void setSyncWord(unsigned int syncWord) {
m_syncWord = syncWord;
}
void setFrameId(uint32_t frameId) {
m_frameId = frameId;
}
void setSignalDb(float db) {
m_signalDb = db;
}
void setNoiseDb(float db) {
m_noiseDb = db;
}
void setMsgTimestamp(const QString& ts) {
m_msgTimestamp = ts;
}
void setPacketSize(unsigned int packetSize) {
m_packetSize = packetSize;
}
void setNbParityBits(unsigned int nbParityBits) {
m_nbParityBits = nbParityBits;
}
void setNbSymbols(unsigned int nbSymbols) {
m_nbSymbols = nbSymbols;
}
void setNbCodewords(unsigned int nbCodewords) {
m_nbCodewords = nbCodewords;
}
void setHasCRC(bool hasCRC) {
m_hasCRC = hasCRC;
}
void setEarlyEOM(bool earlyEOM) {
m_earlyEOM = earlyEOM;
}
void setHeaderParityStatus(int headerParityStatus) {
m_headerParityStatus = headerParityStatus;
}
void setHeaderCRCStatus(bool headerCRCStatus) {
m_headerCRCStatus = headerCRCStatus;
}
void setPayloadParityStatus(int payloadParityStatus) {
m_payloadParityStatus = payloadParityStatus;
}
void setPayloadCRCStatus(bool payloadCRCStatus) {
m_payloadCRCStatus = payloadCRCStatus;
}
void setPipelineMetadata(int pipelineId, const QString& pipelineName, const QString& pipelinePreset) {
m_pipelineId = pipelineId;
m_pipelineName = pipelineName;
m_pipelinePreset = pipelinePreset;
}
void setDechirpedSpectrum(const std::vector<std::vector<float>>& dechirpedSpectrum) {
m_dechirpedSpectrum = dechirpedSpectrum;
}
private:
QByteArray m_bytes;
uint32_t m_frameId;
unsigned int m_syncWord;
float m_signalDb;
float m_noiseDb;
QString m_msgTimestamp;
unsigned int m_packetSize;
unsigned int m_nbParityBits;
unsigned int m_nbSymbols;
unsigned int m_nbCodewords;
bool m_hasCRC;
bool m_earlyEOM;
int m_headerParityStatus;
bool m_headerCRCStatus;
int m_payloadParityStatus;
bool m_payloadCRCStatus;
int m_pipelineId;
QString m_pipelineName;
QString m_pipelinePreset;
std::vector<std::vector<float>> m_dechirpedSpectrum;
MsgReportDecodeBytes(const QByteArray& bytes) :
Message(),
m_bytes(bytes),
m_frameId(0),
m_syncWord(0),
m_signalDb(0.0),
m_noiseDb(0.0),
m_packetSize(0),
m_nbParityBits(0),
m_nbSymbols(0),
m_nbCodewords(0),
m_hasCRC(false),
m_earlyEOM(false),
m_headerParityStatus(false),
m_headerCRCStatus(false),
m_payloadParityStatus((int) MeshtasticDemodSettings::ParityUndefined),
m_payloadCRCStatus(false),
m_pipelineId(-1)
{ }
};
class MsgReportDecodeString : public Message {
MESSAGE_CLASS_DECLARATION
public:
const QString& getString() const { return m_str; }
uint32_t getFrameId() const { return m_frameId; }
unsigned int getSyncWord() const { return m_syncWord; }
float getSingalDb() const { return m_signalDb; }
float getNoiseDb() const { return m_noiseDb; }
const QString& getMsgTimestamp() const { return m_msgTimestamp; }
int getPipelineId() const { return m_pipelineId; }
const QString& getPipelineName() const { return m_pipelineName; }
const QString& getPipelinePreset() const { return m_pipelinePreset; }
const QVector<QPair<QString, QString>>& getStructuredFields() const { return m_structuredFields; }
bool hasStructuredFields() const { return !m_structuredFields.isEmpty(); }
static MsgReportDecodeString* create(const QString& str)
{
return new MsgReportDecodeString(str);
}
void setSyncWord(unsigned int syncWord) {
m_syncWord = syncWord;
}
void setFrameId(uint32_t frameId) {
m_frameId = frameId;
}
void setSignalDb(float db) {
m_signalDb = db;
}
void setNoiseDb(float db) {
m_noiseDb = db;
}
void setMsgTimestamp(const QString& ts) {
m_msgTimestamp = ts;
}
void setPipelineMetadata(int pipelineId, const QString& pipelineName, const QString& pipelinePreset) {
m_pipelineId = pipelineId;
m_pipelineName = pipelineName;
m_pipelinePreset = pipelinePreset;
}
void setStructuredFields(const QVector<QPair<QString, QString>>& fields) {
m_structuredFields = fields;
}
void addStructuredField(const QString& path, const QString& value) {
m_structuredFields.append(qMakePair(path, value));
}
private:
QString m_str;
uint32_t m_frameId;
unsigned int m_syncWord;
float m_signalDb;
float m_noiseDb;
QString m_msgTimestamp;
int m_pipelineId;
QString m_pipelineName;
QString m_pipelinePreset;
QVector<QPair<QString, QString>> m_structuredFields;
MsgReportDecodeString(const QString& str) :
Message(),
m_str(str),
m_frameId(0),
m_syncWord(0),
m_signalDb(0.0),
m_noiseDb(0.0),
m_pipelineId(-1)
{ }
};
class MsgReportDecodeFT : public Message {
MESSAGE_CLASS_DECLARATION
public:
const QString& getMessage() const { return m_message; }
const QString& getCall1() const { return m_call1; }
const QString& getCall2() const { return m_call2; }
const QString& getLoc() const { return m_loc; }
bool isReply() const { return m_reply; }
bool isFreeText() const { return m_freeText; }
unsigned int getSyncWord() const { return m_syncWord; }
float getSingalDb() const { return m_signalDb; }
float getNoiseDb() const { return m_noiseDb; }
const QString& getMsgTimestamp() const { return m_msgTimestamp; }
int getPayloadParityStatus() const { return m_payloadParityStatus; }
bool getPayloadCRCStatus() const { return m_payloadCRCStatus; }
int getPipelineId() const { return m_pipelineId; }
const QString& getPipelineName() const { return m_pipelineName; }
const QString& getPipelinePreset() const { return m_pipelinePreset; }
static MsgReportDecodeFT* create()
{
return new MsgReportDecodeFT();
}
void setMessage(const QString& message) {
m_message = message;
}
void setCall1(const QString& call1) {
m_call1 = call1;
}
void setCall2(const QString& call2) {
m_call2 = call2;
}
void setLoc(const QString& loc) {
m_loc = loc;
}
void setReply(bool reply) {
m_reply = reply;
}
void setFreeText(bool freeText) {
m_freeText = freeText;
}
void setSyncWord(unsigned int syncWord) {
m_syncWord = syncWord;
}
void setSignalDb(float db) {
m_signalDb = db;
}
void setNoiseDb(float db) {
m_noiseDb = db;
}
void setMsgTimestamp(const QString& ts) {
m_msgTimestamp = ts;
}
void setPayloadParityStatus(int payloadParityStatus) {
m_payloadParityStatus = payloadParityStatus;
}
void setPayloadCRCStatus(bool payloadCRCStatus) {
m_payloadCRCStatus = payloadCRCStatus;
}
void setPipelineMetadata(int pipelineId, const QString& pipelineName, const QString& pipelinePreset) {
m_pipelineId = pipelineId;
m_pipelineName = pipelineName;
m_pipelinePreset = pipelinePreset;
}
private:
QString m_message;
QString m_call1;
QString m_call2;
QString m_loc;
bool m_reply;
bool m_freeText;
unsigned int m_syncWord;
float m_signalDb;
float m_noiseDb;
QString m_msgTimestamp;
int m_payloadParityStatus;
bool m_payloadCRCStatus;
int m_pipelineId;
QString m_pipelineName;
QString m_pipelinePreset;
MsgReportDecodeFT() :
Message(),
m_reply(false),
m_freeText(false),
m_syncWord(0),
m_signalDb(0.0),
m_noiseDb(0.0),
m_payloadParityStatus((int) MeshtasticDemodSettings::ParityUndefined),
m_payloadCRCStatus(false),
m_pipelineId(-1)
{ }
};
}
#endif // INCLUDE_MESHTASTICDEMODMSG_H

400
plugins/channelrx/demodmeshtastic/meshtasticdemodsettings.cpp

@ -0,0 +1,400 @@ @@ -0,0 +1,400 @@
///////////////////////////////////////////////////////////////////////////////////
// Copyright (C) 2017-2018, 2020, 2022 Edouard Griffiths, F4EXB <f4exb06@gmail.com> //
// Copyright (C) 2021 Jon Beniston, M7RCE <jon@beniston.com> //
// //
// This program is free software; you can redistribute it and/or modify //
// it under the terms of the GNU General Public License as published by //
// the Free Software Foundation as version 3 of the License, or //
// (at your option) any later version. //
// //
// This program is distributed in the hope that it will be useful, //
// but WITHOUT ANY WARRANTY; without even the implied warranty of //
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //
// GNU General Public License V3 for more details. //
// //
// You should have received a copy of the GNU General Public License //
// along with this program. If not, see <http://www.gnu.org/licenses/>. //
///////////////////////////////////////////////////////////////////////////////////
#include <QColor>
#include "util/simpleserializer.h"
#include "settings/serializable.h"
#include "meshtasticdemodsettings.h"
const int MeshtasticDemodSettings::bandwidths[] = {
325, // 384k / 1024
488, // 500k / 1024
750, // 384k / 512
1500, // 384k / 256
2604, // 333k / 128
3125, // 400k / 128
3906, // 500k / 128
5208, // 333k / 64
6250, // 400k / 64
7813, // 500k / 64
10417, // 333k / 32
12500, // 400k / 32
15625, // 500k / 32
20833, // 333k / 16
25000, // 400k / 16
31250, // 500k / 16
41667, // 333k / 8
50000, // 400k / 8
62500, // 500k / 8
83333, // 333k / 4
100000, // 400k / 4
125000, // 500k / 4
166667, // 333k / 2
200000, // 400k / 2
250000, // 500k / 2
333333, // 333k / 1
400000, // 400k / 1
500000 // 500k / 1
};
const int MeshtasticDemodSettings::nbBandwidths = 3*8 + 4;
// Keep frame-sync input at >=4x BW (matches gr-lora_sdr os_factor=4 expectations)
// so SF11/SF12 Meshtastic presets retain enough timing resolution.
const int MeshtasticDemodSettings::oversampling = 4;
MeshtasticDemodSettings::MeshtasticDemodSettings() :
m_inputFrequencyOffset(0),
m_channelMarker(0),
m_spectrumGUI(0),
m_rollupState(0)
{
resetToDefaults();
}
void MeshtasticDemodSettings::resetToDefaults()
{
m_bandwidthIndex = 5;
m_spreadFactor = 7;
m_deBits = 0;
m_codingScheme = CodingLoRa;
m_decodeActive = true;
m_fftWindow = FFTWindow::Rectangle;
m_eomSquelchTenths = 60;
m_nbSymbolsMax = 255;
m_autoNbSymbolsMax = false;
m_preambleChirps = 17;
m_packetLength = 237;
m_nbParityBits = 1;
m_hasCRC = true;
m_hasHeader = true;
m_sendViaUDP = false;
m_invertRamps = false;
m_udpAddress = "127.0.0.1";
m_udpPort = 9999;
m_meshtasticKeySpecList.clear();
m_meshtasticAutoSampleRate = true;
m_meshtasticRegionCode = "US";
m_meshtasticPresetName = "LONG_FAST";
m_meshtasticChannelIndex = 0;
m_rgbColor = QColor(255, 0, 255).rgb();
m_title = "Meshtastic 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;
}
QByteArray MeshtasticDemodSettings::serialize() const
{
SimpleSerializer s(3);
s.writeS32(1, m_inputFrequencyOffset);
s.writeS32(2, m_bandwidthIndex);
s.writeS32(3, m_spreadFactor);
if (m_spectrumGUI) {
s.writeBlob(4, m_spectrumGUI->serialize());
}
if (m_channelMarker) {
s.writeBlob(5, m_channelMarker->serialize());
}
s.writeString(6, m_title);
s.writeS32(7, m_deBits);
s.writeS32(8, m_codingScheme);
s.writeBool(9, m_decodeActive);
s.writeS32(10, m_eomSquelchTenths);
s.writeU32(11, m_nbSymbolsMax);
s.writeS32(12, m_packetLength);
s.writeS32(13, m_nbParityBits);
s.writeBool(14, m_hasCRC);
s.writeBool(15, m_hasHeader);
s.writeU32(17, m_preambleChirps);
s.writeS32(18, (int) m_fftWindow);
s.writeBool(19, m_invertRamps);
s.writeBool(20, m_useReverseAPI);
s.writeString(21, m_reverseAPIAddress);
s.writeU32(22, m_reverseAPIPort);
s.writeU32(23, m_reverseAPIDeviceIndex);
s.writeU32(24, m_reverseAPIChannelIndex);
s.writeS32(25, m_streamIndex);
s.writeBool(26, m_sendViaUDP);
s.writeString(27, m_udpAddress);
s.writeU32(28, m_udpPort);
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.writeString(33, m_meshtasticKeySpecList);
s.writeBool(34, m_meshtasticAutoSampleRate);
s.writeString(35, m_meshtasticRegionCode);
s.writeString(36, m_meshtasticPresetName);
s.writeS32(37, m_meshtasticChannelIndex);
return s.final();
}
bool MeshtasticDemodSettings::deserialize(const QByteArray& data)
{
SimpleDeserializer d(data);
if(!d.isValid())
{
resetToDefaults();
return false;
}
if ((d.getVersion() == 1) || (d.getVersion() == 2) || (d.getVersion() == 3))
{
QByteArray bytetmp;
int tmp;
unsigned int utmp;
d.readS32(1, &m_inputFrequencyOffset, 0);
d.readS32(2, &m_bandwidthIndex, 0);
d.readS32(3, &m_spreadFactor, 0);
if (m_spectrumGUI)
{
d.readBlob(4, &bytetmp);
m_spectrumGUI->deserialize(bytetmp);
}
if (m_channelMarker)
{
d.readBlob(5, &bytetmp);
m_channelMarker->deserialize(bytetmp);
}
d.readString(6, &m_title, "Meshtastic Demodulator");
d.readS32(7, &m_deBits, 0);
d.readS32(8, &tmp);
m_codingScheme = (CodingScheme) tmp;
d.readBool(9, &m_decodeActive, true);
d.readS32(10, &m_eomSquelchTenths, 60);
d.readU32(11, &m_nbSymbolsMax, 255);
d.readS32(12, &m_packetLength, 237);
d.readS32(13, &m_nbParityBits, 1);
d.readBool(14, &m_hasCRC, true);
d.readBool(15, &m_hasHeader, true);
d.readU32(17, &m_preambleChirps, 17);
d.readS32(18, &tmp, (int) FFTWindow::Rectangle);
m_fftWindow = (FFTWindow::Function) tmp;
d.readBool(19, &m_invertRamps, false);
d.readBool(20, &m_useReverseAPI, false);
d.readString(21, &m_reverseAPIAddress, "127.0.0.1");
d.readU32(22, &utmp, 0);
if ((utmp > 1023) && (utmp < 65535)) {
m_reverseAPIPort = utmp;
} else {
m_reverseAPIPort = 8888;
}
d.readU32(23, &utmp, 0);
m_reverseAPIDeviceIndex = utmp > 99 ? 99 : utmp;
d.readU32(24, &utmp, 0);
m_reverseAPIChannelIndex = utmp > 99 ? 99 : utmp;
d.readS32(25, &m_streamIndex, 0);
d.readBool(26, &m_sendViaUDP, false);
d.readString(27, &m_udpAddress, "127.0.0.1");
d.readU32(28, &utmp, 0);
if ((utmp > 1023) && (utmp < 65535)) {
m_udpPort = utmp;
} else {
m_udpPort = 9999;
}
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.readString(33, &m_meshtasticKeySpecList, "");
d.readBool(34, &m_meshtasticAutoSampleRate, true);
d.readString(35, &m_meshtasticRegionCode, "US");
d.readString(36, &m_meshtasticPresetName, "LONG_FAST");
d.readS32(37, &m_meshtasticChannelIndex, 0);
return true;
}
else
{
resetToDefaults();
return false;
}
}
void MeshtasticDemodSettings::applySettings(const QStringList& settingsKeys, const MeshtasticDemodSettings& settings)
{
if (settingsKeys.contains("inputFrequencyOffset"))
m_inputFrequencyOffset = settings.m_inputFrequencyOffset;
if (settingsKeys.contains("bandwidthIndex"))
m_bandwidthIndex = settings.m_bandwidthIndex;
if (settingsKeys.contains("spreadFactor"))
m_spreadFactor = settings.m_spreadFactor;
if (settingsKeys.contains("deBits"))
m_deBits = settings.m_deBits;
if (settingsKeys.contains("fftWindow"))
m_fftWindow = settings.m_fftWindow;
if (settingsKeys.contains("codingScheme"))
m_codingScheme = settings.m_codingScheme;
if (settingsKeys.contains("decodeActive"))
m_decodeActive = settings.m_decodeActive;
if (settingsKeys.contains("eomSquelchTenths"))
m_eomSquelchTenths = settings.m_eomSquelchTenths;
if (settingsKeys.contains("nbSymbolsMax"))
m_nbSymbolsMax = settings.m_nbSymbolsMax;
if (settingsKeys.contains("preambleChirps"))
m_preambleChirps = settings.m_preambleChirps;
if (settingsKeys.contains("nbParityBits"))
m_nbParityBits = settings.m_nbParityBits;
if (settingsKeys.contains("packetLength"))
m_packetLength = settings.m_packetLength;
if (settingsKeys.contains("hasCRC"))
m_hasCRC = settings.m_hasCRC;
if (settingsKeys.contains("hasHeader"))
m_hasHeader = settings.m_hasHeader;
if (settingsKeys.contains("sendViaUDP"))
m_sendViaUDP = settings.m_sendViaUDP;
if (settingsKeys.contains("invertRamps"))
m_invertRamps = settings.m_invertRamps;
if (settingsKeys.contains("udpAddress"))
m_udpAddress = settings.m_udpAddress;
if (settingsKeys.contains("udpPort"))
m_udpPort = settings.m_udpPort;
if (settingsKeys.contains("meshtasticKeySpecList"))
m_meshtasticKeySpecList = settings.m_meshtasticKeySpecList;
if (settingsKeys.contains("meshtasticAutoSampleRate"))
m_meshtasticAutoSampleRate = settings.m_meshtasticAutoSampleRate;
if (settingsKeys.contains("meshtasticRegionCode"))
m_meshtasticRegionCode = settings.m_meshtasticRegionCode;
if (settingsKeys.contains("meshtasticPresetName"))
m_meshtasticPresetName = settings.m_meshtasticPresetName;
if (settingsKeys.contains("meshtasticChannelIndex"))
m_meshtasticChannelIndex = settings.m_meshtasticChannelIndex;
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("streamIndex"))
m_streamIndex = settings.m_streamIndex;
}
QString MeshtasticDemodSettings::getDebugString(const QStringList& settingsKeys, bool force) const
{
QString debug;
if (force || settingsKeys.contains("inputFrequencyOffset"))
debug += QString("InputFrequencyOffset: %1 ").arg(m_inputFrequencyOffset);
if (force || settingsKeys.contains("bandwidthIndex"))
debug += QString("BandwidthIndex: %1 ").arg(m_bandwidthIndex);
if (force || settingsKeys.contains("spreadFactor"))
debug += QString("SpreadFactor: %1 ").arg(m_spreadFactor);
if (force || settingsKeys.contains("deBits"))
debug += QString("DEBits: %1 ").arg(m_deBits);
if (force || settingsKeys.contains("fftWindow"))
debug += QString("FFTWindow: %1 ").arg((int) m_fftWindow);
if (force || settingsKeys.contains("codingScheme"))
debug += QString("CodingScheme: %1 ").arg((int) m_codingScheme);
if (force || settingsKeys.contains("decodeActive"))
debug += QString("DecodeActive: %1 ").arg(m_decodeActive);
if (force || settingsKeys.contains("eomSquelchTenths"))
debug += QString("EOMSquelchTenths: %1 ").arg(m_eomSquelchTenths);
if (force || settingsKeys.contains("nbSymbolsMax"))
debug += QString("NbSymbolsMax: %1 ").arg(m_nbSymbolsMax);
if (force || settingsKeys.contains("preambleChirps"))
debug += QString("PreambleChirps: %1 ").arg(m_preambleChirps);
if (force || settingsKeys.contains("nbParityBits"))
debug += QString("NbParityBits: %1 ").arg(m_nbParityBits);
if (force || settingsKeys.contains("packetLength"))
debug += QString("PacketLength: %1 ").arg(m_packetLength);
if (force || settingsKeys.contains("hasCRC"))
debug += QString("HasCRC: %1 ").arg(m_hasCRC);
if (force || settingsKeys.contains("hasHeader"))
debug += QString("HasHeader: %1 ").arg(m_hasHeader);
if (force || settingsKeys.contains("sendViaUDP"))
debug += QString("SendViaUDP: %1 ").arg(m_sendViaUDP);
if (force || settingsKeys.contains("invertRamps"))
debug += QString("InvertRamps: %1 ").arg(m_invertRamps);
if (force || settingsKeys.contains("udpAddress"))
debug += QString("UDPAddress: %1 ").arg(m_udpAddress);
if (force || settingsKeys.contains("udpPort"))
debug += QString("UDPPort: %1 ").arg(m_udpPort);
if (force || settingsKeys.contains("meshtasticKeySpecList"))
debug += QString("MeshtasticKeySpecList: %1 ").arg(m_meshtasticKeySpecList);
if (force || settingsKeys.contains("meshtasticAutoSampleRate"))
debug += QString("MeshtasticAutoSampleRate: %1 ").arg(m_meshtasticAutoSampleRate);
if (force || settingsKeys.contains("meshtasticRegionCode"))
debug += QString("MeshtasticRegionCode: %1 ").arg(m_meshtasticRegionCode);
if (force || settingsKeys.contains("meshtasticPresetName"))
debug += QString("MeshtasticPresetName: %1 ").arg(m_meshtasticPresetName);
if (force || settingsKeys.contains("meshtasticChannelIndex"))
debug += QString("MeshtasticChannelIndex: %1 ").arg(m_meshtasticChannelIndex);
if (force || settingsKeys.contains("useReverseAPI"))
debug += QString("UseReverseAPI: %1 ").arg(m_useReverseAPI);
if (force || settingsKeys.contains("reverseAPIAddress"))
debug += QString("ReverseAPIAddress: %1 ").arg(m_reverseAPIAddress);
if (force || settingsKeys.contains("reverseAPIPort"))
debug += QString("ReverseAPIPort: %1 ").arg(m_reverseAPIPort);
if (force || settingsKeys.contains("reverseAPIDeviceIndex"))
debug += QString("ReverseAPIDeviceIndex: %1 ").arg(m_reverseAPIDeviceIndex);
if (force || settingsKeys.contains("reverseAPIChannelIndex"))
debug += QString("ReverseAPIChannelIndex: %1 ").arg(m_reverseAPIChannelIndex);
if (force || settingsKeys.contains("streamIndex"))
debug += QString("StreamIndex: %1 ").arg(m_streamIndex);
return debug;
}
unsigned int MeshtasticDemodSettings::getNbSFDFourths() const
{
switch (m_codingScheme)
{
case CodingLoRa:
return 9;
default:
return 8;
}
}
bool MeshtasticDemodSettings::hasSyncWord() const
{
// Keep sync-symbol handling enabled for live-air compatibility.
// The extracted sync value can still be 0x00 when the on-air flow uses [0,0].
return m_codingScheme == CodingLoRa;
}

111
plugins/channelrx/demodmeshtastic/meshtasticdemodsettings.h

@ -0,0 +1,111 @@ @@ -0,0 +1,111 @@
///////////////////////////////////////////////////////////////////////////////////
// Copyright (C) 2012 maintech GmbH, Otto-Hahn-Str. 15, 97204 Hoechberg, Germany //
// written by Christian Daniel //
// Copyright (C) 2015-2020, 2022 Edouard Griffiths, F4EXB <f4exb06@gmail.com> //
// Copyright (C) 2021 Jon Beniston, M7RCE <jon@beniston.com> //
// //
// This program is free software; you can redistribute it and/or modify //
// it under the terms of the GNU General Public License as published by //
// the Free Software Foundation as version 3 of the License, or //
// (at your option) any later version. //
// //
// This program is distributed in the hope that it will be useful, //
// but WITHOUT ANY WARRANTY; without even the implied warranty of //
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //
// GNU General Public License V3 for more details. //
// //
// You should have received a copy of the GNU General Public License //
// along with this program. If not, see <http://www.gnu.org/licenses/>. //
///////////////////////////////////////////////////////////////////////////////////
#ifndef PLUGINS_CHANNELRX_DEMODMESHTASTIC_MESHTASTICDEMODSETTINGS_H_
#define PLUGINS_CHANNELRX_DEMODMESHTASTIC_MESHTASTICDEMODSETTINGS_H_
#include <QByteArray>
#include <QString>
#include <stdint.h>
#include "dsp/fftwindow.h"
class Serializable;
struct MeshtasticDemodSettings
{
enum CodingScheme
{
CodingLoRa, //!< Standard LoRa
CodingASCII, //!< plain ASCII (7 bits)
CodingTTY, //!< plain TTY (5 bits)
CodingFT //!< FT8/4 scheme (payload 174 bits LDPC)
};
enum ParityStatus
{
ParityUndefined,
ParityError,
ParityCorrected,
ParityOK
};
int m_inputFrequencyOffset;
int m_bandwidthIndex;
int m_spreadFactor;
int m_deBits; //!< Low data rate optimize (DE) bits
FFTWindow::Function m_fftWindow;
CodingScheme m_codingScheme;
bool m_decodeActive;
int m_eomSquelchTenths; //!< Squelch factor to trigger end of message (/10)
unsigned int m_nbSymbolsMax; //!< Maximum number of symbols in a payload
bool m_autoNbSymbolsMax; //!< Set maximum number of symbols in a payload automatically using last message value
unsigned int m_preambleChirps; //!< Number of expected preamble chirps
int m_nbParityBits; //!< Hamming parity bits (LoRa)
int m_packetLength; //!< Payload packet length in bytes or characters (LoRa)
bool m_hasCRC; //!< Payload has CRC (LoRa)
bool m_hasHeader; //!< Header present before actual payload (LoRa)
bool m_sendViaUDP; //!< Send decoded message via UDP
bool m_invertRamps; //!< Invert chirp ramps vs standard LoRa (up/down/up is standard)
QString m_udpAddress; //!< UDP address where to send message
uint16_t m_udpPort; //!< UDP port where to send message
QString m_meshtasticKeySpecList; //!< Optional per-channel Meshtastic decode key list
bool m_meshtasticAutoSampleRate; //!< Auto-tune source sample rate/decimation for selected Meshtastic profile
QString m_meshtasticRegionCode; //!< UI-selected Meshtastic region code (US, EU_868, ...)
QString m_meshtasticPresetName; //!< UI-selected Meshtastic preset (LONG_FAST, ...)
int m_meshtasticChannelIndex; //!< UI-selected Meshtastic channel index (zero-based)
uint32_t m_rgbColor;
QString m_title;
int m_streamIndex;
bool m_useReverseAPI;
QString m_reverseAPIAddress;
uint16_t m_reverseAPIPort;
uint16_t m_reverseAPIDeviceIndex;
uint16_t m_reverseAPIChannelIndex;
int m_workspaceIndex;
QByteArray m_geometryBytes;
bool m_hidden;
Serializable *m_channelMarker;
Serializable *m_spectrumGUI;
Serializable *m_rollupState;
static const int bandwidths[];
static const int nbBandwidths;
static const int oversampling;
MeshtasticDemodSettings();
void resetToDefaults();
void setChannelMarker(Serializable *channelMarker) { m_channelMarker = channelMarker; }
void setRollupState(Serializable *rollupState) { m_rollupState = rollupState; }
void setSpectrumGUI(Serializable *spectrumGUI) { m_spectrumGUI = spectrumGUI; }
unsigned int getNbSFDFourths() const; //!< Get the number of SFD period fourths (depends on coding scheme)
bool hasSyncWord() const; //!< Only LoRa has a syncword (for the moment)
QByteArray serialize() const;
bool deserialize(const QByteArray& data);
void applySettings(const QStringList& settingsKeys, const MeshtasticDemodSettings& settings);
QString getDebugString(const QStringList& settingsKeys, bool force=false) const;
};
#endif /* PLUGINS_CHANNELRX_DEMODMESHTASTIC_MESHTASTICDEMODSETTINGS_H_ */

1972
plugins/channelrx/demodmeshtastic/meshtasticdemodsink.cpp

File diff suppressed because it is too large Load Diff

258
plugins/channelrx/demodmeshtastic/meshtasticdemodsink.h

@ -0,0 +1,258 @@ @@ -0,0 +1,258 @@
///////////////////////////////////////////////////////////////////////////////////
// Copyright (C) 2019-2020 Edouard Griffiths, F4EXB <f4exb06@gmail.com> //
// //
// This program is free software; you can redistribute it and/or modify //
// it under the terms of the GNU General Public License as published by //
// the Free Software Foundation as version 3 of the License, or //
// (at your option) any later version. //
// //
// This program is distributed in the hope that it will be useful, //
// but WITHOUT ANY WARRANTY; without even the implied warranty of //
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //
// GNU General Public License V3 for more details. //
// //
// You should have received a copy of the GNU General Public License //
// along with this program. If not, see <http://www.gnu.org/licenses/>. //
///////////////////////////////////////////////////////////////////////////////////
#ifndef INCLUDE_MESHTASTICDEMODSINK_H
#define INCLUDE_MESHTASTICDEMODSINK_H
#include <vector>
#include <queue>
#include <deque>
#include <cstdint>
#include <QtGlobal>
#include "dsp/channelsamplesink.h"
#include "dsp/nco.h"
#include "dsp/interpolator.h"
#include "dsp/fftwindow.h"
#include "util/movingaverage.h"
#include "meshtasticdemodsettings.h"
class BasebandSampleSink;
class FFTEngine;
namespace MeshtasticDemodMsg {
class MsgDecodeSymbols;
}
class MessageQueue;
class MeshtasticDemodSink : public ChannelSampleSink {
public:
MeshtasticDemodSink();
~MeshtasticDemodSink();
virtual void feed(const SampleVector::const_iterator& begin, const SampleVector::const_iterator& end);
bool getDemodActive() const { return m_demodActive; }
void setDecoderMessageQueue(MessageQueue *messageQueue) { m_decoderMsgQueue = messageQueue; }
void setSpectrumSink(BasebandSampleSink* spectrumSink) { m_spectrumSink = spectrumSink; }
void setDeviceCenterFrequency(qint64 centerFrequency) { m_deviceCenterFrequency = centerFrequency; }
void applyLoRaHeaderFeedback(
uint32_t frameId,
bool valid,
bool hasCRC,
unsigned int nbParityBits,
unsigned int packetLength,
bool ldro,
unsigned int expectedSymbols,
int headerParityStatus,
bool headerCRCStatus
);
void applyChannelSettings(int channelSampleRate, int bandwidth, int channelFrequencyOffset, bool force = false);
void applySettings(const MeshtasticDemodSettings& settings, bool force = false);
double getCurrentNoiseLevel() const { return m_magsqOffAvg.instantAverage() / (1<<m_settings.m_spreadFactor); }
double getTotalPower() const { return m_magsqTotalAvg.instantAverage() / (1<<m_settings.m_spreadFactor); }
private:
enum LoRaFrameSyncState
{
LoRaStateDetect,
LoRaStateSync,
LoRaStateSFOCompensation
};
enum LoRaSyncState
{
LoRaSyncNetId1,
LoRaSyncNetId2,
LoRaSyncDownchirp1,
LoRaSyncDownchirp2,
LoRaSyncQuarterDown
};
enum ChirpChatState
{
ChirpChatStateReset, //!< Reset everything to start all over
ChirpChatStateDetectPreamble, //!< Look for preamble
ChirpChatStatePreambleResyc, //!< Synchronize with what is left of preamble chirp
ChirpChatStatePreamble, //!< Preamble is found and look for SFD start
ChirpChatStateSkipSFD, //!< Skip SFD
ChirpChatStateReadPayload,
ChirpChatStateTest
};
MeshtasticDemodSettings m_settings;
ChirpChatState m_state;
bool m_demodActive;
MeshtasticDemodMsg::MsgDecodeSymbols *m_decodeMsg;
MessageQueue *m_decoderMsgQueue;
int m_bandwidth;
int m_channelSampleRate;
int m_channelFrequencyOffset;
qint64 m_deviceCenterFrequency;
unsigned int m_chirp;
unsigned int m_chirp0;
static constexpr unsigned int m_minRequiredPreambleChirps = 4; //!< Lower bound for preamble validation chirps
static constexpr unsigned int m_maxRequiredPreambleChirps = 64; //!< Upper bound for preamble validation chirps
static constexpr unsigned int m_maxSFDSearchChirps = 64; //!< Maximum number of chirps when looking for SFD after preamble detection
static constexpr unsigned int m_legacyFFTInterpolation = 4; //!< Legacy interpolation for non-LoRa modes
static constexpr unsigned int m_loRaFFTInterpolation = 1; //!< Canonical gr-lora_sdr-like FFT binning for LoRa
FFTEngine *m_fft;
FFTEngine *m_fftSFD;
int m_fftSequence;
int m_fftSFDSequence;
FFTWindow m_fftWindow;
Complex *m_downChirps;
Complex *m_upChirps;
Complex *m_spectrumLine;
unsigned int m_fftCounter;
std::deque<unsigned int> m_preambleBinHistory; //!< Rolling preamble bins for mode (k_hat) estimation
unsigned int m_preambleConsecutive; //!< Consecutive upchirp count in DETECT state
bool m_havePrevPreambleBin;
unsigned int m_prevPreambleBin;
unsigned int m_requiredPreambleChirps;
unsigned int m_preambleHistory[m_maxSFDSearchChirps];
unsigned int m_syncWord;
double m_magsqMax;
MovingAverageUtil<double, double, 10> m_magsqOnAvg;
MovingAverageUtil<double, double, 10> m_magsqOffAvg;
MovingAverageUtil<double, double, 10> m_magsqTotalAvg;
std::queue<double> m_magsqQueue;
unsigned int m_chirpCount; //!< Generic chirp counter
unsigned int m_sfdSkip; //!< Number of samples in a SFD skip or slide (1/4) period
unsigned int m_sfdSkipCounter; //!< Counter of skip or slide periods
bool m_headerLocked; //!< True when header decode succeeded and we have a deterministic symbol budget
unsigned int m_expectedSymbols; //!< Total expected symbols (header + payload) from header decode
bool m_waitHeaderFeedback;
unsigned int m_headerFeedbackWaitSteps;
uint32_t m_loRaFrameId;
static constexpr unsigned int m_headerFeedbackMaxWaitSteps = 128;
unsigned int m_osFactor; //!< Oversampling factor at frame-sync input (gr-lora_sdr os_factor)
unsigned int m_osCenterPhase; //!< Selected downsample phase inside oversampled symbol
unsigned int m_osCounter; //!< Oversampled sample counter
LoRaFrameSyncState m_loRaState;
LoRaSyncState m_loRaSyncState;
std::deque<Complex> m_loRaSampleFifo;
std::vector<Complex> m_loRaInDown;
std::vector<Complex> m_loRaPreambleRaw;
std::vector<Complex> m_loRaPreambleRawUp;
std::vector<Complex> m_loRaPreambleUpchirps;
std::vector<Complex> m_loRaRefUpchirp;
std::vector<Complex> m_loRaRefDownchirp;
std::vector<Complex> m_loRaCFOFracCorrec;
std::vector<Complex> m_loRaPayloadDownchirp;
std::vector<Complex> m_loRaSymbCorr;
std::vector<Complex> m_loRaNetIdSamp;
std::vector<Complex> m_loRaAdditionalSymbolSamp;
std::vector<int> m_loRaPreambleVals;
std::vector<int> m_loRaNetIds;
int m_loRaSymbolCnt;
int m_loRaBinIdx;
int m_loRaKHat;
int m_loRaDownVal;
int m_loRaCFOInt;
int m_loRaNetIdOff;
int m_loRaAdditionalUpchirps;
int m_loRaUpSymbToUse;
unsigned int m_loRaRequiredUpchirps;
unsigned int m_loRaSymbolSpan;
unsigned int m_loRaFrameSymbolCount;
float m_loRaCFOFrac;
float m_loRaSTOFrac;
float m_loRaSFOHat;
float m_loRaSFOCum;
bool m_loRaCFOSTOEstimated;
bool m_loRaReceivedHeader;
bool m_loRaOneSymbolOff;
NCO m_nco;
Interpolator m_interpolator;
Real m_sampleDistanceRemain;
Real m_interpolatorDistance;
BasebandSampleSink* m_spectrumSink;
Complex *m_spectrumBuffer;
unsigned int m_nbSymbols; //!< Number of symbols = length of base FFT
unsigned int m_nbSymbolsEff; //!< effective symbols considering DE bits
unsigned int m_fftLength; //!< Length of base FFT
unsigned int m_fftInterpolation; //!< FFT interpolation factor (LoRa=1, legacy modes=4)
unsigned int m_interpolatedFFTLength; //!< Length of interpolated FFT
int m_deLength; //!< Number of FFT bins collated to represent one symbol
int m_preambleTolerance; //!< Number of FFT bins to collate when looking for preamble
void processSample(const Complex& ci);
void initSF(unsigned int sf, unsigned int deBits, FFTWindow::Function fftWindow); //!< Init tables, FFTs, depending on spread factor
void reset();
unsigned int argmax(
const Complex *fftBins,
unsigned int fftMult,
unsigned int fftLength,
double& magsqMax,
double& magSqTotal,
Complex *specBuffer,
unsigned int specDecim
);
unsigned int argmaxSpreaded( //!< count energy in adjacent bins for same symbol (needs DE bits > 0)
const Complex *fftBins,
unsigned int fftMult,
unsigned int fftLength,
double& magsqMax,
double& magsqNoise,
double& magSqTotal,
Complex *specBuffer,
unsigned int specDecim
);
unsigned int extractMagnitudes(
std::vector<float>& magnitudes,
const Complex *fftBins,
unsigned int fftMult,
unsigned int fftLength,
double& magsqMax,
double& magSqTotal,
Complex *specBuffer,
unsigned int specDecim
);
void decimateSpectrum(Complex *in, Complex *out, unsigned int size, unsigned int decimation);
int toSigned(int u, int intSize);
int circularBinDelta(unsigned int current, unsigned int previous) const;
unsigned int getPreambleModeBin() const;
unsigned int evalSymbol(unsigned int rawSymbol, bool headerSymbol = false);
void tryHeaderLock(); //!< Attempt inline header decode after 8 symbols to determine expected frame length
bool sendLoRaHeaderProbe();
void processSampleLoRa(const Complex& ci);
int processLoRaFrameSyncStep();
void resetLoRaFrameSync();
void clearSpectrumHistoryForNewFrame();
int loRaMod(int a, int b) const;
int loRaRound(float number) const;
unsigned int getLoRaSymbolVal(
const Complex *samples,
const Complex *refChirp,
std::vector<float> *symbolMagnitudes = nullptr,
bool publishSpectrum = false
);
float estimateLoRaCFOFracBernier(const Complex *samples);
float estimateLoRaSTOFrac();
void buildLoRaPayloadDownchirp();
void finalizeLoRaFrame();
};
#endif // INCLUDE_MESHTASTICDEMODSINK_H

52
plugins/channelrx/demodmeshtastic/meshtasticdemodwebapiadapter.cpp

@ -0,0 +1,52 @@ @@ -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 <f4exb06@gmail.com> //
// //
// This program is free software; you can redistribute it and/or modify //
// it under the terms of the GNU General Public License as published by //
// the Free Software Foundation as version 3 of the License, or //
// (at your option) any later version. //
// //
// This program is distributed in the hope that it will be useful, //
// but WITHOUT ANY WARRANTY; without even the implied warranty of //
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //
// GNU General Public License V3 for more details. //
// //
// You should have received a copy of the GNU General Public License //
// along with this program. If not, see <http://www.gnu.org/licenses/>. //
///////////////////////////////////////////////////////////////////////////////////
#include "SWGChannelSettings.h"
#include "meshtasticdemod.h"
#include "meshtasticdemodwebapiadapter.h"
MeshtasticDemodWebAPIAdapter::MeshtasticDemodWebAPIAdapter()
{}
MeshtasticDemodWebAPIAdapter::~MeshtasticDemodWebAPIAdapter()
{}
int MeshtasticDemodWebAPIAdapter::webapiSettingsGet(
SWGSDRangel::SWGChannelSettings& response,
QString& errorMessage)
{
(void) errorMessage;
response.setChirpChatDemodSettings(new SWGSDRangel::SWGChirpChatDemodSettings());
response.getChirpChatDemodSettings()->init();
MeshtasticDemod::webapiFormatChannelSettings(response, m_settings);
return 200;
}
int MeshtasticDemodWebAPIAdapter::webapiSettingsPutPatch(
bool force,
const QStringList& channelSettingsKeys,
SWGSDRangel::SWGChannelSettings& response,
QString& errorMessage)
{
(void) force; // no action
(void) errorMessage;
MeshtasticDemod::webapiUpdateChannelSettings(m_settings, channelSettingsKeys, response);
MeshtasticDemod::webapiFormatChannelSettings(response, m_settings);
return 200;
}

49
plugins/channelrx/demodmeshtastic/meshtasticdemodwebapiadapter.h

@ -0,0 +1,49 @@ @@ -0,0 +1,49 @@
///////////////////////////////////////////////////////////////////////////////////
// Copyright (C) 2019-2020 Edouard Griffiths, F4EXB <f4exb06@gmail.com> //
// //
// This program is free software; you can redistribute it and/or modify //
// it under the terms of the GNU General Public License as published by //
// the Free Software Foundation as version 3 of the License, or //
// (at your option) any later version. //
// //
// This program is distributed in the hope that it will be useful, //
// but WITHOUT ANY WARRANTY; without even the implied warranty of //
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //
// GNU General Public License V3 for more details. //
// //
// You should have received a copy of the GNU General Public License //
// along with this program. If not, see <http://www.gnu.org/licenses/>. //
///////////////////////////////////////////////////////////////////////////////////
#ifndef INCLUDE_MESHTASTICDEMOD_WEBAPIADAPTER_H
#define INCLUDE_MESHTASTICDEMOD_WEBAPIADAPTER_H
#include "channel/channelwebapiadapter.h"
#include "meshtasticdemodsettings.h"
/**
* Standalone API adapter only for the settings
*/
class MeshtasticDemodWebAPIAdapter : public ChannelWebAPIAdapter {
public:
MeshtasticDemodWebAPIAdapter();
virtual ~MeshtasticDemodWebAPIAdapter();
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:
MeshtasticDemodSettings m_settings;
};
#endif // INCLUDE_MESHTASTICDEMOD_WEBAPIADAPTER_H

88
plugins/channelrx/demodmeshtastic/meshtasticplugin.cpp

@ -0,0 +1,88 @@ @@ -0,0 +1,88 @@
///////////////////////////////////////////////////////////////////////////////////
// Copyright (C) 2015-2022 Edouard Griffiths, F4EXB <f4exb06@gmail.com> //
// Copyright (C) 2019 Davide Gerhard <rainbow@irh.it> //
// Copyright (C) 2020 Kacper Michajłow <kasper93@gmail.com> //
// //
// This program is free software; you can redistribute it and/or modify //
// it under the terms of the GNU General Public License as published by //
// the Free Software Foundation as version 3 of the License, or //
// (at your option) any later version. //
// //
// This program is distributed in the hope that it will be useful, //
// but WITHOUT ANY WARRANTY; without even the implied warranty of //
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //
// GNU General Public License V3 for more details. //
// //
// You should have received a copy of the GNU General Public License //
// along with this program. If not, see <http://www.gnu.org/licenses/>. //
///////////////////////////////////////////////////////////////////////////////////
#include <QtPlugin>
#include "plugin/pluginapi.h"
#include "meshtasticplugin.h"
#ifndef SERVER_MODE
#include "meshtasticdemodgui.h"
#endif
#include "meshtasticdemod.h"
const PluginDescriptor MeshtasticPlugin::m_pluginDescriptor = {
MeshtasticDemod::m_channelId,
QStringLiteral("Meshtastic Demodulator"),
QStringLiteral("7.23.1"),
QStringLiteral("(c) Edouard Griffiths, F4EXB"),
QStringLiteral("https://github.com/f4exb/sdrangel"),
true,
QStringLiteral("https://github.com/f4exb/sdrangel")
};
MeshtasticPlugin::MeshtasticPlugin(QObject* parent) :
QObject(parent),
m_pluginAPI(nullptr)
{
}
const PluginDescriptor& MeshtasticPlugin::getPluginDescriptor() const
{
return m_pluginDescriptor;
}
void MeshtasticPlugin::initPlugin(PluginAPI* pluginAPI)
{
m_pluginAPI = pluginAPI;
// register demodulator
m_pluginAPI->registerRxChannel(MeshtasticDemod::m_channelIdURI, MeshtasticDemod::m_channelId, this);
}
void MeshtasticPlugin::createRxChannel(DeviceAPI *deviceAPI, BasebandSampleSink **bs, ChannelAPI **cs) const
{
if (bs || cs)
{
MeshtasticDemod *instance = new MeshtasticDemod(deviceAPI);
if (bs) {
*bs = instance;
}
if (cs) {
*cs = instance;
}
}
}
#ifdef SERVER_MODE
ChannelGUI* MeshtasticPlugin::createRxChannelGUI(
DeviceUISet *deviceUISet,
BasebandSampleSink *rxChannel) const
{
(void) deviceUISet;
(void) rxChannel;
return nullptr;
}
#else
ChannelGUI* MeshtasticPlugin::createRxChannelGUI(DeviceUISet *deviceUISet, BasebandSampleSink *rxChannel) const
{
return MeshtasticDemodGUI::create(m_pluginAPI, deviceUISet, rxChannel);
}
#endif

50
plugins/channelrx/demodmeshtastic/meshtasticplugin.h

@ -0,0 +1,50 @@ @@ -0,0 +1,50 @@
///////////////////////////////////////////////////////////////////////////////////
// Copyright (C) 2012 maintech GmbH, Otto-Hahn-Str. 15, 97204 Hoechberg, Germany //
// written by Christian Daniel //
// Copyright (C) 2015-2020 Edouard Griffiths, F4EXB <f4exb06@gmail.com> //
// Copyright (C) 2015 John Greb <hexameron@spam.no> //
// //
// This program is free software; you can redistribute it and/or modify //
// it under the terms of the GNU General Public License as published by //
// the Free Software Foundation as version 3 of the License, or //
// (at your option) any later version. //
// //
// This program is distributed in the hope that it will be useful, //
// but WITHOUT ANY WARRANTY; without even the implied warranty of //
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //
// GNU General Public License V3 for more details. //
// //
// You should have received a copy of the GNU General Public License //
// along with this program. If not, see <http://www.gnu.org/licenses/>. //
///////////////////////////////////////////////////////////////////////////////////
#ifndef INCLUDE_MESHTASTICPLUGIN_H
#define INCLUDE_MESHTASTICPLUGIN_H
#include <QObject>
#include "plugin/plugininterface.h"
class DeviceUISet;
class BasebandSampleSink;
class MeshtasticPlugin : public QObject, PluginInterface {
Q_OBJECT
Q_INTERFACES(PluginInterface)
Q_PLUGIN_METADATA(IID "sdrangel.channel.meshtasticdemod")
public:
explicit MeshtasticPlugin(QObject* parent = nullptr);
const PluginDescriptor& getPluginDescriptor() const;
void initPlugin(PluginAPI* pluginAPI);
virtual void createRxChannel(DeviceAPI *deviceAPI, BasebandSampleSink **bs, ChannelAPI **cs) const;
virtual ChannelGUI* createRxChannelGUI(DeviceUISet *deviceUISet, BasebandSampleSink *rxChannel) const;
private:
static const PluginDescriptor m_pluginDescriptor;
PluginAPI* m_pluginAPI;
};
#endif // INCLUDE_LoRaPLUGIN_H

384
plugins/channelrx/demodmeshtastic/readme.md

@ -0,0 +1,384 @@ @@ -0,0 +1,384 @@
<h1>Meshtastic demodulator plugin</h1>
<h2>Introduction</h2>
This plugin can be used to demodulate and decode transmissions based on Chirp Spread Spectrum (CSS). The basic idea is to transform each symbol of a MFSK modulation to an ascending frequency ramp shifted in time. It could equally be a descending ramp but this one is reserved to detect a break in the preamble sequence (synchronization). This plugin has been designed to work in conjunction with the ChirpChat modulator plugin that should be used ideally on the transmission side.
It has clearly been inspired by the LoRa technique but is designed for experimentation and extension to other protocols mostly inspired by amateur radio techniques using chirp modulation to transmit symbols. Thanks to the MFSK to chirp translation it is possible to adapt any MFSK based mode.
LoRa is a property of Semtech and the details of the protocol are not made public. However a LoRa compatible protocol has been implemented based on the reverse engineering performed by the community. It is mainly based on the work done in https://github.com/myriadrf/LoRa-SDR. You can find more information about LoRa and chirp modulation here:
- To get an idea of what is LoRa: [here](https://www.link-labs.com/blog/what-is-lora)
- A detailed inspection of LoRa modulation and protocol: [here](https://static1.squarespace.com/static/54cecce7e4b054df1848b5f9/t/57489e6e07eaa0105215dc6c/1464376943218/Reversing-Lora-Knight.pdf)
&#9888; Only spread factors of 11 and 12 are working in LoRa mode with the distance enhancement active (DE=2)
Transmissions from the RN2483 module (SF=11 and SF=12 with DE=2) could be successfully received. It has not been tested with Semtech SX127x hardware. This LoRa decoder is designed for experimentation. For production grade applications it is recommended to use dedicated hardware instead.
Modulation characteristics from LoRa have been augmented with more bandwidths and FFT bin collations (DE factor). Plain TTY and ASCII have also been added and there are plans to add some more complex typically amateur radio MFSK based modes like JT65.
In any case it is recommended to use a non zero distance enhancement factor for successful transmissions.
Note: this plugin is officially supported since version 6.
<h2>Meshtastic decode mode</h2>
In LoRa coding mode, decoded payload bytes are automatically tested as Meshtastic over-the-air frames (16-byte radio header + protobuf `Data` payload). When a frame is decoded successfully, an additional text line is appended in the message window with a `MESH RX|...` summary.
Key handling for decryption supports:
- `none` / plaintext
- Meshtastic shorthand keys (`default`, `simple0..10`)
- Explicit `hex:` and `base64:` keys
- Multiple keys from environment
Environment variables:
- `SDRANGEL_MESHTASTIC_KEYS`: comma-separated key specs. You can optionally bind a channel name using `ChannelName=KeySpec`.
- `SDRANGEL_MESHTASTIC_CHANNEL_NAME`: default channel name used when `SDRANGEL_MESHTASTIC_KEYS` is not set (default: `LongFast`).
- `SDRANGEL_MESHTASTIC_KEY`: default key used when `SDRANGEL_MESHTASTIC_KEYS` is not set (default: `default`).
UI key manager:
- Use the **Keys...** button next to `Region/Preset/Channel` to set a per-channel key list.
- Entries accept the same formats as environment variables and support `channelName=keySpec`.
- When a custom list is saved, it is persisted in the channel settings and takes precedence over environment variables for this demodulator instance.
Examples:
- `SDRANGEL_MESHTASTIC_KEYS=\"LongFast=default,Ops=hex:00112233445566778899aabbccddeeff,none\"`
- `SDRANGEL_MESHTASTIC_KEYS=\"base64:2PG7OiApB1nwvP+rz05pAQ==\"`
<h2>Meshtastic quick profile</h2>
The demodulator includes Meshtastic profile controls in the RF settings section:
- **Region**: Meshtastic region code (`US`, `EU_868`, ...)
- **Preset**: Meshtastic modem preset (`LONG_FAST`, ...)
- **Channel**: Meshtastic channel number, shown as Meshtastic-style zero-based index and auto-populated for selected region/preset
- **Auto Input Tune**: when enabled, tries to set source sample-rate/decimation automatically for the selected LoRa bandwidth
- **Auto Lock**: arms first and waits for on-air activity, then scans `Inv` + frequency offset candidates. For SF11/SF12 it also probes `DE=0` and `DE=2` as compatibility candidates. It scores using decode quality plus source-side intensity (demod activity + power/noise), but only auto-applies candidates with decode evidence (header/payload CRC backed); otherwise it restores baseline settings.
When either selection changes, the demodulator auto-applies LoRa decode parameters for the selected profile:
- bandwidth
- spread factor
- DE bits
- preamble length (16 on sub-GHz presets, 12 on 2.4 GHz)
- FEC parity bits
- header/CRC expectations
If the device center frequency is known, the channel offset is also auto-centered to the selected region/preset default channel.
The demodulator also attempts to auto-tune the device sample rate/decimation (when supported by the device) so effective baseband rate is suitable for the selected LoRa bandwidth.
<h2>Interface</h2>
The top and bottom bars of the channel window are described [here](../../../sdrgui/channel/readme.md)
![Meshtastic Demodulator plugin GUI](../../../doc/img/MeshtasticDemod_plugin.png)
<h3>1: Frequency shift from center frequency of reception</h3>
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.
<h3>2: De-chirped channel power</h3>
This is the total power in the FFT of the de-chirped signal in dB. When no ChirpChat signal is detected this corresponds to the power received in the bandwidth (3). It will show a significant increase in presence of a ChirpChat signal that can be detected.
<h3>3: Bandwidth</h3>
This is the bandwidth of the ChirpChat signal. Similarly to LoRa the signal sweeps between the lower and the upper frequency of this bandwidth. The sample rate of the ChirpChat signal in seconds is exactly one over this bandwidth in Hertz.
In the LoRa standard there are 2 base bandwidths: 500 and 333.333 kHz. A 400 kHz base has been added. Possible bandwidths are obtained by a division of these base bandwidths by a power of two from 1 to 64. Extra divisor of 128 is provided to achieve smaller bandwidths that can fit in a SSB channel. Finally special divisors from a 384 kHz base are provided to allow even more narrow bandwidths.
Thus available bandwidths are:
- **500000** (500000 / 1) Hz
- **400000** (400000 / 1) Hz not in LoRa standard
- **333333** (333333 / 1) Hz
- **250000** (500000 / 2) Hz
- **200000** (400000 / 2) Hz not in LoRa standard
- **166667** (333333 / 2) Hz
- **125000** (500000 / 4) Hz
- **100000** (400000 / 4) Hz not in LoRa standard
- **83333** (333333 / 4) Hz
- **62500** (500000 / 8) Hz
- **50000** (400000 / 8) Hz not in LoRa standard
- **41667** (333333 / 8) Hz
- **31250** (500000 / 16) Hz
- **25000** (400000 / 16) Hz not in LoRa standard
- **20833** (333333 / 16) Hz
- **15625** (500000 / 32) Hz
- **12500** (400000 / 32) Hz not in LoRa standard
- **10417** (333333 / 32) Hz
- **7813** (500000 / 64) Hz
- **6250** (400000 / 64) Hz not in LoRa standard
- **5208** (333333 / 64) Hz
- **3906** (500000 / 128) Hz not in LoRa standard
- **3125** (400000 / 128) Hz not in LoRa standard
- **2604** (333333 / 128) Hz not in LoRa standard
- **1500** (384000 / 256) Hz not in LoRa standard
- **750** (384000 / 512) Hz not in LoRa standard
- **488** (500000 / 1024) Hz not in LoRa standard
- **375** (384000 / 1024) Hz not in LoRa standard
The ChirpChat signal is oversampled by two therefore it needs a baseband of at least twice the bandwidth. This drives the maximum value on the slider automatically.
<h3>4: De-chirped noise maximum power</h3>
This is the maximum power received in one FFT bin (the argmax bin) in dB when no signal is detected. It is averaged over 10 values.
<h3>5. De-chirped signal maximum power</h3>
This is the maximum power received in one FFT bin (the argmax bin) in dB when a signal is detected. It is averaged over 10 values.
<h3>6: De-chirped signal over noise ratio</h3>
The noise level reference is the noise maximum power just before the detected signal starts and the signal level the signal maximum power just before the detected signal stops. To get a significant reading you have to adjust correctly the number of preamble chirps (9) and the End Of Message squelch level (A.3) and/or the message length (A.4) so that signal boundaries are determined correctly.
Decode errors are very likely to happen when this value falls below 4 dB.
<h3>7: FFT Window</h3>
A choice of FFT Windows to apply to the FFT performed on the de-chirped signal is provided. These are the same windows as those used in the spectrum display. The effect of windowing is to reduce the spill over in adjacent bins at the expense of a flatter top and fatter main lobe. When the purpose is frequency detection this is not what is desired necessarily and thus the "Rectangular" window (i.e. no window) should be chosen. However a variety of windows is provided to experiment with. Experimentally the best alternative to "Rectangular" is "Kaiser" then "Bartlett" and "Hanning". The complete list is:
- **Bart**: Bartlett
- **B-H**: 4 term Blackman-Harris
- **FT**: Flat Top
- **Ham**: Hamming
- **Han**: Hanning
- **Rec**: Rectangular (no window)
- **Kai**: Kaiser with &alpha; = &pi;
- **Black**: Blackman (3 term)
- **B-H7**: 7 term Blackman-Harris
<h3>8: Spread Factor</h3>
This is the Spread Factor parameter of the ChirpChat signal. This is the log2 of the FFT size used over the bandwidth (3). The number of symbols is 2<sup>SF-DE</sup> where SF is the spread factor and DE the Distance Enhancement factor (8)
<h3>9: Distance Enhancement factor</h3>
The LoRa standard specifies 0 (no DE) or 2 (DE active). The ChirpChat DE range is extended to all values between 0 and 4 bits.
The LoRa standard also specifies that the LowDataRateOptimizatio flag (thus DE=2 vs DE=0 here) should be set when the symbol time defined as BW / 2^SF exceeds 16 ms (See section 4.1.1.6 of the SX127x datasheet). In practice this happens for SF=11 and SF=12 and large enough bandwidths (you can do the maths).
Here this value is the log2 of the number of FFT bins used for one symbol. Extending the number of FFT bins per symbol decreases the probability to detect the wrong symbol as an adjacent bin. It can also overcome frequency or sampling time drift on long messages particularly for small bandwidths.
In practice it is difficult to make correct decodes if only one FFT bin is used to code one symbol (DE=0) therefore it is recommended to use a DE factor of 2 or more. With medium SNR DE=1 can still achieve good results.
<h3>10: Number of expected preamble chirps</h3>
This is the number of chirps expected in the preamble and has to be agreed between the transmitter and receiver.
<h3>15: Invert chirp ramps</h3>
The LoRa standard is up-chirps for the preamble, down-chirps for the SFD and up-chirps for the payload.
When you check this option it inverts the direction of the chirps thus becoming down-chirps for the preamble, up-chirps for the SFD and down-chirps for the payload.
<h3>A: Payload controls and indicators</h3>
![Meshtastic Demodulator payload controls](../../../doc/img/MeshtasticDemod_payload.png)
<h4>A.1: Coding scheme</h4>
In addition to the LoRa standard plain ASCII and TTY have been added for pure text messages. ASCII and TTY have no form of FEC.
- **LoRa**: LoRa standard (see LoRa documentation)
- **ASCII**: This is plain 7 bit ASCII coded characters. It needs exactly 7 effective bits per symbols (SF - DE = 7)
- **TTY**: Baudot (Teletype) 5 bit encoded characters. It needs exactly 5 effective bits per symbols (SF - DE = 5)
- **FT**: FT8/4 protocol. The 174 payload bits are packed into chirp symbols with zero padding if necessary
<h4>A.2: Start/Stop decoder</h4>
You can suspend and resume decoding activity using this button. This is useful if you want to freeze the payload content display.
<h4>A.3: End Of Message squelch</h4>
This is used to determine the end of message automatically. It can be de-activated by turning the button completely to the right (as shown on the picture). In this case it relies on the message length set with (A.4).
During payload detection the maximum power value in the FFT (at argmax) P<sub>max</sub> is stored and compared to the current argmax power value P<sub>i</sub> if S<sub>EOM</sub> is this squelch value the end of message is detected if S<sub>EOM</sub> &times; S<sub>i</sub> &lt; S<sub>max</sub>
<h4>A.4: Expected message length in symbols</h4>
This is the expected number of symbols in a message. When a header is present in the payload it should match the size given in the header (A.11).
<h4>A.5: Auto message length</h4>
LoRa and DT modes only. Set message length (A.4) equal to the number of symbols specified (or implied for FT) in the message just received. When messages are sent repeatedly this helps adjusting in possible message length changes automatically.
<h4>A.6: Sync word</h4>
This is the message 1 byte sync word displayed in hexadecimal.
<h4>A.7: Expect header in message</h4>
LoRa mode only. Use this checkbox to tell if you expect or not a header in the message.
<h4>A.8: Number of FEC parity bits</h4>
LoRa mode only. This is the number of parity bits in the Hamming code used in the FEC. The standard values are 1 to 4 for H(4,5) to H(4,8) encoding. 0 is a non-standard value to specify no FEC.
When a header is expected this control is disabled because the value used is the one found in the header.
In FT8 mode there is no FEC as FEC is handled within the FT payload (with LDPC)
<h4>A.9: Payload CRC presence</h4>
LoRa mode: Use this checkbox to tell if you expect a 2 byte CRC at the end of the payload. FT mode: there is always a CRC.
LoRa: When a header is expected this control is disabled because the value used is the one found in the header.
<h4>A.10: Packet length</h4>
This is the expected packet length in bytes without header and CRC. For FT this is the number of symbols.
LoRa: When a header is expected this control is disabled because the value used is the one found in the header.
<h4>A.11: Number of symbols and codewords</h4>
This is the number of symbols (left of slash) and codewords (right of slash) used for the payload including header and CRC.
<h4>A.12: Header FEC indicator (LoRa)</h4>
Header uses a H(4,8) FEC. The color of the indicator gives the status of header parity checks:
- **Grey**: undefined
- **Red**: unrecoverable error
- **Blue**: recovered error
- **Green**: no errors
<h4>A.13: Header CRC indicator (LoRa)</h4>
The header has a one byte CRC. The color of this indicator gives the CRC status:
- **Green**: CRC OK
- **Red**: CRC error
<h4>A.14: Payload FEC indicator (LoRa and FT)</h4>
The color of the indicator gives the status of payload parity checks:
- **Grey**: undefined
- **Red**: unrecoverable error. H(4,7) cannot distinguish between recoverable and unrecoverable error. Therefore this is never displayed for H(4,7). For FT it means that LDPC decoding failed.
- **Blue**: recovered error (LoRa only)
- **Green**: no errors
<h4>A.15: Payload CRC indicator (LoRa and FT)</h4>
The payload can have a two byte CRC. The color of this indicator gives the CRC status:
- **Grey**: No CRC (LoRa)
- **Green**: CRC OK
- **Red**: CRC error
<h3>11: Clear message window</h3>
Use this push button to clear the message window (12)
<h3>12: Message window</h3>
This is where the message and status data are displayed. The display varies if the coding scheme is purely text based (TTY, ASCII, FT) or text/binary mixed based (LoRa). The text vs binary consideration concerns the content of the message not the way it is transmitted on air that is by itself binary.
<h4>12.a: Text messages</h4>
The format of a message line is the following:
![Meshtastic Demodulator message string window](../../../doc/img/MeshtasticDemod_message_string.png)
- 1: Timestamp in HH:MM:SS format
- 2: Signal level. Same as (5) for the current message
- 3: Signal Over Noise. Same as (6) for the current message
- 4: Start of text indicator
- 5: Text
<h4>12.b: Binary messages</h4>
![Meshtastic Demodulator message bytes window](../../../doc/img/MeshtasticDemod_message_binary.png)
- 1: Timestamp in HH:NN:SS format
- 2: Sync word. This is the sync word (byte) displayed in hex. Corresponds to (A.5) in the current message.
- 3: De-chirped signal level. This is the de-chirped signal level in dB. Corresponds to (5) in the current message.
- 4: De-chirped signal to noise ratio. This is the de-chirped signal to noise ratio in dB. Corresponds to (6) in the current message.
- 5: Header FEC status. Corresponds to (A.12) indicator in the current message:
- **n/a**: unknown or not applicable
- **err**: unrecoverable error
- **fix**: corrected error
- **ok**: OK
- 6: Header CRC status. Corresponds to (A.13) indicator in the current message
- **ok**: CRC OK
- **err**: CRC error
- **n/a**: not applicable
- 7: Payload FEC status. Corresponds to (A.14) indicator in the current message. If the end of message is reached before expectation then `ERR: too early` is displayed instead and no payload CRC status (next) is displayed.
- **n/a**: unknown or not applicable
- **err**: unrecoverable error
- **fix**: corrected error
- **ok**: OK
- 8: Payload CRC status. Corresponds to (A.15) indicator in the current message:
- **ok**: CRC OK
- **err**: CRC error
- **n/a**: not applicable
- 9: Displacement at start of line. 16 bytes in 4 groups of 4 bytes are displayed per line starting with the displacement in decimal.
- 10: Bytes group. This is a group of 4 bytes displayed as hexadecimal values. The payload is displayed with its possible CRC and without the header.
- 11: Message as text with "TXT" as prefix indicating it is the translation of the message to character representation
<h3>13: Send message via UDP</h3>
Select to send the decoded message via UDP.
<h3>14: UDP address and port</h3>
This is the UDP address and port to where the decoded message is sent when (12) is selected.
<h3>B: De-chirped spectrum</h3>
This is the spectrum of the de-chirped signal when a ChirpChat signal can be decoded. Details on the spectrum view and controls can be found [here](../../../sdrgui/gui/spectrum.md)
The frequency span corresponds to the bandwidth of the ChirpChat signal (3). Default FFT size is 2<sup>SF</sup> where SF is the spread factor (7).
Sequences of successful ChirpChat signal demodulation are separated by blank lines (generated with a string of high value bins).
Controls are the usual controls of spectrum displays with the following restrictions:
- The window type is non operating because the FFT window is chosen by (7)
- The FFT size can be changed however it is set to 2<sup>SF</sup> where SF is the spread factor and thus displays correctly
<h2>Common LoRa settings</h2>
CR is the code rate and translates to FEC according to the following table
| CR | FEC |
| --- | --- |
| 4/5 | 1 |
| 4/6 | 2 |
| 4/7 | 3 |
| 4/8 | 4 |
When DE is on set DE to 2 else 0
<h3>Generic</h3>
| Use Case | SF | CR | BW (kHz) | DE Enabled? | Notes |
| --------------------- | --------- | ------- | -------- | ----------- | ----------------------------------------------------------- |
| High rate/short range | SF7 | 4/5 | 500 | Off | Fastest, urban/close devices |
| Balanced/general IoT | SF7–SF9 | 4/5–4/6 | 125–250 | Off | TTN default, good for gateways |
| Long range/rural | SF10–SF12 | 4/6–4/8 | 125 | On | Max sensitivity (-137 dBm), slow airtime |
| Extreme range | SF12 | 4/8 | 125 | On | Best for weak signals, long packets |
<h3>Meshtastic</h3>
<h4>Quick facts</h4>
- Uses 0x2B sync byte
- In Europe the default channel is centered on 869.525 MHz
<h4>Presets table</h4>
| Preset | SF | CR | BW (kHz) | DE? | Use Case |
| ------------------- | -- | ---- | -------- | --- | ---------------------------------------------------- |
| LONG_FAST (default) | 11 | 4/8 | 250 | On | Long range, moderate speed |
| MEDIUM_SLOW | 10 | 4/7 | 250 | On | Balanced range/reliability​ |
| SHORT_FAST | 9 | 4/7 | 250 | Off | Urban/short hops, faster​ |
| SHORT_TURBO | 7 | 4/5 | 500 | Off | Max speed, shortest range (region-limited)​ |
| LONG_SLOW | 12 | 4/8 | 125 | On | Extreme range, slowest meshtastic​ |

4
plugins/channeltx/CMakeLists.txt

@ -20,6 +20,10 @@ if (ENABLE_CHANNELTX_MODCHIRPCHAT) @@ -20,6 +20,10 @@ if (ENABLE_CHANNELTX_MODCHIRPCHAT)
add_subdirectory(modchirpchat)
endif()
if (ENABLE_CHANNELTX_MODMESHTASTIC)
add_subdirectory(modmeshtastic)
endif()
if (ENABLE_CHANNELTX_MODNFM)
add_subdirectory(modnfm)
endif()

90
plugins/channeltx/modmeshtastic/CMakeLists.txt

@ -0,0 +1,90 @@ @@ -0,0 +1,90 @@
project(modmeshtastic)
if (FT8_SUPPORT)
set(meshtasticmod_FT8_LIB ft8)
set(meshtasticmod_FT8_INCLUDE ${CMAKE_SOURCE_DIR}/ft8)
endif()
set(modmeshtastic_SOURCES
meshtasticmod.cpp
meshtasticmodsettings.cpp
meshtasticmodsource.cpp
meshtasticmodbaseband.cpp
meshtasticmodplugin.cpp
meshtasticmodencoder.cpp
meshtasticmodencodertty.cpp
meshtasticmodencoderascii.cpp
meshtasticmodencoderlora.cpp
meshtasticmodencoderft.cpp
meshtasticmodwebapiadapter.cpp
${CMAKE_SOURCE_DIR}/plugins/meshtasticcommon/meshtasticpacket.cpp
)
set(modmeshtastic_HEADERS
meshtasticmod.h
meshtasticmodsettings.h
meshtasticmodsource.h
meshtasticmodbaseband.h
meshtasticmodplugin.h
meshtasticmodencoder.h
meshtasticmodencodertty.h
meshtasticmodencoderascii.h
meshtasticmodencoderlora.h
meshtasticmodencoderft.h
meshtasticmodwebapiadapter.h
)
include_directories(
${CMAKE_SOURCE_DIR}/swagger/sdrangel/code/qt5/client
${meshtasticmod_FT8_INCLUDE}
${CMAKE_SOURCE_DIR}/plugins/meshtasticcommon
)
if(NOT SERVER_MODE)
set(modmeshtastic_SOURCES
${modmeshtastic_SOURCES}
meshtasticmodgui.cpp
meshtasticmodgui.ui
)
set(modmeshtastic_HEADERS
${modmeshtastic_HEADERS}
meshtasticmodgui.h
)
set(TARGET_NAME ${PLUGINS_PREFIX}modmeshtastic)
set(TARGET_LIB "Qt::Widgets")
set(TARGET_LIB_GUI "sdrgui")
set(INSTALL_FOLDER ${INSTALL_PLUGINS_DIR})
else()
set(TARGET_NAME ${PLUGINSSRV_PREFIX}modmeshtasticsrv)
set(TARGET_LIB "")
set(TARGET_LIB_GUI "")
set(INSTALL_FOLDER ${INSTALL_PLUGINSSRV_DIR})
endif()
if(NOT Qt6_FOUND)
add_library(${TARGET_NAME} ${modmeshtastic_SOURCES})
else()
qt_add_plugin(${TARGET_NAME} CLASS_NAME MeshtasticModPlugin ${modmeshtastic_SOURCES})
endif()
if(NOT BUILD_SHARED_LIBS)
set_property(GLOBAL APPEND PROPERTY STATIC_PLUGINS_PROPERTY ${TARGET_NAME})
endif()
target_link_libraries(${TARGET_NAME} PRIVATE
Qt::Core
${TARGET_LIB}
sdrbase
${TARGET_LIB_GUI}
swagger
${meshtasticmod_FT8_LIB}
)
install(TARGETS ${TARGET_NAME} DESTINATION ${INSTALL_FOLDER})
# Install debug symbols
if (WIN32)
install(FILES $<TARGET_PROPERTY:${TARGET_NAME},RUNTIME_OUTPUT_DIRECTORY>/${TARGET_NAME}stripped.pdb CONFIGURATIONS Release DESTINATION ${INSTALL_FOLDER} RENAME ${TARGET_NAME}.pdb )
install(FILES $<TARGET_PDB_FILE:${TARGET_NAME}> CONFIGURATIONS Debug RelWithDebInfo DESTINATION ${INSTALL_FOLDER} )
endif()

1089
plugins/channeltx/modmeshtastic/meshtasticmod.cpp

File diff suppressed because it is too large Load Diff

206
plugins/channeltx/modmeshtastic/meshtasticmod.h

@ -0,0 +1,206 @@ @@ -0,0 +1,206 @@
///////////////////////////////////////////////////////////////////////////////////
// Copyright (C) 2017-2020, 2022 Edouard Griffiths, F4EXB <f4exb06@gmail.com> //
// Copyright (C) 2020-2021 Jon Beniston, M7RCE <jon@beniston.com> //
// Copyright (C) 2020 Kacper Michajłow <kasper93@gmail.com> //
// Copyright (C) 2022 Jiří Pinkava <jiri.pinkava@rossum.ai> //
// //
// This program is free software; you can redistribute it and/or modify //
// it under the terms of the GNU General Public License as published by //
// the Free Software Foundation as version 3 of the License, or //
// (at your option) any later version. //
// //
// This program is distributed in the hope that it will be useful, //
// but WITHOUT ANY WARRANTY; without even the implied warranty of //
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //
// GNU General Public License V3 for more details. //
// //
// You should have received a copy of the GNU General Public License //
// along with this program. If not, see <http://www.gnu.org/licenses/>. //
///////////////////////////////////////////////////////////////////////////////////
#ifndef PLUGINS_CHANNELTX_MODMESHTASTIC_MESHTASTICMOD_H_
#define PLUGINS_CHANNELTX_MODMESHTASTIC_MESHTASTICMOD_H_
#include <vector>
#include <iostream>
#include <fstream>
#include <QRecursiveMutex>
#include <QNetworkRequest>
#include "dsp/basebandsamplesource.h"
#include "channel/channelapi.h"
#include "util/message.h"
#include "meshtasticmodsettings.h"
#include "meshtasticmodencoder.h"
class QNetworkAccessManager;
class QNetworkReply;
class QThread;
class QUdpSocket;
class DeviceAPI;
class CWKeyer;
class MeshtasticModBaseband;
class ObjectPipe;
class MeshtasticMod : public BasebandSampleSource, public ChannelAPI {
public:
class MsgConfigureMeshtasticMod : public Message {
MESSAGE_CLASS_DECLARATION
public:
const MeshtasticModSettings& getSettings() const { return m_settings; }
bool getForce() const { return m_force; }
static MsgConfigureMeshtasticMod* create(const MeshtasticModSettings& settings, bool force)
{
return new MsgConfigureMeshtasticMod(settings, force);
}
private:
MeshtasticModSettings m_settings;
bool m_force;
MsgConfigureMeshtasticMod(const MeshtasticModSettings& settings, bool force) :
Message(),
m_settings(settings),
m_force(force)
{ }
};
class MsgReportPayloadTime : public Message {
MESSAGE_CLASS_DECLARATION
public:
float getPayloadTimeMs() const { return m_timeMs; }
std::size_t getNbSymbols() const { return m_nbSymbols; }
static MsgReportPayloadTime* create(float timeMs, std::size_t nbSymbols) {
return new MsgReportPayloadTime(timeMs, nbSymbols);
}
private:
float m_timeMs; //!< time in milliseconds
std::size_t m_nbSymbols; //!< number of symbols
MsgReportPayloadTime(float timeMs, std::size_t nbSymbols) :
Message(),
m_timeMs(timeMs),
m_nbSymbols(nbSymbols)
{}
};
//=================================================================
MeshtasticMod(DeviceAPI *deviceAPI);
virtual ~MeshtasticMod();
virtual void destroy() { delete this; }
virtual void setDeviceAPI(DeviceAPI *deviceAPI);
virtual DeviceAPI *getDeviceAPI() { return m_deviceAPI; }
virtual void start();
virtual void stop();
virtual void pull(SampleVector::iterator& begin, unsigned int nbSamples);
virtual void pushMessage(Message *msg) { m_inputMessageQueue.push(msg); }
virtual QString getSourceName() { return objectName(); }
virtual void getIdentifier(QString& id) { id = objectName(); }
virtual QString getIdentifier() const { return objectName(); }
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 m_settings.m_inputFrequencyOffset;
}
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 MeshtasticModSettings& settings);
static void webapiUpdateChannelSettings(
MeshtasticModSettings& settings,
const QStringList& channelSettingsKeys,
SWGSDRangel::SWGChannelSettings& response);
double getMagSq() const;
CWKeyer *getCWKeyer();
void setLevelMeter(QObject *levelMeter);
uint32_t getNumberOfDeviceStreams() const;
bool getModulatorActive() const;
static const char* const m_channelIdURI;
static const char* const m_channelId;
private:
DeviceAPI* m_deviceAPI;
QThread *m_thread;
MeshtasticModBaseband* m_basebandSource;
MeshtasticModEncoder m_encoder; // TODO: check if it needs to be on its own thread
MeshtasticModSettings m_settings;
float m_currentPayloadTime;
std::vector<unsigned short> m_symbols;
SampleVector m_sampleBuffer;
QRecursiveMutex m_settingsMutex;
int m_sampleRate;
QNetworkAccessManager *m_networkManager;
QNetworkRequest m_networkRequest;
QUdpSocket *m_udpSocket;
virtual bool handleMessage(const Message& cmd);
void applySettings(const MeshtasticModSettings& settings, bool force = false);
void webapiFormatChannelReport(SWGSDRangel::SWGChannelReport& response);
void webapiReverseSendSettings(QList<QString>& channelSettingsKeys, const MeshtasticModSettings& settings, bool force);
void sendChannelSettings(
const QList<ObjectPipe*>& pipes,
QList<QString>& channelSettingsKeys,
const MeshtasticModSettings& settings,
bool force
);
void webapiFormatChannelSettings(
QList<QString>& channelSettingsKeys,
SWGSDRangel::SWGChannelSettings *swgChannelSettings,
const MeshtasticModSettings& settings,
bool force
);
void openUDP(const MeshtasticModSettings& settings);
void closeUDP();
private slots:
void networkManagerFinished(QNetworkReply *reply);
void udpRx();
};
#endif /* PLUGINS_CHANNELTX_MODMESHTASTIC_MESHTASTICMOD_H_ */

201
plugins/channeltx/modmeshtastic/meshtasticmodbaseband.cpp

@ -0,0 +1,201 @@ @@ -0,0 +1,201 @@
///////////////////////////////////////////////////////////////////////////////////
// Copyright (C) 2019-2020 Edouard Griffiths, F4EXB <f4exb06@gmail.com> //
// Copyright (C) 2020 Jon Beniston, M7RCE <jon@beniston.com> //
// Copyright (C) 2022 Jiří Pinkava <jiri.pinkava@rossum.ai> //
// //
// This program is free software; you can redistribute it and/or modify //
// it under the terms of the GNU General Public License as published by //
// the Free Software Foundation as version 3 of the License, or //
// (at your option) any later version. //
// //
// This program is distributed in the hope that it will be useful, //
// but WITHOUT ANY WARRANTY; without even the implied warranty of //
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //
// GNU General Public License V3 for more details. //
// //
// You should have received a copy of the GNU General Public License //
// along with this program. If not, see <http://www.gnu.org/licenses/>. //
///////////////////////////////////////////////////////////////////////////////////
#include <QDebug>
#include "dsp/upchannelizer.h"
#include "dsp/dspcommands.h"
#include "meshtasticmodbaseband.h"
MESSAGE_CLASS_DEFINITION(MeshtasticModBaseband::MsgConfigureMeshtasticModBaseband, Message)
MESSAGE_CLASS_DEFINITION(MeshtasticModBaseband::MsgConfigureMeshtasticModPayload, Message)
MeshtasticModBaseband::MeshtasticModBaseband()
{
m_sampleFifo.resize(SampleSourceFifo::getSizePolicy(48000));
m_channelizer = new UpChannelizer(&m_source);
qDebug("MeshtasticModBaseband::MeshtasticModBaseband");
QObject::connect(
&m_sampleFifo,
&SampleSourceFifo::dataRead,
this,
&MeshtasticModBaseband::handleData,
Qt::QueuedConnection
);
connect(&m_inputMessageQueue, SIGNAL(messageEnqueued()), this, SLOT(handleInputMessages()));
}
MeshtasticModBaseband::~MeshtasticModBaseband()
{
delete m_channelizer;
}
void MeshtasticModBaseband::reset()
{
QMutexLocker mutexLocker(&m_mutex);
m_sampleFifo.reset();
}
void MeshtasticModBaseband::pull(const SampleVector::iterator& begin, unsigned int nbSamples)
{
unsigned int part1Begin, part1End, part2Begin, part2End;
m_sampleFifo.read(nbSamples, part1Begin, part1End, part2Begin, part2End);
SampleVector& data = m_sampleFifo.getData();
if (part1Begin != part1End)
{
std::copy(
data.begin() + part1Begin,
data.begin() + part1End,
begin
);
}
unsigned int shift = part1End - part1Begin;
if (part2Begin != part2End)
{
std::copy(
data.begin() + part2Begin,
data.begin() + part2End,
begin + shift
);
}
}
void MeshtasticModBaseband::handleData()
{
QMutexLocker mutexLocker(&m_mutex);
SampleVector& data = m_sampleFifo.getData();
unsigned int ipart1begin;
unsigned int ipart1end;
unsigned int ipart2begin;
unsigned int ipart2end;
qreal rmsLevel, peakLevel;
int numSamples;
unsigned int remainder = m_sampleFifo.remainder();
while ((remainder > 0) && (m_inputMessageQueue.size() == 0))
{
m_sampleFifo.write(remainder, ipart1begin, ipart1end, ipart2begin, ipart2end);
if (ipart1begin != ipart1end) { // first part of FIFO data
processFifo(data, ipart1begin, ipart1end);
}
if (ipart2begin != ipart2end) { // second part of FIFO data (used when block wraps around)
processFifo(data, ipart2begin, ipart2end);
}
remainder = m_sampleFifo.remainder();
}
m_source.getLevels(rmsLevel, peakLevel, numSamples);
emit levelChanged(rmsLevel, peakLevel, numSamples);
}
void MeshtasticModBaseband::processFifo(SampleVector& data, unsigned int iBegin, unsigned int iEnd)
{
m_channelizer->pull(data.begin() + iBegin, iEnd - iBegin);
}
void MeshtasticModBaseband::handleInputMessages()
{
Message* message;
while ((message = m_inputMessageQueue.pop()) != nullptr)
{
if (handleMessage(*message)) {
delete message;
}
}
}
bool MeshtasticModBaseband::handleMessage(const Message& cmd)
{
if (MsgConfigureMeshtasticModBaseband::match(cmd))
{
qDebug() << "MeshtasticModBaseband::handleMessage: MsgConfigureMeshtasticModBaseband";
QMutexLocker mutexLocker(&m_mutex);
MsgConfigureMeshtasticModBaseband& cfg = (MsgConfigureMeshtasticModBaseband&) cmd;
applySettings(cfg.getSettings(), cfg.getForce());
return true;
}
else if (MsgConfigureMeshtasticModPayload::match(cmd))
{
QMutexLocker mutexLocker(&m_mutex);
MsgConfigureMeshtasticModPayload& cfg = (MsgConfigureMeshtasticModPayload&) cmd;
qDebug() << "MeshtasticModBaseband::handleMessage: MsgConfigureMeshtasticModPayload:" << cfg.getPayload().size();
m_source.setSymbols(cfg.getPayload());
return true;
}
else if (DSPSignalNotification::match(cmd))
{
QMutexLocker mutexLocker(&m_mutex);
DSPSignalNotification& notif = (DSPSignalNotification&) cmd;
m_sampleFifo.resize(SampleSourceFifo::getSizePolicy(notif.getSampleRate()));
qDebug() << "MeshtasticModBaseband::handleMessage: DSPSignalNotification: basebandSampleRate: " << notif.getSampleRate();
m_channelizer->setBasebandSampleRate(notif.getSampleRate());
m_source.applyChannelSettings(
m_channelizer->getChannelSampleRate(),
MeshtasticModSettings::bandwidths[m_settings.m_bandwidthIndex],
m_channelizer->getChannelFrequencyOffset()
);
return true;
}
else
{
return false;
}
}
void MeshtasticModBaseband::applySettings(const MeshtasticModSettings& settings, bool force)
{
if ((settings.m_bandwidthIndex != m_settings.m_bandwidthIndex)
|| (settings.m_inputFrequencyOffset != m_settings.m_inputFrequencyOffset) || force)
{
int thisBW = MeshtasticModSettings::bandwidths[settings.m_bandwidthIndex];
m_channelizer->setChannelization(
thisBW * MeshtasticModSettings::oversampling,
settings.m_inputFrequencyOffset
);
m_source.applyChannelSettings(
m_channelizer->getChannelSampleRate(),
thisBW,
m_channelizer->getChannelFrequencyOffset()
);
}
m_source.applySettings(settings, force);
m_settings = settings;
}
int MeshtasticModBaseband::getChannelSampleRate() const
{
return m_channelizer->getChannelSampleRate();
}

120
plugins/channeltx/modmeshtastic/meshtasticmodbaseband.h

@ -0,0 +1,120 @@ @@ -0,0 +1,120 @@
///////////////////////////////////////////////////////////////////////////////////
// Copyright (C) 2019-2020 Edouard Griffiths, F4EXB <f4exb06@gmail.com> //
// Copyright (C) 2022 Jiří Pinkava <jiri.pinkava@rossum.ai> //
// //
// This program is free software; you can redistribute it and/or modify //
// it under the terms of the GNU General Public License as published by //
// the Free Software Foundation as version 3 of the License, or //
// (at your option) any later version. //
// //
// This program is distributed in the hope that it will be useful, //
// but WITHOUT ANY WARRANTY; without even the implied warranty of //
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //
// GNU General Public License V3 for more details. //
// //
// You should have received a copy of the GNU General Public License //
// along with this program. If not, see <http://www.gnu.org/licenses/>. //
///////////////////////////////////////////////////////////////////////////////////
#ifndef INCLUDE_MESHTASTICMODBASEBAND_H
#define INCLUDE_MESHTASTICMODBASEBAND_H
#include <QObject>
#include <QRecursiveMutex>
#include "dsp/samplesourcefifo.h"
#include "util/message.h"
#include "util/messagequeue.h"
#include "meshtasticmodsource.h"
class UpChannelizer;
class MeshtasticModBaseband : public QObject
{
Q_OBJECT
public:
class MsgConfigureMeshtasticModBaseband : public Message {
MESSAGE_CLASS_DECLARATION
public:
const MeshtasticModSettings& getSettings() const { return m_settings; }
bool getForce() const { return m_force; }
static MsgConfigureMeshtasticModBaseband* create(const MeshtasticModSettings& settings, bool force)
{
return new MsgConfigureMeshtasticModBaseband(settings, force);
}
private:
MeshtasticModSettings m_settings;
bool m_force;
MsgConfigureMeshtasticModBaseband(const MeshtasticModSettings& settings, bool force) :
Message(),
m_settings(settings),
m_force(force)
{ }
};
class MsgConfigureMeshtasticModPayload : public Message {
MESSAGE_CLASS_DECLARATION
public:
const std::vector<unsigned short>& getPayload() const { return m_payload; }
static MsgConfigureMeshtasticModPayload* create() {
return new MsgConfigureMeshtasticModPayload();
}
static MsgConfigureMeshtasticModPayload* create(const std::vector<unsigned short>& payload) {
return new MsgConfigureMeshtasticModPayload(payload);
}
private:
std::vector<unsigned short> m_payload;
MsgConfigureMeshtasticModPayload() : // This is empty payload notification
Message()
{}
MsgConfigureMeshtasticModPayload(const std::vector<unsigned short>& payload) :
Message()
{ m_payload = payload; }
};
MeshtasticModBaseband();
~MeshtasticModBaseband();
void reset();
void pull(const SampleVector::iterator& begin, unsigned int nbSamples);
MessageQueue *getInputMessageQueue() { return &m_inputMessageQueue; } //!< Get the queue for asynchronous inbound communication
double getMagSq() const { return m_source.getMagSq(); }
int getChannelSampleRate() const;
bool getActive() const { return m_source.getActive(); }
signals:
/**
* Level changed
* \param rmsLevel RMS level in range 0.0 - 1.0
* \param peakLevel Peak level in range 0.0 - 1.0
* \param numSamples Number of audio samples analyzed
*/
void levelChanged(qreal rmsLevel, qreal peakLevel, int numSamples);
private:
SampleSourceFifo m_sampleFifo;
UpChannelizer *m_channelizer;
MeshtasticModSource m_source;
MessageQueue m_inputMessageQueue; //!< Queue for asynchronous inbound communication
MeshtasticModSettings m_settings;
QRecursiveMutex m_mutex;
void processFifo(SampleVector& data, unsigned int iBegin, unsigned int iEnd);
bool handleMessage(const Message& cmd);
void applySettings(const MeshtasticModSettings& settings, bool force = false);
private slots:
void handleInputMessages();
void handleData(); //!< Handle data when samples have to be processed
};
#endif // INCLUDE_MESHTASTICMODBASEBAND_H

181
plugins/channeltx/modmeshtastic/meshtasticmodencoder.cpp

@ -0,0 +1,181 @@ @@ -0,0 +1,181 @@
///////////////////////////////////////////////////////////////////////////////////
// Copyright (C) 2020 Edouard Griffiths, F4EXB <f4exb06@gmail.com> //
// //
// This program is free software; you can redistribute it and/or modify //
// it under the terms of the GNU General Public License as published by //
// the Free Software Foundation as version 3 of the License, or //
// (at your option) any later version. //
// //
// This program is distributed in the hope that it will be useful, //
// but WITHOUT ANY WARRANTY; without even the implied warranty of //
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //
// GNU General Public License V3 for more details. //
// //
// You should have received a copy of the GNU General Public License //
// along with this program. If not, see <http://www.gnu.org/licenses/>. //
///////////////////////////////////////////////////////////////////////////////////
#include <QDebug>
#include "meshtasticmodencoder.h"
#include "meshtasticmodencodertty.h"
#include "meshtasticmodencoderascii.h"
#include "meshtasticmodencoderlora.h"
#include "meshtasticmodencoderft.h"
#include "meshtasticpacket.h"
MeshtasticModEncoder::MeshtasticModEncoder() :
m_codingScheme(MeshtasticModSettings::CodingTTY),
m_nbSymbolBits(5),
m_nbParityBits(1),
m_hasCRC(true),
m_hasHeader(true)
{}
MeshtasticModEncoder::~MeshtasticModEncoder()
{}
void MeshtasticModEncoder::setNbSymbolBits(unsigned int spreadFactor, unsigned int deBits)
{
m_spreadFactor = spreadFactor;
if (deBits >= spreadFactor) {
m_deBits = m_spreadFactor - 1;
} else {
m_deBits = deBits;
}
m_nbSymbolBits = m_spreadFactor - m_deBits;
}
void MeshtasticModEncoder::encode(MeshtasticModSettings settings, std::vector<unsigned short>& symbols)
{
if (settings.m_codingScheme == MeshtasticModSettings::CodingFT)
{
MeshtasticModEncoderFT::encodeMsg(
settings.m_myCall,
settings.m_urCall,
settings.m_myLoc,
settings.m_myRpt,
settings.m_textMessage,
settings.m_messageType,
m_nbSymbolBits,
symbols
);
}
else
{
if (settings.m_messageType == MeshtasticModSettings::MessageBytes) {
encodeBytes(settings.m_bytesMessage, symbols);
} else if (settings.m_messageType == MeshtasticModSettings::MessageBeacon) {
encodeString(settings.m_beaconMessage, symbols);
} else if (settings.m_messageType == MeshtasticModSettings::MessageCQ) {
encodeString(settings.m_cqMessage, symbols);
} else if (settings.m_messageType == MeshtasticModSettings::MessageReply) {
encodeString(settings.m_replyMessage, symbols);
} else if (settings.m_messageType == MeshtasticModSettings::MessageReport) {
encodeString(settings.m_reportMessage, symbols);
} else if (settings.m_messageType == MeshtasticModSettings::MessageReplyReport) {
encodeString(settings.m_replyReportMessage, symbols);
} else if (settings.m_messageType == MeshtasticModSettings::MessageRRR) {
encodeString(settings.m_rrrMessage, symbols);
} else if (settings.m_messageType == MeshtasticModSettings::Message73) {
encodeString(settings.m_73Message, symbols);
} else if (settings.m_messageType == MeshtasticModSettings::MessageQSOText) {
encodeString(settings.m_qsoTextMessage, symbols);
} else if (settings.m_messageType == MeshtasticModSettings::MessageText) {
encodeString(settings.m_textMessage, symbols);
}
}
}
void MeshtasticModEncoder::encodeString(const QString& str, std::vector<unsigned short>& symbols)
{
switch (m_codingScheme)
{
case MeshtasticModSettings::CodingTTY:
if (m_nbSymbolBits == 5) {
MeshtasticModEncoderTTY::encodeString(str, symbols);
}
break;
case MeshtasticModSettings::CodingASCII:
if (m_nbSymbolBits == 7) {
MeshtasticModEncoderASCII::encodeString(str, symbols);
}
break;
case MeshtasticModSettings::CodingLoRa:
if (m_nbSymbolBits >= 5)
{
QByteArray bytes;
QString summary;
QString error;
if (Meshtastic::Packet::isCommand(str))
{
if (!Meshtastic::Packet::buildFrameFromCommand(str, bytes, summary, error))
{
qWarning() << "MeshtasticModEncoder::encodeString: Meshtastic command error:" << error;
return;
}
qInfo() << "MeshtasticModEncoder::encodeString:" << summary;
}
else
{
bytes = str.toUtf8();
}
encodeBytesLoRa(bytes, symbols);
}
break;
default:
break;
}
}
void MeshtasticModEncoder::encodeBytes(const QByteArray& bytes, std::vector<unsigned short>& symbols)
{
switch (m_codingScheme)
{
case MeshtasticModSettings::CodingLoRa:
{
QByteArray payload(bytes);
if (Meshtastic::Packet::isCommand(QString::fromUtf8(bytes)))
{
QString summary;
QString error;
if (!Meshtastic::Packet::buildFrameFromCommand(QString::fromUtf8(bytes), payload, summary, error))
{
qWarning() << "MeshtasticModEncoder::encodeBytes: Meshtastic command error:" << error;
return;
}
qInfo() << "MeshtasticModEncoder::encodeBytes:" << summary;
}
encodeBytesLoRa(payload, symbols);
break;
}
default:
break;
};
}
void MeshtasticModEncoder::encodeBytesLoRa(const QByteArray& bytes, std::vector<unsigned short>& symbols)
{
QByteArray payload(bytes);
if ((payload.size() + (m_hasCRC ? 2 : 0)) > 255)
{
qWarning() << "MeshtasticModEncoder::encodeBytesLoRa: payload too large:" << payload.size();
return;
}
if (m_hasCRC) {
MeshtasticModEncoderLoRa::addChecksum(payload);
}
MeshtasticModEncoderLoRa::encodeBytes(payload, symbols, m_nbSymbolBits, m_hasHeader, m_hasCRC, m_nbParityBits);
}

57
plugins/channeltx/modmeshtastic/meshtasticmodencoder.h

@ -0,0 +1,57 @@ @@ -0,0 +1,57 @@
///////////////////////////////////////////////////////////////////////////////////
// Copyright (C) 2012 maintech GmbH, Otto-Hahn-Str. 15, 97204 Hoechberg, Germany //
// written by Christian Daniel //
// Copyright (C) 2016-2020 Edouard Griffiths, F4EXB <f4exb06@gmail.com> //
// //
// This program is free software; you can redistribute it and/or modify //
// it under the terms of the GNU General Public License as published by //
// the Free Software Foundation as version 3 of the License, or //
// (at your option) any later version. //
// //
// This program is distributed in the hope that it will be useful, //
// but WITHOUT ANY WARRANTY; without even the implied warranty of //
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //
// GNU General Public License V3 for more details. //
// //
// You should have received a copy of the GNU General Public License //
// along with this program. If not, see <http://www.gnu.org/licenses/>. //
///////////////////////////////////////////////////////////////////////////////////
#ifndef PLUGINS_CHANNELTX_MODMESHTASTIC_MESHTASTICMODENCODER_H_
#define PLUGINS_CHANNELTX_MODMESHTASTIC_MESHTASTICMODENCODER_H_
#include <vector>
#include "meshtasticmodsettings.h"
class MeshtasticModEncoder
{
public:
MeshtasticModEncoder();
~MeshtasticModEncoder();
void setCodingScheme(MeshtasticModSettings::CodingScheme codingScheme) { m_codingScheme = codingScheme; }
void setNbSymbolBits(unsigned int spreadFactor, unsigned int deBits);
void setLoRaParityBits(unsigned int parityBits) { m_nbParityBits = parityBits; }
void setLoRaHasHeader(bool hasHeader) { m_hasHeader = hasHeader; }
void setLoRaHasCRC(bool hasCRC) { m_hasCRC = hasCRC; }
void encodeBytes(const QByteArray& bytes, std::vector<unsigned short>& symbols);
void encode(MeshtasticModSettings settings, std::vector<unsigned short>& symbols);
private:
void encodeString(const QString& str, std::vector<unsigned short>& symbols);
// LoRa functions
void encodeBytesLoRa(const QByteArray& bytes, std::vector<unsigned short>& symbols);
// General attributes
MeshtasticModSettings::CodingScheme m_codingScheme;
unsigned int m_spreadFactor;
unsigned int m_deBits;
unsigned int m_nbSymbolBits;
// LoRa attributes
unsigned int m_nbParityBits; //!< 1 to 4 Hamming FEC bits for 4 payload bits
bool m_hasCRC;
bool m_hasHeader;
};
#endif // PLUGINS_CHANNELTX_MODMESHTASTIC_MESHTASTICMODENCODER_H_

30
plugins/channeltx/modmeshtastic/meshtasticmodencoderascii.cpp

@ -0,0 +1,30 @@ @@ -0,0 +1,30 @@
///////////////////////////////////////////////////////////////////////////////////
// Copyright (C) 2012 maintech GmbH, Otto-Hahn-Str. 15, 97204 Hoechberg, Germany //
// written by Christian Daniel //
// Copyright (C) 2015-2020 Edouard Griffiths, F4EXB <f4exb06@gmail.com> //
// //
// This program is free software; you can redistribute it and/or modify //
// it under the terms of the GNU General Public License as published by //
// the Free Software Foundation as version 3 of the License, or //
// (at your option) any later version. //
// //
// This program is distributed in the hope that it will be useful, //
// but WITHOUT ANY WARRANTY; without even the implied warranty of //
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //
// GNU General Public License V3 for more details. //
// //
// You should have received a copy of the GNU General Public License //
// along with this program. If not, see <http://www.gnu.org/licenses/>. //
///////////////////////////////////////////////////////////////////////////////////
#include "meshtasticmodencoderascii.h"
void MeshtasticModEncoderASCII::encodeString(const QString& str, std::vector<unsigned short>& symbols)
{
QByteArray asciiStr = str.toUtf8();
QByteArray::const_iterator it = asciiStr.begin();
for (; it != asciiStr.end(); ++it) {
symbols.push_back(*it & 0x7F);
}
}

32
plugins/channeltx/modmeshtastic/meshtasticmodencoderascii.h

@ -0,0 +1,32 @@ @@ -0,0 +1,32 @@
///////////////////////////////////////////////////////////////////////////////////
// Copyright (C) 2012 maintech GmbH, Otto-Hahn-Str. 15, 97204 Hoechberg, Germany //
// written by Christian Daniel //
// Copyright (C) 2015-2020 Edouard Griffiths, F4EXB <f4exb06@gmail.com> //
// //
// This program is free software; you can redistribute it and/or modify //
// it under the terms of the GNU General Public License as published by //
// the Free Software Foundation as version 3 of the License, or //
// (at your option) any later version. //
// //
// This program is distributed in the hope that it will be useful, //
// but WITHOUT ANY WARRANTY; without even the implied warranty of //
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //
// GNU General Public License V3 for more details. //
// //
// You should have received a copy of the GNU General Public License //
// along with this program. If not, see <http://www.gnu.org/licenses/>. //
///////////////////////////////////////////////////////////////////////////////////
#ifndef PLUGINS_CHANNELTX_MODMESHTASTIC_MESHTASTICMODENCODERASCII_H_
#define PLUGINS_CHANNELTX_MODMESHTASTIC_MESHTASTICMODENCODERASCII_H_
#include <vector>
#include <QString>
class MeshtasticModEncoderASCII
{
public:
static void encodeString(const QString& str, std::vector<unsigned short>& symbols);
};
#endif // PLUGINS_CHANNELTX_MODMESHTASTIC_MESHTASTICMODENCODERASCII_H_

246
plugins/channeltx/modmeshtastic/meshtasticmodencoderft.cpp

@ -0,0 +1,246 @@ @@ -0,0 +1,246 @@
///////////////////////////////////////////////////////////////////////////////////
// Copyright (C) 2024 Edouard Griffiths, F4EXB <f4exb06@gmail.com> //
// //
// This program is free software; you can redistribute it and/or modify //
// it under the terms of the GNU General Public License as published by //
// the Free Software Foundation as version 3 of the License, or //
// (at your option) any later version. //
// //
// This program is distributed in the hope that it will be useful, //
// but WITHOUT ANY WARRANTY; without even the implied warranty of //
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //
// GNU General Public License V3 for more details. //
// //
// You should have received a copy of the GNU General Public License //
// along with this program. If not, see <http://www.gnu.org/licenses/>. //
///////////////////////////////////////////////////////////////////////////////////
#include "meshtasticmodencoderft.h"
#ifndef HAS_FT8
void MeshtasticModEncoderFT::encodeMsg(
const QString& myCall,
const QString& urCall,
const QString& myLocator,
const QString& myReport,
const QString& textMessage,
MeshtasticModSettings::MessageType messageType,
unsigned int nbSymbolBits,
std::vector<unsigned short>& symbols
)
{
qDebug("MeshtasticModEncoderFT::encodeMsg: not implemented");
}
#else
#include "ft8.h"
#include "packing.h"
void MeshtasticModEncoderFT::encodeMsg(
const QString& myCall,
const QString& urCall,
const QString& myLocator,
const QString& myReport,
const QString& textMessage,
MeshtasticModSettings::MessageType messageType,
unsigned int nbSymbolBits,
std::vector<unsigned short>& symbols
)
{
int a174[174]; // FT payload is 174 bits
if (messageType == MeshtasticModSettings::MessageNone) {
return; // do nothing
} else if (messageType == MeshtasticModSettings::MessageBeacon) {
encodeMsgBeaconOrCQ(myCall, myLocator, "DE", a174);
} else if (messageType == MeshtasticModSettings::MessageCQ) {
encodeMsgBeaconOrCQ(myCall, myLocator, "CQ", a174);
} else if (messageType == MeshtasticModSettings::MessageReply) {
encodeMsgReply(myCall, urCall, myLocator, a174);
} else if (messageType == MeshtasticModSettings::MessageReport) {
encodeMsgReport(myCall, urCall, myReport, 0, a174);
} else if (messageType == MeshtasticModSettings::MessageReplyReport) {
encodeMsgReport(myCall, urCall, myReport, 1, a174);
} else if (messageType == MeshtasticModSettings::MessageRRR) {
encodeMsgReport(myCall, urCall, "RRR", 1, a174);
} else if (messageType == MeshtasticModSettings::Message73) {
encodeMsgReport(myCall, urCall, "73", 1, a174);
} else {
encodeTextMsg(textMessage, a174);
}
int allBits = ((174 / nbSymbolBits) + (174 % nbSymbolBits == 0 ? 0 : 1))*nbSymbolBits; // ensures zero bits padding
int iBit;
int symbol = 0;
interleave174(a174);
for (int i = 0; i < allBits; i++)
{
iBit = nbSymbolBits - (i % nbSymbolBits) - 1; // MSB first
if (i < 174) {
symbol += a174[i] * (1<<iBit);
}
if ((i % nbSymbolBits) == (nbSymbolBits - 1))
{
symbol = symbol ^ (symbol >> 1); // Gray code
symbols.push_back(symbol);
symbol = 0;
}
}
}
void MeshtasticModEncoderFT::encodeTextMsg(const QString& text, int a174[])
{
int a77[77];
std::fill(a77, a77 + 77, 0);
QString sentMsg = text.rightJustified(13, ' ', true);
if (!FT8::Packing::packfree(a77, sentMsg.toUpper().toStdString()))
{
qDebug("MeshtasticModEncoderFT::encodeTextMsg: failed to encode free text message (%s)", qPrintable(sentMsg));
return;
}
FT8::FT8::encode(a174, a77);
}
void MeshtasticModEncoderFT::encodeMsgBeaconOrCQ(const QString& myCall, const QString& myLocator, const QString& shorthand, int a174[])
{
int c28_1, c28_2, g15;
if (!FT8::Packing::packcall_std(c28_1, shorthand.toUpper().toStdString())) //
{
qDebug("MeshtasticModEncoderFT::encodeMsgBeaconOrCQ: failed to encode call1 (%s)", qPrintable(shorthand));
return;
}
if (!FT8::Packing::packcall_std(c28_2, myCall.toUpper().toStdString()))
{
qDebug("MeshtasticModEncoderFT::encodeMsgBeaconOrCQ: failed to encode call2 (%s)", qPrintable(myCall));
return;
}
if (myLocator.size() < 4)
{
qDebug("MeshtasticModEncoderFT::encodeMsgBeaconOrCQ: locator invalid (%s)", qPrintable(myLocator));
return;
}
if (!FT8::Packing::packgrid(g15, myLocator.left(4).toUpper().toStdString()))
{
qDebug("MeshtasticModEncoderFT::encodeMsgBeaconOrCQ: failed to encode locator (%s)", qPrintable(myLocator));
return;
}
int a77[77];
std::fill(a77, a77 + 77, 0);
FT8::Packing::pack1(a77, c28_1, c28_2, g15, 0);
FT8::FT8::encode(a174, a77);
}
void MeshtasticModEncoderFT::encodeMsgReply(const QString& myCall, const QString& urCall, const QString& myLocator, int a174[])
{
int c28_1, c28_2, g15;
if (!FT8::Packing::packcall_std(c28_1, urCall.toUpper().toStdString())) //
{
qDebug("MeshtasticModEncoderFT::encodeMsgReply: failed to encode call1 (%s)", qPrintable(urCall));
return;
}
if (!FT8::Packing::packcall_std(c28_2, myCall.toUpper().toStdString()))
{
qDebug("MeshtasticModEncoderFT::encodeMsgReply: failed to encode call2 (%s)", qPrintable(myCall));
return;
}
if (myLocator.size() < 4)
{
qDebug("MeshtasticModEncoderFT::encodeMsgReply: locator invalid (%s)", qPrintable(myLocator));
return;
}
if (!FT8::Packing::packgrid(g15, myLocator.left(4).toUpper().toStdString()))
{
qDebug("MeshtasticModEncoderFT::encodeMsgReply: failed to encode locator (%s)", qPrintable(myLocator));
return;
}
int a77[77];
std::fill(a77, a77 + 77, 0);
FT8::Packing::pack1(a77, c28_1, c28_2, g15, 0);
FT8::FT8::encode(a174, a77);
}
void MeshtasticModEncoderFT::encodeMsgReport(const QString& myCall, const QString& urCall, const QString& myReport, int reply, int a174[])
{
int c28_1, c28_2, g15;
if (!FT8::Packing::packcall_std(c28_1, urCall.toUpper().toStdString())) //
{
qDebug("MeshtasticModEncoderFT::encodeMsgReport: failed to encode call1 (%s)", qPrintable(urCall));
return;
}
if (!FT8::Packing::packcall_std(c28_2, myCall.toUpper().toStdString()))
{
qDebug("MeshtasticModEncoderFT::encodeMsgReport: failed to encode call2 (%s)", qPrintable(myCall));
return;
}
if (!FT8::Packing::packgrid(g15, myReport.toUpper().toStdString()))
{
qDebug("MeshtasticModEncoderFT::encodeMsgReport: failed to encode report (%s)", qPrintable(myReport));
return;
}
int a77[77];
std::fill(a77, a77 + 77, 0);
FT8::Packing::pack1(a77, c28_1, c28_2, g15, reply);
FT8::FT8::encode(a174, a77);
}
void MeshtasticModEncoderFT::encodeMsgFinish(const QString& myCall, const QString& urCall, const QString& shorthand, int a174[])
{
int c28_1, c28_2, g15;
if (!FT8::Packing::packcall_std(c28_1, urCall.toUpper().toStdString())) //
{
qDebug("MeshtasticModEncoderFT::encodeMsgFinish: failed to encode call1 (%s)", qPrintable(urCall));
return;
}
if (!FT8::Packing::packcall_std(c28_2, myCall.toUpper().toStdString()))
{
qDebug("MeshtasticModEncoderFT::encodeMsgFinish: failed to encode call2 (%s)", qPrintable(myCall));
return;
}
if (!FT8::Packing::packgrid(g15, shorthand.toUpper().toStdString()))
{
qDebug("MeshtasticModEncoderFT::encodeMsgFinish: failed to encode shorthand (%s)", qPrintable(shorthand));
return;
}
int a77[77];
std::fill(a77, a77 + 77, 0);
FT8::Packing::pack1(a77, c28_1, c28_2, g15, 0);
FT8::FT8::encode(a174, a77);
}
void MeshtasticModEncoderFT::interleave174(int a174[])
{
// 174 = 2*3*29
int t174[174];
std::copy(a174, a174+174, t174);
for (int i = 0; i < 174; i++) {
a174[i] = t174[(i%6)*29 + (i%29)];
}
}
#endif // HAS_FT8

49
plugins/channeltx/modmeshtastic/meshtasticmodencoderft.h

@ -0,0 +1,49 @@ @@ -0,0 +1,49 @@
///////////////////////////////////////////////////////////////////////////////////
// Copyright (C) 2024 Edouard Griffiths, F4EXB <f4exb06@gmail.com> //
// //
// This program is free software; you can redistribute it and/or modify //
// it under the terms of the GNU General Public License as published by //
// the Free Software Foundation as version 3 of the License, or //
// (at your option) any later version. //
// //
// This program is distributed in the hope that it will be useful, //
// but WITHOUT ANY WARRANTY; without even the implied warranty of //
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //
// GNU General Public License V3 for more details. //
// //
// You should have received a copy of the GNU General Public License //
// along with this program. If not, see <http://www.gnu.org/licenses/>. //
///////////////////////////////////////////////////////////////////////////////////
#ifndef PLUGINS_CHANNELTX_MODMESHTASTIC_MESHTASTICMODENCODEFT_H_
#define PLUGINS_CHANNELTX_MODMESHTASTIC_MESHTASTICMODENCODEFT_H_
#include <vector>
#include <QString>
#include "meshtasticmodsettings.h"
class MeshtasticModEncoderFT
{
public:
static void encodeMsg(
const QString& myCall,
const QString& urCall,
const QString& myLocator,
const QString& myReport,
const QString& textMessage,
MeshtasticModSettings::MessageType messageType,
unsigned int nbSymbolBits,
std::vector<unsigned short>& symbols
);
private:
static void encodeTextMsg(const QString& text, int a174[]);
static void encodeMsgBeaconOrCQ(const QString& myCall, const QString& myLocator, const QString& shorthand, int a174[]);
static void encodeMsgReply(const QString& myCall, const QString& urCall, const QString& myLocator, int a174[]);
static void encodeMsgReport(const QString& myCall, const QString& urCall, const QString& myReport, int reply, int a174[]);
static void encodeMsgFinish(const QString& myCall, const QString& urCall, const QString& shorthand, int a174[]);
static void interleave174(int a174[]);
};
#endif // PLUGINS_CHANNELTX_MODMESHTASTIC_MESHTASTICMODENCODEFT_H_

148
plugins/channeltx/modmeshtastic/meshtasticmodencoderlora.cpp

@ -0,0 +1,148 @@ @@ -0,0 +1,148 @@
///////////////////////////////////////////////////////////////////////////////////
// Copyright (C) 2020 Edouard Griffiths, F4EXB <f4exb06@gmail.com> //
// //
// Inspired by: https://github.com/myriadrf/LoRa-SDR //
// //
// This program is free software; you can redistribute it and/or modify //
// it under the terms of the GNU General Public License as published by //
// the Free Software Foundation as version 3 of the License, or //
// (at your option) any later version. //
// //
// This program is distributed in the hope that it will be useful, //
// but WITHOUT ANY WARRANTY; without even the implied warranty of //
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //
// GNU General Public License V3 for more details. //
// //
// You should have received a copy of the GNU General Public License //
// along with this program. If not, see <http://www.gnu.org/licenses/>. //
///////////////////////////////////////////////////////////////////////////////////
#include "meshtasticmodencoderlora.h"
void MeshtasticModEncoderLoRa::addChecksum(QByteArray& bytes)
{
uint16_t crc = sx1272DataChecksum(reinterpret_cast<const uint8_t*>(bytes.data()), bytes.size());
bytes.append(crc & 0xff);
bytes.append((crc >> 8) & 0xff);
}
void MeshtasticModEncoderLoRa::encodeBytes(
const QByteArray& bytes,
std::vector<unsigned short>& symbols,
unsigned int nbSymbolBits,
bool hasHeader,
bool hasCRC,
unsigned int nbParityBits
)
{
if (nbSymbolBits < 5) {
return;
}
const unsigned int numCodewords = roundUp(bytes.size()*2 + (hasHeader ? headerCodewords : 0), nbSymbolBits); // uses payload + CRC for encoding size
unsigned int cOfs = 0;
unsigned int dOfs = 0;
std::vector<uint8_t> codewords(numCodewords);
if (hasHeader)
{
std::vector<uint8_t> hdr(3);
unsigned int payloadSize = bytes.size() - (hasCRC ? 2 : 0); // actual payload size is without CRC
hdr[0] = payloadSize % 256;
hdr[1] = (hasCRC ? 1 : 0) | (nbParityBits << 1);
hdr[2] = headerChecksum(hdr.data());
// Nibble decomposition and parity bit(s) addition. LSNibble first.
codewords[cOfs++] = encodeHamming84sx(hdr[0] >> 4);
codewords[cOfs++] = encodeHamming84sx(hdr[0] & 0xf); // length
codewords[cOfs++] = encodeHamming84sx(hdr[1] & 0xf); // crc / fec info
codewords[cOfs++] = encodeHamming84sx(hdr[2] >> 4); // checksum
codewords[cOfs++] = encodeHamming84sx(hdr[2] & 0xf);
}
unsigned int headerSize = cOfs;
// fill nbSymbolBits codewords with 8 bit codewords using payload data (ecode and whiten)
encodeFec(codewords, 4, cOfs, dOfs, reinterpret_cast<const uint8_t*>(bytes.data()), nbSymbolBits - headerSize);
Sx1272ComputeWhitening(codewords.data() + headerSize, nbSymbolBits - headerSize, 0, headerParityBits);
// encode and whiten the rest of the payload with 4 + nbParityBits bits codewords
if (numCodewords > nbSymbolBits)
{
unsigned int cOfs2 = cOfs;
encodeFec(codewords, nbParityBits, cOfs, dOfs, reinterpret_cast<const uint8_t*>(bytes.data()), numCodewords - nbSymbolBits);
Sx1272ComputeWhitening(codewords.data() + cOfs2, numCodewords - nbSymbolBits, nbSymbolBits - headerSize, nbParityBits);
}
// header is always coded with 8 bits and yields exactly 8 symbols (headerSymbols)
const unsigned int numSymbols = headerSymbols + (numCodewords / nbSymbolBits - 1) * (4 + nbParityBits);
// interleave the codewords into symbols
symbols.clear();
symbols.resize(numSymbols);
diagonalInterleaveSx(codewords.data(), nbSymbolBits, symbols.data(), nbSymbolBits, headerParityBits);
if (numCodewords > nbSymbolBits) {
diagonalInterleaveSx(codewords.data() + nbSymbolBits, numCodewords - nbSymbolBits, symbols.data() + headerSymbols, nbSymbolBits, nbParityBits);
}
// gray decode
for (auto &sym : symbols) {
sym = grayToBinary16(sym);
}
}
void MeshtasticModEncoderLoRa::encodeFec(
std::vector<uint8_t> &codewords,
unsigned int nbParityBits,
unsigned int& cOfs,
unsigned int& dOfs,
const uint8_t *bytes,
const unsigned int codewordCount
)
{
for (unsigned int i = 0; i < codewordCount; i++, dOfs++)
{
if (nbParityBits == 1)
{
if (dOfs % 2 == 1) {
codewords[cOfs++] = encodeParity54(bytes[dOfs/2] >> 4);
} else {
codewords[cOfs++] = encodeParity54(bytes[dOfs/2] & 0xf);
}
}
else if (nbParityBits == 2)
{
if (dOfs % 2 == 1) {
codewords[cOfs++] = encodeParity64(bytes[dOfs/2] >> 4);
} else {
codewords[cOfs++] = encodeParity64(bytes[dOfs/2] & 0xf);
}
}
else if (nbParityBits == 3)
{
if (dOfs % 2 == 1) {
codewords[cOfs++] = encodeHamming74sx(bytes[dOfs/2] >> 4);
} else {
codewords[cOfs++] = encodeHamming74sx(bytes[dOfs/2] & 0xf);
}
}
else if (nbParityBits == 4)
{
if (dOfs % 2 == 1) {
codewords[cOfs++] = encodeHamming84sx(bytes[dOfs/2] >> 4);
} else {
codewords[cOfs++] = encodeHamming84sx(bytes[dOfs/2] & 0xf);
}
}
else
{
if (dOfs % 2 == 1) {
codewords[cOfs++] = bytes[dOfs/2] >> 4;
} else {
codewords[cOfs++] = bytes[dOfs/2] & 0xf;
}
}
}
}

274
plugins/channeltx/modmeshtastic/meshtasticmodencoderlora.h

@ -0,0 +1,274 @@ @@ -0,0 +1,274 @@
///////////////////////////////////////////////////////////////////////////////////
// Copyright (C) 2020 Edouard Griffiths, F4EXB <f4exb06@gmail.com> //
// //
// Inspired by: https://github.com/myriadrf/LoRa-SDR //
// //
// This program is free software; you can redistribute it and/or modify //
// it under the terms of the GNU General Public License as published by //
// the Free Software Foundation as version 3 of the License, or //
// (at your option) any later version. //
// //
// This program is distributed in the hope that it will be useful, //
// but WITHOUT ANY WARRANTY; without even the implied warranty of //
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //
// GNU General Public License V3 for more details. //
// //
// You should have received a copy of the GNU General Public License //
// along with this program. If not, see <http://www.gnu.org/licenses/>. //
///////////////////////////////////////////////////////////////////////////////////
#ifndef PLUGINS_CHANNELTX_MODMESHTASTIC_MESHTASTICMODENCODERLORA_H_
#define PLUGINS_CHANNELTX_MODMESHTASTIC_MESHTASTICMODENCODERLORA_H_
#include <vector>
#include <QByteArray>
class MeshtasticModEncoderLoRa
{
public:
static void addChecksum(QByteArray& bytes);
static void encodeBytes(
const QByteArray& bytes,
std::vector<unsigned short>& symbols,
unsigned int nbSymbolBits,
bool hasHeader,
bool hasCRC,
unsigned int nbParityBits
);
private:
static void encodeFec(
std::vector<uint8_t> &codewords,
unsigned int nbParityBits,
unsigned int& cOfs,
unsigned int& dOfs,
const uint8_t *bytes,
const unsigned int codewordCount
);
static constexpr unsigned int headerParityBits = 4;
static constexpr unsigned int headerSymbols = 8;
static constexpr unsigned int headerCodewords = 5;
/***********************************************************************
* Round functions
**********************************************************************/
static inline unsigned roundUp(unsigned num, unsigned factor)
{
return ((num + factor - 1) / factor) * factor;
}
/***********************************************************************
* Encode a 4 bit word into a 8 bits with parity
* Non standard version used in sx1272.
* https://en.wikipedia.org/wiki/Hamming_code
**********************************************************************/
static inline unsigned char encodeHamming84sx(const unsigned char x)
{
auto d0 = (x >> 0) & 0x1;
auto d1 = (x >> 1) & 0x1;
auto d2 = (x >> 2) & 0x1;
auto d3 = (x >> 3) & 0x1;
unsigned char b = x & 0xf;
b |= (d0 ^ d1 ^ d2) << 4;
b |= (d1 ^ d2 ^ d3) << 5;
b |= (d0 ^ d1 ^ d3) << 6;
b |= (d0 ^ d2 ^ d3) << 7;
return b;
}
/***********************************************************************
* Encode a 4 bit word into a 7 bits with parity.
* Non standard version used in sx1272.
**********************************************************************/
static inline unsigned char encodeHamming74sx(const unsigned char x)
{
auto d0 = (x >> 0) & 0x1;
auto d1 = (x >> 1) & 0x1;
auto d2 = (x >> 2) & 0x1;
auto d3 = (x >> 3) & 0x1;
unsigned char b = x & 0xf;
b |= (d0 ^ d1 ^ d2) << 4;
b |= (d1 ^ d2 ^ d3) << 5;
b |= (d0 ^ d1 ^ d3) << 6;
return b;
}
/***********************************************************************
* Encode a 4 bit word into a 6 bits with parity.
**********************************************************************/
static inline unsigned char encodeParity64(const unsigned char b)
{
auto x = b ^ (b >> 1) ^ (b >> 2);
auto y = x ^ b ^ (b >> 3);
return ((x & 1) << 4) | ((y & 1) << 5) | (b & 0xf);
}
/***********************************************************************
* Encode a 4 bit word into a 5 bits with parity.
**********************************************************************/
static inline unsigned char encodeParity54(const unsigned char b)
{
auto x = b ^ (b >> 2);
x = x ^ (x >> 1);
return (b & 0xf) | ((x << 4) & 0x10);
}
/***********************************************************************
* CRC reverse engineered from Sx1272 data stream.
* Modified CCITT crc with masking of the output with an 8bit lfsr
**********************************************************************/
static inline uint16_t crc16sx(uint16_t crc, const uint16_t poly)
{
for (int i = 0; i < 8; i++)
{
if (crc & 0x8000) {
crc = (crc << 1) ^ poly;
} else {
crc <<= 1;
}
}
return crc;
}
static inline uint8_t xsum8(uint8_t t)
{
t ^= t >> 4;
t ^= t >> 2;
t ^= t >> 1;
return (t & 1);
}
static inline uint16_t sx1272DataChecksum(const uint8_t *data, int length)
{
uint16_t res = 0;
uint8_t v = 0xff;
uint16_t crc = 0;
for (int i = 0; i < length; i++)
{
crc = crc16sx(res, 0x1021);
v = xsum8(v & 0xB8) | (v << 1);
res = crc ^ data[i];
}
res ^= v;
v = xsum8(v & 0xB8) | (v << 1);
res ^= v << 8;
return res;
}
/***********************************************************************
* Specific checksum for header
**********************************************************************/
static inline uint8_t headerChecksum(const uint8_t *h)
{
auto a0 = (h[0] >> 4) & 0x1;
auto a1 = (h[0] >> 5) & 0x1;
auto a2 = (h[0] >> 6) & 0x1;
auto a3 = (h[0] >> 7) & 0x1;
auto b0 = (h[0] >> 0) & 0x1;
auto b1 = (h[0] >> 1) & 0x1;
auto b2 = (h[0] >> 2) & 0x1;
auto b3 = (h[0] >> 3) & 0x1;
auto c0 = (h[1] >> 0) & 0x1;
auto c1 = (h[1] >> 1) & 0x1;
auto c2 = (h[1] >> 2) & 0x1;
auto c3 = (h[1] >> 3) & 0x1;
uint8_t res;
res = (a0 ^ a1 ^ a2 ^ a3) << 4;
res |= (a3 ^ b1 ^ b2 ^ b3 ^ c0) << 3;
res |= (a2 ^ b0 ^ b3 ^ c1 ^ c3) << 2;
res |= (a1 ^ b0 ^ b2 ^ c0 ^ c1 ^ c2) << 1;
res |= a0 ^ b1 ^ c0 ^ c1 ^ c2 ^ c3;
return res;
}
/***********************************************************************
* Whitening generator reverse engineered from Sx1272 data stream.
* Each bit of a codeword is combined with the output from a different position in the whitening sequence.
**********************************************************************/
static inline void Sx1272ComputeWhitening(uint8_t *buffer, uint16_t bufferSize, const int bitOfs, const int nbParityBits)
{
static const int ofs0[8] = {6,4,2,0,-112,-114,-302,-34 }; // offset into sequence for each bit
static const int ofs1[5] = {6,4,2,0,-360 }; // different offsets used for single parity mode (1 == nbParityBits)
static const int whiten_len = 510; // length of whitening sequence
static const uint64_t whiten_seq[8] = { // whitening sequence
0x0102291EA751AAFFL,0xD24B050A8D643A17L,0x5B279B671120B8F4L,0x032B37B9F6FB55A2L,
0x994E0F87E95E2D16L,0x7CBCFC7631984C26L,0x281C8E4F0DAEF7F9L,0x1741886EB7733B15L
};
const int *ofs = (1 == nbParityBits) ? ofs1 : ofs0;
int i, j;
for (j = 0; j < bufferSize; j++)
{
uint8_t x = 0;
for (i = 0; i < 4 + nbParityBits; i++)
{
int t = (ofs[i] + j + bitOfs + whiten_len) % whiten_len;
if (whiten_seq[t >> 6] & ((uint64_t)1 << (t & 0x3F))) {
x |= 1 << i;
}
}
buffer[j] ^= x;
}
}
/***********************************************************************
* Diagonal interleaver + deinterleaver
**********************************************************************/
static inline void diagonalInterleaveSx(
const uint8_t *codewords,
const size_t numCodewords,
uint16_t *symbols,
const size_t nbSymbolBits,
const size_t nbParityBits
)
{
for (size_t x = 0; x < numCodewords / nbSymbolBits; x++)
{
const size_t cwOff = x*nbSymbolBits;
const size_t symOff = x*(4 + nbParityBits);
for (size_t k = 0; k < 4 + nbParityBits; k++)
{
for (size_t m = 0; m < nbSymbolBits; m++)
{
const size_t i = (m + k + nbSymbolBits) % nbSymbolBits;
const auto bit = (codewords[cwOff + i] >> k) & 0x1;
symbols[symOff + k] |= (bit << m);
}
}
}
}
/***********************************************************************
* https://en.wikipedia.org/wiki/Gray_code
**********************************************************************/
/*
* A more efficient version, for Gray codes of 16 or fewer bits.
*/
static inline unsigned short grayToBinary16(unsigned short num)
{
num = num ^ (num >> 8);
num = num ^ (num >> 4);
num = num ^ (num >> 2);
num = num ^ (num >> 1);
return num;
}
};
#endif // PLUGINS_CHANNELTX_MODMESHTASTIC_MESHTASTICMODENCODERLORA_H_

133
plugins/channeltx/modmeshtastic/meshtasticmodencodertty.cpp

@ -0,0 +1,133 @@ @@ -0,0 +1,133 @@
///////////////////////////////////////////////////////////////////////////////////
// Copyright (C) 2020 Edouard Griffiths, F4EXB <f4exb06@gmail.com> //
// //
// This program is free software; you can redistribute it and/or modify //
// it under the terms of the GNU General Public License as published by //
// the Free Software Foundation as version 3 of the License, or //
// (at your option) any later version. //
// //
// This program is distributed in the hope that it will be useful, //
// but WITHOUT ANY WARRANTY; without even the implied warranty of //
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //
// GNU General Public License V3 for more details. //
// //
// You should have received a copy of the GNU General Public License //
// along with this program. If not, see <http://www.gnu.org/licenses/>. //
///////////////////////////////////////////////////////////////////////////////////
#include "meshtasticmodencodertty.h"
const signed char MeshtasticModEncoderTTY::asciiToTTYLetters[128] = {
// '\x00' '\x01' '\x02' '\x03' '\x04' '\x05' '\x06' '\x07'
0x00, -1 , -1 , -1 , -1 , -1 , -1 , -1 ,
// '\x08' '\t' '\n' '\x0b' '\x0c' '\r' '\x0e' '\x0f'
-1 , -1 , 0x02, -1 , -1 , 0x08, -1 , -1 ,
// '\x10' '\x11' '\x12' '\x13' '\x14' '\x15' '\x16' '\x17'
-1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 ,
// '\x18' '\x19' '\x1a' '\x1b' '\x1c' '\x1d' '\x1e' '\x1f'
-1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 ,
// ' ' '!' '"' '#' '$' '%' '&' "'"
0x04, -1 , -1 , -1 , -1 , -1 , -1 , -1 ,
// '(' ')' '*' '+' ',' '-' '.' '/'
-1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 ,
// '0' '1' '2' '3' '4' '5' '6' '7'
-1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 ,
// '8' '9' ':' ';' '<' '=' '>' '?'
-1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 ,
// '@' 'A' 'B' 'C' 'D' 'E' 'F' 'G'
-1 , 0x03, 0x19, 0x0e, 0x09, 0x01, 0x0d, 0x1a,
// 'H' 'I' 'J' 'K' 'L' 'M' 'N' 'O'
0x14, 0x06, 0x0b, 0x0f, 0x12, 0x1c, 0x0c, 0x18,
// 'P' 'Q' 'R' 'S' 'T' 'U' 'V' 'W'
0x16, 0x17, 0x0a, 0x05, 0x10, 0x07, 0x1e, 0x13,
// 'X' 'Y' 'Z' '[' '\\' ']' '^' '_'
0x1d, 0x15, 0x11, -1 , -1 , -1 , -1 , -1 ,
// '`' 'a' 'b' 'c' 'd' 'e' 'f' 'g'
-1 , 0x03, 0x19, 0x0e, 0x09, 0x01, 0x0d, 0x1a,
// 'h' 'i' 'j' 'k' 'l' 'm' 'n' 'o'
0x14, 0x06, 0x0b, 0x0f, 0x12, 0x1c, 0x0c, 0x18,
// 'p' 'q' 'r' 's' 't' 'u' 'v' 'w'
0x16, 0x17, 0x0a, 0x05, 0x10, 0x07, 0x1e, 0x13,
// 'x' 'y' 'z' '{' '|' '}' '~' '\x7f'
0x1d, 0x15, 0x11, -1 , -1 , -1 , -1 , -1
};
const signed char MeshtasticModEncoderTTY::asciiToTTYFigures[128] = {
// '\x00' '\x01' '\x02' '\x03' '\x04' '\x05' '\x06' '\x07'
0x00, -1 , -1 , -1 , -1 , -1 , -1 , 0x05,
// '\x08' '\t' '\n' '\x0b' '\x0c' '\r' '\x0e' '\x0f'
-1 , -1 , 0x02, -1 , -1 , 0x08, -1 , -1 ,
// '\x10' '\x11' '\x12' '\x13' '\x14' '\x15' '\x16' '\x17'
-1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 ,
// '\x18' '\x19' '\x1a' '\x1b' '\x1c' '\x1d' '\x1e' '\x1f'
-1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 ,
// ' ' '!' '"' '#' '$' '%' '&' "'"
0x04, 0x0d, 0x11, 0x14, 0x09, -1 , 0x1a, -1 ,
// '(' ')' '*' '+' ',' '-' '.' '/'
0x0f, 0x12, -1 , -1 , 0x0c, 0x03, 0x1c, 0x1d,
// '0' '1' '2' '3' '4' '5' '6' '7'
0x16, 0x17, 0x13, 0x01, 0x0a, 0x10, 0x15, 0x07,
// '8' '9' ':' ';' '<' '=' '>' '?'
0x06, 0x18, 0x0e, 0x1e, -1 , -1 , -1 , 0x19,
// '@' 'A' 'B' 'C' 'D' 'E' 'F' 'G'
-1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 ,
// 'H' 'I' 'J' 'K' 'L' 'M' 'N' 'O'
-1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 ,
// 'P' 'Q' 'R' 'S' 'T' 'U' 'V' 'W'
-1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 ,
// 'X' 'Y' 'Z' '[' '\\' ']' '^' '_'
-1 , -1 , -1 , -1 , 0x0b, -1 , -1 , -1 ,
// '`' 'a' 'b' 'c' 'd' 'e' 'f' 'g'
-1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 ,
// 'h' 'i' 'j' 'k' 'l' 'm' 'n' 'o'
-1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 ,
// 'p' 'q' 'r' 's' 't' 'u' 'v' 'w'
-1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 ,
// 'x' 'y' 'z' '{' '|' '}' '~' '\x7f'
-1 , -1 , -1 , -1 , -1 , -1 , -1 , -1
};
void MeshtasticModEncoderTTY::encodeString(const QString& str, std::vector<unsigned short>& symbols)
{
TTYState ttyState = TTYLetters;
QByteArray asciiStr = str.toUtf8();
QByteArray::const_iterator it = asciiStr.begin();
for (; it != asciiStr.end(); ++it)
{
char asciiChar = *it & 0x7F;
int ttyLetter = asciiToTTYLetters[(int) asciiChar];
int ttyFigure = asciiToTTYFigures[(int) asciiChar];
if (ttyLetter < 0)
{
if (ttyFigure >= 0)
{
if (ttyState != TTYFigures)
{
symbols.push_back(ttyFigures);
ttyState = TTYFigures;
}
symbols.push_back(ttyFigure);
} // else skip
}
else
{
if (ttyFigure >= 0)
{
symbols.push_back(ttyFigure); // same TTY character no state change
}
else
{
if (ttyState != TTYLetters)
{
symbols.push_back(ttyLetters);
ttyState = TTYLetters;
}
symbols.push_back(ttyLetter);
}
}
}
}

44
plugins/channeltx/modmeshtastic/meshtasticmodencodertty.h

@ -0,0 +1,44 @@ @@ -0,0 +1,44 @@
///////////////////////////////////////////////////////////////////////////////////
// Copyright (C) 2012 maintech GmbH, Otto-Hahn-Str. 15, 97204 Hoechberg, Germany //
// written by Christian Daniel //
// Copyright (C) 2015-2020 Edouard Griffiths, F4EXB <f4exb06@gmail.com> //
// //
// This program is free software; you can redistribute it and/or modify //
// it under the terms of the GNU General Public License as published by //
// the Free Software Foundation as version 3 of the License, or //
// (at your option) any later version. //
// //
// This program is distributed in the hope that it will be useful, //
// but WITHOUT ANY WARRANTY; without even the implied warranty of //
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //
// GNU General Public License V3 for more details. //
// //
// You should have received a copy of the GNU General Public License //
// along with this program. If not, see <http://www.gnu.org/licenses/>. //
///////////////////////////////////////////////////////////////////////////////////
#ifndef PLUGINS_CHANNELTX_MODMESHTASTIC_MESHTASTICMODENCODERTTY_H_
#define PLUGINS_CHANNELTX_MODMESHTASTIC_MESHTASTICMODENCODERTTY_H_
#include <vector>
#include <QString>
class MeshtasticModEncoderTTY
{
public:
static void encodeString(const QString& str, std::vector<unsigned short>& symbols);
private:
enum TTYState
{
TTYLetters,
TTYFigures
};
static const signed char asciiToTTYLetters[128];
static const signed char asciiToTTYFigures[128];
static const char ttyLetters = 0x1f;
static const char ttyFigures = 0x1b;
};
#endif // PLUGINS_CHANNELTX_MODMESHTASTIC_MESHTASTICMODENCODERTTY_H_

880
plugins/channeltx/modmeshtastic/meshtasticmodgui.cpp

@ -0,0 +1,880 @@ @@ -0,0 +1,880 @@
///////////////////////////////////////////////////////////////////////////////////
// Copyright (C) 2020-2022 Edouard Griffiths, F4EXB <f4exb06@gmail.com> //
// Copyright (C) 2021-2023 Jon Beniston, M7RCE <jon@beniston.com> //
// //
// This program is free software; you can redistribute it and/or modify //
// it under the terms of the GNU General Public License as published by //
// the Free Software Foundation as version 3 of the License, or //
// (at your option) any later version. //
// //
// This program is distributed in the hope that it will be useful, //
// but WITHOUT ANY WARRANTY; without even the implied warranty of //
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //
// GNU General Public License V3 for more details. //
// //
// You should have received a copy of the GNU General Public License //
// along with this program. If not, see <http://www.gnu.org/licenses/>. //
///////////////////////////////////////////////////////////////////////////////////
#include <QDockWidget>
#include <QMainWindow>
#include <QFileDialog>
#include <QTime>
#include <QDebug>
#include <cmath>
#include "device/deviceuiset.h"
#include "plugin/pluginapi.h"
#include "util/db.h"
#include "dsp/dspengine.h"
#include "dsp/dspcommands.h"
#include "gui/basicchannelsettingsdialog.h"
#include "gui/dialpopup.h"
#include "gui/dialogpositioner.h"
#include "maincore.h"
#include "ui_meshtasticmodgui.h"
#include "meshtasticmodgui.h"
#include "meshtasticpacket.h"
MeshtasticModGUI* MeshtasticModGUI::create(PluginAPI* pluginAPI, DeviceUISet *deviceUISet, BasebandSampleSource *channelTx)
{
MeshtasticModGUI* gui = new MeshtasticModGUI(pluginAPI, deviceUISet, channelTx);
return gui;
}
void MeshtasticModGUI::destroy()
{
delete this;
}
void MeshtasticModGUI::resetToDefaults()
{
m_settings.resetToDefaults();
displaySettings();
applySettings(true);
}
QByteArray MeshtasticModGUI::serialize() const
{
return m_settings.serialize();
}
bool MeshtasticModGUI::deserialize(const QByteArray& data)
{
if (m_settings.deserialize(data))
{
displaySettings();
applySettings(true);
return true;
}
else
{
resetToDefaults();
return false;
}
}
bool MeshtasticModGUI::handleMessage(const Message& message)
{
if (MeshtasticMod::MsgConfigureMeshtasticMod::match(message))
{
const MeshtasticMod::MsgConfigureMeshtasticMod& cfg = (MeshtasticMod::MsgConfigureMeshtasticMod&) message;
m_settings = cfg.getSettings();
blockApplySettings(true);
m_channelMarker.updateSettings(static_cast<const ChannelMarker*>(m_settings.m_channelMarker));
displaySettings();
blockApplySettings(false);
return true;
}
else if (MeshtasticMod::MsgReportPayloadTime::match(message))
{
const MeshtasticMod::MsgReportPayloadTime& rpt = (MeshtasticMod::MsgReportPayloadTime&) message;
float fourthsMs = ((1<<m_settings.m_spreadFactor) * 250.0) / MeshtasticModSettings::bandwidths[m_settings.m_bandwidthIndex];
int fourthsChirps = 4*m_settings.m_preambleChirps;
fourthsChirps += m_settings.hasSyncWord() ? 8 : 0;
fourthsChirps += m_settings.getNbSFDFourths();
float controlMs = fourthsChirps * fourthsMs; // preamble + sync word + SFD
ui->timeMessageLengthText->setText(tr("%1").arg(rpt.getNbSymbols()));
ui->timePayloadText->setText(tr("%1 ms").arg(QString::number(rpt.getPayloadTimeMs(), 'f', 0)));
ui->timeTotalText->setText(tr("%1 ms").arg(QString::number(rpt.getPayloadTimeMs() + controlMs, 'f', 0)));
ui->timeSymbolText->setText(tr("%1 ms").arg(QString::number(4.0*fourthsMs, 'f', 1)));
return true;
}
else if (DSPSignalNotification::match(message))
{
DSPSignalNotification& notif = (DSPSignalNotification&) message;
m_deviceCenterFrequency = notif.getCenterFrequency();
int basebandSampleRate = notif.getSampleRate();
qDebug() << "MeshtasticModGUI::handleMessage: DSPSignalNotification: m_basebandSampleRate: " << basebandSampleRate;
if (basebandSampleRate != m_basebandSampleRate)
{
m_basebandSampleRate = basebandSampleRate;
setBandwidths();
}
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
{
return false;
}
}
void MeshtasticModGUI::channelMarkerChangedByCursor()
{
ui->deltaFrequency->setValue(m_channelMarker.getCenterFrequency());
m_settings.m_inputFrequencyOffset = m_channelMarker.getCenterFrequency();
applySettings();
}
void MeshtasticModGUI::handleSourceMessages()
{
Message* message;
while ((message = getInputMessageQueue()->pop()) != 0)
{
if (handleMessage(*message))
{
delete message;
}
}
}
QString MeshtasticModGUI::getActivePayloadText() const
{
switch (m_settings.m_messageType)
{
case MeshtasticModSettings::MessageBeacon:
return m_settings.m_beaconMessage;
case MeshtasticModSettings::MessageCQ:
return m_settings.m_cqMessage;
case MeshtasticModSettings::MessageReply:
return m_settings.m_replyMessage;
case MeshtasticModSettings::MessageReport:
return m_settings.m_reportMessage;
case MeshtasticModSettings::MessageReplyReport:
return m_settings.m_replyReportMessage;
case MeshtasticModSettings::MessageRRR:
return m_settings.m_rrrMessage;
case MeshtasticModSettings::Message73:
return m_settings.m_73Message;
case MeshtasticModSettings::MessageQSOText:
return m_settings.m_qsoTextMessage;
case MeshtasticModSettings::MessageText:
return m_settings.m_textMessage;
case MeshtasticModSettings::MessageBytes:
return QString::fromUtf8(m_settings.m_bytesMessage);
default:
return QString();
}
}
int MeshtasticModGUI::findBandwidthIndex(int bandwidthHz) const
{
int bestIndex = -1;
int bestDelta = 1 << 30;
for (int i = 0; i < MeshtasticModSettings::nbBandwidths; ++i)
{
const int delta = std::abs(MeshtasticModSettings::bandwidths[i] - bandwidthHz);
if (delta < bestDelta)
{
bestDelta = delta;
bestIndex = i;
}
}
return bestIndex;
}
void MeshtasticModGUI::applyMeshtasticRadioSettingsIfPresent(const QString& payloadText)
{
if (m_settings.m_codingScheme != MeshtasticModSettings::CodingLoRa) {
return;
}
if (!Meshtastic::Packet::isCommand(payloadText)) {
return;
}
Meshtastic::TxRadioSettings meshRadio;
QString error;
if (!Meshtastic::Packet::deriveTxRadioSettings(payloadText, meshRadio, error))
{
qWarning() << "MeshtasticModGUI::applyMeshtasticRadioSettingsIfPresent:" << error;
return;
}
bool changed = false;
const int bwIndex = findBandwidthIndex(meshRadio.bandwidthHz);
if (bwIndex >= 0 && bwIndex != m_settings.m_bandwidthIndex) {
m_settings.m_bandwidthIndex = bwIndex;
changed = true;
}
if (meshRadio.spreadFactor > 0 && meshRadio.spreadFactor != m_settings.m_spreadFactor) {
m_settings.m_spreadFactor = meshRadio.spreadFactor;
changed = true;
}
if (meshRadio.parityBits > 0 && meshRadio.parityBits != m_settings.m_nbParityBits) {
m_settings.m_nbParityBits = meshRadio.parityBits;
changed = true;
}
if (meshRadio.deBits != m_settings.m_deBits) {
m_settings.m_deBits = meshRadio.deBits;
changed = true;
}
if (meshRadio.syncWord != m_settings.m_syncWord) {
m_settings.m_syncWord = meshRadio.syncWord;
changed = true;
}
if (meshRadio.hasCenterFrequency)
{
if (m_deviceCenterFrequency != 0)
{
const qint64 wantedOffset = meshRadio.centerFrequencyHz - m_deviceCenterFrequency;
if (wantedOffset != m_settings.m_inputFrequencyOffset)
{
m_settings.m_inputFrequencyOffset = static_cast<int>(wantedOffset);
changed = true;
}
}
else
{
qWarning() << "MeshtasticModGUI::applyMeshtasticRadioSettingsIfPresent: device center frequency unknown, cannot auto-center";
}
}
if (!changed) {
return;
}
qInfo() << "MeshtasticModGUI::applyMeshtasticRadioSettingsIfPresent:" << meshRadio.summary;
const int thisBW = MeshtasticModSettings::bandwidths[m_settings.m_bandwidthIndex];
m_channelMarker.blockSignals(true);
m_channelMarker.setCenterFrequency(m_settings.m_inputFrequencyOffset);
m_channelMarker.setBandwidth(thisBW);
m_channelMarker.blockSignals(false);
blockApplySettings(true);
ui->deltaFrequency->setValue(m_settings.m_inputFrequencyOffset);
ui->bw->setValue(m_settings.m_bandwidthIndex);
ui->bwText->setText(QString("%1 Hz").arg(thisBW));
ui->spread->setValue(m_settings.m_spreadFactor);
ui->spreadText->setText(tr("%1").arg(m_settings.m_spreadFactor));
ui->deBits->setValue(m_settings.m_deBits);
ui->deBitsText->setText(tr("%1").arg(m_settings.m_deBits));
ui->fecParity->setValue(m_settings.m_nbParityBits);
ui->fecParityText->setText(tr("%1").arg(m_settings.m_nbParityBits));
ui->syncWord->setText(tr("%1").arg(m_settings.m_syncWord, 2, 16));
blockApplySettings(false);
updateAbsoluteCenterFrequency();
}
void MeshtasticModGUI::on_deltaFrequency_changed(qint64 value)
{
m_channelMarker.setCenterFrequency(value);
m_settings.m_inputFrequencyOffset = m_channelMarker.getCenterFrequency();
updateAbsoluteCenterFrequency();
applySettings();
}
void MeshtasticModGUI::on_bw_valueChanged(int value)
{
if (value < 0) {
m_settings.m_bandwidthIndex = 0;
} else if (value < MeshtasticModSettings::nbBandwidths) {
m_settings.m_bandwidthIndex = value;
} else {
m_settings.m_bandwidthIndex = MeshtasticModSettings::nbBandwidths - 1;
}
int thisBW = MeshtasticModSettings::bandwidths[value];
ui->bwText->setText(QString("%1 Hz").arg(thisBW));
m_channelMarker.setBandwidth(thisBW);
applySettings();
}
void MeshtasticModGUI::on_channelMute_toggled(bool checked)
{
m_settings.m_channelMute = checked;
applySettings();
}
void MeshtasticModGUI::on_spread_valueChanged(int value)
{
m_settings.m_spreadFactor = value;
ui->spreadText->setText(tr("%1").arg(value));
applySettings();
}
void MeshtasticModGUI::on_deBits_valueChanged(int value)
{
m_settings.m_deBits = value;
ui->deBitsText->setText(tr("%1").arg(m_settings.m_deBits));
applySettings();
}
void MeshtasticModGUI::on_preambleChirps_valueChanged(int value)
{
m_settings.m_preambleChirps = value;
ui->preambleChirpsText->setText(tr("%1").arg(m_settings.m_preambleChirps));
applySettings();
}
void MeshtasticModGUI::on_idleTime_valueChanged(int value)
{
m_settings.m_quietMillis = value * 100;
ui->idleTimeText->setText(tr("%1").arg(m_settings.m_quietMillis / 1000.0, 0, 'f', 1));
applySettings();
}
void MeshtasticModGUI::on_syncWord_editingFinished()
{
bool ok;
unsigned int syncWord = ui->syncWord->text().toUInt(&ok, 16);
if (ok)
{
m_settings.m_syncWord = syncWord > 255 ? 0 : syncWord;
applySettings();
}
}
void MeshtasticModGUI::on_scheme_currentIndexChanged(int index)
{
m_settings.m_codingScheme = (MeshtasticModSettings::CodingScheme) index;
ui->fecParity->setEnabled(m_settings.m_codingScheme == MeshtasticModSettings::CodingLoRa);
ui->crc->setEnabled(m_settings.m_codingScheme == MeshtasticModSettings::CodingLoRa);
ui->header->setEnabled(m_settings.m_codingScheme == MeshtasticModSettings::CodingLoRa);
applySettings();
}
void MeshtasticModGUI::on_fecParity_valueChanged(int value)
{
m_settings.m_nbParityBits = value;
ui->fecParityText->setText(tr("%1").arg(m_settings.m_nbParityBits));
applySettings();
}
void MeshtasticModGUI::on_crc_stateChanged(int state)
{
m_settings.m_hasCRC = (state == Qt::Checked);
applySettings();
}
void MeshtasticModGUI::on_header_stateChanged(int state)
{
m_settings.m_hasHeader = (state == Qt::Checked);
applySettings();
}
void MeshtasticModGUI::on_myCall_editingFinished()
{
m_settings.m_myCall = ui->myCall->text();
applySettings();
}
void MeshtasticModGUI::on_urCall_editingFinished()
{
m_settings.m_urCall = ui->urCall->text();
applySettings();
}
void MeshtasticModGUI::on_myLocator_editingFinished()
{
m_settings.m_myLoc = ui->myLocator->text();
applySettings();
}
void MeshtasticModGUI::on_report_editingFinished()
{
m_settings.m_myRpt = ui->report->text();
applySettings();
}
void MeshtasticModGUI::on_msgType_currentIndexChanged(int index)
{
m_settings.m_messageType = (MeshtasticModSettings::MessageType) index;
displayCurrentPayloadMessage();
applyMeshtasticRadioSettingsIfPresent(getActivePayloadText());
applySettings();
}
void MeshtasticModGUI::on_resetMessages_clicked(bool checked)
{
(void) checked;
m_settings.setDefaultTemplates();
displayCurrentPayloadMessage();
applySettings();
}
void MeshtasticModGUI::on_playMessage_clicked(bool checked)
{
(void) checked;
applyMeshtasticRadioSettingsIfPresent(getActivePayloadText());
// Switch to message None then back to current message type to trigger sending process
MeshtasticModSettings::MessageType msgType = m_settings.m_messageType;
m_settings.m_messageType = MeshtasticModSettings::MessageNone;
applySettings();
m_settings.m_messageType = msgType;
applySettings();
}
void MeshtasticModGUI::on_repeatMessage_valueChanged(int value)
{
m_settings.m_messageRepeat = value;
ui->repeatText->setText(tr("%1").arg(m_settings.m_messageRepeat));
applySettings();
}
void MeshtasticModGUI::on_generateMessages_clicked(bool checked)
{
(void) checked;
m_settings.generateMessages();
displayCurrentPayloadMessage();
applySettings();
}
void MeshtasticModGUI::on_messageText_editingFinished()
{
if (m_settings.m_messageType == MeshtasticModSettings::MessageBeacon) {
m_settings.m_beaconMessage = ui->messageText->toPlainText();
} else if (m_settings.m_messageType == MeshtasticModSettings::MessageCQ) {
m_settings.m_cqMessage = ui->messageText->toPlainText();
} else if (m_settings.m_messageType == MeshtasticModSettings::MessageReply) {
m_settings.m_replyMessage = ui->messageText->toPlainText();
} else if (m_settings.m_messageType == MeshtasticModSettings::MessageReport) {
m_settings.m_reportMessage = ui->messageText->toPlainText();
} else if (m_settings.m_messageType == MeshtasticModSettings::MessageReplyReport) {
m_settings.m_replyReportMessage = ui->messageText->toPlainText();
} else if (m_settings.m_messageType == MeshtasticModSettings::MessageRRR) {
m_settings.m_rrrMessage = ui->messageText->toPlainText();
} else if (m_settings.m_messageType == MeshtasticModSettings::Message73) {
m_settings.m_73Message = ui->messageText->toPlainText();
} else if (m_settings.m_messageType == MeshtasticModSettings::MessageQSOText) {
m_settings.m_qsoTextMessage = ui->messageText->toPlainText();
} else if (m_settings.m_messageType == MeshtasticModSettings::MessageText) {
m_settings.m_textMessage = ui->messageText->toPlainText();
}
applyMeshtasticRadioSettingsIfPresent(getActivePayloadText());
applySettings();
}
void MeshtasticModGUI::on_hexText_editingFinished()
{
m_settings.m_bytesMessage = QByteArray::fromHex(ui->hexText->text().toLatin1());
applyMeshtasticRadioSettingsIfPresent(getActivePayloadText());
applySettings();
}
void MeshtasticModGUI::on_udpEnabled_clicked(bool checked)
{
m_settings.m_udpEnabled = checked;
applySettings();
}
void MeshtasticModGUI::on_udpAddress_editingFinished()
{
m_settings.m_udpAddress = ui->udpAddress->text();
applySettings();
}
void MeshtasticModGUI::on_udpPort_editingFinished()
{
m_settings.m_udpPort = ui->udpPort->text().toInt();
applySettings();
}
void MeshtasticModGUI::on_invertRamps_stateChanged(int state)
{
m_settings.m_invertRamps = (state == Qt::Checked);
applySettings();
}
void MeshtasticModGUI::onWidgetRolled(QWidget* widget, bool rollDown)
{
(void) widget;
(void) rollDown;
getRollupContents()->saveState(m_rollupState);
applySettings();
}
void MeshtasticModGUI::onMenuDialogCalled(const QPoint &p)
{
if (m_contextMenuType == ContextMenuType::ContextMenuChannelSettings)
{
BasicChannelSettingsDialog dialog(&m_channelMarker, this);
dialog.setUseReverseAPI(m_settings.m_useReverseAPI);
dialog.setReverseAPIAddress(m_settings.m_reverseAPIAddress);
dialog.setReverseAPIPort(m_settings.m_reverseAPIPort);
dialog.setReverseAPIDeviceIndex(m_settings.m_reverseAPIDeviceIndex);
dialog.setReverseAPIChannelIndex(m_settings.m_reverseAPIChannelIndex);
dialog.setDefaultTitle(m_displayedName);
if (m_deviceUISet->m_deviceMIMOEngine)
{
dialog.setNumberOfStreams(m_chirpChatMod->getNumberOfDeviceStreams());
dialog.setStreamIndex(m_settings.m_streamIndex);
}
dialog.move(p);
new DialogPositioner(&dialog, false);
dialog.exec();
m_settings.m_rgbColor = m_channelMarker.getColor().rgb();
m_settings.m_title = m_channelMarker.getTitle();
m_settings.m_useReverseAPI = dialog.useReverseAPI();
m_settings.m_reverseAPIAddress = dialog.getReverseAPIAddress();
m_settings.m_reverseAPIPort = dialog.getReverseAPIPort();
m_settings.m_reverseAPIDeviceIndex = dialog.getReverseAPIDeviceIndex();
m_settings.m_reverseAPIChannelIndex = dialog.getReverseAPIChannelIndex();
setWindowTitle(m_settings.m_title);
setTitle(m_channelMarker.getTitle());
setTitleColor(m_settings.m_rgbColor);
if (m_deviceUISet->m_deviceMIMOEngine)
{
m_settings.m_streamIndex = dialog.getSelectedStreamIndex();
m_channelMarker.clearStreamIndexes();
m_channelMarker.addStreamIndex(m_settings.m_streamIndex);
updateIndexLabel();
}
applySettings();
}
resetContextMenuType();
}
MeshtasticModGUI::MeshtasticModGUI(PluginAPI* pluginAPI, DeviceUISet *deviceUISet, BasebandSampleSource *channelTx, QWidget* parent) :
ChannelGUI(parent),
ui(new Ui::MeshtasticModGUI),
m_pluginAPI(pluginAPI),
m_deviceUISet(deviceUISet),
m_channelMarker(this),
m_deviceCenterFrequency(0),
m_basebandSampleRate(125000),
m_doApplySettings(true),
m_tickCount(0)
{
setAttribute(Qt::WA_DeleteOnClose, true);
m_helpURL = "plugins/channeltx/modmeshtastic/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_chirpChatMod = (MeshtasticMod*) channelTx;
m_chirpChatMod->setMessageQueueToGUI(getInputMessageQueue());
connect(&MainCore::instance()->getMasterTimer(), SIGNAL(timeout()), this, SLOT(tick()));
ui->deltaFrequencyLabel->setText(QString("%1f").arg(QChar(0x94, 0x03)));
ui->deltaFrequency->setColorMapper(ColorMapper(ColorMapper::GrayGold));
ui->deltaFrequency->setValueRange(false, 7, -9999999, 9999999);
ui->deltaFrequency->setToolTip(tr("Offset from device center frequency (Hz)."));
ui->deltaFrequencyLabel->setToolTip(tr("Frequency offset control for the modulator channel."));
ui->deltaUnits->setToolTip(tr("Frequency unit for the offset control."));
ui->bw->setToolTip(tr("LoRa transmit bandwidth."));
ui->bwLabel->setToolTip(tr("LoRa transmit bandwidth selector."));
ui->bwText->setToolTip(tr("Current LoRa transmit bandwidth in Hz."));
ui->spread->setToolTip(tr("LoRa spreading factor (SF)."));
ui->spreadLabel->setToolTip(tr("LoRa spreading factor selector."));
ui->spreadText->setToolTip(tr("Current spreading factor value."));
ui->deBits->setToolTip(tr("Low data-rate optimization bits (DE)."));
ui->deBitsLabel->setToolTip(tr("Low data-rate optimization setting."));
ui->deBitsText->setToolTip(tr("Current low data-rate optimization value."));
ui->preambleChirps->setToolTip(tr("LoRa preamble chirp count."));
ui->preambleChirpsLabel->setToolTip(tr("LoRa preamble chirp count selector."));
ui->preambleChirpsText->setToolTip(tr("Current preamble chirp value."));
ui->idleTime->setToolTip(tr("Silence interval between repeated messages (x0.1s)."));
ui->idleTimeLabel->setToolTip(tr("Idle interval between repeated transmissions."));
ui->idleTimeText->setToolTip(tr("Current idle interval in seconds."));
ui->syncWord->setToolTip(tr("LoRa sync word in hexadecimal (00-ff)."));
ui->syncLabel->setToolTip(tr("LoRa sync word."));
ui->scheme->setToolTip(tr("Encoder mode. Use LoRa for Meshtastic-compatible payloads."));
ui->schemeLabel->setToolTip(tr("Select encoding scheme."));
ui->fecParity->setToolTip(tr("LoRa coding rate parity denominator (CR)."));
ui->fecParityLabel->setToolTip(tr("LoRa coding rate parity setting."));
ui->fecParityText->setToolTip(tr("Current coding rate parity value."));
ui->crc->setToolTip(tr("Append payload CRC."));
ui->header->setToolTip(tr("Use explicit LoRa header mode."));
ui->channelMute->setToolTip(tr("Mute this channel output."));
ui->myCall->setToolTip(tr("Source callsign used by template messages."));
ui->myCallLabel->setToolTip(tr("Source callsign field."));
ui->urCall->setToolTip(tr("Destination callsign used by template messages."));
ui->urCallLabel->setToolTip(tr("Destination callsign field."));
ui->myLocator->setToolTip(tr("Source locator used by template messages."));
ui->myLocatorLabel->setToolTip(tr("Source locator field."));
ui->report->setToolTip(tr("Signal report used by template messages."));
ui->reportLabel->setToolTip(tr("Signal report field."));
ui->msgType->setToolTip(tr("Select which payload template is edited/transmitted."));
ui->msgTypeLabel->setToolTip(tr("Payload template type."));
ui->resetMessages->setToolTip(tr("Reset payload templates to defaults."));
ui->playMessage->setToolTip(tr("Queue one transmission of current message type."));
ui->repeatMessage->setToolTip(tr("Number of repetitions for each triggered transmission."));
ui->repeatLabel->setToolTip(tr("Transmission repetition count."));
ui->generateMessages->setToolTip(tr("Generate standardized payload templates from current fields."));
ui->messageText->setToolTip(tr("Text payload editor. Meshtastic MESH: commands can auto-apply radio settings."));
ui->msgLabel->setToolTip(tr("Message payload editor."));
ui->hexText->setToolTip(tr("Raw hexadecimal payload bytes."));
ui->hexLabel->setToolTip(tr("Hexadecimal payload editor."));
ui->udpEnabled->setToolTip(tr("Receive message payloads from UDP input."));
ui->udpAddress->setToolTip(tr("UDP listen address for incoming payloads."));
ui->udpPort->setToolTip(tr("UDP listen port for incoming payloads."));
ui->udpSeparator->setToolTip(tr("UDP input controls."));
ui->invertRamps->setToolTip(tr("Invert chirp ramp direction."));
ui->channelPower->setToolTip(tr("Estimated channel output power."));
ui->timesLabel->setToolTip(tr("Estimated timing values for current LoRa frame."));
ui->timeSymbolText->setToolTip(tr("Estimated LoRa symbol time."));
ui->timeSymbolLabel->setToolTip(tr("LoRa symbol time estimate."));
ui->timeMessageLengthText->setToolTip(tr("Estimated payload symbol count."));
ui->timeMessageLengthLabel->setToolTip(tr("Payload symbol count estimate."));
ui->timePayloadText->setToolTip(tr("Estimated payload airtime."));
ui->timePayloadLabel->setToolTip(tr("Payload airtime estimate."));
ui->timeTotalText->setToolTip(tr("Estimated total airtime including preamble/control."));
ui->timeTotalLabel->setToolTip(tr("Total frame airtime estimate."));
ui->repeatText->setToolTip(tr("Current repetition count."));
m_channelMarker.blockSignals(true);
m_channelMarker.setColor(Qt::red);
m_channelMarker.setBandwidth(12500);
m_channelMarker.setCenterFrequency(0);
m_channelMarker.setTitle("Meshtastic Modulator");
m_channelMarker.setSourceOrSinkStream(false);
m_channelMarker.blockSignals(false);
m_channelMarker.setVisible(true); // activate signal on the last setting only
m_deviceUISet->addChannelMarker(&m_channelMarker);
connect(&m_channelMarker, SIGNAL(changedByCursor()), this, SLOT(channelMarkerChangedByCursor()));
connect(getInputMessageQueue(), SIGNAL(messageEnqueued()), this, SLOT(handleSourceMessages()));
m_settings.setChannelMarker(&m_channelMarker);
m_settings.setRollupState(&m_rollupState);
setBandwidths();
displaySettings();
makeUIConnections();
applySettings();
DialPopup::addPopupsToChildDials(this);
m_resizer.enableChildMouseTracking();
}
MeshtasticModGUI::~MeshtasticModGUI()
{
delete ui;
}
void MeshtasticModGUI::blockApplySettings(bool block)
{
m_doApplySettings = !block;
}
void MeshtasticModGUI::applySettings(bool force)
{
if (m_doApplySettings)
{
MeshtasticMod::MsgConfigureMeshtasticMod *msg = MeshtasticMod::MsgConfigureMeshtasticMod::create(m_settings, force);
m_chirpChatMod->getInputMessageQueue()->push(msg);
}
}
void MeshtasticModGUI::displaySettings()
{
int thisBW = MeshtasticModSettings::bandwidths[m_settings.m_bandwidthIndex];
m_channelMarker.blockSignals(true);
m_channelMarker.setTitle(m_settings.m_title);
m_channelMarker.setCenterFrequency(m_settings.m_inputFrequencyOffset);
m_channelMarker.setBandwidth(thisBW);
m_channelMarker.blockSignals(false);
m_channelMarker.setColor(m_settings.m_rgbColor);
setTitleColor(m_settings.m_rgbColor);
setWindowTitle(m_channelMarker.getTitle());
setTitle(m_channelMarker.getTitle());
updateIndexLabel();
displayCurrentPayloadMessage();
displayBinaryMessage();
ui->fecParity->setEnabled(m_settings.m_codingScheme == MeshtasticModSettings::CodingLoRa);
ui->crc->setEnabled(m_settings.m_codingScheme == MeshtasticModSettings::CodingLoRa);
ui->header->setEnabled(m_settings.m_codingScheme == MeshtasticModSettings::CodingLoRa);
blockApplySettings(true);
ui->deltaFrequency->setValue(m_channelMarker.getCenterFrequency());
ui->bwText->setText(QString("%1 Hz").arg(thisBW));
ui->bw->setValue(m_settings.m_bandwidthIndex);
ui->spread->setValue(m_settings.m_spreadFactor);
ui->spreadText->setText(tr("%1").arg(m_settings.m_spreadFactor));
ui->deBits->setValue(m_settings.m_deBits);
ui->deBitsText->setText(tr("%1").arg(m_settings.m_deBits));
ui->preambleChirps->setValue(m_settings.m_preambleChirps);
ui->preambleChirpsText->setText(tr("%1").arg(m_settings.m_preambleChirps));
ui->idleTime->setValue(m_settings.m_quietMillis / 100);
ui->idleTimeText->setText(tr("%1").arg(m_settings.m_quietMillis / 1000.0, 0, 'f', 1));
ui->syncWord->setText((tr("%1").arg(m_settings.m_syncWord, 2, 16)));
ui->channelMute->setChecked(m_settings.m_channelMute);
ui->scheme->setCurrentIndex((int) m_settings.m_codingScheme);
ui->fecParity->setValue(m_settings.m_nbParityBits);
ui->fecParityText->setText(tr("%1").arg(m_settings.m_nbParityBits));
ui->crc->setChecked(m_settings.m_hasCRC);
ui->header->setChecked(m_settings.m_hasHeader);
ui->myCall->setText(m_settings.m_myCall);
ui->urCall->setText(m_settings.m_urCall);
ui->myLocator->setText(m_settings.m_myLoc);
ui->report->setText(m_settings.m_myRpt);
ui->repeatMessage->setValue(m_settings.m_messageRepeat);
ui->repeatText->setText(tr("%1").arg(m_settings.m_messageRepeat));
ui->msgType->setCurrentIndex((int) m_settings.m_messageType);
ui->udpEnabled->setChecked(m_settings.m_udpEnabled);
ui->udpAddress->setText(m_settings.m_udpAddress);
ui->udpPort->setText(QString::number(m_settings.m_udpPort));
ui->invertRamps->setChecked(m_settings.m_invertRamps);
getRollupContents()->restoreState(m_rollupState);
updateAbsoluteCenterFrequency();
blockApplySettings(false);
}
void MeshtasticModGUI::displayCurrentPayloadMessage()
{
ui->messageText->blockSignals(true);
if (m_settings.m_messageType == MeshtasticModSettings::MessageNone) {
ui->messageText->clear();
} else if (m_settings.m_messageType == MeshtasticModSettings::MessageBeacon) {
ui->messageText->setText(m_settings.m_beaconMessage);
} else if (m_settings.m_messageType == MeshtasticModSettings::MessageCQ) {
ui->messageText->setText(m_settings.m_cqMessage);
} else if (m_settings.m_messageType == MeshtasticModSettings::MessageReply) {
ui->messageText->setText(m_settings.m_replyMessage);
} else if (m_settings.m_messageType == MeshtasticModSettings::MessageReport) {
ui->messageText->setText(m_settings.m_reportMessage);
} else if (m_settings.m_messageType == MeshtasticModSettings::MessageReplyReport) {
ui->messageText->setText(m_settings.m_replyReportMessage);
} else if (m_settings.m_messageType == MeshtasticModSettings::MessageRRR) {
ui->messageText->setText(m_settings.m_rrrMessage);
} else if (m_settings.m_messageType == MeshtasticModSettings::Message73) {
ui->messageText->setText(m_settings.m_73Message);
} else if (m_settings.m_messageType == MeshtasticModSettings::MessageQSOText) {
ui->messageText->setText(m_settings.m_qsoTextMessage);
} else if (m_settings.m_messageType == MeshtasticModSettings::MessageText) {
ui->messageText->setText(m_settings.m_textMessage);
}
ui->messageText->blockSignals(false);
}
void MeshtasticModGUI::displayBinaryMessage()
{
ui->hexText->setText(m_settings.m_bytesMessage.toHex());
}
void MeshtasticModGUI::setBandwidths()
{
int maxBandwidth = m_basebandSampleRate / MeshtasticModSettings::oversampling;
int maxIndex = 0;
for (; (maxIndex < MeshtasticModSettings::nbBandwidths) && (MeshtasticModSettings::bandwidths[maxIndex] <= maxBandwidth); maxIndex++)
{}
if (maxIndex != 0)
{
qDebug("MeshtasticModGUI::setBandwidths: avl: %d max: %d", maxBandwidth, MeshtasticModSettings::bandwidths[maxIndex-1]);
ui->bw->setMaximum(maxIndex - 1);
int index = ui->bw->value();
ui->bwText->setText(QString("%1 Hz").arg(MeshtasticModSettings::bandwidths[index]));
}
}
void MeshtasticModGUI::leaveEvent(QEvent* event)
{
m_channelMarker.setHighlighted(false);
ChannelGUI::leaveEvent(event);
}
void MeshtasticModGUI::enterEvent(EnterEventType* event)
{
m_channelMarker.setHighlighted(true);
ChannelGUI::enterEvent(event);
}
void MeshtasticModGUI::tick()
{
if (m_tickCount < 10)
{
m_tickCount++;
}
else
{
m_tickCount = 0;
double powDb = CalcDb::dbPower(m_chirpChatMod->getMagSq());
m_channelPowerDbAvg(powDb);
ui->channelPower->setText(tr("%1 dB").arg(m_channelPowerDbAvg.asDouble(), 0, 'f', 1));
if (m_chirpChatMod->getModulatorActive()) {
ui->playMessage->setStyleSheet("QPushButton { background-color : green; }");
} else {
ui->playMessage->setStyleSheet("QPushButton { background:rgb(79,79,79); }");
}
}
}
void MeshtasticModGUI::makeUIConnections()
{
QObject::connect(ui->deltaFrequency, &ValueDialZ::changed, this, &MeshtasticModGUI::on_deltaFrequency_changed);
QObject::connect(ui->bw, &QSlider::valueChanged, this, &MeshtasticModGUI::on_bw_valueChanged);
QObject::connect(ui->spread, &QSlider::valueChanged, this, &MeshtasticModGUI::on_spread_valueChanged);
QObject::connect(ui->deBits, &QSlider::valueChanged, this, &MeshtasticModGUI::on_deBits_valueChanged);
QObject::connect(ui->preambleChirps, &QSlider::valueChanged, this, &MeshtasticModGUI::on_preambleChirps_valueChanged);
QObject::connect(ui->idleTime, &QSlider::valueChanged, this, &MeshtasticModGUI::on_idleTime_valueChanged);
QObject::connect(ui->syncWord, &QLineEdit::editingFinished, this, &MeshtasticModGUI::on_syncWord_editingFinished);
QObject::connect(ui->channelMute, &QToolButton::toggled, this, &MeshtasticModGUI::on_channelMute_toggled);
QObject::connect(ui->scheme, QOverload<int>::of(&QComboBox::currentIndexChanged), this, &MeshtasticModGUI::on_scheme_currentIndexChanged);
QObject::connect(ui->fecParity, &QDial::valueChanged, this, &MeshtasticModGUI::on_fecParity_valueChanged);
QObject::connect(ui->crc, &QCheckBox::stateChanged, this, &MeshtasticModGUI::on_crc_stateChanged);
QObject::connect(ui->header, &QCheckBox::stateChanged, this, &MeshtasticModGUI::on_header_stateChanged);
QObject::connect(ui->myCall, &QLineEdit::editingFinished, this, &MeshtasticModGUI::on_myCall_editingFinished);
QObject::connect(ui->urCall, &QLineEdit::editingFinished, this, &MeshtasticModGUI::on_urCall_editingFinished);
QObject::connect(ui->myLocator, &QLineEdit::editingFinished, this, &MeshtasticModGUI::on_myLocator_editingFinished);
QObject::connect(ui->report, &QLineEdit::editingFinished, this, &MeshtasticModGUI::on_report_editingFinished);
QObject::connect(ui->msgType, QOverload<int>::of(&QComboBox::currentIndexChanged), this, &MeshtasticModGUI::on_msgType_currentIndexChanged);
QObject::connect(ui->resetMessages, &QPushButton::clicked, this, &MeshtasticModGUI::on_resetMessages_clicked);
QObject::connect(ui->playMessage, &QPushButton::clicked, this, &MeshtasticModGUI::on_playMessage_clicked);
QObject::connect(ui->repeatMessage, &QDial::valueChanged, this, &MeshtasticModGUI::on_repeatMessage_valueChanged);
QObject::connect(ui->generateMessages, &QPushButton::clicked, this, &MeshtasticModGUI::on_generateMessages_clicked);
QObject::connect(ui->messageText, &CustomTextEdit::editingFinished, this, &MeshtasticModGUI::on_messageText_editingFinished);
QObject::connect(ui->hexText, &QLineEdit::editingFinished, this, &MeshtasticModGUI::on_hexText_editingFinished);
QObject::connect(ui->udpEnabled, &QCheckBox::clicked, this, &MeshtasticModGUI::on_udpEnabled_clicked);
QObject::connect(ui->udpAddress, &QLineEdit::editingFinished, this, &MeshtasticModGUI::on_udpAddress_editingFinished);
QObject::connect(ui->udpPort, &QLineEdit::editingFinished, this, &MeshtasticModGUI::on_udpPort_editingFinished);
QObject::connect(ui->invertRamps, &QCheckBox::stateChanged, this, &MeshtasticModGUI::on_invertRamps_stateChanged);
}
void MeshtasticModGUI::updateAbsoluteCenterFrequency()
{
setStatusFrequency(m_deviceCenterFrequency + m_settings.m_inputFrequencyOffset);
}

135
plugins/channeltx/modmeshtastic/meshtasticmodgui.h

@ -0,0 +1,135 @@ @@ -0,0 +1,135 @@
///////////////////////////////////////////////////////////////////////////////////
// Copyright (C) 2016-2020, 2022 Edouard Griffiths, F4EXB <f4exb06@gmail.com> //
// Copyright (C) 2021-2022 Jon Beniston, M7RCE <jon@beniston.com> //
// //
// This program is free software; you can redistribute it and/or modify //
// it under the terms of the GNU General Public License as published by //
// the Free Software Foundation as version 3 of the License, or //
// (at your option) any later version. //
// //
// This program is distributed in the hope that it will be useful, //
// but WITHOUT ANY WARRANTY; without even the implied warranty of //
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //
// GNU General Public License V3 for more details. //
// //
// You should have received a copy of the GNU General Public License //
// along with this program. If not, see <http://www.gnu.org/licenses/>. //
///////////////////////////////////////////////////////////////////////////////////
#ifndef PLUGINS_CHANNELTX_MODLORA_LORAMODGUI_H_
#define PLUGINS_CHANNELTX_MODLORA_LORAMODGUI_H_
#include "channel/channelgui.h"
#include "dsp/channelmarker.h"
#include "util/movingaverage.h"
#include "util/messagequeue.h"
#include "settings/rollupstate.h"
#include "meshtasticmod.h"
#include "meshtasticmodsettings.h"
class PluginAPI;
class DeviceUISet;
class BasebandSampleSource;
namespace Ui {
class MeshtasticModGUI;
}
class MeshtasticModGUI : public ChannelGUI {
Q_OBJECT
public:
static MeshtasticModGUI* create(PluginAPI* pluginAPI, DeviceUISet *deviceUISet, BasebandSampleSource *channelTx);
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();
private:
Ui::MeshtasticModGUI* ui;
PluginAPI* m_pluginAPI;
DeviceUISet* m_deviceUISet;
ChannelMarker m_channelMarker;
RollupState m_rollupState;
MeshtasticModSettings m_settings;
qint64 m_deviceCenterFrequency;
int m_basebandSampleRate;
bool m_doApplySettings;
MeshtasticMod* m_chirpChatMod;
MovingAverageUtil<double, double, 20> m_channelPowerDbAvg;
std::size_t m_tickCount;
MessageQueue m_inputMessageQueue;
explicit MeshtasticModGUI(PluginAPI* pluginAPI, DeviceUISet *deviceUISet, BasebandSampleSource *channelTx, QWidget* parent = nullptr);
virtual ~MeshtasticModGUI();
void blockApplySettings(bool block);
void applySettings(bool force = false);
void displaySettings();
void displayCurrentPayloadMessage();
void displayBinaryMessage();
void setBandwidths();
QString getActivePayloadText() const;
int findBandwidthIndex(int bandwidthHz) const;
void applyMeshtasticRadioSettingsIfPresent(const QString& payloadText);
bool handleMessage(const Message& message);
void makeUIConnections();
void updateAbsoluteCenterFrequency();
void leaveEvent(QEvent*);
void enterEvent(EnterEventType*);
private slots:
void handleSourceMessages();
void on_deltaFrequency_changed(qint64 value);
void on_bw_valueChanged(int value);
void on_spread_valueChanged(int value);
void on_deBits_valueChanged(int value);
void on_preambleChirps_valueChanged(int value);
void on_idleTime_valueChanged(int value);
void on_syncWord_editingFinished();
void on_channelMute_toggled(bool checked);
void on_scheme_currentIndexChanged(int index);
void on_fecParity_valueChanged(int value);
void on_crc_stateChanged(int state);
void on_header_stateChanged(int state);
void on_myCall_editingFinished();
void on_urCall_editingFinished();
void on_myLocator_editingFinished();
void on_report_editingFinished();
void on_msgType_currentIndexChanged(int index);
void on_resetMessages_clicked(bool checked);
void on_playMessage_clicked(bool checked);
void on_repeatMessage_valueChanged(int value);
void on_generateMessages_clicked(bool checked);
void on_messageText_editingFinished();
void on_hexText_editingFinished();
void on_udpEnabled_clicked(bool checked);
void on_udpAddress_editingFinished();
void on_udpPort_editingFinished();
void on_invertRamps_stateChanged(int state);
void onWidgetRolled(QWidget* widget, bool rollDown);
void onMenuDialogCalled(const QPoint& p);
void tick();
};
#endif /* PLUGINS_CHANNELTX_MODLORA_LORAMODGUI_H_ */

1260
plugins/channeltx/modmeshtastic/meshtasticmodgui.ui

File diff suppressed because it is too large Load Diff

96
plugins/channeltx/modmeshtastic/meshtasticmodplugin.cpp

@ -0,0 +1,96 @@ @@ -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 <f4exb06@gmail.com> //
// Copyright (C) 2019 Davide Gerhard <rainbow@irh.it> //
// Copyright (C) 2020 Kacper Michajłow <kasper93@gmail.com> //
// //
// This program is free software; you can redistribute it and/or modify //
// it under the terms of the GNU General Public License as published by //
// the Free Software Foundation as version 3 of the License, or //
// (at your option) any later version. //
// //
// This program is distributed in the hope that it will be useful, //
// but WITHOUT ANY WARRANTY; without even the implied warranty of //
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //
// GNU General Public License V3 for more details. //
// //
// You should have received a copy of the GNU General Public License //
// along with this program. If not, see <http://www.gnu.org/licenses/>. //
///////////////////////////////////////////////////////////////////////////////////
#include <QtPlugin>
#include "plugin/pluginapi.h"
#ifndef SERVER_MODE
#include "meshtasticmodgui.h"
#endif
#include "meshtasticmod.h"
#include "meshtasticmodwebapiadapter.h"
#include "meshtasticmodplugin.h"
const PluginDescriptor MeshtasticModPlugin::m_pluginDescriptor = {
MeshtasticMod::m_channelId,
QStringLiteral("Meshtastic Modulator"),
QStringLiteral("7.23.1"),
QStringLiteral("(c) Edouard Griffiths, F4EXB"),
QStringLiteral("https://github.com/f4exb/sdrangel"),
true,
QStringLiteral("https://github.com/f4exb/sdrangel")
};
MeshtasticModPlugin::MeshtasticModPlugin(QObject* parent) :
QObject(parent),
m_pluginAPI(0)
{
}
const PluginDescriptor& MeshtasticModPlugin::getPluginDescriptor() const
{
return m_pluginDescriptor;
}
void MeshtasticModPlugin::initPlugin(PluginAPI* pluginAPI)
{
m_pluginAPI = pluginAPI;
// register LoRa modulator
m_pluginAPI->registerTxChannel(MeshtasticMod::m_channelIdURI, MeshtasticMod::m_channelId, this);
}
void MeshtasticModPlugin::createTxChannel(DeviceAPI *deviceAPI, BasebandSampleSource **bs, ChannelAPI **cs) const
{
if (bs || cs)
{
MeshtasticMod *instance = new MeshtasticMod(deviceAPI);
if (bs) {
*bs = instance;
}
if (cs) {
*cs = instance;
}
}
}
#ifdef SERVER_MODE
ChannelGUI* MeshtasticModPlugin::createTxChannelGUI(
DeviceUISet *deviceUISet,
BasebandSampleSource *txChannel) const
{
(void) deviceUISet;
(void) txChannel;
return nullptr;
}
#else
ChannelGUI* MeshtasticModPlugin::createTxChannelGUI(DeviceUISet *deviceUISet, BasebandSampleSource *txChannel) const
{
return MeshtasticModGUI::create(m_pluginAPI, deviceUISet, txChannel);
}
#endif
ChannelWebAPIAdapter* MeshtasticModPlugin::createChannelWebAPIAdapter() const
{
return new MeshtasticModWebAPIAdapter();
}

51
plugins/channeltx/modmeshtastic/meshtasticmodplugin.h

@ -0,0 +1,51 @@ @@ -0,0 +1,51 @@
///////////////////////////////////////////////////////////////////////////////////
// Copyright (C) 2012 maintech GmbH, Otto-Hahn-Str. 15, 97204 Hoechberg, Germany //
// written by Christian Daniel //
// Copyright (C) 2015-2017, 2019-2020 Edouard Griffiths, F4EXB <f4exb06@gmail.com> //
// Copyright (C) 2015 John Greb <hexameron@spam.no> //
// //
// This program is free software; you can redistribute it and/or modify //
// it under the terms of the GNU General Public License as published by //
// the Free Software Foundation as version 3 of the License, or //
// (at your option) any later version. //
// //
// This program is distributed in the hope that it will be useful, //
// but WITHOUT ANY WARRANTY; without even the implied warranty of //
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //
// GNU General Public License V3 for more details. //
// //
// You should have received a copy of the GNU General Public License //
// along with this program. If not, see <http://www.gnu.org/licenses/>. //
///////////////////////////////////////////////////////////////////////////////////
#ifndef INCLUDE_MESHTASTICMODPLUGIN_H
#define INCLUDE_MESHTASTICMODPLUGIN_H
#include <QObject>
#include "plugin/plugininterface.h"
class DeviceUISet;
class BasebandSampleSource;
class MeshtasticModPlugin : public QObject, PluginInterface {
Q_OBJECT
Q_INTERFACES(PluginInterface)
Q_PLUGIN_METADATA(IID "sdrangel.channeltx.modmeshtastic")
public:
explicit MeshtasticModPlugin(QObject* parent = nullptr);
const PluginDescriptor& getPluginDescriptor() const;
void initPlugin(PluginAPI* pluginAPI);
virtual void createTxChannel(DeviceAPI *deviceAPI, BasebandSampleSource **bs, ChannelAPI **cs) const;
virtual ChannelGUI* createTxChannelGUI(DeviceUISet *deviceUISet, BasebandSampleSource *rxChannel) const;
virtual ChannelWebAPIAdapter* createChannelWebAPIAdapter() const;
private:
static const PluginDescriptor m_pluginDescriptor;
PluginAPI* m_pluginAPI;
};
#endif // INCLUDE_MESHTASTICMODPLUGIN_H

492
plugins/channeltx/modmeshtastic/meshtasticmodsettings.cpp

@ -0,0 +1,492 @@ @@ -0,0 +1,492 @@
///////////////////////////////////////////////////////////////////////////////////
// Copyright (C) 2012 maintech GmbH, Otto-Hahn-Str. 15, 97204 Hoechberg, Germany //
// written by Christian Daniel //
// Copyright (C) 2015-2020, 2022 Edouard Griffiths, F4EXB <f4exb06@gmail.com> //
// Copyright (C) 2021 Jon Beniston, M7RCE <jon@beniston.com> //
// //
// This program is free software; you can redistribute it and/or modify //
// it under the terms of the GNU General Public License as published by //
// the Free Software Foundation as version 3 of the License, or //
// (at your option) any later version. //
// //
// This program is distributed in the hope that it will be useful, //
// but WITHOUT ANY WARRANTY; without even the implied warranty of //
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //
// GNU General Public License V3 for more details. //
// //
// You should have received a copy of the GNU General Public License //
// along with this program. If not, see <http://www.gnu.org/licenses/>. //
///////////////////////////////////////////////////////////////////////////////////
#include <QColor>
#include "util/simpleserializer.h"
#include "settings/serializable.h"
#include "meshtasticmodsettings.h"
const int MeshtasticModSettings::bandwidths[] = {
325, // 384k / 1024
488, // 500k / 1024
750, // 384k / 512
1500, // 384k / 256
2604, // 333k / 128
3125, // 400k / 128
3906, // 500k / 128
5208, // 333k / 64
6250, // 400k / 64
7813, // 500k / 64
10417, // 333k / 32
12500, // 400k / 32
15625, // 500k / 32
20833, // 333k / 16
25000, // 400k / 16
31250, // 500k / 16
41667, // 333k / 8
50000, // 400k / 8
62500, // 500k / 8
83333, // 333k / 4
100000, // 400k / 4
125000, // 500k / 4
166667, // 333k / 2
200000, // 400k / 2
250000, // 500k / 2
333333, // 333k / 1
400000, // 400k / 1
500000 // 500k / 1
};
const int MeshtasticModSettings::nbBandwidths = 3*8 + 4;
const int MeshtasticModSettings::oversampling = 4;
MeshtasticModSettings::MeshtasticModSettings() :
m_inputFrequencyOffset(0),
m_channelMarker(nullptr),
m_rollupState(nullptr)
{
resetToDefaults();
}
void MeshtasticModSettings::resetToDefaults()
{
m_bandwidthIndex = 5;
m_spreadFactor = 7;
m_deBits = 0;
m_preambleChirps = 8;
m_quietMillis = 1000;
m_codingScheme = CodingLoRa;
m_nbParityBits = 1;
m_hasCRC = true;
m_hasHeader = true;
m_textMessage = "Hello LoRa";
m_myCall = "MYCALL";
m_urCall = "URCALL";
m_myLoc = "AA00AA";
m_myRpt = "59";
m_syncWord = 0x34;
m_channelMute = false;
m_messageRepeat = 1;
m_udpEnabled = false;
m_udpAddress = "127.0.0.1";
m_udpPort = 9998;
m_invertRamps = false;
m_rgbColor = QColor(255, 0, 255).rgb();
m_title = "Meshtastic Modulator";
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;
setDefaultTemplates();
}
void MeshtasticModSettings::setDefaultTemplates()
{
// %1: myCall %2: urCall %3: myLoc %4: report
m_beaconMessage = "VVV DE %1 %2"; // Beacon
m_cqMessage = "CQ DE %1 %2"; // caller calls CQ
m_replyMessage = "%1 %2 %3"; // Reply to CQ from caller
m_reportMessage = "%1 %2 %3"; // Report to caller
m_replyReportMessage = "%1 %2 R%3"; // Report to callee
m_rrrMessage = "%1 %2 RRR"; // RRR to callee
m_73Message = "%1 %2 73"; // 73 to caller
m_qsoTextMessage = "%1 %2 %3"; // Freeflow message to caller - %3 is m_textMessage
}
void MeshtasticModSettings::generateMessages()
{
m_beaconMessage = m_beaconMessage
.arg(m_myCall).arg(m_myLoc);
m_cqMessage = m_cqMessage
.arg(m_myCall).arg(m_myLoc);
m_replyMessage = m_replyMessage
.arg(m_urCall).arg(m_myCall).arg(m_myLoc);
m_reportMessage = m_reportMessage
.arg(m_urCall).arg(m_myCall).arg(m_myRpt);
m_replyReportMessage = m_replyReportMessage
.arg(m_urCall).arg(m_myCall).arg(m_myRpt);
m_rrrMessage = m_rrrMessage
.arg(m_urCall).arg(m_myCall);
m_73Message = m_73Message
.arg(m_urCall).arg(m_myCall);
m_qsoTextMessage = m_qsoTextMessage
.arg(m_urCall).arg(m_myCall).arg(m_textMessage);
}
unsigned int MeshtasticModSettings::getNbSFDFourths() const
{
switch (m_codingScheme)
{
case CodingLoRa:
return 9;
default:
return 8;
}
}
bool MeshtasticModSettings::hasSyncWord() const
{
return m_codingScheme == CodingLoRa;
}
QByteArray MeshtasticModSettings::serialize() const
{
SimpleSerializer s(1);
s.writeS32(1, m_inputFrequencyOffset);
s.writeS32(2, m_bandwidthIndex);
s.writeS32(3, m_spreadFactor);
s.writeS32(4, m_codingScheme);
if (m_channelMarker) {
s.writeBlob(5, m_channelMarker->serialize());
}
s.writeString(6, m_title);
s.writeS32(7, m_deBits);
s.writeBool(8, m_channelMute);
s.writeU32(9, m_syncWord);
s.writeU32(10, m_preambleChirps);
s.writeS32(11, m_quietMillis);
s.writeBool(12, m_invertRamps);
s.writeString(20, m_beaconMessage);
s.writeString(21, m_cqMessage);
s.writeString(22, m_replyMessage);
s.writeString(23, m_reportMessage);
s.writeString(24, m_replyReportMessage);
s.writeString(25, m_rrrMessage);
s.writeString(26, m_73Message);
s.writeString(27, m_qsoTextMessage);
s.writeString(28, m_textMessage);
s.writeBlob(29, m_bytesMessage);
s.writeS32(30, (int) m_messageType);
s.writeS32(31, m_nbParityBits);
s.writeBool(32, m_hasCRC);
s.writeBool(33, m_hasHeader);
s.writeString(40, m_myCall);
s.writeString(41, m_urCall);
s.writeString(42, m_myLoc);
s.writeString(43, m_myRpt);
s.writeS32(44, m_messageRepeat);
s.writeBool(50, m_useReverseAPI);
s.writeString(51, m_reverseAPIAddress);
s.writeU32(52, m_reverseAPIPort);
s.writeU32(53, m_reverseAPIDeviceIndex);
s.writeU32(54, m_reverseAPIChannelIndex);
s.writeS32(55, m_streamIndex);
s.writeBool(56, m_udpEnabled);
s.writeString(57, m_udpAddress);
s.writeU32(58, m_udpPort);
if (m_rollupState) {
s.writeBlob(59, m_rollupState->serialize());
}
s.writeS32(60, m_workspaceIndex);
s.writeBlob(61, m_geometryBytes);
s.writeBool(62, m_hidden);
return s.final();
}
bool MeshtasticModSettings::deserialize(const QByteArray& data)
{
SimpleDeserializer d(data);
if(!d.isValid())
{
resetToDefaults();
return false;
}
if(d.getVersion() == 1)
{
QByteArray bytetmp;
unsigned int utmp;
int tmp;
d.readS32(1, &m_inputFrequencyOffset, 0);
d.readS32(2, &m_bandwidthIndex, 0);
d.readS32(3, &m_spreadFactor, 0);
d.readS32(4, &tmp, 0);
m_codingScheme = (CodingScheme) tmp;
if (m_channelMarker)
{
d.readBlob(5, &bytetmp);
m_channelMarker->deserialize(bytetmp);
}
d.readString(6, &m_title, "LoRa Demodulator");
d.readS32(7, &m_deBits, 0);
d.readBool(8, &m_channelMute, false);
d.readU32(9, &utmp, 0x34);
m_syncWord = utmp > 255 ? 0 : utmp;
d.readU32(10, &m_preambleChirps, 8);
d.readS32(11, &m_quietMillis, 1000);
d.readBool(11, &m_useReverseAPI, false);
d.readBool(12, &m_invertRamps, false);
d.readString(20, &m_beaconMessage, "VVV DE %1 %2");
d.readString(21, &m_cqMessage, "CQ DE %1 %2");
d.readString(22, &m_replyMessage, "%2 %1 %3");
d.readString(23, &m_reportMessage, "%2 %1 %3");
d.readString(24, &m_replyReportMessage, "%2 %1 R%3");
d.readString(25, &m_rrrMessage, "%2 %1 RRR");
d.readString(26, &m_73Message, "%2 %1 73");
d.readString(27, &m_qsoTextMessage, "%2 %1 Hello LoRa");
d.readString(28, &m_textMessage, "Hello LoRa");
d.readBlob(29, &m_bytesMessage);
d.readS32(30, &tmp, 0);
m_messageType = (MessageType) tmp;
d.readS32(31, &m_nbParityBits, 1);
d.readBool(32, &m_hasCRC, true);
d.readBool(33, &m_hasHeader, true);
d.readString(40, &m_myCall, "MYCALL");
d.readString(41, &m_urCall, "URCALL");
d.readString(42, &m_myLoc, "AA00AA");
d.readString(43, &m_myRpt, "59");
d.readS32(44, &m_messageRepeat, 1);
d.readBool(50, &m_useReverseAPI, false);
d.readString(51, &m_reverseAPIAddress, "127.0.0.1");
d.readU32(52, &utmp, 0);
if ((utmp > 1023) && (utmp < 65535)) {
m_reverseAPIPort = utmp;
} else {
m_reverseAPIPort = 8888;
}
d.readU32(53, &utmp, 0);
m_reverseAPIDeviceIndex = utmp > 99 ? 99 : utmp;
d.readU32(54, &utmp, 0);
m_reverseAPIChannelIndex = utmp > 99 ? 99 : utmp;
d.readS32(55, &m_streamIndex, 0);
d.readBool(56, &m_udpEnabled);
d.readString(57, &m_udpAddress, "127.0.0.1");
d.readU32(58, &utmp);
if ((utmp > 1023) && (utmp < 65535)) {
m_udpPort = utmp;
} else {
m_udpPort = 9998;
}
if (m_rollupState)
{
d.readBlob(59, &bytetmp);
m_rollupState->deserialize(bytetmp);
}
d.readS32(60, &m_workspaceIndex, 0);
d.readBlob(61, &m_geometryBytes);
d.readBool(62, &m_hidden, false);
return true;
}
else
{
resetToDefaults();
return false;
}
}
void MeshtasticModSettings::applySettings(const QStringList& settingsKeys, const MeshtasticModSettings& settings)
{
if (settingsKeys.contains("inputFrequencyOffset"))
m_inputFrequencyOffset = settings.m_inputFrequencyOffset;
if (settingsKeys.contains("bandwidthIndex"))
m_bandwidthIndex = settings.m_bandwidthIndex;
if (settingsKeys.contains("spreadFactor"))
m_spreadFactor = settings.m_spreadFactor;
if (settingsKeys.contains("deBits"))
m_deBits = settings.m_deBits;
if (settingsKeys.contains("codingScheme"))
m_codingScheme = settings.m_codingScheme;
if (settingsKeys.contains("preambleChirps"))
m_preambleChirps = settings.m_preambleChirps;
if (settingsKeys.contains("quietMillis"))
m_quietMillis = settings.m_quietMillis;
if (settingsKeys.contains("invertRamps"))
m_invertRamps = settings.m_invertRamps;
if (settingsKeys.contains("syncWord"))
m_syncWord = settings.m_syncWord;
if (settingsKeys.contains("channelMute"))
m_channelMute = settings.m_channelMute;
if (settingsKeys.contains("title"))
m_title = settings.m_title;
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("streamIndex"))
m_streamIndex = settings.m_streamIndex;
if (settingsKeys.contains("useReverseAPI"))
m_useReverseAPI = settings.m_useReverseAPI;
if (settingsKeys.contains("reverseAPIAddress"))
m_reverseAPIAddress = settings.m_reverseAPIAddress;
if (settingsKeys.contains("reverseAPIPort"))
m_reverseAPIPort = settings.m_reverseAPIPort;
if (settingsKeys.contains("reverseAPIDeviceIndex"))
m_reverseAPIDeviceIndex = settings.m_reverseAPIDeviceIndex;
if (settingsKeys.contains("reverseAPIChannelIndex"))
m_reverseAPIChannelIndex = settings.m_reverseAPIChannelIndex;
if (settingsKeys.contains("workspaceIndex"))
m_workspaceIndex = settings.m_workspaceIndex;
if (settingsKeys.contains("geometryBytes"))
m_geometryBytes = settings.m_geometryBytes;
if (settingsKeys.contains("hidden"))
m_hidden = settings.m_hidden;
if (settingsKeys.contains("channelMarker") && m_channelMarker && settings.m_channelMarker)
m_channelMarker->deserialize(settings.m_channelMarker->serialize());
if (settingsKeys.contains("rollupState") && m_rollupState && settings.m_rollupState)
m_rollupState->deserialize(settings.m_rollupState->serialize());
if (settingsKeys.contains("beaconMessage"))
m_beaconMessage = settings.m_beaconMessage;
if (settingsKeys.contains("cqMessage"))
m_cqMessage = settings.m_cqMessage;
if (settingsKeys.contains("replyMessage"))
m_replyMessage = settings.m_replyMessage;
if (settingsKeys.contains("reportMessage"))
m_reportMessage = settings.m_reportMessage;
if (settingsKeys.contains("replyReportMessage"))
m_replyReportMessage = settings.m_replyReportMessage;
if (settingsKeys.contains("rrrMessage"))
m_rrrMessage = settings.m_rrrMessage;
if (settingsKeys.contains("73Message"))
m_73Message = settings.m_73Message;
if (settingsKeys.contains("qsoTextMessage"))
m_qsoTextMessage = settings.m_qsoTextMessage;
if (settingsKeys.contains("textMessage"))
m_textMessage = settings.m_textMessage;
if (settingsKeys.contains("bytesMessage"))
m_bytesMessage = settings.m_bytesMessage;
if (settingsKeys.contains("messageType"))
m_messageType = settings.m_messageType;
if (settingsKeys.contains("nbParityBits"))
m_nbParityBits = settings.m_nbParityBits;
if (settingsKeys.contains("hasCRC"))
m_hasCRC = settings.m_hasCRC;
if (settingsKeys.contains("hasHeader"))
m_hasHeader = settings.m_hasHeader;
if (settingsKeys.contains("myCall"))
m_myCall = settings.m_myCall;
if (settingsKeys.contains("urCall"))
m_urCall = settings.m_urCall;
if (settingsKeys.contains("myLoc"))
m_myLoc = settings.m_myLoc;
if (settingsKeys.contains("myRpt"))
m_myRpt = settings.m_myRpt;
if (settingsKeys.contains("messageRepeat"))
m_messageRepeat = settings.m_messageRepeat;
}
QString MeshtasticModSettings::getDebugString(const QStringList& settingsKeys, bool force) const
{
QString debug;
if (settingsKeys.contains("inputFrequencyOffset") || force)
debug += QString("Input Frequency Offset: %1\n").arg(m_inputFrequencyOffset);
if (settingsKeys.contains("bandwidthIndex") || force)
debug += QString("Bandwidth Index: %1\n").arg(m_bandwidthIndex);
if (settingsKeys.contains("spreadFactor") || force)
debug += QString("Spread Factor: %1\n").arg(m_spreadFactor);
if (settingsKeys.contains("deBits") || force)
debug += QString("DE Bits: %1\n").arg(m_deBits);
if (settingsKeys.contains("codingScheme") || force)
debug += QString("Coding Scheme: %1\n").arg(m_codingScheme);
if (settingsKeys.contains("preambleChirps") || force)
debug += QString("Preamble Chirps: %1\n").arg(m_preambleChirps);
if (settingsKeys.contains("quietMillis") || force)
debug += QString("Quiet Millis: %1\n").arg(m_quietMillis);
if (settingsKeys.contains("invertRamps") || force)
debug += QString("Invert Ramps: %1\n").arg(m_invertRamps);
if (settingsKeys.contains("syncWord") || force)
debug += QString("Sync Word: %1\n").arg(m_syncWord);
if (settingsKeys.contains("channelMute") || force)
debug += QString("Channel Mute: %1\n").arg(m_channelMute);
if (settingsKeys.contains("title") || force)
debug += QString("Title: %1\n").arg(m_title);
if (settingsKeys.contains("udpEnabled") || force)
debug += QString("UDP Enabled: %1\n").arg(m_udpEnabled);
if (settingsKeys.contains("udpAddress") || force)
debug += QString("UDP Address: %1\n").arg(m_udpAddress);
if (settingsKeys.contains("udpPort") || force)
debug += QString("UDP Port: %1\n").arg(m_udpPort);
if (settingsKeys.contains("streamIndex") || force)
debug += QString("Stream Index: %1\n").arg(m_streamIndex);
if (settingsKeys.contains("useReverseAPI") || force)
debug += QString("Use Reverse API: %1\n").arg(m_useReverseAPI);
if (settingsKeys.contains("reverseAPIAddress") || force)
debug += QString("Reverse API Address: %1\n").arg(m_reverseAPIAddress);
if (settingsKeys.contains("reverseAPIPort") || force)
debug += QString("Reverse API Port: %1\n").arg(m_reverseAPIPort);
if (settingsKeys.contains("reverseAPIDeviceIndex") || force)
debug += QString("Reverse API Device Index: %1\n").arg(m_reverseAPIDeviceIndex);
if (settingsKeys.contains("reverseAPIChannelIndex") || force)
debug += QString("Reverse API Channel Index: %1\n").arg(m_reverseAPIChannelIndex);
if (settingsKeys.contains("workspaceIndex") || force)
debug += QString("Workspace Index: %1\n").arg(m_workspaceIndex);
if (settingsKeys.contains("hidden") || force)
debug += QString("Hidden: %1\n").arg(m_hidden);
if (settingsKeys.contains("beaconMessage") || force)
debug += QString("Beacon Message: %1\n").arg(m_beaconMessage);
if (settingsKeys.contains("cqMessage") || force)
debug += QString("CQ Message: %1\n").arg(m_cqMessage);
if (settingsKeys.contains("replyMessage") || force)
debug += QString("Reply Message: %1\n").arg(m_replyMessage);
if (settingsKeys.contains("reportMessage") || force)
debug += QString("Report Message: %1\n").arg(m_reportMessage);
if (settingsKeys.contains("replyReportMessage") || force)
debug += QString("Reply Report Message: %1\n").arg(m_replyReportMessage);
if (settingsKeys.contains("rrrMessage") || force)
debug += QString("RRR Message: %1\n").arg(m_rrrMessage);
if (settingsKeys.contains("73Message") || force)
debug += QString("73 Message: %1\n").arg(m_73Message);
if (settingsKeys.contains("qsoTextMessage") || force)
debug += QString("QSO Text Message: %1\n").arg(m_qsoTextMessage);
if (settingsKeys.contains("textMessage") || force)
debug += QString("Text Message: %1\n").arg(m_textMessage);
if (settingsKeys.contains("messageType") || force)
debug += QString("Message Type: %1\n").arg(m_messageType);
if (settingsKeys.contains("nbParityBits") || force)
debug += QString("Number of Parity Bits: %1\n").arg(m_nbParityBits);
if (settingsKeys.contains("hasCRC") || force)
debug += QString("Has CRC: %1\n").arg(m_hasCRC);
if (settingsKeys.contains("hasHeader") || force)
debug += QString("Has Header: %1\n").arg(m_hasHeader);
if (settingsKeys.contains("myCall") || force)
debug += QString("My Call: %1\n").arg(m_myCall);
if (settingsKeys.contains("urCall") || force)
debug += QString("UR Call: %1\n").arg(m_urCall);
if (settingsKeys.contains("myLoc") || force)
debug += QString("My Loc: %1\n").arg(m_myLoc);
if (settingsKeys.contains("myRpt") || force)
debug += QString("My Rpt: %1\n").arg(m_myRpt);
if (settingsKeys.contains("messageRepeat") || force)
debug += QString("Message Repeat: %1\n").arg(m_messageRepeat);
return debug;
}

123
plugins/channeltx/modmeshtastic/meshtasticmodsettings.h

@ -0,0 +1,123 @@ @@ -0,0 +1,123 @@
///////////////////////////////////////////////////////////////////////////////////
// Copyright (C) 2012 maintech GmbH, Otto-Hahn-Str. 15, 97204 Hoechberg, Germany //
// written by Christian Daniel //
// Copyright (C) 2015-2020, 2022 Edouard Griffiths, F4EXB <f4exb06@gmail.com> //
// Copyright (C) 2021 Jon Beniston, M7RCE <jon@beniston.com> //
// //
// This program is free software; you can redistribute it and/or modify //
// it under the terms of the GNU General Public License as published by //
// the Free Software Foundation as version 3 of the License, or //
// (at your option) any later version. //
// //
// This program is distributed in the hope that it will be useful, //
// but WITHOUT ANY WARRANTY; without even the implied warranty of //
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //
// GNU General Public License V3 for more details. //
// //
// You should have received a copy of the GNU General Public License //
// along with this program. If not, see <http://www.gnu.org/licenses/>. //
///////////////////////////////////////////////////////////////////////////////////
#ifndef PLUGINS_CHANNELTX_MODMESHTASTIC_MESHTASTICMODSETTINGS_H_
#define PLUGINS_CHANNELTX_MODMESHTASTIC_MESHTASTICMODSETTINGS_H_
#include <QByteArray>
#include <QString>
#include <stdint.h>
class Serializable;
struct MeshtasticModSettings
{
enum CodingScheme
{
CodingLoRa, //!< Standard LoRa
CodingASCII, //!< plain ASCII (7 bits)
CodingTTY, //!< plain TTY (5 bits)
CodingFT //!< FT8/4 scheme (payload 174 bits LDPC)
};
enum MessageType
{
MessageNone,
MessageBeacon,
MessageCQ,
MessageReply,
MessageReport,
MessageReplyReport,
MessageRRR,
Message73,
MessageQSOText,
MessageText,
MessageBytes
};
int m_inputFrequencyOffset;
int m_bandwidthIndex;
int m_spreadFactor;
int m_deBits; //!< Low data rate optimize (DE) bits
unsigned int m_preambleChirps; //!< Number of preamble chirps
int m_quietMillis; //!< Number of milliseconds to pause between transmissions
int m_nbParityBits; //!< Hamming parity bits (LoRa)
bool m_hasCRC; //!< Payload has CRC (LoRa)
bool m_hasHeader; //!< Header present before actual payload (LoRa)
unsigned char m_syncWord;
bool m_channelMute;
CodingScheme m_codingScheme;
QString m_myCall; //!< QSO mode: my callsign
QString m_urCall; //!< QSO mode: your callsign
QString m_myLoc; //!< QSO mode: my locator
QString m_myRpt; //!< QSO mode: my report
MessageType m_messageType;
QString m_beaconMessage;
QString m_cqMessage;
QString m_replyMessage;
QString m_reportMessage;
QString m_replyReportMessage;
QString m_rrrMessage;
QString m_73Message;
QString m_qsoTextMessage;
QString m_textMessage;
QByteArray m_bytesMessage;
int m_messageRepeat;
bool m_udpEnabled;
QString m_udpAddress;
uint16_t m_udpPort;
bool m_invertRamps; //!< Invert chirp ramps vs standard LoRa (up/down/up is standard)
uint32_t m_rgbColor;
QString m_title;
int m_streamIndex;
bool m_useReverseAPI;
QString m_reverseAPIAddress;
uint16_t m_reverseAPIPort;
uint16_t m_reverseAPIDeviceIndex;
uint16_t m_reverseAPIChannelIndex;
int m_workspaceIndex;
QByteArray m_geometryBytes;
bool m_hidden;
Serializable *m_channelMarker;
Serializable *m_rollupState;
static const int bandwidths[];
static const int nbBandwidths;
static const int oversampling;
MeshtasticModSettings();
void resetToDefaults();
void setDefaultTemplates();
void generateMessages();
unsigned int getNbSFDFourths() const; //!< Get the number of SFD period fourths (depends on coding scheme)
bool hasSyncWord() const; //!< Only LoRa has a syncword (for the moment)
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 MeshtasticModSettings& settings);
QString getDebugString(const QStringList& settingsKeys, bool force=false) const;
};
#endif /* PLUGINS_CHANNELTX_MODMESHTASTIC_MESHTASTICMODSETTINGS_H_ */

410
plugins/channeltx/modmeshtastic/meshtasticmodsource.cpp

@ -0,0 +1,410 @@ @@ -0,0 +1,410 @@
///////////////////////////////////////////////////////////////////////////////////
// Copyright (C) 2020 Edouard Griffiths, F4EXB <f4exb06@gmail.com> //
// //
// This program is free software; you can redistribute it and/or modify //
// it under the terms of the GNU General Public License as published by //
// the Free Software Foundation as version 3 of the License, or //
// (at your option) any later version. //
// //
// This program is distributed in the hope that it will be useful, //
// but WITHOUT ANY WARRANTY; without even the implied warranty of //
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //
// GNU General Public License V3 for more details. //
// //
// You should have received a copy of the GNU General Public License //
// along with this program. If not, see <http://www.gnu.org/licenses/>. //
///////////////////////////////////////////////////////////////////////////////////
#include <QDebug>
#include "meshtasticmodsource.h"
const int MeshtasticModSource::m_levelNbSamples = 480; // every 10ms
MeshtasticModSource::MeshtasticModSource() :
m_channelSampleRate(48000),
m_channelFrequencyOffset(0),
m_phaseIncrements(nullptr),
m_repeatCount(0),
m_active(false),
m_modPhasor(0.0f),
m_levelCalcCount(0),
m_peakLevel(0.0f),
m_levelSum(0.0f)
{
m_magsq = 0.0;
initSF(m_settings.m_spreadFactor);
initTest(m_settings.m_spreadFactor, m_settings.m_deBits);
reset();
applySettings(m_settings, true);
applyChannelSettings(m_channelSampleRate, m_channelFrequencyOffset, true);
}
MeshtasticModSource::~MeshtasticModSource()
{
delete[] m_phaseIncrements;
}
void MeshtasticModSource::initSF(unsigned int sf)
{
m_fftLength = 1 << sf;
m_state = ChirpChatStateIdle;
m_quarterSamples = (m_fftLength/4)*MeshtasticModSettings::oversampling;
float halfAngle = M_PI/MeshtasticModSettings::oversampling;
float phase = -halfAngle;
if (m_phaseIncrements) {
delete[] m_phaseIncrements;
}
m_phaseIncrements = new double[2*m_fftLength*MeshtasticModSettings::oversampling];
phase = -halfAngle;
for (unsigned int i = 0; i < m_fftLength*MeshtasticModSettings::oversampling; i++)
{
m_phaseIncrements[i] = phase;
phase += (2*halfAngle) / (m_fftLength*MeshtasticModSettings::oversampling);
}
std::copy(
m_phaseIncrements,
m_phaseIncrements+m_fftLength*MeshtasticModSettings::oversampling,
m_phaseIncrements+m_fftLength*MeshtasticModSettings::oversampling
);
}
void MeshtasticModSource::initTest(unsigned int sf, unsigned int deBits)
{
unsigned int fftLength = 1<<sf;
unsigned int symbolRange = fftLength/(1<<deBits);
m_symbols.clear();
for (unsigned int seq = 0; seq < 1; seq++)
{
for (unsigned int symbol = 0; symbol < symbolRange; symbol += symbolRange/4)
{
m_symbols.push_back(symbol);
m_symbols.push_back(symbol+1);
}
}
}
void MeshtasticModSource::reset()
{
m_chirp = 0;
m_chirp0 = 0;
m_sampleCounter = 0;
m_fftCounter = 0;
m_chirpCount = 0;
}
void MeshtasticModSource::pull(SampleVector::iterator begin, unsigned int nbSamples)
{
std::for_each(
begin,
begin + nbSamples,
[this](Sample& s) {
pullOne(s);
}
);
}
void MeshtasticModSource::pullOne(Sample& sample)
{
if (m_settings.m_channelMute)
{
sample.m_real = 0.0f;
sample.m_imag = 0.0f;
m_magsq = 0.0;
return;
}
Complex ci;
if (m_interpolatorDistance > 1.0f) // decimate
{
modulateSample();
while (!m_interpolator.decimate(&m_interpolatorDistanceRemain, m_modSample, &ci))
{
modulateSample();
}
}
else
{
if (m_interpolator.interpolate(&m_interpolatorDistanceRemain, m_modSample, &ci))
{
modulateSample();
}
}
m_interpolatorDistanceRemain += m_interpolatorDistance;
ci *= m_carrierNco.nextIQ(); // shift to carrier frequency
if (!(m_state == ChirpChatStateIdle))
{
double magsq = std::norm(ci);
magsq /= (SDR_TX_SCALED*SDR_TX_SCALED);
m_movingAverage(magsq);
m_magsq = m_movingAverage.asDouble();
}
sample.m_real = (FixReal) ci.real();
sample.m_imag = (FixReal) ci.imag();
}
void MeshtasticModSource::modulateSample()
{
if (m_state == ChirpChatStateIdle)
{
m_modSample = Complex{0.0, 0.0};
m_sampleCounter++;
if (m_sampleCounter == m_quietSamples*MeshtasticModSettings::oversampling) // done with quiet time
{
m_chirp0 = 0;
m_chirp = m_fftLength*MeshtasticModSettings::oversampling - 1;
if (m_symbols.size() != 0) // some payload to transmit
{
if (m_settings.m_messageRepeat == 0) // infinite
{
m_state = ChirpChatStatePreamble;
m_active = true;
}
else
{
if (m_repeatCount != 0)
{
m_repeatCount--;
m_state = ChirpChatStatePreamble;
m_active = true;
}
else
{
m_active = false;
}
}
}
else
{
m_active = false;
}
}
}
else if (m_state == ChirpChatStatePreamble)
{
m_modPhasor += (m_settings.m_invertRamps ? -1 : 1) * m_phaseIncrements[m_chirp]; // preamble chirps
m_modSample = Complex(std::polar(0.891235351562 * SDR_TX_SCALED, m_modPhasor));
m_fftCounter++;
if (m_fftCounter == m_fftLength*MeshtasticModSettings::oversampling)
{
m_chirpCount++;
m_fftCounter = 0;
if (m_chirpCount == m_settings.m_preambleChirps)
{
m_chirpCount = 0;
if (m_settings.hasSyncWord())
{
m_chirp0 = ((m_settings.m_syncWord >> ((1-m_chirpCount)*4)) & 0xf)*8;
m_chirp = (m_chirp0 + m_fftLength)*MeshtasticModSettings::oversampling - 1;
m_state = ChirpChatStateSyncWord;
}
else
{
m_sampleCounter = 0;
m_chirp0 = 0;
m_chirp = m_fftLength*MeshtasticModSettings::oversampling - 1;
m_state = ChirpChatStateSFD;
}
}
}
}
else if (m_state == ChirpChatStateSyncWord)
{
m_modPhasor += (m_settings.m_invertRamps ? -1 : 1) * m_phaseIncrements[m_chirp]; // sync chirps same orientation as preamble
m_modSample = Complex(std::polar(0.891235351562 * SDR_TX_SCALED, m_modPhasor));
m_fftCounter++;
if (m_fftCounter == m_fftLength*MeshtasticModSettings::oversampling)
{
m_chirpCount++;
m_chirp0 = ((m_settings.m_syncWord >> ((1-m_chirpCount)*4)) & 0xf)*8;
m_chirp = (m_chirp0 + m_fftLength)*MeshtasticModSettings::oversampling - 1;
m_fftCounter = 0;
if (m_chirpCount == 2)
{
m_sampleCounter = 0;
m_chirpCount = 0;
m_chirp0 = 0;
m_chirp = m_fftLength*MeshtasticModSettings::oversampling - 1;
m_state = ChirpChatStateSFD;
}
}
}
else if (m_state == ChirpChatStateSFD)
{
m_modPhasor -= (m_settings.m_invertRamps ? -1 : 1) * m_phaseIncrements[m_chirp]; // SFD chirps
m_modSample = Complex(std::polar(0.891235351562 * SDR_TX_SCALED, m_modPhasor));
m_fftCounter++;
m_sampleCounter++;
if (m_fftCounter == m_fftLength*MeshtasticModSettings::oversampling)
{
m_chirp0 = 0;
m_chirp = m_fftLength*MeshtasticModSettings::oversampling - 1;
m_fftCounter = 0;
}
if (m_sampleCounter == m_quarterSamples)
{
m_chirpCount++;
m_sampleCounter = 0;
}
if (m_chirpCount == m_settings.getNbSFDFourths())
{
m_fftCounter = 0;
m_chirpCount = 0;
m_chirp0 = encodeSymbol(m_symbols[m_chirpCount]);
m_chirp = (m_chirp0 + m_fftLength)*MeshtasticModSettings::oversampling - 1;
m_state = ChirpChatStatePayload;
}
}
else if (m_state == ChirpChatStatePayload)
{
m_modPhasor += (m_settings.m_invertRamps ? -1 : 1) * m_phaseIncrements[m_chirp]; // payload chirps
m_modSample = Complex(std::polar(0.891235351562 * SDR_TX_SCALED, m_modPhasor));
m_fftCounter++;
if (m_fftCounter == m_fftLength*MeshtasticModSettings::oversampling)
{
m_chirpCount++;
if (m_chirpCount == m_symbols.size())
{
reset();
m_state = ChirpChatStateIdle;
}
else
{
m_chirp0 = encodeSymbol(m_symbols[m_chirpCount]);
m_chirp = (m_chirp0 + m_fftLength)*MeshtasticModSettings::oversampling - 1;
m_fftCounter = 0;
}
}
}
// limit phasor range to ]-pi,pi]
if (m_modPhasor > M_PI) {
m_modPhasor -= (2.0f * M_PI);
}
m_chirp++;
if (m_chirp >= (m_chirp0 + m_fftLength)*MeshtasticModSettings::oversampling) {
m_chirp = m_chirp0*MeshtasticModSettings::oversampling;
}
}
unsigned short MeshtasticModSource::encodeSymbol(unsigned short symbol)
{
if (m_settings.m_deBits == 0) {
return symbol;
}
unsigned int deWidth = 1<<m_settings.m_deBits;
unsigned int baseSymbol = symbol % (m_fftLength/deWidth); // symbols range control
return deWidth*baseSymbol;
// return deWidth*baseSymbol + (deWidth/2) - 1;
}
void MeshtasticModSource::calculateLevel(Real& sample)
{
if (m_levelCalcCount < m_levelNbSamples)
{
m_peakLevel = std::max(std::fabs(m_peakLevel), sample);
m_levelSum += sample * sample;
m_levelCalcCount++;
}
else
{
m_rmsLevel = sqrt(m_levelSum / m_levelNbSamples);
m_peakLevelOut = m_peakLevel;
m_peakLevel = 0.0f;
m_levelSum = 0.0f;
m_levelCalcCount = 0;
}
}
void MeshtasticModSource::applySettings(const MeshtasticModSettings& settings, bool force)
{
if ((settings.m_spreadFactor != m_settings.m_spreadFactor)
|| (settings.m_deBits != m_settings.m_deBits)
|| (settings.m_preambleChirps != m_settings.m_preambleChirps)|| force)
{
initSF(settings.m_spreadFactor);
initTest(settings.m_spreadFactor, settings.m_deBits);
reset();
}
if ((settings.m_quietMillis != m_settings.m_quietMillis) || force)
{
m_quietSamples = (m_bandwidth*settings.m_quietMillis) / 1000;
reset();
}
if ((settings.m_messageRepeat != m_settings.m_messageRepeat) || force) {
m_repeatCount = settings.m_messageRepeat;
}
m_settings = settings;
}
void MeshtasticModSource::applyChannelSettings(int channelSampleRate, int bandwidth, int channelFrequencyOffset, bool force)
{
qDebug() << "MeshtasticModSource::applyChannelSettings:"
<< " channelSampleRate: " << channelSampleRate
<< " channelFrequencyOffset: " << channelFrequencyOffset
<< " bandwidth: " << bandwidth
<< " SR: " << bandwidth * MeshtasticModSettings::oversampling;
if ((channelFrequencyOffset != m_channelFrequencyOffset)
|| (channelSampleRate != m_channelSampleRate) || force)
{
m_carrierNco.setFreq(channelFrequencyOffset, channelSampleRate);
}
if ((channelSampleRate != m_channelSampleRate)
|| (bandwidth != m_bandwidth) || force)
{
m_interpolatorDistanceRemain = 0;
m_interpolatorConsumed = false;
m_interpolatorDistance = (Real) (bandwidth*MeshtasticModSettings::oversampling) / (Real) channelSampleRate;
m_interpolator.create(16, bandwidth, bandwidth / 2.2);
}
m_channelSampleRate = channelSampleRate;
m_channelFrequencyOffset = channelFrequencyOffset;
m_bandwidth = bandwidth;
m_quietSamples = (bandwidth*m_settings.m_quietMillis) / 1000;
m_state = ChirpChatStateIdle;
reset();
}
void MeshtasticModSource::setSymbols(const std::vector<unsigned short>& symbols)
{
m_symbols = symbols;
qDebug("MeshtasticModSource::setSymbols: m_symbols: %lu", m_symbols.size());
m_repeatCount = m_settings.m_messageRepeat;
m_state = ChirpChatStateIdle; // first reset to idle
reset();
m_sampleCounter = m_quietSamples*MeshtasticModSettings::oversampling - 1; // start immediately
}

112
plugins/channeltx/modmeshtastic/meshtasticmodsource.h

@ -0,0 +1,112 @@ @@ -0,0 +1,112 @@
///////////////////////////////////////////////////////////////////////////////////
// Copyright (C) 2019-2020 Edouard Griffiths, F4EXB <f4exb06@gmail.com> //
// //
// This program is free software; you can redistribute it and/or modify //
// it under the terms of the GNU General Public License as published by //
// the Free Software Foundation as version 3 of the License, or //
// (at your option) any later version. //
// //
// This program is distributed in the hope that it will be useful, //
// but WITHOUT ANY WARRANTY; without even the implied warranty of //
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //
// GNU General Public License V3 for more details. //
// //
// You should have received a copy of the GNU General Public License //
// along with this program. If not, see <http://www.gnu.org/licenses/>. //
///////////////////////////////////////////////////////////////////////////////////
#ifndef INCLUDE_MESHTASTICMODSOURCE_H
#define INCLUDE_MESHTASTICMODSOURCE_H
#include <QMutex>
#include "dsp/channelsamplesource.h"
#include "dsp/nco.h"
#include "dsp/interpolator.h"
#include "dsp/firfilter.h"
#include "util/movingaverage.h"
#include "meshtasticmodsettings.h"
class MeshtasticModSource : public ChannelSampleSource
{
public:
MeshtasticModSource();
virtual ~MeshtasticModSource();
virtual void pull(SampleVector::iterator begin, unsigned int nbSamples);
virtual void pullOne(Sample& sample);
virtual void prefetch(unsigned int nbSamples) { (void) nbSamples; }
double getMagSq() const { return m_magsq; }
void getLevels(qreal& rmsLevel, qreal& peakLevel, int& numSamples) const
{
rmsLevel = m_rmsLevel;
peakLevel = m_peakLevelOut;
numSamples = m_levelNbSamples;
}
void applySettings(const MeshtasticModSettings& settings, bool force = false);
void applyChannelSettings(int channelSampleRate, int bandwidth, int channelFrequencyOffset, bool force = false);
void setSymbols(const std::vector<unsigned short>& symbols);
bool getActive() const { return m_active; }
private:
enum ChirpChatState
{
ChirpChatStateIdle, //!< Quiet time
ChirpChatStatePreamble, //!< Transmit preamble
ChirpChatStateSyncWord, //!< Transmit sync word
ChirpChatStateSFD, //!< Transmit SFD
ChirpChatStatePayload //!< Tramsmoit payload
};
int m_channelSampleRate;
int m_channelFrequencyOffset;
int m_bandwidth;
MeshtasticModSettings m_settings;
ChirpChatState m_state;
double *m_phaseIncrements;
std::vector<unsigned short> m_symbols;
unsigned int m_fftLength; //!< chirp length in samples
unsigned int m_chirp; //!< actual chirp index in chirps table
unsigned int m_chirp0; //!< half index of chirp start in chirps table
unsigned int m_sampleCounter; //!< actual sample counter
unsigned int m_fftCounter; //!< chirp sample counter
unsigned int m_chirpCount; //!< chirp or quarter chirp counter
unsigned int m_quietSamples; //!< number of samples during quiet period
unsigned int m_quarterSamples; //!< number of samples in a quarter chirp
unsigned int m_repeatCount; //!< message repetition counter
bool m_active; //!< modulator is in a sending sequence (including periodic quiet times)
NCO m_carrierNco;
double m_modPhasor; //!< baseband modulator phasor
Complex m_modSample;
Interpolator m_interpolator;
Real m_interpolatorDistance;
Real m_interpolatorDistanceRemain;
bool m_interpolatorConsumed;
Bandpass<Real> m_bandpass;
double m_magsq;
MovingAverageUtil<double, double, 16> m_movingAverage;
quint32 m_levelCalcCount;
qreal m_rmsLevel;
qreal m_peakLevelOut;
Real m_peakLevel;
Real m_levelSum;
static const int m_levelNbSamples;
void initSF(unsigned int sf); //!< Init tables, FFTs, depending on spread factor
void initTest(unsigned int sf, unsigned int deBits);
void reset();
void calculateLevel(Real& sample);
void modulateSample();
unsigned short encodeSymbol(unsigned short symbol); //!< Encodes symbol with possible DE bits spacing
};
#endif // INCLUDE_MESHTASTICMODSOURCE_H

52
plugins/channeltx/modmeshtastic/meshtasticmodwebapiadapter.cpp

@ -0,0 +1,52 @@ @@ -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 <f4exb06@gmail.com> //
// //
// This program is free software; you can redistribute it and/or modify //
// it under the terms of the GNU General Public License as published by //
// the Free Software Foundation as version 3 of the License, or //
// (at your option) any later version. //
// //
// This program is distributed in the hope that it will be useful, //
// but WITHOUT ANY WARRANTY; without even the implied warranty of //
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //
// GNU General Public License V3 for more details. //
// //
// You should have received a copy of the GNU General Public License //
// along with this program. If not, see <http://www.gnu.org/licenses/>. //
///////////////////////////////////////////////////////////////////////////////////
#include "SWGChannelSettings.h"
#include "meshtasticmod.h"
#include "meshtasticmodwebapiadapter.h"
MeshtasticModWebAPIAdapter::MeshtasticModWebAPIAdapter()
{}
MeshtasticModWebAPIAdapter::~MeshtasticModWebAPIAdapter()
{}
int MeshtasticModWebAPIAdapter::webapiSettingsGet(
SWGSDRangel::SWGChannelSettings& response,
QString& errorMessage)
{
(void) errorMessage;
response.setChirpChatModSettings(new SWGSDRangel::SWGChirpChatModSettings());
response.getChirpChatModSettings()->init();
MeshtasticMod::webapiFormatChannelSettings(response, m_settings);
return 200;
}
int MeshtasticModWebAPIAdapter::webapiSettingsPutPatch(
bool force,
const QStringList& channelSettingsKeys,
SWGSDRangel::SWGChannelSettings& response,
QString& errorMessage)
{
(void) force; // no action
(void) errorMessage;
MeshtasticMod::webapiUpdateChannelSettings(m_settings, channelSettingsKeys, response);
MeshtasticMod::webapiFormatChannelSettings(response, m_settings);
return 200;
}

49
plugins/channeltx/modmeshtastic/meshtasticmodwebapiadapter.h

@ -0,0 +1,49 @@ @@ -0,0 +1,49 @@
///////////////////////////////////////////////////////////////////////////////////
// Copyright (C) 2019-2020 Edouard Griffiths, F4EXB <f4exb06@gmail.com> //
// //
// This program is free software; you can redistribute it and/or modify //
// it under the terms of the GNU General Public License as published by //
// the Free Software Foundation as version 3 of the License, or //
// (at your option) any later version. //
// //
// This program is distributed in the hope that it will be useful, //
// but WITHOUT ANY WARRANTY; without even the implied warranty of //
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //
// GNU General Public License V3 for more details. //
// //
// You should have received a copy of the GNU General Public License //
// along with this program. If not, see <http://www.gnu.org/licenses/>. //
///////////////////////////////////////////////////////////////////////////////////
#ifndef INCLUDE_MESHTASTICMOD_WEBAPIADAPTER_H
#define INCLUDE_MESHTASTICMOD_WEBAPIADAPTER_H
#include "channel/channelwebapiadapter.h"
#include "meshtasticmodsettings.h"
/**
* Standalone API adapter only for the settings
*/
class MeshtasticModWebAPIAdapter : public ChannelWebAPIAdapter {
public:
MeshtasticModWebAPIAdapter();
virtual ~MeshtasticModWebAPIAdapter();
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:
MeshtasticModSettings m_settings;
};
#endif // INCLUDE_LORAMOD_WEBAPIADAPTER_H

272
plugins/channeltx/modmeshtastic/readme.md

@ -0,0 +1,272 @@ @@ -0,0 +1,272 @@
<h1>Meshtastic modulator plugin</h1>
<h2>Introduction</h2>
This plugin can be used to code and modulate a transmission signal based on Chirp Spread Spectrum (CSS). The basic idea is to transform each symbol of a MFSK modulation to an ascending frequency ramp shifted in time. It could equally be a descending ramp but this one is reserved to detect a break in the preamble sequence (synchronization). This plugin has been designed to work in conjunction with the ChirpChat demodulator plugin that should be used ideally on the reception side.
It has clearly been inspired by the LoRa technique but is designed for experimentation and extension to other protocols mostly inspired by amateur radio techniques using chirp modulation to transmit symbols. Thanks to the MFSK to chirp translation it is possible to adapt any MFSK based mode.
LoRa is a property of Semtech and the details of the protocol are not made public. However a LoRa compatible protocol has been implemented based on the reverse engineering performed by the community. It is mainly based on the work done in https://github.com/myriadrf/LoRa-SDR. You can find more information about LoRa and chirp modulation here:
- To get an idea of what is LoRa: [here](https://www.link-labs.com/blog/what-is-lora)
- A detailed inspection of LoRa modulation and protocol: [here](https://static1.squarespace.com/static/54cecce7e4b054df1848b5f9/t/57489e6e07eaa0105215dc6c/1464376943218/Reversing-Lora-Knight.pdf)
This LoRa encoder is designed for experimentation. For production grade applications it is recommended to use dedicated hardware instead.
Modulation characteristics from LoRa have been augmented with more bandwidths and FFT bin collations (DE factor). Plain TTY and ASCII have also been added that match character value to symbols directly. The FT protocol used in FT8 and FT4 is introduced packing the 174 bits payload into (SF -DE) bits symbols. There are plans to add some more of these typically amateur radio MFSK based modes like JT65.
<h2>Meshtastic frame mode</h2>
In LoRa coding mode, if the message text starts with `MESH:` the plugin will build a full Meshtastic over-the-air frame (16-byte header + protobuf `Data` payload) and encrypt it with AES-CTR when enabled.
Quick example (Text mode):
`MESH:from=0x11223344;to=0xffffffff;id=0x1234;channel_name=LongFast;key=default;port=TEXT;text=hello mesh;want_ack=1;hop_limit=3`
Supported fields:
- Header: `to`, `from`, `id`, `hop_limit`, `hop_start`, `want_ack`, `via_mqtt`, `channel_hash` (or `channel`), `channel_name`, `next_hop`, `relay_node`
- Preset helper: `preset` / `modem_preset` (`LONG_FAST`, `LONG_SLOW`, `LONG_TURBO`, `LONG_MODERATE`, `MEDIUM_FAST`, `MEDIUM_SLOW`, `SHORT_FAST`, `SHORT_SLOW`, `SHORT_TURBO`) maps to channel naming/hash defaults
- Radio planner: `region`, `channel_num`, `frequency`/`freq`/`freq_hz`, `frequency_offset`/`frequency_offset_hz`
- Data protobuf: `port`/`portnum`, `text`, `payload_hex`, `payload_base64`/`payload_b64`, `want_response`, `dest`, `source`, `request_id`, `reply_id`, `emoji`, `bitfield`
- Crypto: `key`/`psk` (`default`, `none`, `simple0..10`, `hex:<...>`, `base64:<...>`), `encrypt` (`true|false|auto`)
Notes:
- If `encrypt=true` then `key` must resolve to 16 or 32 bytes.
- If `channel_hash` is not provided, it is derived from `channel_name` and `key` using Meshtastic hash rules.
- In GUI mode, when the active message is a valid `MESH:` command, the plugin auto-applies LoRa settings (`BW/SF/CR/DE`, `syncword=0x2B`) from `modem_preset`.
- If `region` (+ optional `channel_num`) or explicit `frequency` is present, GUI mode also auto-centers the channel when device center frequency is known.
- If a `MESH:` command is invalid it is rejected (no payload is emitted), and an error is logged.
<h2>Interface</h2>
The top and bottom bars of the channel window are described [here](../../../sdrgui/channel/readme.md)
![Meshtastic Modulator plugin GUI](../../../doc/img/MeshtasticMod_plugin.png)
<h3>1: Frequency shift from center frequency of reception</h3>
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.
<h3>2: Channel power</h3>
The signal is frequency modulated with a constant envelope hence this value should be constant. To prevent possible overshoots the signal is reduced by 1 dB from the full scale. Thus this should always display `-1 dB`.
<h3>3: Channel mute</h3>
Use this button to mute/unmute transmission.
<h3>4: Bandwidth</h3>
This is the bandwidth of the ChirpChat signal. Similarly to LoRa the signal sweeps between the lower and the upper frequency of this bandwidth. The sample rate of the ChirpChat signal in seconds is exactly one over this bandwidth in Hertz.
In the LoRa standard there are 2 base bandwidths: 500 and 333.333 kHz. A 400 kHz base has been added. Possible bandwidths are obtained by a division of these base bandwidths by a power of two from 1 to 64. Extra divisor of 128 is provided to achieve smaller bandwidths that can fit in a SSB channel. Finally special divisors from a 384 kHz base are provided to allow even more narrow bandwidths.
Thus available bandwidths are:
- **500000** (500000 / 1) Hz
- **400000** (400000 / 1) Hz not in LoRa standard
- **333333** (333333 / 1) Hz
- **250000** (500000 / 2) Hz
- **200000** (400000 / 2) Hz not in LoRa standard
- **166667** (333333 / 2) Hz
- **125000** (500000 / 4) Hz
- **100000** (400000 / 4) Hz not in LoRa standard
- **83333** (333333 / 4) Hz
- **62500** (500000 / 8) Hz
- **50000** (400000 / 8) Hz not in LoRa standard
- **41667** (333333 / 8) Hz
- **31250** (500000 / 16) Hz
- **25000** (400000 / 16) Hz not in LoRa standard
- **20833** (333333 / 16) Hz
- **15625** (500000 / 32) Hz
- **12500** (400000 / 32) Hz not in LoRa standard
- **10417** (333333 / 32) Hz
- **7813** (500000 / 64) Hz
- **6250** (400000 / 64) Hz not in LoRa standard
- **5208** (333333 / 64) Hz
- **3906** (500000 / 128) Hz not in LoRa standard
- **3125** (400000 / 128) Hz not in LoRa standard
- **2604** (333333 / 128) Hz not in LoRa standard
- **1500** (384000 / 256) Hz not in LoRa standard
- **750** (384000 / 512) Hz not in LoRa standard
- **488** (500000 / 1024) Hz not in LoRa standard
- **375** (384000 / 1024) Hz not in LoRa standard
The ChirpChat signal is oversampled by four therefore it needs a baseband of at least four times the bandwidth. This drives the maximum value on the slider automatically.
<h3>16: Invert chirp ramps</h3>
The LoRa standard is up-chirps for the preamble, down-chirps for the SFD and up-chirps for the payload.
When you check this option it inverts the direction of the chirps thus becoming down-chirps for the preamble, up-chirps for the SFD and down-chirps for the payload.
<h3>5: Spread Factor</h3>
This is the Spread Factor parameter of the ChirpChat signal. This is the log2 of the possible frequency shifts used over the bandwidth (3). The number of symbols is 2<sup>SF-DE</sup> where SF is the spread factor and DE the Distance Enhancement factor (6).
<h3>6: Distance Enhancement factor</h3>
The LoRa standard specifies 0 (no DE) or 2 (DE active). The ChirpChat range is extended to all values between 0 and 4 bits.
The LoRa standard also specifies that the LowDataRateOptimization flag (thus DE=2 vs DE=0 here) should be set when the symbol time defined as BW / 2^SF exceeds 16 ms (See section 4.1.1.6 of the SX127x datasheet). In practice this happens for SF=11 and SF=12 and large enough bandwidths (you can do the maths).
Here this value is the log2 of the number of frequency shifts separating two consecutive shifts that represent a symbol. On the receiving side this decreases the probability to detect the wrong symbol as an adjacent FFT bin. It can also overcome frequency or sampling time drift on long messages particularly for small bandwidths.
In practice it is difficult on the Rx side to make correct decodes if only one FFT bin is used to code one symbol (DE=0). It is therefore recommended to use a factor of 1 or more.
<h3>8: Number of preamble chirps</h3>
This is the number of preamble chirps to transmit that are used for the Rx to synchronize. The LoRa standard specifies it can be between 2 and 65535. Here it is limited to the 4 to 20 range that corresponds to realistic values. The RN2483 uses 6 preamble chirps. You may use 12 preamble chirps or more to facilitate signal acquisition with poor SNR on the Rx side.
<h3>9: Idle time between transmissions</h3>
When sending a message repeatedly this is the time between the end of one transmission and the start of the next transmission.
<h3>10: Message and encoding details</h3>
![Meshtastic Modulator plugin GUI](../../../doc/img/MeshtasticMod_payload.png)
ChirpChat is primarily designed to make QSOs in the amateur radio sense. To be efficient the messages have to be kept short and minimal therefore the standard exchange follows WSJT scheme and is reflected in the sequence of messages you can follow with the message selection combo (10.9): CQ, Reply to CQ, Report to callee, Report to caller (R-Report), RRR and 73.
To populate messages you can specify your callsign (10.5), the other party callsign (10.6), your QRA locator (10.7) and a signal report (10.8)
<h4>10.1: Modulation scheme</h4>
- **LoRa**: LoRa compatible
- **ASCII**: 7 bit plain ASCII without FEC and CRC. Requires exactly 7 bit effective samples thus SF-DE = 7 where SF is the spreading factor (5) and DE the distance enhancement factor (6)
- **TTY**: 5 bit Baudot (Teletype) without FEC and CRC. Requires exactly 5 bit effective samples thus SF-DE = 5 where SF is the spreading factor (5) and DE the distance enhancement factor (6)
- **FT**: FT8/FT4 coding is applied using data in (10.5) to (10.8) to encode the 174 bit message payload with CRC and FEC as per FT8/FT4 protocol using a type 1 (standard) type of message. Note that the report (10.8) must comply with the FT rule (coded "-35" to "+99" with a leading 0 for the number) and would usually represent the integer part of the S/N ratio in the ChirpChat demodulator receiver. Calls should not be prefixed nor suffixed and the first 4 characters of the locator must represent a valid 4 character grid square. Plain text messages (13 characters) are also supported with the 0.0 type of message using the text entered in the message box (11). These 174 bits are packed into (SF - DE) bits symbols padded with zero bits if necessary. For the details of the FT protocol see: https://wsjt.sourceforge.io/FT4_FT8_QEX.pdf For example for SF=9 and DE=3 we have 6 bits per symbols so the 174 bits are packed in exactly 29 symbols this should appear in the message length ML (13)
<h4>10.2: Number of FEC parity bits (LoRa)</h4>
This is a LoRa specific feature. Each byte of the payload is split into two four bit nibbles and Hamming code of various "strength" in number of parity bits can be applied to these nibbles. The number of parity bits can vary from 1 to 4. 0 (no FEC) has been added but is not part of the LoRa original standard:
- **0**: no FEC
- **1**: 1 bit parity thus Hamming H(4,5) applies
- **2**: 2 bit parity thus Hamming H(4,6) applies
- **3**: 3 bit parity thus Hamming H(4,7) applies
- **4**: 4 bit parity thus Hamming H(4,8) applies
<h4>10.3: Append two byte CRC to payload (LoRa)</h4>
This is a LoRa specific feature. A 2 bytes CRC can be appended to the payload.
<h4>10.4: Send a header at the start of the payload (LoRa)</h4>
This is a LoRa specific feature and is also known as explicit (with header) or implicit (without header) modes. In explicit mode a header with net payload length in bytes, presence of a CRC and number of parity bits is prepended to the actual payload. This header has a 1 byte CRC and is coded with H(4,8) FEC.
<h4>10.5: My callsign (QSO mode)</h4>
Enter your callsign so it can populate message placeholders (See next)
<h4>10.6: Your callsign (QSO mode)</h4>
Enter the other party callsign so it can populate message placeholders (See next)
<h4>10.7: My locator (QSO mode)</h4>
Enter your Maidenhead QRA locator so it can populate message placeholders (See next)
<h4>10.8: My report (QSO mode)</h4>
Enter the signal report you will send to the other party so it can populate message placeholders (See next)
<h4>10.9: Message selector</h4>
This lets you choose which pre-formatted message to send:
- **None**: empty message. In fact this is used to make a transition to trigger sending of the same message again. It is used internally by the "play" button (11) and can be used with the REST API.
- **Beacon**: a beacon message
- **CQ**: (QSO mode) CQ general call message
- **Reply**: (QSO mode) reply to a CQ call
- **Report**: (QSO mode) signal report to the callee of a CQ call
- **R-Report**: (QSO mode) signal report to the caller of a CQ call
- **RRR**: (QSO mode) report received confirmation to the callee
- **73**: (QSO mode) confirmation back to the caller and closing the QSO
- **QSO text**: (QSO mode) free form message with callsigns
- **Text**: plain text
- **Bytes**: binary message in the form of a string of bytes. Use the hex window (12) to specify the message
In FT mode standard FT type messages are generated regardless of placeholders based on MyCall, YourCall, MyLoc, Report and Msg data (entered while in "Text" format). Locators are 4 character grids i.e. only the 4 first characters are taken. Reports must be valid FT reports from -35 to 99 coded as < sign>< zero padded value> (e.g -12, -04, +00, +04, +12) :
- **Beacon**: DE < MyCall > < MyLoc >
- **CQ**: CQ < MyCall> < MyLoc >
- **Reply**: < YourCall > < MyCall > < MyLoc >
- **Report**: < YourCall > < MyCall > < Report >
- **R-Report**: < YourCall > < MyCall > R< Report >
- **RRR**: < YourCall > < MyCall > RRR
- **73**: < YourCall > < MyCall > 73
- **QSO text**: < Msg >
- **Text**: < Msg >
- **Bytes**: < Msg >
<h4>10.10: Revert to standard messages</h4>
Reformat all predefined messages in standard messages with placeholders. The Generate button (13) replaces the placeholders with the given QSO elements (10.5 to 10.8)
- **Beacon**: `VVV DE %1 %2`
- **CQ**: `CQ DE %1 %2`
- **Reply**: `%1 %2 %3`
- **Report**: `%1 %2 %3`
- **R-Reply**: `%1 %2 R%3`
- **RRR**: `%1 %2 RRR`
- **73**: `%1 %2 73`
- **QSO text**: `%1 %2 %3`
<h4>10.11 Play current message immediately</h4>
This starts playing the current selected message immediately. It may be necessary to use this button after a change of modulation and/or coding parameters.
<h4>10.12: Number of message repetitions</h4>
The message is repeated this number of times (use 0 for infinite). The end of one message sequence and the start of the next is separated by the delay specified with the "Idle" slidebar (9)
<h4>10.13: Generate messages</h4>
This applies the QSO elements (10.5 to 10.8) to the placeholders in messages to generate the final messages:
- **Beacon**: `VVV DE %1 %2`: `%1` is my call (10.5) and `%2` is my locator (10.7)
- **CQ**: `CQ DE %1 %2`: `%1` is my call (10.5) and `%2` is my locator (10.7)
- **Reply**: `%1 %2 %3`: `%1` is your call (10.6), `%2` is my call (10.5) and `%3` is my locator (10.7)
- **Report**: `%1 %2 %3`: `%1` is your call (10.6), `%2` is my call (10.5) and `%3` is my report (10.8)
- **R-Reply**: `%1 %2 R%3`: `%1` is your call (10.6), `%2` is my call (10.5) and `%3` is my report (10.8)
- **RRR**: `%1 %2 RRR`: `%1` is your call (10.6) and `%2` is my call (10.5)
- **73**: `%1 %2 73`: `%1` is your call (10.6) and `%2` is my call (10.5)
- **QSO text**: `%1 %2 %3`: `%1` is your call (10.6), `%2` is my call (10.5) and `%3` is the text specified as the free form text message
<h4>10.14: Sync word</h4>
This is a LoRa specific feature and is the sync word (byte) to transmit entered as a 2 nibble hexadecimal number.
<h3>11: Message text</h3>
This window lets you edit the message selected in (10.9). You can use `%n` placeholders that depend on the type of message selected.
- **Beacon**: `%1` is my callsign and `%2` is my locator
- **CQ message**: `%1` is my callsign and `%2` is my locator
- **Reply**: `%1` is the other callsign, `%2` is my callsign and `%3` is my locator
- **Report**: `%1` is the other callsign, `%2` is my callsign and `%3` is my report
- **R-Report**: `%1` is the other callsign, `%2` is my callsign and `%3` is my report
- **RRR**: `%1` is the other callsign and `%2` is my callsign
- **73**: `%1` is the other callsign and `%2` is my callsign
- **QSO Text**: `%1` is the other callsign, `%2` is my callsign and `%3` is the free text message
- **Text**: free text message no placeholders
- **Bytes**: binary message no placeholders
<h3>12: Message bytes</h3>
Use this line editor to specify the hex string used as the bytes message.
<h3>13: Symbol time and message length</h3>
This is the duration of a symbol or chirp in milliseconds followed by the message length in the number of symbols
<h3>14: Payload time</h3>
This is the duration of the message payload in milliseconds. It excludes the preamble, the sync word and synchronization (SFD) sequence.
<h3>15: Total time</h3>
This is the duration of the full message in milliseconds.

2167
plugins/meshtasticcommon/meshtasticpacket.cpp

File diff suppressed because it is too large Load Diff

90
plugins/meshtasticcommon/meshtasticpacket.h

@ -0,0 +1,90 @@ @@ -0,0 +1,90 @@
///////////////////////////////////////////////////////////////////////////////////
// Copyright (C) 2026 //
// SPDX-License-Identifier: GPL-3.0-or-later //
///////////////////////////////////////////////////////////////////////////////////
#ifndef PLUGINS_CHIRPCHATCOMMON_MESHTASTICPACKET_H_
#define PLUGINS_CHIRPCHATCOMMON_MESHTASTICPACKET_H_
#include <QByteArray>
#include <QString>
#include <QtGlobal>
#include <QVector>
#include <stdint.h>
namespace Meshtastic
{
struct DecodeResult
{
struct Field
{
QString path;
QString value;
};
bool isFrame = false;
bool dataDecoded = false;
bool decrypted = false;
QString keyLabel;
QString summary;
QVector<Field> fields;
};
struct TxRadioSettings
{
bool hasCommand = false;
bool hasLoRaParams = false;
int bandwidthHz = 0;
int spreadFactor = 0;
int parityBits = 0; // 1..4 maps to CR 4/5 .. 4/8
int deBits = 0;
uint8_t syncWord = 0x00; // Meshtastic_SDR/gr-lora_sdr reference flow uses [0,0]
int preambleChirps = 17;
bool hasCenterFrequency = false;
qint64 centerFrequencyHz = 0;
QString summary;
};
class Packet
{
public:
static bool isCommand(const QString& text);
static bool buildFrameFromCommand(
const QString& command,
QByteArray& frame,
QString& summary,
QString& error
);
static bool decodeFrame(
const QByteArray& frame,
DecodeResult& result
);
static bool decodeFrame(
const QByteArray& frame,
DecodeResult& result,
const QString& keySpecList
);
static bool validateKeySpecList(
const QString& keySpecList,
QString& error,
int* keyCount = nullptr
);
static bool deriveTxRadioSettings(
const QString& command,
TxRadioSettings& settings,
QString& error
);
};
} // namespace Meshtastic
#endif // PLUGINS_CHIRPCHATCOMMON_MESHTASTICPACKET_H_

18
plugins/samplesource/fileinput/fileinput.cpp

@ -292,15 +292,15 @@ bool FileInput::start() @@ -292,15 +292,15 @@ bool FileInput::start()
QMutexLocker mutexLocker(&m_mutex);
qDebug() << "FileInput::start";
#ifdef ANDROID
m_inputFile.seek(0);
#else
if (m_ifstream.tellg() != (std::streampos)0)
{
m_ifstream.clear();
m_ifstream.seekg(sizeof(FileRecord::Header), std::ios::beg);
}
#endif
#ifdef ANDROID
m_inputFile.seek(0);
#else
if (m_ifstream.tellg() != (std::streampos)0)
{
m_ifstream.clear();
m_ifstream.seekg(m_dataStartPos, std::ios::beg);
}
#endif
if (!m_sampleFifo.setSize(m_settings.m_accelerationFactor * m_sampleRate * sizeof(Sample)))
{

5
plugins/samplesource/remotetcpinput/remotetcpinput.cpp

@ -228,7 +228,7 @@ bool RemoteTCPInput::handleMessage(const Message& message) @@ -228,7 +228,7 @@ bool RemoteTCPInput::handleMessage(const Message& message)
{
qDebug() << "RemoteTCPInput::handleMessage:" << message.getIdentifier();
const RemoteTCPInputTCPHandler::MsgReportConnection& report = (const RemoteTCPInputTCPHandler::MsgReportConnection&) message;
if (report.getConnected())
if (!report.getConnected())
{
qDebug() << "Disconnected - stopping DSP";
m_deviceAPI->stopDeviceEngine();
@ -444,6 +444,9 @@ void RemoteTCPInput::webapiUpdateDeviceSettings( @@ -444,6 +444,9 @@ void RemoteTCPInput::webapiUpdateDeviceSettings(
if (deviceSettingsKeys.contains("agc")) {
settings.m_agc = response.getRemoteTcpInputSettings()->getAgc() != 0;
}
if (deviceSettingsKeys.contains("gain")) {
settings.m_gain[0] = response.getRemoteTcpInputSettings()->getGain();
}
if (deviceSettingsKeys.contains("rfBW")) {
settings.m_rfBW = response.getRemoteTcpInputSettings()->getRfBw();
}

27
plugins/samplesource/remotetcpinput/remotetcpinputgui.cpp

@ -341,10 +341,12 @@ void RemoteTCPInputGui::displayEnabled() @@ -341,10 +341,12 @@ void RemoteTCPInputGui::displayEnabled()
bool enableSquelchEnable;
bool enableSquelch;
bool sdra;
bool spyServer;
if (state == DeviceAPI::StRunning)
{
sdra = m_sdra;
spyServer = m_spyServer;
remoteControl = m_remoteControl;
enableMessages = !m_iqOnly;
enableSquelchEnable = !m_iqOnly;
@ -353,6 +355,7 @@ void RemoteTCPInputGui::displayEnabled() @@ -353,6 +355,7 @@ void RemoteTCPInputGui::displayEnabled()
else
{
sdra = m_settings.m_protocol == "SDRangel";
spyServer = m_settings.m_protocol == "Spy Server";
remoteControl = m_settings.m_overrideRemoteSettings;
enableMessages = false;
enableSquelchEnable = m_settings.m_overrideRemoteSettings;
@ -371,18 +374,18 @@ void RemoteTCPInputGui::displayEnabled() @@ -371,18 +374,18 @@ void RemoteTCPInputGui::displayEnabled()
ui->channelSampleRateLabel->setEnabled(m_settings.m_channelDecimation && sdra && remoteControl);
ui->channelSampleRateUnit->setEnabled(m_settings.m_channelDecimation && sdra && remoteControl);
ui->devSampleRateLabel->setEnabled(!m_spyServer && remoteControl);
ui->devSampleRate->setEnabled(!m_spyServer && remoteControl);
ui->devSampleRateUnits->setEnabled(!m_spyServer && remoteControl);
ui->agc->setEnabled(!m_spyServer && remoteControl);
ui->rfBWLabel->setEnabled(!m_spyServer && remoteControl);
ui->rfBW->setEnabled(!m_spyServer && remoteControl);
ui->rfBWUnits->setEnabled(!m_spyServer && remoteControl);
ui->dcOffset->setEnabled(!m_spyServer && remoteControl);
ui->iqImbalance->setEnabled(!m_spyServer && remoteControl);
ui->ppm->setEnabled(!m_spyServer && remoteControl);
ui->ppmLabel->setEnabled(!m_spyServer && remoteControl);
ui->ppmText->setEnabled(!m_spyServer && remoteControl);
ui->devSampleRateLabel->setEnabled(!spyServer && remoteControl);
ui->devSampleRate->setEnabled(!spyServer && remoteControl);
ui->devSampleRateUnits->setEnabled(!spyServer && remoteControl);
ui->agc->setEnabled(!spyServer && remoteControl);
ui->rfBWLabel->setEnabled(!spyServer && remoteControl);
ui->rfBW->setEnabled(!spyServer && remoteControl);
ui->rfBWUnits->setEnabled(!spyServer && remoteControl);
ui->dcOffset->setEnabled(!spyServer && remoteControl);
ui->iqImbalance->setEnabled(!spyServer && remoteControl);
ui->ppm->setEnabled(!spyServer && remoteControl);
ui->ppmLabel->setEnabled(!spyServer && remoteControl);
ui->ppmText->setEnabled(!spyServer && remoteControl);
ui->centerFrequency->setEnabled(remoteControl);
ui->biasTee->setEnabled(remoteControl);

76
sdrbase/channel/channelwebapiutils.cpp

@ -43,6 +43,15 @@ @@ -43,6 +43,15 @@
#include "feature/featureset.h"
#include "feature/feature.h"
namespace {
QString defaultReverseAPIScheme()
{
// Keep reverse API compatibility with legacy host-only addresses.
static const char kHttpScheme[] = {'h', 't', 't', 'p', '\0'};
return QString::fromLatin1(kHttpScheme);
}
}
bool ChannelWebAPIUtils::getDeviceSettings(unsigned int deviceIndex, SWGSDRangel::SWGDeviceSettings &deviceSettingsResponse, DeviceSet *&deviceSet)
{
QString errorResponse;
@ -1170,6 +1179,73 @@ bool ChannelWebAPIUtils::getDeviceSetting(unsigned int deviceIndex, const QStrin @@ -1170,6 +1179,73 @@ bool ChannelWebAPIUtils::getDeviceSetting(unsigned int deviceIndex, const QStrin
}
}
bool ChannelWebAPIUtils::getDeviceSetting(unsigned int deviceIndex, const QString &setting, QString &value)
{
SWGSDRangel::SWGDeviceSettings deviceSettingsResponse;
DeviceSet *deviceSet;
if (getDeviceSettings(deviceIndex, deviceSettingsResponse, deviceSet))
{
QJsonObject *jsonObj = deviceSettingsResponse.asJsonObject();
bool result = WebAPIUtils::getSubObjectString(*jsonObj, setting, value);
delete jsonObj;
return result;
}
else
{
return false;
}
}
QUrl ChannelWebAPIUtils::buildChannelSettingsURL(
const QString& reverseAPIAddress,
unsigned int reverseAPIPort,
unsigned int reverseAPIDeviceIndex,
unsigned int reverseAPIChannelIndex)
{
const QString address = reverseAPIAddress.trimmed();
QUrl parsedAddress = QUrl::fromUserInput(address);
QString scheme = defaultReverseAPIScheme();
QString host = address;
if (parsedAddress.isValid() && !parsedAddress.host().isEmpty())
{
host = parsedAddress.host();
if (!parsedAddress.scheme().isEmpty()) {
scheme = parsedAddress.scheme();
}
if ((parsedAddress.port() > 0) && (parsedAddress.port() <= 65535)) {
reverseAPIPort = static_cast<unsigned int>(parsedAddress.port());
}
}
else
{
const QUrl authorityOnly = QUrl::fromUserInput(QStringLiteral("//%1").arg(address));
if (authorityOnly.isValid() && !authorityOnly.host().isEmpty())
{
host = authorityOnly.host();
if ((authorityOnly.port() > 0) && (authorityOnly.port() <= 65535)) {
reverseAPIPort = static_cast<unsigned int>(authorityOnly.port());
}
}
}
QUrl channelSettingsURL;
channelSettingsURL.setScheme(scheme);
channelSettingsURL.setHost(host);
channelSettingsURL.setPort(static_cast<int>(reverseAPIPort));
channelSettingsURL.setPath(
QString("/sdrangel/deviceset/%1/channel/%2/settings")
.arg(reverseAPIDeviceIndex)
.arg(reverseAPIChannelIndex));
return channelSettingsURL;
}
bool ChannelWebAPIUtils::getDeviceReportValue(unsigned int deviceIndex, const QString &key, QString &value)
{
SWGSDRangel::SWGDeviceReport deviceReport;

8
sdrbase/channel/channelwebapiutils.h

@ -24,6 +24,7 @@ @@ -24,6 +24,7 @@
#include <QString>
#include <QJsonArray>
#include <QTimer>
#include <QUrl>
#include "SWGDeviceSettings.h"
#include "SWGDeviceReport.h"
@ -97,6 +98,12 @@ public: @@ -97,6 +98,12 @@ public:
static bool satelliteAOS(const QString name, bool northToSouthPass, const QString &tle, QDateTime dateTime);
static bool satelliteLOS(const QString name);
static bool getDeviceSetting(unsigned int deviceIndex, const QString &setting, int &value);
static bool getDeviceSetting(unsigned int deviceIndex, const QString &setting, QString &value);
static QUrl buildChannelSettingsURL(
const QString& reverseAPIAddress,
unsigned int reverseAPIPort,
unsigned int reverseAPIDeviceIndex,
unsigned int reverseAPIChannelIndex);
static bool getDeviceReportValue(unsigned int deviceIndex, const QString &key, QString &value);
static bool getDeviceReportList(unsigned int deviceIndex, const QString &key, const QString &subKey, QList<int> &values);
static bool getDevicePosition(unsigned int deviceIndex, float& latitude, float& longitude, float& altitude);
@ -138,4 +145,3 @@ protected: @@ -138,4 +145,3 @@ protected:
};
#endif // SDRBASE_CHANNEL_CHANNELWEBAPIUTILS_H_

2
sdrbase/webapi/webapiutils.cpp

@ -37,6 +37,7 @@ const QMap<QString, QString> WebAPIUtils::m_channelURIToSettingsKey = { @@ -37,6 +37,7 @@ const QMap<QString, QString> WebAPIUtils::m_channelURIToSettingsKey = {
{"sdrangel.channel.chanalyzerng", "ChannelAnalyzerSettings"}, // remap
{"org.f4exb.sdrangelove.channel.chanalyzer", "ChannelAnalyzerSettings"}, // remap
{"sdrangel.channel.chirpchatdemod", "ChirpChatDemodSettings"},
{"sdrangel.channel.meshtasticdemod", "ChirpChatDemodSettings"}, // alias: Meshtastic uses ChirpChatDemodSettings schema
{"sdrangel.channel.modchirpchat", "ChirpChatModSettings"},
{"sdrangel.channel.demodatv", "ATVDemodSettings"},
{"sdrangel.channel.demoddatv", "DATVDemodSettings"},
@ -162,6 +163,7 @@ const QMap<QString, QString> WebAPIUtils::m_channelTypeToSettingsKey = { @@ -162,6 +163,7 @@ const QMap<QString, QString> WebAPIUtils::m_channelTypeToSettingsKey = {
{"BFMDemod", "BFMDemodSettings"},
{"ChannelAnalyzer", "ChannelAnalyzerSettings"},
{"ChirpChatDemod", "ChirpChatDemodSettings"},
{"MeshtasticDemod", "ChirpChatDemodSettings"}, // alias: Meshtastic uses ChirpChatDemodSettings schema
{"ChirpChatMod", "ChirpChatModSettings"},
{"ChannelPower", "ChannelPowerSettings"},
{"DATVDemod", "DATVDemodSettings"},

Loading…
Cancel
Save