diff options
Diffstat (limited to 'Network')
| -rwxr-xr-x | Network/Cloudlog.cpp | 174 | ||||
| -rwxr-xr-x | Network/Cloudlog.hpp | 36 | ||||
| -rwxr-xr-x | Network/FileDownload.cpp | 458 | ||||
| -rwxr-xr-x | Network/FileDownload.hpp | 108 | ||||
| -rwxr-xr-x | Network/FoxVerifier.cpp | 250 | ||||
| -rwxr-xr-x | Network/FoxVerifier.hpp | 126 | ||||
| -rwxr-xr-x | Network/LotWUsers.cpp | 392 | ||||
| -rwxr-xr-x | Network/LotWUsers.hpp | 84 | ||||
| -rwxr-xr-x | Network/MessageClient.cpp | 1358 | ||||
| -rwxr-xr-x | Network/MessageClient.hpp | 287 | ||||
| -rwxr-xr-x | Network/Network.pri | 42 | ||||
| -rwxr-xr-x | Network/NetworkAccessManager.cpp | 124 | ||||
| -rwxr-xr-x | Network/NetworkAccessManager.hpp | 68 | ||||
| -rwxr-xr-x | Network/NetworkMessage.cpp | 272 | ||||
| -rwxr-xr-x | Network/NetworkMessage.hpp | 1252 | ||||
| -rwxr-xr-x | Network/NetworkServerLookup.cpp | 170 | ||||
| -rwxr-xr-x | Network/NetworkServerLookup.hpp | 76 | ||||
| -rwxr-xr-x | Network/PSKReporter.cpp | 1393 | ||||
| -rwxr-xr-x | Network/PSKReporter.hpp | 90 | ||||
| -rwxr-xr-x | Network/tests/PSKReporter/PSKReporter.IESpec | 24 | ||||
| -rwxr-xr-x | Network/tests/PSKReporter/listener.py | 188 | ||||
| -rwxr-xr-x | Network/tests/PSKReporter/python-ipfix.patch | 128 | ||||
| -rwxr-xr-x | Network/wsprnet.cpp | 686 | ||||
| -rwxr-xr-x | Network/wsprnet.h | 120 |
24 files changed, 4060 insertions, 3846 deletions
diff --git a/Network/Cloudlog.cpp b/Network/Cloudlog.cpp new file mode 100755 index 00000000..3f642a60 --- /dev/null +++ b/Network/Cloudlog.cpp @@ -0,0 +1,174 @@ +#include "Cloudlog.hpp"
+
+#include <future>
+#include <chrono>
+
+#include <QHash>
+#include <QString>
+#include <QDate>
+#include <QFile>
+#include <QTextStream>
+#include <QDir>
+#include <QFileInfo>
+#include <QPointer>
+#include <QSaveFile>
+#include <QUrl>
+#include <QNetworkAccessManager>
+#include <QNetworkReply>
+#include <QDebug>
+#include <QMessageBox>
+#include <QIcon>
+#include <QJsonDocument>
+#include <QJsonObject>
+
+#include "pimpl_impl.hpp"
+
+#include "moc_Cloudlog.cpp"
+
+#include "Configuration.hpp"
+
+namespace
+{
+ // Dictionary mapping call sign to date of last upload to LotW
+ using dictionary = QHash<QString, QDate>;
+}
+
+class Cloudlog::impl final
+ : public QObject
+{
+ Q_OBJECT
+
+public:
+ impl (Cloudlog * self, Configuration const * config, QNetworkAccessManager * network_manager)
+ : self_ {self}
+ , config_ {config}
+ , network_manager_ {network_manager}
+ {
+ }
+
+ void logQso (QByteArray ADIF)
+ {
+ QByteArray data;
+
+ QString str = QString("") +
+ "{" +
+ "\"key\":\""+ config_->cloudlog_api_key() +"\"," +
+ "\"station_profile_id\":\""+ QVariant(config_->cloudlog_api_station_id()).toString() +"\"," +
+ "\"type\":\"adif\"," +
+ "\"string\":\"" + ADIF + "<eor>" + "\"" +
+ "}";
+ data = str.toUtf8();
+
+ QUrl u = QUrl(config_->cloudlog_api_url()+"/index.php/api/qso");
+
+ QNetworkRequest request(u);
+ request.setHeader(QNetworkRequest::ContentTypeHeader, QVariant("application/json"));
+ reply_ = network_manager_->post(request, data);
+ connect (reply_.data (), &QNetworkReply::finished, this, &Cloudlog::impl::reply_logqso);
+
+ }
+
+ void testApi (QString const& url, QString const& apiKey)
+ {
+ QString apiUrl = url;
+#if QT_VERSION < QT_VERSION_CHECK(5, 15, 0)
+ if (QNetworkAccessManager::Accessible != network_manager_->networkAccessible ())
+ {
+ // try and recover network access for QNAM
+ network_manager_->setNetworkAccessible (QNetworkAccessManager::Accessible);
+ }
+#endif
+
+ // Remove trailing slash if given
+ if (apiUrl.endsWith('/')) {
+ apiUrl.remove(-1, 1);
+ }
+ // Remove full path to API if given
+ if (apiUrl.endsWith("/index.php/api/qso")) {
+ apiUrl.remove(-18, 18);
+ }
+
+ QNetworkRequest request {apiUrl+"/index.php/api/auth/"+apiKey};
+ request.setRawHeader ("User-Agent", "WSJT-X Cloudlog API");
+ request.setOriginatingObject (this);
+ reply_ = network_manager_->get (request);
+ connect (reply_.data (), &QNetworkReply::finished, this, &Cloudlog::impl::reply_apitest);
+ }
+
+ void reply_apitest()
+ {
+ QString result;
+ if (reply_ && reply_->isFinished ())
+ {
+ result = reply_->readAll();
+ if (result.contains("<status>Valid</status>"))
+ {
+ if (result.contains("<rights>rw</rights>"))
+ {
+ // fprintf(stderr, "API key OK\n");
+ Q_EMIT self_->apikey_ok ();
+ } else {
+ // fprintf(stderr, "API key not writable!\n");
+ Q_EMIT self_->apikey_ro ();
+ }
+ } else {
+ // fprintf(stderr, "API key invalid!\n");
+ Q_EMIT self_->apikey_invalid ();
+ }
+ }
+ }
+
+ void reply_logqso()
+ {
+ QString result;
+ if (reply_ && reply_->isFinished ())
+ {
+ result = reply_->readAll();
+ QJsonDocument data = QJsonDocument::fromJson(result.toUtf8());
+ QJsonObject obj = data.object();
+ if (obj["status"] == "failed") {
+ QMessageBox msgBox;
+ msgBox.setIcon(QMessageBox::Warning);
+ msgBox.setWindowTitle("Cloudlog Error!");
+ msgBox.setText("QSO could not be sent to Cloudlog!\nPlease check your log.");
+ msgBox.setDetailedText("Reason: "+obj["reason"].toString());
+ msgBox.exec();
+ }
+ }
+ }
+
+ void abort ()
+ {
+ if (reply_ && reply_->isRunning ())
+ {
+ reply_->abort ();
+ }
+ }
+
+ Cloudlog * self_;
+ Configuration const * config_;
+ QNetworkAccessManager * network_manager_;
+ QPointer<QNetworkReply> reply_;
+};
+
+#include "Cloudlog.moc"
+
+Cloudlog::Cloudlog (Configuration const * config, QNetworkAccessManager * network_manager, QObject * parent)
+ : QObject {parent}
+ , m_ {this, config, network_manager}
+{
+}
+
+Cloudlog::~Cloudlog ()
+{
+}
+
+void Cloudlog::testApi (QString const& url, QString const& apiKey)
+{
+ m_->testApi (url, apiKey);
+}
+
+void Cloudlog::logQso (QByteArray ADIF)
+{
+ m_->logQso(ADIF);
+}
diff --git a/Network/Cloudlog.hpp b/Network/Cloudlog.hpp new file mode 100755 index 00000000..c35f7947 --- /dev/null +++ b/Network/Cloudlog.hpp @@ -0,0 +1,36 @@ +#ifndef CLOUDLOG_HPP_
+#define CLOUDLOG_HPP_
+
+#include <boost/core/noncopyable.hpp>
+#include <QObject>
+#include "pimpl_h.hpp"
+
+class QString;
+class QNetworkAccessManager;
+class Configuration;
+
+//
+// Cloudlog
+//
+class Cloudlog final
+ : public QObject
+{
+ Q_OBJECT
+
+public:
+ explicit Cloudlog (Configuration const *, QNetworkAccessManager *, QObject * parent = 0);
+ ~Cloudlog ();
+
+ void logQso(QByteArray ADIF);
+ Q_SLOT void testApi (QString const& url, QString const& apiKey);
+
+ Q_SIGNAL void apikey_ok () const;
+ Q_SIGNAL void apikey_ro () const;
+ Q_SIGNAL void apikey_invalid () const;
+
+private:
+ class impl;
+ pimpl<impl> m_;
+};
+
+#endif
diff --git a/Network/FileDownload.cpp b/Network/FileDownload.cpp index 3ab2a7c6..7647dab5 100755 --- a/Network/FileDownload.cpp +++ b/Network/FileDownload.cpp @@ -1,229 +1,229 @@ - -#include "FileDownload.hpp" -#include <QCoreApplication> -#include <QUrl> -#include <QNetworkRequest> -#include <QtNetwork/QNetworkAccessManager> -#include <QtNetwork/QNetworkReply> -#include <QFileInfo> -#include <QDir> -#include <QIODevice> -#include "qt_helpers.hpp" -#include "Logger.hpp" - -FileDownload::FileDownload() : QObject(nullptr) -{ - redirect_count_ = 0; - url_valid_ = false; -} - -FileDownload::~FileDownload() -{ -} -#if QT_VERSION >= QT_VERSION_CHECK(5, 15, 0) -void FileDownload::errorOccurred(QNetworkReply::NetworkError code) -{ - LOG_INFO(QString{"FileDownload [%1]: errorOccurred %2 -> %3"}.arg(user_agent_).arg(code).arg(reply_->errorString())); - Q_EMIT error (reply_->errorString ()); - destfile_.cancelWriting (); - destfile_.commit (); -} -#else -void FileDownload::obsoleteError() -{ - LOG_INFO(QString{"FileDownload [%1]: error -> %3"}.arg(user_agent_).arg(reply_->errorString())); - Q_EMIT error (reply_->errorString ()); - destfile_.cancelWriting (); - destfile_.commit (); -} -#endif - -void FileDownload::configure(QNetworkAccessManager *network_manager, const QString &source_url, const QString &destination_path, const QString &user_agent) -{ - manager_ = network_manager; - source_url_ = source_url; - destination_filename_ = destination_path; - user_agent_ = user_agent; -} - -void FileDownload::store() -{ - if (destfile_.isOpen()) - destfile_.write (reply_->read (reply_->bytesAvailable ())); - else - LOG_INFO(QString{ "FileDownload [%1]: file is not open."}.arg(user_agent_)); -} - -void FileDownload::replyComplete() -{ - QFileInfo destination_file(destination_filename_); - QDir tmpdir_(destination_file.absoluteFilePath()); - - LOG_DEBUG(QString{ "FileDownload [%1]: replyComplete"}.arg(user_agent_)); - if (!reply_) - { - Q_EMIT load_finished (); - return; // we probably deleted it in an earlier call - } - - QUrl redirect_url {reply_->attribute (QNetworkRequest::RedirectionTargetAttribute).toUrl ()}; - - if (reply_->error () == QNetworkReply::NoError && !redirect_url.isEmpty ()) - { - if ("https" == redirect_url.scheme () && !QSslSocket::supportsSsl ()) - { - Q_EMIT download_error (tr ("Network Error - SSL/TLS support not installed, cannot fetch:\n\'%1\'") - .arg (redirect_url.toDisplayString ())); - url_valid_ = false; // reset - Q_EMIT load_finished (); - } - else if (++redirect_count_ < 10) // maintain sanity - { - // follow redirect - download (reply_->url ().resolved (redirect_url)); - } - else - { - Q_EMIT download_error (tr ("Network Error - Too many redirects:\n\'%1\'") - .arg (redirect_url.toDisplayString ())); - url_valid_ = false; // reset - Q_EMIT load_finished (); - } - } - else if (reply_->error () != QNetworkReply::NoError) - { - destfile_.cancelWriting(); - destfile_.commit(); - url_valid_ = false; // reset - // report errors that are not due to abort - if (QNetworkReply::OperationCanceledError != reply_->error ()) - { - Q_EMIT download_error (tr ("Network Error:\n%1") - .arg (reply_->errorString ())); - } - Q_EMIT load_finished (); - } - else - { - if (!url_valid_) - { - // now get the body content - url_valid_ = true; - download (reply_->url ().resolved (redirect_url)); - } - else // the body has completed. Save it. - { - url_valid_ = false; // reset - // load the database asynchronously - // future_load_ = std::async (std::launch::async, &LotWUsers::impl::load_dictionary, this, csv_file_.fileName ()); - LOG_INFO(QString{ "FileDownload [%1]: complete. File path is %2"}.arg(user_agent_).arg(destfile_.fileName())); - destfile_.commit(); - emit complete(destination_filename_); - } - } - - if (reply_ && reply_->isFinished ()) - { - reply_->deleteLater (); - } - -} - -void FileDownload::downloadComplete(QNetworkReply *data) -{ - // make a temp file in the same place as the file we're downloading. Needs to be on the same - // filesystem as where we eventually want to 'mv' it. - - QUrl r = request_.url(); - LOG_INFO(QString{"FileDownload [%1]: finished %2 of %3 -> %4 (%5)"}.arg(user_agent_).arg(data->operation()).arg(source_url_).arg(destination_filename_).arg(r.url())); - -#ifdef DEBUG_FILEDOWNLOAD - LOG_INFO("Request Headers:"); - Q_FOREACH (const QByteArray& hdr, request_.rawHeaderList()) { - LOG_INFO(QString{ "%1 -> %2"}.arg(QString(hdr)).arg(QString(request_.rawHeader(hdr)))); - } - - LOG_INFO("Response Headers:"); - Q_FOREACH (const QByteArray& hdr, reply_->rawHeaderList()) { - LOG_INFO(QString{ "%1 -> %2"}.arg(QString(hdr)).arg(QString(reply_->rawHeader(hdr)))); - } -#endif - data->deleteLater(); -} - -void FileDownload::start_download() -{ - url_valid_ = false; - download(QUrl(source_url_)); -} - -void FileDownload::download(QUrl qurl) -{ - request_.setUrl(qurl); - -#if QT_VERSION < QT_VERSION_CHECK(5, 15, 0) - if (QNetworkAccessManager::Accessible != manager_->networkAccessible ()) - { - // try and recover network access for QNAM - manager_->setNetworkAccessible (QNetworkAccessManager::Accessible); - } -#endif - - LOG_INFO(QString{"FileDownload [%1]: Starting download of %2 to %3"}.arg(user_agent_).arg(source_url_).arg(destination_filename_)); - - request_.setAttribute(QNetworkRequest::FollowRedirectsAttribute, true); - request_.setRawHeader("Accept", "*/*"); - request_.setRawHeader ("User-Agent", user_agent_.toLocal8Bit()); // Must have a UA for some sites, like country-files - - if (!url_valid_) - { - reply_ = manager_->head(request_); - } - else - { - reply_ = manager_->get (request_); - } - - QObject::connect(manager_, &QNetworkAccessManager::finished, this, &FileDownload::downloadComplete, Qt::UniqueConnection); - QObject::connect(reply_, &QNetworkReply::downloadProgress, this, &FileDownload::downloadProgress, Qt::UniqueConnection); - QObject::connect(reply_, &QNetworkReply::finished, this, &FileDownload::replyComplete, Qt::UniqueConnection); -#if QT_VERSION >= QT_VERSION_CHECK(5, 15, 0) - QObject::connect(reply_, &QNetworkReply::errorOccurred,this, &FileDownload::errorOccurred, Qt::UniqueConnection); -#else - QObject::connect(reply_, QOverload<QNetworkReply::NetworkError>::of(&QNetworkReply::error), this, &FileDownload::obsoleteError, Qt::UniqueConnection); -#endif - QObject::connect(reply_, &QNetworkReply::readyRead, this, &FileDownload::store, Qt::UniqueConnection); - - QFileInfo destination_file(destination_filename_); - QString const tmpfile_base = destination_file.fileName(); - QString const &tmpfile_path = destination_file.absolutePath(); - QDir tmpdir{}; - if (!tmpdir.mkpath(tmpfile_path)) - { - LOG_INFO(QString{"FileDownload [%1]: Directory %2 does not exist"}.arg(user_agent_).arg(tmpfile_path).arg( - destfile_.errorString())); - } - - if (url_valid_) { - destfile_.setFileName(destination_file.absoluteFilePath()); - if (!destfile_.open(QSaveFile::WriteOnly | QIODevice::WriteOnly)) { - LOG_INFO(QString{"FileDownload [%1]: Unable to open %2: %3"}.arg(user_agent_).arg(destfile_.fileName()).arg( - destfile_.errorString())); - return; - } - } -} - -void FileDownload::downloadProgress(qint64 received, qint64 total) -{ - LOG_DEBUG(QString{"FileDownload: [%1] Progress %2 from %3, total %4, so far %5"}.arg(user_agent_).arg(destination_filename_).arg(source_url_).arg(total).arg(received)); - Q_EMIT progress(QString{"%4 bytes downloaded"}.arg(received)); -} - -void FileDownload::abort () -{ - if (reply_ && reply_->isRunning ()) - { - reply_->abort (); - } -} +
+#include "FileDownload.hpp"
+#include <QCoreApplication>
+#include <QUrl>
+#include <QNetworkRequest>
+#include <QtNetwork/QNetworkAccessManager>
+#include <QtNetwork/QNetworkReply>
+#include <QFileInfo>
+#include <QDir>
+#include <QIODevice>
+#include "qt_helpers.hpp"
+#include "Logger.hpp"
+
+FileDownload::FileDownload() : QObject(nullptr)
+{
+ redirect_count_ = 0;
+ url_valid_ = false;
+}
+
+FileDownload::~FileDownload()
+{
+}
+#if QT_VERSION >= QT_VERSION_CHECK(5, 15, 0)
+void FileDownload::errorOccurred(QNetworkReply::NetworkError code)
+{
+ LOG_INFO(QString{"FileDownload [%1]: errorOccurred %2 -> %3"}.arg(user_agent_).arg(code).arg(reply_->errorString()));
+ Q_EMIT error (reply_->errorString ());
+ destfile_.cancelWriting ();
+ destfile_.commit ();
+}
+#else
+void FileDownload::obsoleteError()
+{
+ LOG_INFO(QString{"FileDownload [%1]: error -> %3"}.arg(user_agent_).arg(reply_->errorString()));
+ Q_EMIT error (reply_->errorString ());
+ destfile_.cancelWriting ();
+ destfile_.commit ();
+}
+#endif
+
+void FileDownload::configure(QNetworkAccessManager *network_manager, const QString &source_url, const QString &destination_path, const QString &user_agent)
+{
+ manager_ = network_manager;
+ source_url_ = source_url;
+ destination_filename_ = destination_path;
+ user_agent_ = user_agent;
+}
+
+void FileDownload::store()
+{
+ if (destfile_.isOpen())
+ destfile_.write (reply_->read (reply_->bytesAvailable ()));
+ else
+ LOG_INFO(QString{ "FileDownload [%1]: file is not open."}.arg(user_agent_));
+}
+
+void FileDownload::replyComplete()
+{
+ QFileInfo destination_file(destination_filename_);
+ QDir tmpdir_(destination_file.absoluteFilePath());
+
+ LOG_DEBUG(QString{ "FileDownload [%1]: replyComplete"}.arg(user_agent_));
+ if (!reply_)
+ {
+ Q_EMIT load_finished ();
+ return; // we probably deleted it in an earlier call
+ }
+
+ QUrl redirect_url {reply_->attribute (QNetworkRequest::RedirectionTargetAttribute).toUrl ()};
+
+ if (reply_->error () == QNetworkReply::NoError && !redirect_url.isEmpty ())
+ {
+ if ("https" == redirect_url.scheme () && !QSslSocket::supportsSsl ())
+ {
+ Q_EMIT download_error (tr ("Network Error - SSL/TLS support not installed, cannot fetch:\n\'%1\'")
+ .arg (redirect_url.toDisplayString ()));
+ url_valid_ = false; // reset
+ Q_EMIT load_finished ();
+ }
+ else if (++redirect_count_ < 10) // maintain sanity
+ {
+ // follow redirect
+ download (reply_->url ().resolved (redirect_url));
+ }
+ else
+ {
+ Q_EMIT download_error (tr ("Network Error - Too many redirects:\n\'%1\'")
+ .arg (redirect_url.toDisplayString ()));
+ url_valid_ = false; // reset
+ Q_EMIT load_finished ();
+ }
+ }
+ else if (reply_->error () != QNetworkReply::NoError)
+ {
+ destfile_.cancelWriting();
+ destfile_.commit();
+ url_valid_ = false; // reset
+ // report errors that are not due to abort
+ if (QNetworkReply::OperationCanceledError != reply_->error ())
+ {
+ Q_EMIT download_error (tr ("Network Error:\n%1")
+ .arg (reply_->errorString ()));
+ }
+ Q_EMIT load_finished ();
+ }
+ else
+ {
+ if (!url_valid_)
+ {
+ // now get the body content
+ url_valid_ = true;
+ download (reply_->url ().resolved (redirect_url));
+ }
+ else // the body has completed. Save it.
+ {
+ url_valid_ = false; // reset
+ // load the database asynchronously
+ // future_load_ = std::async (std::launch::async, &LotWUsers::impl::load_dictionary, this, csv_file_.fileName ());
+ LOG_INFO(QString{ "FileDownload [%1]: complete. File path is %2"}.arg(user_agent_).arg(destfile_.fileName()));
+ destfile_.commit();
+ emit complete(destination_filename_);
+ }
+ }
+
+ if (reply_ && reply_->isFinished ())
+ {
+ reply_->deleteLater ();
+ }
+
+}
+
+void FileDownload::downloadComplete(QNetworkReply *data)
+{
+ // make a temp file in the same place as the file we're downloading. Needs to be on the same
+ // filesystem as where we eventually want to 'mv' it.
+
+ QUrl r = request_.url();
+ LOG_INFO(QString{"FileDownload [%1]: finished %2 of %3 -> %4 (%5)"}.arg(user_agent_).arg(data->operation()).arg(source_url_).arg(destination_filename_).arg(r.url()));
+
+#ifdef DEBUG_FILEDOWNLOAD
+ LOG_INFO("Request Headers:");
+ Q_FOREACH (const QByteArray& hdr, request_.rawHeaderList()) {
+ LOG_INFO(QString{ "%1 -> %2"}.arg(QString(hdr)).arg(QString(request_.rawHeader(hdr))));
+ }
+
+ LOG_INFO("Response Headers:");
+ Q_FOREACH (const QByteArray& hdr, reply_->rawHeaderList()) {
+ LOG_INFO(QString{ "%1 -> %2"}.arg(QString(hdr)).arg(QString(reply_->rawHeader(hdr))));
+ }
+#endif
+ data->deleteLater();
+}
+
+void FileDownload::start_download()
+{
+ url_valid_ = false;
+ download(QUrl(source_url_));
+}
+
+void FileDownload::download(QUrl qurl)
+{
+ request_.setUrl(qurl);
+
+#if QT_VERSION < QT_VERSION_CHECK(5, 15, 0)
+ if (QNetworkAccessManager::Accessible != manager_->networkAccessible ())
+ {
+ // try and recover network access for QNAM
+ manager_->setNetworkAccessible (QNetworkAccessManager::Accessible);
+ }
+#endif
+
+ LOG_INFO(QString{"FileDownload [%1]: Starting download of %2 to %3"}.arg(user_agent_).arg(source_url_).arg(destination_filename_));
+
+ request_.setAttribute(QNetworkRequest::FollowRedirectsAttribute, true);
+ request_.setRawHeader("Accept", "*/*");
+ request_.setRawHeader ("User-Agent", user_agent_.toLocal8Bit()); // Must have a UA for some sites, like country-files
+
+ if (!url_valid_)
+ {
+ reply_ = manager_->head(request_);
+ }
+ else
+ {
+ reply_ = manager_->get (request_);
+ }
+
+ QObject::connect(manager_, &QNetworkAccessManager::finished, this, &FileDownload::downloadComplete, Qt::UniqueConnection);
+ QObject::connect(reply_, &QNetworkReply::downloadProgress, this, &FileDownload::downloadProgress, Qt::UniqueConnection);
+ QObject::connect(reply_, &QNetworkReply::finished, this, &FileDownload::replyComplete, Qt::UniqueConnection);
+#if QT_VERSION >= QT_VERSION_CHECK(5, 15, 0)
+ QObject::connect(reply_, &QNetworkReply::errorOccurred,this, &FileDownload::errorOccurred, Qt::UniqueConnection);
+#else
+ QObject::connect(reply_, QOverload<QNetworkReply::NetworkError>::of(&QNetworkReply::error), this, &FileDownload::obsoleteError, Qt::UniqueConnection);
+#endif
+ QObject::connect(reply_, &QNetworkReply::readyRead, this, &FileDownload::store, Qt::UniqueConnection);
+
+ QFileInfo destination_file(destination_filename_);
+ QString const tmpfile_base = destination_file.fileName();
+ QString const &tmpfile_path = destination_file.absolutePath();
+ QDir tmpdir{};
+ if (!tmpdir.mkpath(tmpfile_path))
+ {
+ LOG_INFO(QString{"FileDownload [%1]: Directory %2 does not exist"}.arg(user_agent_).arg(tmpfile_path).arg(
+ destfile_.errorString()));
+ }
+
+ if (url_valid_) {
+ destfile_.setFileName(destination_file.absoluteFilePath());
+ if (!destfile_.open(QSaveFile::WriteOnly | QIODevice::WriteOnly)) {
+ LOG_INFO(QString{"FileDownload [%1]: Unable to open %2: %3"}.arg(user_agent_).arg(destfile_.fileName()).arg(
+ destfile_.errorString()));
+ return;
+ }
+ }
+}
+
+void FileDownload::downloadProgress(qint64 received, qint64 total)
+{
+ LOG_DEBUG(QString{"FileDownload: [%1] Progress %2 from %3, total %4, so far %5"}.arg(user_agent_).arg(destination_filename_).arg(source_url_).arg(total).arg(received));
+ Q_EMIT progress(QString{"%4 bytes downloaded"}.arg(received));
+}
+
+void FileDownload::abort ()
+{
+ if (reply_ && reply_->isRunning ())
+ {
+ reply_->abort ();
+ }
+}
diff --git a/Network/FileDownload.hpp b/Network/FileDownload.hpp index c32948dd..140283c3 100755 --- a/Network/FileDownload.hpp +++ b/Network/FileDownload.hpp @@ -1,54 +1,54 @@ -#ifndef WSJTX_FILEDOWNLOAD_H -#define WSJTX_FILEDOWNLOAD_H - -#include <QObject> -#include <QString> -#include <QPointer> -#include <QtNetwork/QNetworkAccessManager> -#include <QtNetwork/QNetworkReply> -#include <QTemporaryFile> -#include <QSaveFile> - -class FileDownload : public QObject { - Q_OBJECT - -public: - explicit FileDownload(); - ~FileDownload(); - - void configure(QNetworkAccessManager *network_manager, const QString& source_url, const QString& destination_filename, const QString& user_agent); - -private: - QNetworkAccessManager *manager_; - QString source_url_; - QString destination_filename_; - QString user_agent_; - QPointer<QNetworkReply> reply_; - QNetworkRequest request_; - QSaveFile destfile_; - bool url_valid_; - int redirect_count_; -signals: - void complete(QString filename); - void progress(QString filename); - void load_finished() const; - void download_error (QString const& reason) const; - void error(QString const& reason) const; - - -public slots: - void start_download(); - void download(QUrl url); - void store(); - void abort(); - void downloadComplete(QNetworkReply* data); - void downloadProgress(qint64 recieved, qint64 total); -#if QT_VERSION >= QT_VERSION_CHECK(5, 15, 0) - void errorOccurred(QNetworkReply::NetworkError code); -#else - void obsoleteError(); -#endif - void replyComplete(); -}; - -#endif //WSJTX_FILEDOWNLOAD_H +#ifndef WSJTX_FILEDOWNLOAD_H
+#define WSJTX_FILEDOWNLOAD_H
+
+#include <QObject>
+#include <QString>
+#include <QPointer>
+#include <QtNetwork/QNetworkAccessManager>
+#include <QtNetwork/QNetworkReply>
+#include <QTemporaryFile>
+#include <QSaveFile>
+
+class FileDownload : public QObject {
+ Q_OBJECT
+
+public:
+ explicit FileDownload();
+ ~FileDownload();
+
+ void configure(QNetworkAccessManager *network_manager, const QString& source_url, const QString& destination_filename, const QString& user_agent);
+
+private:
+ QNetworkAccessManager *manager_;
+ QString source_url_;
+ QString destination_filename_;
+ QString user_agent_;
+ QPointer<QNetworkReply> reply_;
+ QNetworkRequest request_;
+ QSaveFile destfile_;
+ bool url_valid_;
+ int redirect_count_;
+signals:
+ void complete(QString filename);
+ void progress(QString filename);
+ void load_finished() const;
+ void download_error (QString const& reason) const;
+ void error(QString const& reason) const;
+
+
+public slots:
+ void start_download();
+ void download(QUrl url);
+ void store();
+ void abort();
+ void downloadComplete(QNetworkReply* data);
+ void downloadProgress(qint64 recieved, qint64 total);
+#if QT_VERSION >= QT_VERSION_CHECK(5, 15, 0)
+ void errorOccurred(QNetworkReply::NetworkError code);
+#else
+ void obsoleteError();
+#endif
+ void replyComplete();
+};
+
+#endif //WSJTX_FILEDOWNLOAD_H
diff --git a/Network/FoxVerifier.cpp b/Network/FoxVerifier.cpp index 36e55442..2882f34a 100755 --- a/Network/FoxVerifier.cpp +++ b/Network/FoxVerifier.cpp @@ -1,125 +1,125 @@ -#include "FoxVerifier.hpp" -#include "Logger.hpp" - -FoxVerifier::FoxVerifier(QString user_agent, QNetworkAccessManager *manager,QString base_url, QString callsign, QDateTime timestamp, QString code, unsigned int hz=750) : QObject(nullptr) -{ - manager_ = manager; - finished_ = false; - errored_ = false; - callsign_ = callsign; - code_ = code; - ts_ = timestamp; - hz_ = hz; - - // make sure we URLencode the callsign, for things like E51D/MM - QString encodedCall = QString::fromUtf8(QUrl::toPercentEncoding(callsign)); - QString url = QString("%1/check/").arg(base_url) + encodedCall + QString("/%1/%2.text").arg(timestamp.toString(Qt::ISODate)).arg(code); - LOG_INFO(QString("FoxVerifier: url %1").arg(url).toStdString()); - q_url_ = QUrl(url); - if (manager_ == nullptr) { - LOG_INFO("FoxVerifier: manager is null, creating new one"); - manager_ = new QNetworkAccessManager(this); - manager_->deleteLater(); - } - if (q_url_.isValid()) { - request_ = QNetworkRequest(q_url_); - request_.setRawHeader( "User-Agent" , user_agent.toUtf8()); - request_.setRawHeader( "Accept" , "*/*" ); - request_.setAttribute(QNetworkRequest::FollowRedirectsAttribute, true); - -#if QT_VERSION >= QT_VERSION_CHECK(5, 15, 0) - request_.setTransferTimeout(FOXVERIFIER_DEFAULT_TIMEOUT_MSEC); -#endif - - reply_ = manager_->get(request_); - connect(reply_, &QNetworkReply::finished, this, &FoxVerifier::httpFinished); -#if QT_VERSION >= QT_VERSION_CHECK(5, 15, 0) - connect(reply_, &QNetworkReply::errorOccurred, this, &FoxVerifier::errorOccurred); -#endif - connect(reply_, &QNetworkReply::redirected, this, &FoxVerifier::httpRedirected); - connect(reply_, &QNetworkReply::encrypted, this, &FoxVerifier::httpEncrypted); -#if QT_CONFIG(ssl) - connect(reply_, &QNetworkReply::sslErrors, this, &FoxVerifier::sslErrors); -#else - LOG_INFO("FoxVerifier: ssl not supported"); -#endif - - } else { - LOG_INFO(QString("FoxVerifier: url invalid ! %1").arg(url).toStdString()); - } -} - -FoxVerifier::~FoxVerifier() { -} - -bool FoxVerifier::finished() { - return finished_; -} - -#if QT_VERSION >= QT_VERSION_CHECK(5, 15, 0) -void FoxVerifier::errorOccurred(QNetworkReply::NetworkError code) -{ - int status = reply_->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(); - QString reason = reply_->attribute(QNetworkRequest::HttpReasonPhraseAttribute).toString(); - errored_ = true; - error_reason_ = reply_->errorString(); - if (reply_->error() != QNetworkReply::NoError) { - - LOG_INFO(QString("FoxVerifier: errorOccurred status %1 error [%2][%3] isFinished %4 isrunning %5 code %6").arg(status).arg( - reason).arg(error_reason_).arg(reply_->isFinished()).arg(reply_->isRunning()).arg(code).toStdString()); - return; - } - // TODO emit -} -#endif - -void FoxVerifier::httpFinished() -{ - int status = reply_->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(); - QString reason = reply_->attribute(QNetworkRequest::HttpReasonPhraseAttribute).toString(); - if (reply_->error() != QNetworkReply::NoError) { - LOG_INFO(QString("FoxVerifier: httpFinished error:[%1 - %2] msg:[%3]").arg(status).arg(reason).arg(reply_->errorString()).toStdString()); - reply_->abort(); - emit verifyError(status, ts_, callsign_, code_, hz_, reply_->errorString()); - } - return_value = reply_->read(1024); // limit amount we get - LOG_INFO(QString("FoxVerifier: httpFinished status:[%1 - %2] body:[%3] ").arg(status).arg(reason).arg(return_value).toStdString()); - finished_ = true; - reply_->deleteLater(); - if (status >= 200 && status <= 299) { - emit verifyComplete(status, ts_, callsign_, code_, hz_, return_value); - } -} - -void FoxVerifier::sslErrors(const QList<QSslError> &) -{ - LOG_INFO(QString("FoxVerifier: sslErrors").toStdString()); - reply_->ignoreSslErrors(); -} - -void FoxVerifier::httpRedirected(const QUrl &url) { - LOG_INFO(QString("FoxVerifier: redirected to %1").arg(url.toString()).toStdString()); -} - -void FoxVerifier::httpEncrypted() { - LOG_INFO("FoxVerifier: httpEncrypted"); -} - -QString FoxVerifier::formatDecodeMessage(QDateTime ts, QString callsign, unsigned int hz_, QString const& verify_message) { - //"172100 -00 0.0 750 ~ K8R VERIFIED" - QTime rx_time = ts.time(); - QString hz=QString("%1").arg(hz_, 4, 10 ); // insert Hz - if (verify_message.endsWith(" VERIFIED")) { - return QString("%1 0 0.0 %2 ~ %3 verified").arg(rx_time.toString("hhmmss")).arg(hz).arg(callsign); - } else - if (verify_message.endsWith(" INVALID")) - { - return QString("%1 0 0.0 %2 ~ %3 invalid").arg(rx_time.toString("hhmmss")).arg(hz).arg(callsign); - } - else - return QString{}; -} - -QString FoxVerifier::default_url() { - return QString(FOXVERIFIER_DEFAULT_BASE_URL); -} +#include "FoxVerifier.hpp"
+#include "Logger.hpp"
+
+FoxVerifier::FoxVerifier(QString user_agent, QNetworkAccessManager *manager,QString base_url, QString callsign, QDateTime timestamp, QString code, unsigned int hz=750) : QObject(nullptr)
+{
+ manager_ = manager;
+ finished_ = false;
+ errored_ = false;
+ callsign_ = callsign;
+ code_ = code;
+ ts_ = timestamp;
+ hz_ = hz;
+
+ // make sure we URLencode the callsign, for things like E51D/MM
+ QString encodedCall = QString::fromUtf8(QUrl::toPercentEncoding(callsign));
+ QString url = QString("%1/check/").arg(base_url) + encodedCall + QString("/%1/%2.text").arg(timestamp.toString(Qt::ISODate)).arg(code);
+ LOG_INFO(QString("FoxVerifier: url %1").arg(url).toStdString());
+ q_url_ = QUrl(url);
+ if (manager_ == nullptr) {
+ LOG_INFO("FoxVerifier: manager is null, creating new one");
+ manager_ = new QNetworkAccessManager(this);
+ manager_->deleteLater();
+ }
+ if (q_url_.isValid()) {
+ request_ = QNetworkRequest(q_url_);
+ request_.setRawHeader( "User-Agent" , user_agent.toUtf8());
+ request_.setRawHeader( "Accept" , "*/*" );
+ request_.setAttribute(QNetworkRequest::FollowRedirectsAttribute, true);
+
+#if QT_VERSION >= QT_VERSION_CHECK(5, 15, 0)
+ request_.setTransferTimeout(FOXVERIFIER_DEFAULT_TIMEOUT_MSEC);
+#endif
+
+ reply_ = manager_->get(request_);
+ connect(reply_, &QNetworkReply::finished, this, &FoxVerifier::httpFinished);
+#if QT_VERSION >= QT_VERSION_CHECK(5, 15, 0)
+ connect(reply_, &QNetworkReply::errorOccurred, this, &FoxVerifier::errorOccurred);
+#endif
+ connect(reply_, &QNetworkReply::redirected, this, &FoxVerifier::httpRedirected);
+ connect(reply_, &QNetworkReply::encrypted, this, &FoxVerifier::httpEncrypted);
+#if QT_CONFIG(ssl)
+ connect(reply_, &QNetworkReply::sslErrors, this, &FoxVerifier::sslErrors);
+#else
+ LOG_INFO("FoxVerifier: ssl not supported");
+#endif
+
+ } else {
+ LOG_INFO(QString("FoxVerifier: url invalid ! %1").arg(url).toStdString());
+ }
+}
+
+FoxVerifier::~FoxVerifier() {
+}
+
+bool FoxVerifier::finished() {
+ return finished_;
+}
+
+#if QT_VERSION >= QT_VERSION_CHECK(5, 15, 0)
+void FoxVerifier::errorOccurred(QNetworkReply::NetworkError code)
+{
+ int status = reply_->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
+ QString reason = reply_->attribute(QNetworkRequest::HttpReasonPhraseAttribute).toString();
+ errored_ = true;
+ error_reason_ = reply_->errorString();
+ if (reply_->error() != QNetworkReply::NoError) {
+
+ LOG_INFO(QString("FoxVerifier: errorOccurred status %1 error [%2][%3] isFinished %4 isrunning %5 code %6").arg(status).arg(
+ reason).arg(error_reason_).arg(reply_->isFinished()).arg(reply_->isRunning()).arg(code).toStdString());
+ return;
+ }
+ // TODO emit
+}
+#endif
+
+void FoxVerifier::httpFinished()
+{
+ int status = reply_->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
+ QString reason = reply_->attribute(QNetworkRequest::HttpReasonPhraseAttribute).toString();
+ if (reply_->error() != QNetworkReply::NoError) {
+ LOG_INFO(QString("FoxVerifier: httpFinished error:[%1 - %2] msg:[%3]").arg(status).arg(reason).arg(reply_->errorString()).toStdString());
+ reply_->abort();
+ emit verifyError(status, ts_, callsign_, code_, hz_, reply_->errorString());
+ }
+ return_value = reply_->read(1024); // limit amount we get
+ LOG_INFO(QString("FoxVerifier: httpFinished status:[%1 - %2] body:[%3] ").arg(status).arg(reason).arg(return_value).toStdString());
+ finished_ = true;
+ reply_->deleteLater();
+ if (status >= 200 && status <= 299) {
+ emit verifyComplete(status, ts_, callsign_, code_, hz_, return_value);
+ }
+}
+
+void FoxVerifier::sslErrors(const QList<QSslError> &)
+{
+ LOG_INFO(QString("FoxVerifier: sslErrors").toStdString());
+ reply_->ignoreSslErrors();
+}
+
+void FoxVerifier::httpRedirected(const QUrl &url) {
+ LOG_INFO(QString("FoxVerifier: redirected to %1").arg(url.toString()).toStdString());
+}
+
+void FoxVerifier::httpEncrypted() {
+ LOG_INFO("FoxVerifier: httpEncrypted");
+}
+
+QString FoxVerifier::formatDecodeMessage(QDateTime ts, QString callsign, unsigned int hz_, QString const& verify_message) {
+ //"172100 -00 0.0 750 ~ K8R VERIFIED"
+ QTime rx_time = ts.time();
+ QString hz=QString("%1").arg(hz_, 4, 10 ); // insert Hz
+ if (verify_message.endsWith(" VERIFIED")) {
+ return QString("%1 0 0.0 %2 ~ %3 verified").arg(rx_time.toString("hhmmss")).arg(hz).arg(callsign);
+ } else
+ if (verify_message.endsWith(" INVALID"))
+ {
+ return QString("%1 0 0.0 %2 ~ %3 invalid").arg(rx_time.toString("hhmmss")).arg(hz).arg(callsign);
+ }
+ else
+ return QString{};
+}
+
+QString FoxVerifier::default_url() {
+ return QString(FOXVERIFIER_DEFAULT_BASE_URL);
+}
diff --git a/Network/FoxVerifier.hpp b/Network/FoxVerifier.hpp index 8d8cada0..0a645189 100755 --- a/Network/FoxVerifier.hpp +++ b/Network/FoxVerifier.hpp @@ -1,63 +1,63 @@ - -#ifndef WSJTX2_FOXVERIFIER_HPP -#define WSJTX2_FOXVERIFIER_HPP - -#include <QObject> -#include <QString> -#include <QPointer> -#include <QtNetwork/QNetworkAccessManager> -#include <QtNetwork/QNetworkReply> -#include <QMutex> - -#define FOXVERIFIER_DEFAULT_TIMEOUT_MSEC 5000 -#define FOXVERIFIER_DEFAULT_BASE_URL "https://www.9dx.cc" - -class FoxVerifier : public QObject { - Q_OBJECT - QMutex mutex_; - -public: - explicit FoxVerifier(QString user_agent, QNetworkAccessManager *manager, QString base_url, QString callsign, QDateTime timestamp, QString code, unsigned int); - ~FoxVerifier(); - - QString return_value; - bool finished(); - static QString formatDecodeMessage(QDateTime ts, QString callsign, unsigned int hz, QString const& verify_message); - static QString default_url(); - -private: - QNetworkAccessManager* manager_; - QNetworkReply* reply_; - QNetworkRequest request_; - QUrl q_url_; - bool finished_; - bool errored_; - unsigned int hz_; - QString error_reason_; - QDateTime ts_; - QString callsign_; - QString code_; - -private slots: - void httpFinished(); - void httpRedirected(const QUrl &url); - void httpEncrypted(); -#ifndef QT_NO_SSL - void sslErrors(const QList<QSslError> &); -#endif -#if QT_VERSION >= QT_VERSION_CHECK(5, 15, 0) - void errorOccurred(QNetworkReply::NetworkError code); -#endif -//signals: - //void results(QString verify_response); - //void error(QString const& reason) const; - -public slots: -signals: - void verifyComplete(int status, QDateTime ts, QString callsign, QString code, unsigned int hz, QString const& response); - void verifyError(int status, QDateTime ts, QString callsign, QString code, unsigned int hz, QString const& response); - -}; - - -#endif //WSJTX2_FOXVERIFIER_HPP +
+#ifndef WSJTX2_FOXVERIFIER_HPP
+#define WSJTX2_FOXVERIFIER_HPP
+
+#include <QObject>
+#include <QString>
+#include <QPointer>
+#include <QtNetwork/QNetworkAccessManager>
+#include <QtNetwork/QNetworkReply>
+#include <QMutex>
+
+#define FOXVERIFIER_DEFAULT_TIMEOUT_MSEC 5000
+#define FOXVERIFIER_DEFAULT_BASE_URL "https://www.9dx.cc"
+
+class FoxVerifier : public QObject {
+ Q_OBJECT
+ QMutex mutex_;
+
+public:
+ explicit FoxVerifier(QString user_agent, QNetworkAccessManager *manager, QString base_url, QString callsign, QDateTime timestamp, QString code, unsigned int);
+ ~FoxVerifier();
+
+ QString return_value;
+ bool finished();
+ static QString formatDecodeMessage(QDateTime ts, QString callsign, unsigned int hz, QString const& verify_message);
+ static QString default_url();
+
+private:
+ QNetworkAccessManager* manager_;
+ QNetworkReply* reply_;
+ QNetworkRequest request_;
+ QUrl q_url_;
+ bool finished_;
+ bool errored_;
+ unsigned int hz_;
+ QString error_reason_;
+ QDateTime ts_;
+ QString callsign_;
+ QString code_;
+
+private slots:
+ void httpFinished();
+ void httpRedirected(const QUrl &url);
+ void httpEncrypted();
+#ifndef QT_NO_SSL
+ void sslErrors(const QList<QSslError> &);
+#endif
+#if QT_VERSION >= QT_VERSION_CHECK(5, 15, 0)
+ void errorOccurred(QNetworkReply::NetworkError code);
+#endif
+//signals:
+ //void results(QString verify_response);
+ //void error(QString const& reason) const;
+
+public slots:
+signals:
+ void verifyComplete(int status, QDateTime ts, QString callsign, QString code, unsigned int hz, QString const& response);
+ void verifyError(int status, QDateTime ts, QString callsign, QString code, unsigned int hz, QString const& response);
+
+};
+
+
+#endif //WSJTX2_FOXVERIFIER_HPP
diff --git a/Network/LotWUsers.cpp b/Network/LotWUsers.cpp index 10a9a4d8..73480f68 100755 --- a/Network/LotWUsers.cpp +++ b/Network/LotWUsers.cpp @@ -1,196 +1,196 @@ -#include "LotWUsers.hpp" - -#include <future> -#include <chrono> - -#include <QHash> -#include <QString> -#include <QDate> -#include <QFile> -#include <QTextStream> -#include <QDir> -#include <QFileInfo> -#include <QPointer> -#include <QSaveFile> -#include <QUrl> -#include <QNetworkAccessManager> -#include <QNetworkReply> -#include <QDebug> -#include "qt_helpers.hpp" -#include "Logger.hpp" -#include "FileDownload.hpp" -#include "pimpl_impl.hpp" - -#include "moc_LotWUsers.cpp" - -namespace -{ - // Dictionary mapping call sign to date of last upload to LotW - using dictionary = QHash<QString, QDate>; -} - -class LotWUsers::impl final - : public QObject -{ - Q_OBJECT - -public: - impl (LotWUsers * self, QNetworkAccessManager * network_manager) - : self_ {self} - , network_manager_ {network_manager} - , url_valid_ {false} - , redirect_count_ {0} - , age_constraint_ {365} - , connected_ {false} - { - } - - void load (QString const& url, bool fetch, bool forced_fetch) - { - abort (); // abort any active download - auto csv_file_name = csv_file_.fileName (); - auto exists = QFileInfo::exists (csv_file_name); - if (fetch && (!exists || forced_fetch)) - { - current_url_.setUrl(url); - if (current_url_.isValid() && !QSslSocket::supportsSsl()) - { - current_url_.setScheme("http"); - } - redirect_count_ = 0; - - Q_EMIT self_->progress (QString("Starting download from %1").arg(url)); - - lotw_downloader_.configure(network_manager_, - url, - csv_file_name, - "WSJT-X LotW User Downloader"); - if (!connected_) - { - connect(&lotw_downloader_, &FileDownload::complete, [this, csv_file_name] { - LOG_INFO(QString{"LotWUsers: Loading LotW file %1"}.arg(csv_file_name)); - future_load_ = std::async(std::launch::async, &LotWUsers::impl::load_dictionary, this, csv_file_name); - }); - connect(&lotw_downloader_, &FileDownload::error, [this] (QString const& msg) { - LOG_INFO(QString{"LotWUsers: Error downloading LotW file: %1"}.arg(msg)); - Q_EMIT self_->LotW_users_error (msg); - }); - connect( &lotw_downloader_, &FileDownload::progress, [this] (QString const& msg) { - Q_EMIT self_->progress (msg); - }); - connected_ = true; - } - lotw_downloader_.start_download(); - } - else - { - if (exists) - { - // load the database asynchronously - future_load_ = std::async (std::launch::async, &LotWUsers::impl::load_dictionary, this, csv_file_name); - } - } - } - - void abort () - { - lotw_downloader_.abort(); - } - - // Load the database from the given file name - // - // Expects the file to be in CSV format with no header with one - // record per line. Record fields are call sign followed by upload - // date in yyyy-MM-dd format followed by upload time (ignored) - dictionary load_dictionary (QString const& lotw_csv_file) - { - dictionary result; - QFile f {lotw_csv_file}; - if (f.open (QFile::ReadOnly | QFile::Text)) - { - QTextStream s {&f}; - for (auto l = s.readLine (); !l.isNull (); l = s.readLine ()) - { - auto pos = l.indexOf (','); - result[l.left (pos)] = QDate::fromString (l.mid (pos + 1, l.indexOf (',', pos + 1) - pos - 1), "yyyy-MM-dd"); - } - } - else - { - throw std::runtime_error {QObject::tr ("Failed to open LotW users CSV file: '%1'").arg (f.fileName ()).toStdString ()}; - } - LOG_INFO(QString{"LotWUsers: Loaded %1 records from %2"}.arg(result.size()).arg(lotw_csv_file)); - Q_EMIT self_->progress (QString{"Loaded %1 records from LotW."}.arg(result.size())); - Q_EMIT self_->load_finished(); - return result; - } - - LotWUsers * self_; - QNetworkAccessManager * network_manager_; - QSaveFile csv_file_; - bool url_valid_; - QUrl current_url_; // may be a redirect - int redirect_count_; - QPointer<QNetworkReply> reply_; - std::future<dictionary> future_load_; - dictionary last_uploaded_; - qint64 age_constraint_; // days - FileDownload lotw_downloader_; - bool connected_; -}; - -#include "LotWUsers.moc" - -LotWUsers::LotWUsers (QNetworkAccessManager * network_manager, QObject * parent) - : QObject {parent} - , m_ {this, network_manager} -{ - -} - -LotWUsers::~LotWUsers () -{ -} - -void LotWUsers::set_local_file_path (QString const& path) -{ - m_->csv_file_.setFileName (path); -} - -void LotWUsers::load (QString const& url, bool fetch, bool force_download) -{ - m_->load (url, fetch, force_download); -} - -void LotWUsers::set_age_constraint (qint64 uploaded_since_days) -{ - m_->age_constraint_ = uploaded_since_days; -} - -bool LotWUsers::user (QString const& call) const -{ - // check if a pending asynchronous load is ready - if (m_->future_load_.valid () - && std::future_status::ready == m_->future_load_.wait_for (std::chrono::seconds {0})) - { - try - { - // wait for the load to finish if necessary - const_cast<dictionary&> (m_->last_uploaded_) = const_cast<std::future<dictionary>&> (m_->future_load_).get (); - } - catch (std::exception const& e) - { - Q_EMIT LotW_users_error (e.what ()); - } - Q_EMIT load_finished (); - } - if (m_->last_uploaded_.size ()) - { - auto p = m_->last_uploaded_.constFind (call); - if (p != m_->last_uploaded_.end ()) - { - return p.value ().daysTo (QDate::currentDate ()) <= m_->age_constraint_; - } - } - return false; -} +#include "LotWUsers.hpp"
+
+#include <future>
+#include <chrono>
+
+#include <QHash>
+#include <QString>
+#include <QDate>
+#include <QFile>
+#include <QTextStream>
+#include <QDir>
+#include <QFileInfo>
+#include <QPointer>
+#include <QSaveFile>
+#include <QUrl>
+#include <QNetworkAccessManager>
+#include <QNetworkReply>
+#include <QDebug>
+#include "qt_helpers.hpp"
+#include "Logger.hpp"
+#include "FileDownload.hpp"
+#include "pimpl_impl.hpp"
+
+#include "moc_LotWUsers.cpp"
+
+namespace
+{
+ // Dictionary mapping call sign to date of last upload to LotW
+ using dictionary = QHash<QString, QDate>;
+}
+
+class LotWUsers::impl final
+ : public QObject
+{
+ Q_OBJECT
+
+public:
+ impl (LotWUsers * self, QNetworkAccessManager * network_manager)
+ : self_ {self}
+ , network_manager_ {network_manager}
+ , url_valid_ {false}
+ , redirect_count_ {0}
+ , age_constraint_ {365}
+ , connected_ {false}
+ {
+ }
+
+ void load (QString const& url, bool fetch, bool forced_fetch)
+ {
+ abort (); // abort any active download
+ auto csv_file_name = csv_file_.fileName ();
+ auto exists = QFileInfo::exists (csv_file_name);
+ if (fetch && (!exists || forced_fetch))
+ {
+ current_url_.setUrl(url);
+ if (current_url_.isValid() && !QSslSocket::supportsSsl())
+ {
+ current_url_.setScheme("http");
+ }
+ redirect_count_ = 0;
+
+ Q_EMIT self_->progress (QString("Starting download from %1").arg(url));
+
+ lotw_downloader_.configure(network_manager_,
+ url,
+ csv_file_name,
+ "WSJT-X LotW User Downloader");
+ if (!connected_)
+ {
+ connect(&lotw_downloader_, &FileDownload::complete, [this, csv_file_name] {
+ LOG_INFO(QString{"LotWUsers: Loading LotW file %1"}.arg(csv_file_name));
+ future_load_ = std::async(std::launch::async, &LotWUsers::impl::load_dictionary, this, csv_file_name);
+ });
+ connect(&lotw_downloader_, &FileDownload::error, [this] (QString const& msg) {
+ LOG_INFO(QString{"LotWUsers: Error downloading LotW file: %1"}.arg(msg));
+ Q_EMIT self_->LotW_users_error (msg);
+ });
+ connect( &lotw_downloader_, &FileDownload::progress, [this] (QString const& msg) {
+ Q_EMIT self_->progress (msg);
+ });
+ connected_ = true;
+ }
+ lotw_downloader_.start_download();
+ }
+ else
+ {
+ if (exists)
+ {
+ // load the database asynchronously
+ future_load_ = std::async (std::launch::async, &LotWUsers::impl::load_dictionary, this, csv_file_name);
+ }
+ }
+ }
+
+ void abort ()
+ {
+ lotw_downloader_.abort();
+ }
+
+ // Load the database from the given file name
+ //
+ // Expects the file to be in CSV format with no header with one
+ // record per line. Record fields are call sign followed by upload
+ // date in yyyy-MM-dd format followed by upload time (ignored)
+ dictionary load_dictionary (QString const& lotw_csv_file)
+ {
+ dictionary result;
+ QFile f {lotw_csv_file};
+ if (f.open (QFile::ReadOnly | QFile::Text))
+ {
+ QTextStream s {&f};
+ for (auto l = s.readLine (); !l.isNull (); l = s.readLine ())
+ {
+ auto pos = l.indexOf (',');
+ result[l.left (pos)] = QDate::fromString (l.mid (pos + 1, l.indexOf (',', pos + 1) - pos - 1), "yyyy-MM-dd");
+ }
+ }
+ else
+ {
+ throw std::runtime_error {QObject::tr ("Failed to open LotW users CSV file: '%1'").arg (f.fileName ()).toStdString ()};
+ }
+ LOG_INFO(QString{"LotWUsers: Loaded %1 records from %2"}.arg(result.size()).arg(lotw_csv_file));
+ Q_EMIT self_->progress (QString{"Loaded %1 records from LotW."}.arg(result.size()));
+ Q_EMIT self_->load_finished();
+ return result;
+ }
+
+ LotWUsers * self_;
+ QNetworkAccessManager * network_manager_;
+ QSaveFile csv_file_;
+ bool url_valid_;
+ QUrl current_url_; // may be a redirect
+ int redirect_count_;
+ QPointer<QNetworkReply> reply_;
+ std::future<dictionary> future_load_;
+ dictionary last_uploaded_;
+ qint64 age_constraint_; // days
+ FileDownload lotw_downloader_;
+ bool connected_;
+};
+
+#include "LotWUsers.moc"
+
+LotWUsers::LotWUsers (QNetworkAccessManager * network_manager, QObject * parent)
+ : QObject {parent}
+ , m_ {this, network_manager}
+{
+
+}
+
+LotWUsers::~LotWUsers ()
+{
+}
+
+void LotWUsers::set_local_file_path (QString const& path)
+{
+ m_->csv_file_.setFileName (path);
+}
+
+void LotWUsers::load (QString const& url, bool fetch, bool force_download)
+{
+ m_->load (url, fetch, force_download);
+}
+
+void LotWUsers::set_age_constraint (qint64 uploaded_since_days)
+{
+ m_->age_constraint_ = uploaded_since_days;
+}
+
+bool LotWUsers::user (QString const& call) const
+{
+ // check if a pending asynchronous load is ready
+ if (m_->future_load_.valid ()
+ && std::future_status::ready == m_->future_load_.wait_for (std::chrono::seconds {0}))
+ {
+ try
+ {
+ // wait for the load to finish if necessary
+ const_cast<dictionary&> (m_->last_uploaded_) = const_cast<std::future<dictionary>&> (m_->future_load_).get ();
+ }
+ catch (std::exception const& e)
+ {
+ Q_EMIT LotW_users_error (e.what ());
+ }
+ Q_EMIT load_finished ();
+ }
+ if (m_->last_uploaded_.size ())
+ {
+ auto p = m_->last_uploaded_.constFind (call);
+ if (p != m_->last_uploaded_.end ())
+ {
+ return p.value ().daysTo (QDate::currentDate ()) <= m_->age_constraint_;
+ }
+ }
+ return false;
+}
diff --git a/Network/LotWUsers.hpp b/Network/LotWUsers.hpp index 2d4d1307..cfb9b890 100755 --- a/Network/LotWUsers.hpp +++ b/Network/LotWUsers.hpp @@ -1,42 +1,42 @@ -#ifndef LOTW_USERS_HPP_ -#define LOTW_USERS_HPP_ - -#include <boost/core/noncopyable.hpp> -#include <QObject> -#include "pimpl_h.hpp" - -class QString; -class QDate; -class QNetworkAccessManager; - -// -// LotWUsers - Lookup Logbook of the World users -// -class LotWUsers final - : public QObject -{ - Q_OBJECT - -public: - explicit LotWUsers (QNetworkAccessManager *, QObject * parent = 0); - ~LotWUsers (); - - void set_local_file_path (QString const&); - - Q_SLOT void load (QString const& url, bool fetch = true, bool force_download = false); - Q_SLOT void set_age_constraint (qint64 uploaded_since_days); - - // returns true if the specified call sign 'call' has uploaded their - // log to LotW in the last 'age_constraint_days' days - bool user (QString const& call) const; - - Q_SIGNAL void LotW_users_error (QString const& reason) const; - Q_SIGNAL void progress (QString const& reason) const; - Q_SIGNAL void load_finished () const; - -private: - class impl; - pimpl<impl> m_; -}; - -#endif +#ifndef LOTW_USERS_HPP_
+#define LOTW_USERS_HPP_
+
+#include <boost/core/noncopyable.hpp>
+#include <QObject>
+#include "pimpl_h.hpp"
+
+class QString;
+class QDate;
+class QNetworkAccessManager;
+
+//
+// LotWUsers - Lookup Logbook of the World users
+//
+class LotWUsers final
+ : public QObject
+{
+ Q_OBJECT
+
+public:
+ explicit LotWUsers (QNetworkAccessManager *, QObject * parent = 0);
+ ~LotWUsers ();
+
+ void set_local_file_path (QString const&);
+
+ Q_SLOT void load (QString const& url, bool fetch = true, bool force_download = false);
+ Q_SLOT void set_age_constraint (qint64 uploaded_since_days);
+
+ // returns true if the specified call sign 'call' has uploaded their
+ // log to LotW in the last 'age_constraint_days' days
+ bool user (QString const& call) const;
+
+ Q_SIGNAL void LotW_users_error (QString const& reason) const;
+ Q_SIGNAL void progress (QString const& reason) const;
+ Q_SIGNAL void load_finished () const;
+
+private:
+ class impl;
+ pimpl<impl> m_;
+};
+
+#endif
diff --git a/Network/MessageClient.cpp b/Network/MessageClient.cpp index c2100d1b..933bc8a7 100755 --- a/Network/MessageClient.cpp +++ b/Network/MessageClient.cpp @@ -1,678 +1,680 @@ -#include "MessageClient.hpp" - -#include <stdexcept> -#include <vector> -#include <algorithm> -#include <limits> - -#include <QUdpSocket> -#include <QNetworkInterface> -#include <QHostInfo> -#include <QTimer> -#include <QQueue> -#include <QByteArray> -#include <QColor> -#include <QDebug> - -#include "NetworkMessage.hpp" -#include "qt_helpers.hpp" -#include "pimpl_impl.hpp" - -#include "moc_MessageClient.cpp" - -// some trace macros -#if WSJT_TRACE_UDP -#define TRACE_UDP(MSG) qDebug () << QString {"MessageClient::%1:"}.arg (__func__) << MSG -#else -#define TRACE_UDP(MSG) -#endif - -class MessageClient::impl - : public QUdpSocket -{ - Q_OBJECT; - -public: - impl (QString const& id, QString const& version, QString const& revision, - port_type server_port, int TTL, MessageClient * self) - : self_ {self} - , enabled_ {false} - , id_ {id} - , version_ {version} - , revision_ {revision} - , dns_lookup_id_ {-1} - , server_port_ {server_port} - , TTL_ {TTL} - , schema_ {2} // use 2 prior to negotiation not 1 which is broken - , heartbeat_timer_ {new QTimer {this}} - { - connect (heartbeat_timer_, &QTimer::timeout, this, &impl::heartbeat); - connect (this, &QIODevice::readyRead, this, &impl::pending_datagrams); - - heartbeat_timer_->start (NetworkMessage::pulse * 1000); - } - - ~impl () - { - closedown (); - if (dns_lookup_id_ != -1) - { - QHostInfo::abortHostLookup (dns_lookup_id_); - } - } - - enum StreamStatus {Fail, Short, OK}; - - void set_server (QString const& server_name, QStringList const& network_interface_names); - Q_SLOT void host_info_results (QHostInfo); - void start (); - void parse_message (QByteArray const&); - void pending_datagrams (); - void heartbeat (); - void closedown (); - StreamStatus check_status (QDataStream const&) const; - void send_message (QByteArray const&, bool queue_if_pending = true, bool allow_duplicates = false); - void send_message (QDataStream const& out, QByteArray const& message, bool queue_if_pending = true, bool allow_duplicates = false) - { - if (OK == check_status (out)) - { - send_message (message, queue_if_pending, allow_duplicates); - } - else - { - Q_EMIT self_->error ("Error creating UDP message"); - } - } - - MessageClient * self_; - bool enabled_; - QString id_; - QString version_; - QString revision_; - int dns_lookup_id_; - QHostAddress server_; - port_type server_port_; - int TTL_; - std::vector<QNetworkInterface> network_interfaces_; - quint32 schema_; - QTimer * heartbeat_timer_; - std::vector<QHostAddress> blocked_addresses_; - - // hold messages sent before host lookup completes asynchronously - QQueue<QByteArray> pending_messages_; - QByteArray last_message_; -}; - -#include "MessageClient.moc" - -void MessageClient::impl::set_server (QString const& server_name, QStringList const& network_interface_names) -{ - // qDebug () << "MessageClient server:" << server_name << "port:" << server_port_ << "interfaces:" << network_interface_names; - server_.setAddress (server_name); - network_interfaces_.clear (); - for (auto const& net_if_name : network_interface_names) - { - network_interfaces_.push_back (QNetworkInterface::interfaceFromName (net_if_name)); - } - - if (server_.isNull () && server_name.size ()) // DNS lookup required - { - // queue a host address lookup -#if QT_VERSION >= QT_VERSION_CHECK(5, 9, 0) - dns_lookup_id_ = QHostInfo::lookupHost (server_name, this, &MessageClient::impl::host_info_results); -#else - dns_lookup_id_ = QHostInfo::lookupHost (server_name, this, SLOT (host_info_results (QHostInfo))); -#endif - } - else - { - start (); - } -} - -void MessageClient::impl::host_info_results (QHostInfo host_info) -{ - if (host_info.lookupId () != dns_lookup_id_) return; - dns_lookup_id_ = -1; - if (QHostInfo::NoError != host_info.error ()) - { - Q_EMIT self_->error ("UDP server DNS lookup failed: " + host_info.errorString ()); - return; - } - else - { - auto const& server_addresses = host_info.addresses (); - if (server_addresses.size ()) - { - server_ = server_addresses[0]; - } - } - start (); -} - -void MessageClient::impl::start () -{ - if (server_.isNull ()) - { - Q_EMIT self_->close (); - pending_messages_.clear (); // discard - return; - } - - if (is_broadcast_address (server_)) - { - Q_EMIT self_->error ("IPv4 broadcast not supported, please specify the loop-back address, a server host address, or multicast group address"); - pending_messages_.clear (); // discard - return; - } - - if (blocked_addresses_.end () != std::find (blocked_addresses_.begin (), blocked_addresses_.end (), server_)) - { - Q_EMIT self_->error ("UDP server blocked, please try another"); - pending_messages_.clear (); // discard - return; - } - - TRACE_UDP ("Trying server:" << server_.toString ()); - QHostAddress interface_addr {IPv6Protocol == server_.protocol () ? QHostAddress::AnyIPv6 : QHostAddress::AnyIPv4}; - - if (localAddress () != interface_addr) - { - if (UnconnectedState != state () || state ()) - { - close (); - } - // bind to an ephemeral port on the selected interface and set - // up for sending datagrams - bind (interface_addr); - // qDebug () << "Bound to UDP port:" << localPort () << "on:" << localAddress (); - - // set multicast TTL to limit scope when sending to multicast - // group addresses - setSocketOption (MulticastTtlOption, TTL_); - } - - // send initial heartbeat which allows schema negotiation - heartbeat (); - - // clear any backlog - while (pending_messages_.size ()) - { - send_message (pending_messages_.dequeue (), true, false); - } -} - -void MessageClient::impl::pending_datagrams () -{ - while (hasPendingDatagrams ()) - { - QByteArray datagram; - datagram.resize (pendingDatagramSize ()); - QHostAddress sender_address; - port_type sender_port; - if (0 <= readDatagram (datagram.data (), datagram.size (), &sender_address, &sender_port)) - { - TRACE_UDP ("message received from:" << sender_address << "port:" << sender_port); - parse_message (datagram); - } - } -} - -void MessageClient::impl::parse_message (QByteArray const& msg) -{ - try - { - // - // message format is described in NetworkMessage.hpp - // - NetworkMessage::Reader in {msg}; - if (OK == check_status (in)) - { - if (schema_ < in.schema ()) // one time record of server's - // negotiated schema - { - schema_ = in.schema (); - } - - if (!enabled_) - { - TRACE_UDP ("message processing disabled for id:" << in.id ()); - return; - } - - // - // message format is described in NetworkMessage.hpp - // - switch (in.type ()) - { - case NetworkMessage::Reply: - { - // unpack message - QTime time; - qint32 snr; - float delta_time; - quint32 delta_frequency; - QByteArray mode; - QByteArray message; - bool low_confidence {false}; - quint8 modifiers {0}; - in >> time >> snr >> delta_time >> delta_frequency >> mode >> message - >> low_confidence >> modifiers; - TRACE_UDP ("Reply: time:" << time << "snr:" << snr << "dt:" << delta_time << "df:" << delta_frequency << "mode:" << mode << "message:" << message << "low confidence:" << low_confidence << "modifiers: 0x" -#if QT_VERSION >= QT_VERSION_CHECK (5, 15, 0) - << Qt::hex -#else - << hex -#endif - << modifiers); - if (check_status (in) != Fail) - { - Q_EMIT self_->reply (time, snr, delta_time, delta_frequency - , QString::fromUtf8 (mode), QString::fromUtf8 (message) - , low_confidence, modifiers); - } - } - break; - - case NetworkMessage::Clear: - { - quint8 window {0}; - in >> window; - TRACE_UDP ("Clear window:" << window); - if (check_status (in) != Fail) - { - Q_EMIT self_->clear_decodes (window); - } - } - break; - - case NetworkMessage::Close: - TRACE_UDP ("Close"); - if (check_status (in) != Fail) - { - last_message_.clear (); - Q_EMIT self_->close (); - } - break; - - case NetworkMessage::Replay: - TRACE_UDP ("Replay"); - if (check_status (in) != Fail) - { - last_message_.clear (); - Q_EMIT self_->replay (); - } - break; - - case NetworkMessage::HaltTx: - { - bool auto_only {false}; - in >> auto_only; - TRACE_UDP ("Halt Tx auto_only:" << auto_only); - if (check_status (in) != Fail) - { - Q_EMIT self_->halt_tx (auto_only); - } - } - break; - - case NetworkMessage::FreeText: - { - QByteArray message; - bool send {true}; - in >> message >> send; - TRACE_UDP ("FreeText message:" << message << "send:" << send); - if (check_status (in) != Fail) - { - Q_EMIT self_->free_text (QString::fromUtf8 (message), send); - } - } - break; - - case NetworkMessage::Location: - { - QByteArray location; - in >> location; - TRACE_UDP ("Location location:" << location); - if (check_status (in) != Fail) - { - Q_EMIT self_->location (QString::fromUtf8 (location)); - } - } - break; - - case NetworkMessage::HighlightCallsign: - { - QByteArray call; - QColor bg; // default invalid color - QColor fg; // default invalid color - bool last_only {false}; - in >> call >> bg >> fg >> last_only; - TRACE_UDP ("HighlightCallsign call:" << call << "bg:" << bg << "fg:" << fg << "last only:" << last_only); - if (check_status (in) != Fail && call.size ()) - { - Q_EMIT self_->highlight_callsign (QString::fromUtf8 (call), bg, fg, last_only); - } - } - break; - - case NetworkMessage::SwitchConfiguration: - { - QByteArray configuration_name; - in >> configuration_name; - TRACE_UDP ("Switch Configuration name:" << configuration_name); - if (check_status (in) != Fail) - { - Q_EMIT self_->switch_configuration (QString::fromUtf8 (configuration_name)); - } - } - break; - - case NetworkMessage::Configure: - { - QByteArray mode; - quint32 frequency_tolerance; - QByteArray submode; - bool fast_mode {false}; - quint32 tr_period {std::numeric_limits<quint32>::max ()}; - quint32 rx_df {std::numeric_limits<quint32>::max ()}; - QByteArray dx_call; - QByteArray dx_grid; - bool generate_messages {false}; - in >> mode >> frequency_tolerance >> submode >> fast_mode >> tr_period >> rx_df - >> dx_call >> dx_grid >> generate_messages; - TRACE_UDP ("Configure mode:" << mode << "frequency tolerance:" << frequency_tolerance << "submode:" << submode << "fast mode:" << fast_mode << "T/R period:" << tr_period << "rx df:" << rx_df << "dx call:" << dx_call << "dx grid:" << dx_grid << "generate messages:" << generate_messages); - if (check_status (in) != Fail) - { - Q_EMIT self_->configure (QString::fromUtf8 (mode), frequency_tolerance - , QString::fromUtf8 (submode), fast_mode, tr_period, rx_df - , QString::fromUtf8 (dx_call), QString::fromUtf8 (dx_grid) - , generate_messages); - } - } - break; - - case NetworkMessage::AnnotationInfo: { - QByteArray dx_call; - bool sort_order_provided{false}; - quint32 sort_order{std::numeric_limits<quint32>::max()}; - in >> dx_call >> sort_order_provided >> sort_order; - TRACE_UDP ("External Callsign Info:" << dx_call << "sort_order_provided:" << sort_order_provided - << "sort_order:" << sort_order); - if (sort_order > 50000) sort_order = 50000; - if (check_status(in) != Fail) { - Q_EMIT - self_->annotation_info(QString::fromUtf8(dx_call), sort_order_provided, sort_order); - } - } - break; - - default: - // Ignore - // - // Note that although server heartbeat messages are not - // parsed here they are still partially parsed in the - // message reader class to negotiate the maximum schema - // number being used on the network. - if (NetworkMessage::Heartbeat != in.type ()) - { - TRACE_UDP ("ignoring message type:" << in.type ()); - } - break; - } - } - else - { - TRACE_UDP ("ignored message for id:" << in.id ()); - } - } - catch (std::exception const& e) - { - Q_EMIT self_->error (QString {"MessageClient exception: %1"}.arg (e.what ())); - } - catch (...) - { - Q_EMIT self_->error ("Unexpected exception in MessageClient"); - } -} - -void MessageClient::impl::heartbeat () -{ - if (server_port_ && !server_.isNull ()) - { - QByteArray message; - NetworkMessage::Builder out {&message, NetworkMessage::Heartbeat, id_, schema_}; - out << NetworkMessage::Builder::schema_number // maximum schema number accepted - << version_.toUtf8 () << revision_.toUtf8 (); - TRACE_UDP ("schema:" << schema_ << "max schema:" << NetworkMessage::Builder::schema_number << "version:" << version_ << "revision:" << revision_); - send_message (out, message, false, true); - } -} - -void MessageClient::impl::closedown () -{ - if (server_port_ && !server_.isNull ()) - { - QByteArray message; - NetworkMessage::Builder out {&message, NetworkMessage::Close, id_, schema_}; - TRACE_UDP (""); - send_message (out, message, false); - } -} - -void MessageClient::impl::send_message (QByteArray const& message, bool queue_if_pending, bool allow_duplicates) -{ - if (server_port_) - { - if (!server_.isNull ()) - { - if (allow_duplicates || message != last_message_) // avoid duplicates - { - if (is_multicast_address (server_)) - { - // send datagram on each selected network interface - std::for_each (network_interfaces_.begin (), network_interfaces_.end () - , [&] (QNetworkInterface const& net_if) { - setMulticastInterface (net_if); - // qDebug () << "Multicast UDP datagram sent to:" << server_ << "port:" << server_port_ << "on:" << multicastInterface ().humanReadableName (); - writeDatagram (message, server_, server_port_); - }); - } - else - { - // qDebug () << "Unicast UDP datagram sent to:" << server_ << "port:" << server_port_; - writeDatagram (message, server_, server_port_); - } - last_message_ = message; - } - } - else if (queue_if_pending) - { - pending_messages_.enqueue (message); - } - } -} - -auto MessageClient::impl::check_status (QDataStream const& stream) const -> StreamStatus -{ - auto stat = stream.status (); - StreamStatus result {Fail}; - switch (stat) - { - case QDataStream::ReadPastEnd: - result = Short; - break; - - case QDataStream::ReadCorruptData: - Q_EMIT self_->error ("Message serialization error: read corrupt data"); - break; - - case QDataStream::WriteFailed: - Q_EMIT self_->error ("Message serialization error: write error"); - break; - - default: - result = OK; - break; - } - return result; -} - -MessageClient::MessageClient (QString const& id, QString const& version, QString const& revision, - QString const& server_name, port_type server_port, - QStringList const& network_interface_names, - int TTL, QObject * self) - : QObject {self} - , m_ {id, version, revision, server_port, TTL, this} -{ - connect (&*m_ -#if QT_VERSION < QT_VERSION_CHECK(5, 15, 0) - , static_cast<void (impl::*) (impl::SocketError)> (&impl::error), [this] (impl::SocketError e) -#else - , &impl::errorOccurred, [this] (impl::SocketError e) -#endif - { -#if defined (Q_OS_WIN) - if (e != impl::NetworkError // take this out when Qt 5.5 stops doing this spuriously - && e != impl::ConnectionRefusedError) // not interested in this with UDP socket - { -#else - { - Q_UNUSED (e); -#endif - Q_EMIT error (m_->errorString ()); - } - }); - m_->set_server (server_name, network_interface_names); -} - -QHostAddress MessageClient::server_address () const -{ - return m_->server_; -} - -auto MessageClient::server_port () const -> port_type -{ - return m_->server_port_; -} - -void MessageClient::set_server (QString const& server_name, QStringList const& network_interface_names) -{ - m_->set_server (server_name, network_interface_names); -} - -void MessageClient::set_server_port (port_type server_port) -{ - m_->server_port_ = server_port; -} - -void MessageClient::set_TTL (int TTL) -{ - m_->TTL_ = TTL; - m_->setSocketOption (QAbstractSocket::MulticastTtlOption, m_->TTL_); -} - -void MessageClient::enable (bool flag) -{ - m_->enabled_ = flag; -} - -void MessageClient::status_update (Frequency f, QString const& mode, QString const& dx_call - , QString const& report, QString const& tx_mode - , bool tx_enabled, bool transmitting, bool decoding - , quint32 rx_df, quint32 tx_df, QString const& de_call - , QString const& de_grid, QString const& dx_grid - , bool watchdog_timeout, QString const& sub_mode - , bool fast_mode, quint8 special_op_mode - , quint32 frequency_tolerance, quint32 tr_period - , QString const& configuration_name - , QString const& tx_message) -{ - if (m_->server_port_ && !m_->server_.isNull ()) - { - QByteArray message; - NetworkMessage::Builder out {&message, NetworkMessage::Status, m_->id_, m_->schema_}; - out << f << mode.toUtf8 () << dx_call.toUtf8 () << report.toUtf8 () << tx_mode.toUtf8 () - << tx_enabled << transmitting << decoding << rx_df << tx_df << de_call.toUtf8 () - << de_grid.toUtf8 () << dx_grid.toUtf8 () << watchdog_timeout << sub_mode.toUtf8 () - << fast_mode << special_op_mode << frequency_tolerance << tr_period << configuration_name.toUtf8 () - << tx_message.toUtf8 (); - TRACE_UDP ("frequency:" << f << "mode:" << mode << "DX:" << dx_call << "report:" << report << "Tx mode:" << tx_mode << "tx_enabled:" << tx_enabled << "Tx:" << transmitting << "decoding:" << decoding << "Rx df:" << rx_df << "Tx df:" << tx_df << "DE:" << de_call << "DE grid:" << de_grid << "DX grid:" << dx_grid << "w/d t/o:" << watchdog_timeout << "sub_mode:" << sub_mode << "fast mode:" << fast_mode << "spec op mode:" << special_op_mode << "frequency tolerance:" << frequency_tolerance << "T/R period:" << tr_period << "configuration name:" << configuration_name << "Tx message:" << tx_message); - m_->send_message (out, message); - } -} - -void MessageClient::decode (bool is_new, QTime time, qint32 snr, float delta_time, quint32 delta_frequency - , QString const& mode, QString const& message_text, bool low_confidence - , bool off_air) -{ - if (m_->server_port_ && !m_->server_.isNull ()) - { - QByteArray message; - NetworkMessage::Builder out {&message, NetworkMessage::Decode, m_->id_, m_->schema_}; - out << is_new << time << snr << delta_time << delta_frequency << mode.toUtf8 () - << message_text.toUtf8 () << low_confidence << off_air; - TRACE_UDP ("new" << is_new << "time:" << time << "snr:" << snr << "dt:" << delta_time << "df:" << delta_frequency << "mode:" << mode << "text:" << message_text << "low conf:" << low_confidence << "off air:" << off_air); - m_->send_message (out, message); - } -} - -void MessageClient::WSPR_decode (bool is_new, QTime time, qint32 snr, float delta_time, Frequency frequency - , qint32 drift, QString const& callsign, QString const& grid, qint32 power - , bool off_air) -{ - if (m_->server_port_ && !m_->server_.isNull ()) - { - QByteArray message; - NetworkMessage::Builder out {&message, NetworkMessage::WSPRDecode, m_->id_, m_->schema_}; - out << is_new << time << snr << delta_time << frequency << drift << callsign.toUtf8 () - << grid.toUtf8 () << power << off_air; - TRACE_UDP ("new:" << is_new << "time:" << time << "snr:" << snr << "dt:" << delta_time << "frequency:" << frequency << "drift:" << drift << "call:" << callsign << "grid:" << grid << "pwr:" << power << "off air:" << off_air); - m_->send_message (out, message); - } -} - -void MessageClient::decodes_cleared () -{ - if (m_->server_port_ && !m_->server_.isNull ()) - { - QByteArray message; - NetworkMessage::Builder out {&message, NetworkMessage::Clear, m_->id_, m_->schema_}; - TRACE_UDP (""); - m_->send_message (out, message); - } -} - -void MessageClient::qso_logged (QDateTime time_off, QString const& dx_call, QString const& dx_grid - , Frequency dial_frequency, QString const& mode, QString const& report_sent - , QString const& report_received, QString const& tx_power - , QString const& comments, QString const& name, QDateTime time_on - , QString const& operator_call, QString const& my_call - , QString const& my_grid, QString const& exchange_sent - , QString const& exchange_rcvd, QString const& propmode) -{ - if (m_->server_port_ && !m_->server_.isNull ()) - { - QByteArray message; - NetworkMessage::Builder out {&message, NetworkMessage::QSOLogged, m_->id_, m_->schema_}; - out << time_off << dx_call.toUtf8 () << dx_grid.toUtf8 () << dial_frequency << mode.toUtf8 () - << report_sent.toUtf8 () << report_received.toUtf8 () << tx_power.toUtf8 () << comments.toUtf8 () - << name.toUtf8 () << time_on << operator_call.toUtf8 () << my_call.toUtf8 () << my_grid.toUtf8 () - << exchange_sent.toUtf8 () << exchange_rcvd.toUtf8 () << propmode.toUtf8 (); - TRACE_UDP ("time off:" << time_off << "DX:" << dx_call << "DX grid:" << dx_grid << "dial:" << dial_frequency << "mode:" << mode << "sent:" << report_sent << "rcvd:" << report_received << "pwr:" << tx_power << "comments:" << comments << "name:" << name << "time on:" << time_on << "op:" << operator_call << "DE:" << my_call << "DE grid:" << my_grid << "exch sent:" << exchange_sent << "exch rcvd:" << exchange_rcvd << "prop_mode:" << propmode); - m_->send_message (out, message); - } -} - -void MessageClient::logged_ADIF (QByteArray const& ADIF_record) -{ - if (m_->server_port_ && !m_->server_.isNull ()) - { - QByteArray message; - NetworkMessage::Builder out {&message, NetworkMessage::LoggedADIF, m_->id_, m_->schema_}; - QByteArray ADIF {"\n<adif_ver:5>3.1.0\n<programid:6>WSJT-X\n<EOH>\n" + ADIF_record + " <EOR>"}; - out << ADIF; - TRACE_UDP ("ADIF:" << ADIF); - m_->send_message (out, message); - } -} +#include "MessageClient.hpp"
+
+#include <stdexcept>
+#include <vector>
+#include <algorithm>
+#include <limits>
+
+#include <QUdpSocket>
+#include <QNetworkInterface>
+#include <QHostInfo>
+#include <QTimer>
+#include <QQueue>
+#include <QByteArray>
+#include <QColor>
+#include <QDebug>
+
+#include "NetworkMessage.hpp"
+#include "qt_helpers.hpp"
+#include "pimpl_impl.hpp"
+
+#include "moc_MessageClient.cpp"
+
+// some trace macros
+#if WSJT_TRACE_UDP
+#define TRACE_UDP(MSG) qDebug () << QString {"MessageClient::%1:"}.arg (__func__) << MSG
+#else
+#define TRACE_UDP(MSG)
+#endif
+
+class MessageClient::impl
+ : public QUdpSocket
+{
+ Q_OBJECT;
+
+public:
+ impl (QString const& id, QString const& version, QString const& revision,
+ port_type server_port, int TTL, MessageClient * self)
+ : self_ {self}
+ , enabled_ {false}
+ , id_ {id}
+ , version_ {version}
+ , revision_ {revision}
+ , dns_lookup_id_ {-1}
+ , server_port_ {server_port}
+ , TTL_ {TTL}
+ , schema_ {2} // use 2 prior to negotiation not 1 which is broken
+ , heartbeat_timer_ {new QTimer {this}}
+ {
+ connect (heartbeat_timer_, &QTimer::timeout, this, &impl::heartbeat);
+ connect (this, &QIODevice::readyRead, this, &impl::pending_datagrams);
+
+ heartbeat_timer_->start (NetworkMessage::pulse * 1000);
+ }
+
+ ~impl ()
+ {
+ closedown ();
+ if (dns_lookup_id_ != -1)
+ {
+ QHostInfo::abortHostLookup (dns_lookup_id_);
+ }
+ }
+
+ enum StreamStatus {Fail, Short, OK};
+
+ void set_server (QString const& server_name, QStringList const& network_interface_names);
+ Q_SLOT void host_info_results (QHostInfo);
+ void start ();
+ void parse_message (QByteArray const&);
+ void pending_datagrams ();
+ void heartbeat ();
+ void closedown ();
+ StreamStatus check_status (QDataStream const&) const;
+ void send_message (QByteArray const&, bool queue_if_pending = true, bool allow_duplicates = false);
+ void send_message (QDataStream const& out, QByteArray const& message, bool queue_if_pending = true, bool allow_duplicates = false)
+ {
+ if (OK == check_status (out))
+ {
+ send_message (message, queue_if_pending, allow_duplicates);
+ }
+ else
+ {
+ Q_EMIT self_->error ("Error creating UDP message");
+ }
+ }
+
+ MessageClient * self_;
+ bool enabled_;
+ QString id_;
+ QString version_;
+ QString revision_;
+ int dns_lookup_id_;
+ QHostAddress server_;
+ port_type server_port_;
+ int TTL_;
+ std::vector<QNetworkInterface> network_interfaces_;
+ quint32 schema_;
+ QTimer * heartbeat_timer_;
+ std::vector<QHostAddress> blocked_addresses_;
+
+ // hold messages sent before host lookup completes asynchronously
+ QQueue<QByteArray> pending_messages_;
+ QByteArray last_message_;
+};
+
+#include "MessageClient.moc"
+
+void MessageClient::impl::set_server (QString const& server_name, QStringList const& network_interface_names)
+{
+ // qDebug () << "MessageClient server:" << server_name << "port:" << server_port_ << "interfaces:" << network_interface_names;
+ server_.setAddress (server_name);
+ network_interfaces_.clear ();
+ for (auto const& net_if_name : network_interface_names)
+ {
+ network_interfaces_.push_back (QNetworkInterface::interfaceFromName (net_if_name));
+ }
+
+ if (server_.isNull () && server_name.size ()) // DNS lookup required
+ {
+ // queue a host address lookup
+#if QT_VERSION >= QT_VERSION_CHECK(5, 9, 0)
+ dns_lookup_id_ = QHostInfo::lookupHost (server_name, this, &MessageClient::impl::host_info_results);
+#else
+ dns_lookup_id_ = QHostInfo::lookupHost (server_name, this, SLOT (host_info_results (QHostInfo)));
+#endif
+ }
+ else
+ {
+ start ();
+ }
+}
+
+void MessageClient::impl::host_info_results (QHostInfo host_info)
+{
+ if (host_info.lookupId () != dns_lookup_id_) return;
+ dns_lookup_id_ = -1;
+ if (QHostInfo::NoError != host_info.error ())
+ {
+ Q_EMIT self_->error ("UDP server DNS lookup failed: " + host_info.errorString ());
+ return;
+ }
+ else
+ {
+ auto const& server_addresses = host_info.addresses ();
+ if (server_addresses.size ())
+ {
+ server_ = server_addresses[0];
+ }
+ }
+ start ();
+}
+
+void MessageClient::impl::start ()
+{
+ if (server_.isNull ())
+ {
+ Q_EMIT self_->close ();
+ pending_messages_.clear (); // discard
+ return;
+ }
+
+ if (is_broadcast_address (server_))
+ {
+ Q_EMIT self_->error ("IPv4 broadcast not supported, please specify the loop-back address, a server host address, or multicast group address");
+ pending_messages_.clear (); // discard
+ return;
+ }
+
+ if (blocked_addresses_.end () != std::find (blocked_addresses_.begin (), blocked_addresses_.end (), server_))
+ {
+ Q_EMIT self_->error ("UDP server blocked, please try another");
+ pending_messages_.clear (); // discard
+ return;
+ }
+
+ TRACE_UDP ("Trying server:" << server_.toString ());
+ QHostAddress interface_addr {IPv6Protocol == server_.protocol () ? QHostAddress::AnyIPv6 : QHostAddress::AnyIPv4};
+
+ if (localAddress () != interface_addr)
+ {
+ if (UnconnectedState != state () || state ())
+ {
+ close ();
+ }
+ // bind to an ephemeral port on the selected interface and set
+ // up for sending datagrams
+ bind (interface_addr);
+ // qDebug () << "Bound to UDP port:" << localPort () << "on:" << localAddress ();
+
+ // set multicast TTL to limit scope when sending to multicast
+ // group addresses
+ setSocketOption (MulticastTtlOption, TTL_);
+ }
+
+ // send initial heartbeat which allows schema negotiation
+ heartbeat ();
+
+ // clear any backlog
+ while (pending_messages_.size ())
+ {
+ send_message (pending_messages_.dequeue (), true, false);
+ }
+}
+
+void MessageClient::impl::pending_datagrams ()
+{
+ while (hasPendingDatagrams ())
+ {
+ QByteArray datagram;
+ datagram.resize (pendingDatagramSize ());
+ QHostAddress sender_address;
+ port_type sender_port;
+ if (0 <= readDatagram (datagram.data (), datagram.size (), &sender_address, &sender_port))
+ {
+ TRACE_UDP ("message received from:" << sender_address << "port:" << sender_port);
+ parse_message (datagram);
+ }
+ }
+}
+
+void MessageClient::impl::parse_message (QByteArray const& msg)
+{
+ try
+ {
+ //
+ // message format is described in NetworkMessage.hpp
+ //
+ NetworkMessage::Reader in {msg};
+ if (OK == check_status (in))
+ {
+ if (schema_ < in.schema ()) // one time record of server's
+ // negotiated schema
+ {
+ schema_ = in.schema ();
+ }
+
+ if (!enabled_)
+ {
+ TRACE_UDP ("message processing disabled for id:" << in.id ());
+ return;
+ }
+
+ //
+ // message format is described in NetworkMessage.hpp
+ //
+ switch (in.type ())
+ {
+ case NetworkMessage::Reply:
+ {
+ // unpack message
+ QTime time;
+ qint32 snr;
+ float delta_time;
+ quint32 delta_frequency;
+ QByteArray mode;
+ QByteArray message;
+ bool low_confidence {false};
+ quint8 modifiers {0};
+ in >> time >> snr >> delta_time >> delta_frequency >> mode >> message
+ >> low_confidence >> modifiers;
+ TRACE_UDP ("Reply: time:" << time << "snr:" << snr << "dt:" << delta_time << "df:" << delta_frequency << "mode:" << mode << "message:" << message << "low confidence:" << low_confidence << "modifiers: 0x"
+#if QT_VERSION >= QT_VERSION_CHECK (5, 15, 0)
+ << Qt::hex
+#else
+ << hex
+#endif
+ << modifiers);
+ if (check_status (in) != Fail)
+ {
+ Q_EMIT self_->reply (time, snr, delta_time, delta_frequency
+ , QString::fromUtf8 (mode), QString::fromUtf8 (message)
+ , low_confidence, modifiers);
+ }
+ }
+ break;
+
+ case NetworkMessage::Clear:
+ {
+ quint8 window {0};
+ in >> window;
+ TRACE_UDP ("Clear window:" << window);
+ if (check_status (in) != Fail)
+ {
+ Q_EMIT self_->clear_decodes (window);
+ }
+ }
+ break;
+
+ case NetworkMessage::Close:
+ TRACE_UDP ("Close");
+ if (check_status (in) != Fail)
+ {
+ last_message_.clear ();
+ Q_EMIT self_->close ();
+ }
+ break;
+
+ case NetworkMessage::Replay:
+ TRACE_UDP ("Replay");
+ if (check_status (in) != Fail)
+ {
+ last_message_.clear ();
+ Q_EMIT self_->replay ();
+ }
+ break;
+
+ case NetworkMessage::HaltTx:
+ {
+ bool auto_only {false};
+ in >> auto_only;
+ TRACE_UDP ("Halt Tx auto_only:" << auto_only);
+ if (check_status (in) != Fail)
+ {
+ Q_EMIT self_->halt_tx (auto_only);
+ }
+ }
+ break;
+
+ case NetworkMessage::FreeText:
+ {
+ QByteArray message;
+ bool send {true};
+ in >> message >> send;
+ TRACE_UDP ("FreeText message:" << message << "send:" << send);
+ if (check_status (in) != Fail)
+ {
+ Q_EMIT self_->free_text (QString::fromUtf8 (message), send);
+ }
+ }
+ break;
+
+ case NetworkMessage::Location:
+ {
+ QByteArray location;
+ in >> location;
+ TRACE_UDP ("Location location:" << location);
+ if (check_status (in) != Fail)
+ {
+ Q_EMIT self_->location (QString::fromUtf8 (location));
+ }
+ }
+ break;
+
+ case NetworkMessage::HighlightCallsign:
+ {
+ QByteArray call;
+ QColor bg; // default invalid color
+ QColor fg; // default invalid color
+ bool last_only {false};
+ in >> call >> bg >> fg >> last_only;
+ TRACE_UDP ("HighlightCallsign call:" << call << "bg:" << bg << "fg:" << fg << "last only:" << last_only);
+ if (check_status (in) != Fail && call.size ())
+ {
+ Q_EMIT self_->highlight_callsign (QString::fromUtf8 (call), bg, fg, last_only);
+ }
+ }
+ break;
+
+ case NetworkMessage::SwitchConfiguration:
+ {
+ QByteArray configuration_name;
+ in >> configuration_name;
+ TRACE_UDP ("Switch Configuration name:" << configuration_name);
+ if (check_status (in) != Fail)
+ {
+ Q_EMIT self_->switch_configuration (QString::fromUtf8 (configuration_name));
+ }
+ }
+ break;
+
+ case NetworkMessage::Configure:
+ {
+ QByteArray mode;
+ quint32 frequency_tolerance;
+ QByteArray submode;
+ bool fast_mode {false};
+ quint32 tr_period {std::numeric_limits<quint32>::max ()};
+ quint32 rx_df {std::numeric_limits<quint32>::max ()};
+ QByteArray dx_call;
+ QByteArray dx_grid;
+ bool generate_messages {false};
+ in >> mode >> frequency_tolerance >> submode >> fast_mode >> tr_period >> rx_df
+ >> dx_call >> dx_grid >> generate_messages;
+ TRACE_UDP ("Configure mode:" << mode << "frequency tolerance:" << frequency_tolerance << "submode:" << submode << "fast mode:" << fast_mode << "T/R period:" << tr_period << "rx df:" << rx_df << "dx call:" << dx_call << "dx grid:" << dx_grid << "generate messages:" << generate_messages);
+ if (check_status (in) != Fail)
+ {
+ Q_EMIT self_->configure (QString::fromUtf8 (mode), frequency_tolerance
+ , QString::fromUtf8 (submode), fast_mode, tr_period, rx_df
+ , QString::fromUtf8 (dx_call), QString::fromUtf8 (dx_grid)
+ , generate_messages);
+ }
+ }
+ break;
+
+ case NetworkMessage::AnnotationInfo: {
+ QByteArray dx_call;
+ bool sort_order_provided{false};
+ quint32 sort_order{std::numeric_limits<quint32>::max()};
+ in >> dx_call >> sort_order_provided >> sort_order;
+ TRACE_UDP ("External Callsign Info:" << dx_call << "sort_order_provided:" << sort_order_provided
+ << "sort_order:" << sort_order);
+ if (sort_order > 50000) sort_order = 50000;
+ if (check_status(in) != Fail) {
+ Q_EMIT
+ self_->annotation_info(QString::fromUtf8(dx_call), sort_order_provided, sort_order);
+ }
+ }
+ break;
+
+ default:
+ // Ignore
+ //
+ // Note that although server heartbeat messages are not
+ // parsed here they are still partially parsed in the
+ // message reader class to negotiate the maximum schema
+ // number being used on the network.
+ if (NetworkMessage::Heartbeat != in.type ())
+ {
+ TRACE_UDP ("ignoring message type:" << in.type ());
+ }
+ break;
+ }
+ }
+ else
+ {
+ TRACE_UDP ("ignored message for id:" << in.id ());
+ }
+ }
+ catch (std::exception const& e)
+ {
+ Q_EMIT self_->error (QString {"MessageClient exception: %1"}.arg (e.what ()));
+ }
+ catch (...)
+ {
+ Q_EMIT self_->error ("Unexpected exception in MessageClient");
+ }
+}
+
+void MessageClient::impl::heartbeat ()
+{
+ if (server_port_ && !server_.isNull ())
+ {
+ QByteArray message;
+ NetworkMessage::Builder out {&message, NetworkMessage::Heartbeat, id_, schema_};
+ out << NetworkMessage::Builder::schema_number // maximum schema number accepted
+ << version_.toUtf8 () << revision_.toUtf8 ();
+ TRACE_UDP ("schema:" << schema_ << "max schema:" << NetworkMessage::Builder::schema_number << "version:" << version_ << "revision:" << revision_);
+ send_message (out, message, false, true);
+ }
+}
+
+void MessageClient::impl::closedown ()
+{
+ if (server_port_ && !server_.isNull ())
+ {
+ QByteArray message;
+ NetworkMessage::Builder out {&message, NetworkMessage::Close, id_, schema_};
+ TRACE_UDP ("");
+ send_message (out, message, false);
+ }
+}
+
+void MessageClient::impl::send_message (QByteArray const& message, bool queue_if_pending, bool allow_duplicates)
+{
+ if (server_port_)
+ {
+ if (!server_.isNull ())
+ {
+ if (allow_duplicates || message != last_message_) // avoid duplicates
+ {
+ if (is_multicast_address (server_))
+ {
+ // send datagram on each selected network interface
+ std::for_each (network_interfaces_.begin (), network_interfaces_.end ()
+ , [&] (QNetworkInterface const& net_if) {
+ setMulticastInterface (net_if);
+ // qDebug () << "Multicast UDP datagram sent to:" << server_ << "port:" << server_port_ << "on:" << multicastInterface ().humanReadableName ();
+ writeDatagram (message, server_, server_port_);
+ });
+ }
+ else
+ {
+ // qDebug () << "Unicast UDP datagram sent to:" << server_ << "port:" << server_port_;
+ writeDatagram (message, server_, server_port_);
+ }
+ last_message_ = message;
+ }
+ }
+ else if (queue_if_pending)
+ {
+ pending_messages_.enqueue (message);
+ }
+ }
+}
+
+auto MessageClient::impl::check_status (QDataStream const& stream) const -> StreamStatus
+{
+ auto stat = stream.status ();
+ StreamStatus result {Fail};
+ switch (stat)
+ {
+ case QDataStream::ReadPastEnd:
+ result = Short;
+ break;
+
+ case QDataStream::ReadCorruptData:
+ Q_EMIT self_->error ("Message serialization error: read corrupt data");
+ break;
+
+ case QDataStream::WriteFailed:
+ Q_EMIT self_->error ("Message serialization error: write error");
+ break;
+
+ default:
+ result = OK;
+ break;
+ }
+ return result;
+}
+
+MessageClient::MessageClient (QString const& id, QString const& version, QString const& revision,
+ QString const& server_name, port_type server_port,
+ QStringList const& network_interface_names,
+ int TTL, QObject * self)
+ : QObject {self}
+ , m_ {id, version, revision, server_port, TTL, this}
+{
+ connect (&*m_
+#if QT_VERSION < QT_VERSION_CHECK(5, 15, 0)
+ , static_cast<void (impl::*) (impl::SocketError)> (&impl::error), [this] (impl::SocketError e)
+#else
+ , &impl::errorOccurred, [this] (impl::SocketError e)
+#endif
+ {
+#if defined (Q_OS_WIN)
+ if (e != impl::NetworkError // take this out when Qt 5.5 stops doing this spuriously
+ && e != impl::ConnectionRefusedError) // not interested in this with UDP socket
+ {
+#else
+ {
+ Q_UNUSED (e);
+#endif
+ Q_EMIT error (m_->errorString ());
+ }
+ });
+ m_->set_server (server_name, network_interface_names);
+}
+
+QHostAddress MessageClient::server_address () const
+{
+ return m_->server_;
+}
+
+auto MessageClient::server_port () const -> port_type
+{
+ return m_->server_port_;
+}
+
+void MessageClient::set_server (QString const& server_name, QStringList const& network_interface_names)
+{
+ m_->set_server (server_name, network_interface_names);
+}
+
+void MessageClient::set_server_port (port_type server_port)
+{
+ m_->server_port_ = server_port;
+}
+
+void MessageClient::set_TTL (int TTL)
+{
+ m_->TTL_ = TTL;
+ m_->setSocketOption (QAbstractSocket::MulticastTtlOption, m_->TTL_);
+}
+
+void MessageClient::enable (bool flag)
+{
+ m_->enabled_ = flag;
+}
+
+void MessageClient::status_update (Frequency f, QString const& mode, QString const& dx_call
+ , QString const& report, QString const& tx_mode
+ , bool tx_enabled, bool transmitting, bool decoding
+ , quint32 rx_df, quint32 tx_df, QString const& de_call
+ , QString const& de_grid, QString const& dx_grid
+ , bool watchdog_timeout, QString const& sub_mode
+ , bool fast_mode, quint8 special_op_mode
+ , quint32 frequency_tolerance, quint32 tr_period
+ , QString const& configuration_name
+ , QString const& tx_message)
+{
+ if (m_->server_port_ && !m_->server_.isNull ())
+ {
+ QByteArray message;
+ NetworkMessage::Builder out {&message, NetworkMessage::Status, m_->id_, m_->schema_};
+ out << f << mode.toUtf8 () << dx_call.toUtf8 () << report.toUtf8 () << tx_mode.toUtf8 ()
+ << tx_enabled << transmitting << decoding << rx_df << tx_df << de_call.toUtf8 ()
+ << de_grid.toUtf8 () << dx_grid.toUtf8 () << watchdog_timeout << sub_mode.toUtf8 ()
+ << fast_mode << special_op_mode << frequency_tolerance << tr_period << configuration_name.toUtf8 ()
+ << tx_message.toUtf8 ();
+ TRACE_UDP ("frequency:" << f << "mode:" << mode << "DX:" << dx_call << "report:" << report << "Tx mode:" << tx_mode << "tx_enabled:" << tx_enabled << "Tx:" << transmitting << "decoding:" << decoding << "Rx df:" << rx_df << "Tx df:" << tx_df << "DE:" << de_call << "DE grid:" << de_grid << "DX grid:" << dx_grid << "w/d t/o:" << watchdog_timeout << "sub_mode:" << sub_mode << "fast mode:" << fast_mode << "spec op mode:" << special_op_mode << "frequency tolerance:" << frequency_tolerance << "T/R period:" << tr_period << "configuration name:" << configuration_name << "Tx message:" << tx_message);
+ m_->send_message (out, message);
+ }
+}
+
+void MessageClient::decode (bool is_new, QTime time, qint32 snr, float delta_time, quint32 delta_frequency
+ , QString const& mode, QString const& message_text, bool low_confidence
+ , bool off_air)
+{
+ if (m_->server_port_ && !m_->server_.isNull ())
+ {
+ QByteArray message;
+ NetworkMessage::Builder out {&message, NetworkMessage::Decode, m_->id_, m_->schema_};
+ out << is_new << time << snr << delta_time << delta_frequency << mode.toUtf8 ()
+ << message_text.toUtf8 () << low_confidence << off_air;
+ TRACE_UDP ("new" << is_new << "time:" << time << "snr:" << snr << "dt:" << delta_time << "df:" << delta_frequency << "mode:" << mode << "text:" << message_text << "low conf:" << low_confidence << "off air:" << off_air);
+ m_->send_message (out, message);
+ }
+}
+
+void MessageClient::WSPR_decode (bool is_new, QTime time, qint32 snr, float delta_time, Frequency frequency
+ , qint32 drift, QString const& callsign, QString const& grid, qint32 power
+ , bool off_air)
+{
+ if (m_->server_port_ && !m_->server_.isNull ())
+ {
+ QByteArray message;
+ NetworkMessage::Builder out {&message, NetworkMessage::WSPRDecode, m_->id_, m_->schema_};
+ out << is_new << time << snr << delta_time << frequency << drift << callsign.toUtf8 ()
+ << grid.toUtf8 () << power << off_air;
+ TRACE_UDP ("new:" << is_new << "time:" << time << "snr:" << snr << "dt:" << delta_time << "frequency:" << frequency << "drift:" << drift << "call:" << callsign << "grid:" << grid << "pwr:" << power << "off air:" << off_air);
+ m_->send_message (out, message);
+ }
+}
+
+void MessageClient::decodes_cleared ()
+{
+ if (m_->server_port_ && !m_->server_.isNull ())
+ {
+ QByteArray message;
+ NetworkMessage::Builder out {&message, NetworkMessage::Clear, m_->id_, m_->schema_};
+ TRACE_UDP ("");
+ m_->send_message (out, message);
+ }
+}
+
+void MessageClient::qso_logged (QDateTime time_off, QString const& dx_call, QString const& dx_grid
+ , Frequency dial_frequency, QString const& mode, QString const& report_sent
+ , QString const& report_received, QString const& tx_power
+ , QString const& comments, QString const& name, QDateTime time_on
+ , QString const& operator_call, QString const& my_call
+ , QString const& my_grid, QString const& exchange_sent
+ , QString const& exchange_rcvd, QString const& propmode
+ , QString const& satellite, QString const& satmode, QString const& freqRx)
+{
+ if (m_->server_port_ && !m_->server_.isNull ())
+ {
+ QByteArray message;
+ NetworkMessage::Builder out {&message, NetworkMessage::QSOLogged, m_->id_, m_->schema_};
+ out << time_off << dx_call.toUtf8 () << dx_grid.toUtf8 () << dial_frequency << mode.toUtf8 ()
+ << report_sent.toUtf8 () << report_received.toUtf8 () << tx_power.toUtf8 () << comments.toUtf8 ()
+ << name.toUtf8 () << time_on << operator_call.toUtf8 () << my_call.toUtf8 () << my_grid.toUtf8 ()
+ << exchange_sent.toUtf8 () << exchange_rcvd.toUtf8 () << propmode.toUtf8 () << satellite.toUtf8 ()
+ << satmode.toUtf8 () << freqRx.toUtf8 ();
+ TRACE_UDP ("time off:" << time_off << "DX:" << dx_call << "DX grid:" << dx_grid << "dial:" << dial_frequency << "mode:" << mode << "sent:" << report_sent << "rcvd:" << report_received << "pwr:" << tx_power << "comments:" << comments << "name:" << name << "time on:" << time_on << "op:" << operator_call << "DE:" << my_call << "DE grid:" << my_grid << "exch sent:" << exchange_sent << "exch rcvd:" << exchange_rcvd << "prop_mode:" << propmode << "sat_name:" << satellite << "sat_mode:" << satmode << "freq_rx:" << freqRx);
+ m_->send_message (out, message);
+ }
+}
+
+void MessageClient::logged_ADIF (QByteArray const& ADIF_record)
+{
+ if (m_->server_port_ && !m_->server_.isNull ())
+ {
+ QByteArray message;
+ NetworkMessage::Builder out {&message, NetworkMessage::LoggedADIF, m_->id_, m_->schema_};
+ QByteArray ADIF {"\n<adif_ver:5>3.1.0\n<programid:6>WSJT-X\n<EOH>\n" + ADIF_record + " <EOR>"};
+ out << ADIF;
+ TRACE_UDP ("ADIF:" << ADIF);
+ m_->send_message (out, message);
+ }
+}
diff --git a/Network/MessageClient.hpp b/Network/MessageClient.hpp index 2c87fe7a..1fffda26 100755 --- a/Network/MessageClient.hpp +++ b/Network/MessageClient.hpp @@ -1,143 +1,144 @@ -#ifndef MESSAGE_CLIENT_HPP__ -#define MESSAGE_CLIENT_HPP__ - -#include <QObject> -#include <QTime> -#include <QDateTime> -#include <QString> -#include <QHostAddress> - -#include "Radio.hpp" -#include "pimpl_h.hpp" - -class QByteArray; -class QHostAddress; -class QColor; - -// -// MessageClient - Manage messages sent and replies received from a -// matching server (MessageServer) at the other end of -// the wire -// -// -// Each outgoing message type is a Qt slot -// -class MessageClient - : public QObject -{ - Q_OBJECT; - -public: - using Frequency = Radio::Frequency; - using port_type = quint16; - - // instantiate and initiate a host lookup on the server - // - // messages will be silently dropped until a server host lookup is complete - MessageClient (QString const& id, QString const& version, QString const& revision, - QString const& server_name, port_type server_port, - QStringList const& network_interface_names, - int TTL, QObject * parent = nullptr); - - // query server details - QHostAddress server_address () const; - port_type server_port () const; - - // initiate a new server host lookup or if the server name is empty - // the sending of messages is disabled, if an interface is specified - // then that interface is used for outgoing datagrams - Q_SLOT void set_server (QString const& server_name, QStringList const& network_interface_names); - - // change the server port messages are sent to - Q_SLOT void set_server_port (port_type server_port = 0u); - - // change the server port messages are sent to - Q_SLOT void set_TTL (int TTL); - - // enable incoming messages - Q_SLOT void enable (bool); - - // outgoing messages - Q_SLOT void status_update (Frequency, QString const& mode, QString const& dx_call, QString const& report - , QString const& tx_mode, bool tx_enabled, bool transmitting, bool decoding - , quint32 rx_df, quint32 tx_df, QString const& de_call, QString const& de_grid - , QString const& dx_grid, bool watchdog_timeout, QString const& sub_mode - , bool fast_mode, quint8 special_op_mode, quint32 frequency_tolerance - , quint32 tr_period, QString const& configuration_name - , QString const& tx_message); - Q_SLOT void decode (bool is_new, QTime time, qint32 snr, float delta_time, quint32 delta_frequency - , QString const& mode, QString const& message, bool low_confidence - , bool off_air); - Q_SLOT void WSPR_decode (bool is_new, QTime time, qint32 snr, float delta_time, Frequency - , qint32 drift, QString const& callsign, QString const& grid, qint32 power - , bool off_air); - Q_SLOT void decodes_cleared (); - Q_SLOT void qso_logged (QDateTime time_off, QString const& dx_call, QString const& dx_grid - , Frequency dial_frequency, QString const& mode, QString const& report_sent - , QString const& report_received, QString const& tx_power, QString const& comments - , QString const& name, QDateTime time_on, QString const& operator_call - , QString const& my_call, QString const& my_grid - , QString const& exchange_sent, QString const& exchange_rcvd - , QString const& propmode); - - // ADIF_record argument should be valid ADIF excluding any <EOR> end - // of record marker - Q_SLOT void logged_ADIF (QByteArray const& ADIF_record); - - // this signal is emitted if the server has requested a decode - // window clear action - Q_SIGNAL void clear_decodes (quint8 window); - - // this signal is emitted if the server sends us a reply, the only - // reply supported is reply to a prior CQ or QRZ message - Q_SIGNAL void reply (QTime, qint32 snr, float delta_time, quint32 delta_frequency, QString const& mode - , QString const& message_text, bool low_confidence, quint8 modifiers); - - // this signal is emitted if the server has requested this client to - // close down gracefully - Q_SIGNAL void close (); - - // this signal is emitted if the server has requested a replay of - // all decodes - Q_SIGNAL void replay (); - - // this signal is emitted if the server has requested immediate (or - // auto Tx if auto_only is true) transmission to halt - Q_SIGNAL void halt_tx (bool auto_only); - - // this signal is emitted if the server has requested a new free - // message text - Q_SIGNAL void free_text (QString const&, bool send); - - // this signal is emitted if the server has sent a highlight - // callsign request for the specified call - Q_SIGNAL void highlight_callsign (QString const& callsign, QColor const& bg, QColor const& fg, bool last_only); - - // this signal is emitted if the server has requested a - // configuration switch - Q_SIGNAL void switch_configuration (QString const& configuration_name); - - // this signal is emitted if the server has requested a - // configuration change - Q_SIGNAL void configure (QString const& mode, quint32 frequency_tolerance, QString const& submode - , bool fast_mode, quint32 tr_period, quint32 rx_df, QString const& dx_call - , QString const& dx_grid, bool generate_messages); - - // this signal is emitted if the server has sent information about a callsign - Q_SIGNAL void annotation_info (QString const& dx_call, bool sort_order_provided, quint32 sort_order); - - // this signal is emitted when network errors occur or if a host - // lookup fails - Q_SIGNAL void error (QString const&) const; - - // this signal is emitted if the message obtains a location from a - // server. (It doesn't have to be new, could be a periodic location - // update) - Q_SIGNAL void location (QString const&); - -private: - class impl; - pimpl<impl> m_; -}; - -#endif +#ifndef MESSAGE_CLIENT_HPP__
+#define MESSAGE_CLIENT_HPP__
+
+#include <QObject>
+#include <QTime>
+#include <QDateTime>
+#include <QString>
+#include <QHostAddress>
+
+#include "Radio.hpp"
+#include "pimpl_h.hpp"
+
+class QByteArray;
+class QHostAddress;
+class QColor;
+
+//
+// MessageClient - Manage messages sent and replies received from a
+// matching server (MessageServer) at the other end of
+// the wire
+//
+//
+// Each outgoing message type is a Qt slot
+//
+class MessageClient
+ : public QObject
+{
+ Q_OBJECT;
+
+public:
+ using Frequency = Radio::Frequency;
+ using port_type = quint16;
+
+ // instantiate and initiate a host lookup on the server
+ //
+ // messages will be silently dropped until a server host lookup is complete
+ MessageClient (QString const& id, QString const& version, QString const& revision,
+ QString const& server_name, port_type server_port,
+ QStringList const& network_interface_names,
+ int TTL, QObject * parent = nullptr);
+
+ // query server details
+ QHostAddress server_address () const;
+ port_type server_port () const;
+
+ // initiate a new server host lookup or if the server name is empty
+ // the sending of messages is disabled, if an interface is specified
+ // then that interface is used for outgoing datagrams
+ Q_SLOT void set_server (QString const& server_name, QStringList const& network_interface_names);
+
+ // change the server port messages are sent to
+ Q_SLOT void set_server_port (port_type server_port = 0u);
+
+ // change the server port messages are sent to
+ Q_SLOT void set_TTL (int TTL);
+
+ // enable incoming messages
+ Q_SLOT void enable (bool);
+
+ // outgoing messages
+ Q_SLOT void status_update (Frequency, QString const& mode, QString const& dx_call, QString const& report
+ , QString const& tx_mode, bool tx_enabled, bool transmitting, bool decoding
+ , quint32 rx_df, quint32 tx_df, QString const& de_call, QString const& de_grid
+ , QString const& dx_grid, bool watchdog_timeout, QString const& sub_mode
+ , bool fast_mode, quint8 special_op_mode, quint32 frequency_tolerance
+ , quint32 tr_period, QString const& configuration_name
+ , QString const& tx_message);
+ Q_SLOT void decode (bool is_new, QTime time, qint32 snr, float delta_time, quint32 delta_frequency
+ , QString const& mode, QString const& message, bool low_confidence
+ , bool off_air);
+ Q_SLOT void WSPR_decode (bool is_new, QTime time, qint32 snr, float delta_time, Frequency
+ , qint32 drift, QString const& callsign, QString const& grid, qint32 power
+ , bool off_air);
+ Q_SLOT void decodes_cleared ();
+ Q_SLOT void qso_logged (QDateTime time_off, QString const& dx_call, QString const& dx_grid
+ , Frequency dial_frequency, QString const& mode, QString const& report_sent
+ , QString const& report_received, QString const& tx_power, QString const& comments
+ , QString const& name, QDateTime time_on, QString const& operator_call
+ , QString const& my_call, QString const& my_grid
+ , QString const& exchange_sent, QString const& exchange_rcvd
+ , QString const& propmode, QString const& satellite
+ , QString const& satmode, QString const& freqRx);
+
+ // ADIF_record argument should be valid ADIF excluding any <EOR> end
+ // of record marker
+ Q_SLOT void logged_ADIF (QByteArray const& ADIF_record);
+
+ // this signal is emitted if the server has requested a decode
+ // window clear action
+ Q_SIGNAL void clear_decodes (quint8 window);
+
+ // this signal is emitted if the server sends us a reply, the only
+ // reply supported is reply to a prior CQ or QRZ message
+ Q_SIGNAL void reply (QTime, qint32 snr, float delta_time, quint32 delta_frequency, QString const& mode
+ , QString const& message_text, bool low_confidence, quint8 modifiers);
+
+ // this signal is emitted if the server has requested this client to
+ // close down gracefully
+ Q_SIGNAL void close ();
+
+ // this signal is emitted if the server has requested a replay of
+ // all decodes
+ Q_SIGNAL void replay ();
+
+ // this signal is emitted if the server has requested immediate (or
+ // auto Tx if auto_only is true) transmission to halt
+ Q_SIGNAL void halt_tx (bool auto_only);
+
+ // this signal is emitted if the server has requested a new free
+ // message text
+ Q_SIGNAL void free_text (QString const&, bool send);
+
+ // this signal is emitted if the server has sent a highlight
+ // callsign request for the specified call
+ Q_SIGNAL void highlight_callsign (QString const& callsign, QColor const& bg, QColor const& fg, bool last_only);
+
+ // this signal is emitted if the server has requested a
+ // configuration switch
+ Q_SIGNAL void switch_configuration (QString const& configuration_name);
+
+ // this signal is emitted if the server has requested a
+ // configuration change
+ Q_SIGNAL void configure (QString const& mode, quint32 frequency_tolerance, QString const& submode
+ , bool fast_mode, quint32 tr_period, quint32 rx_df, QString const& dx_call
+ , QString const& dx_grid, bool generate_messages);
+
+ // this signal is emitted if the server has sent information about a callsign
+ Q_SIGNAL void annotation_info (QString const& dx_call, bool sort_order_provided, quint32 sort_order);
+
+ // this signal is emitted when network errors occur or if a host
+ // lookup fails
+ Q_SIGNAL void error (QString const&) const;
+
+ // this signal is emitted if the message obtains a location from a
+ // server. (It doesn't have to be new, could be a periodic location
+ // update)
+ Q_SIGNAL void location (QString const&);
+
+private:
+ class impl;
+ pimpl<impl> m_;
+};
+
+#endif
diff --git a/Network/Network.pri b/Network/Network.pri index 723001e9..ac590793 100755 --- a/Network/Network.pri +++ b/Network/Network.pri @@ -1,21 +1,21 @@ -SOURCES += \ -Network/FileDownload.cpp \ -Network/FoxVerifier.cpp \ -Network/LotWUsers.cpp \ -Network/MessageClient.cpp \ -Network/NetworkAccessManager.cpp \ -Network/NetworkMessage.cpp \ -Network/NetworkServerLookup.cpp \ -Network/PSKReporter.cpp \ -Network/wsprnet.cpp - -HEADERS += \ -Network/FileDownload.hpp \ -Network/FoxVerifier.hpp \ -Network/LotWUsers.hpp \ -Network/MessageClient.hpp \ -Network/NetworkAccessManager.hpp \ -Network/NetworkMessage.hpp \ -Network/NetworkServerLookup.hpp \ -Network/PSKReporter.hpp \ -Network/wsprnet.h +SOURCES += \
+Network/FileDownload.cpp \
+Network/FoxVerifier.cpp \
+Network/LotWUsers.cpp \
+Network/MessageClient.cpp \
+Network/NetworkAccessManager.cpp \
+Network/NetworkMessage.cpp \
+Network/NetworkServerLookup.cpp \
+Network/PSKReporter.cpp \
+Network/wsprnet.cpp
+
+HEADERS += \
+Network/FileDownload.hpp \
+Network/FoxVerifier.hpp \
+Network/LotWUsers.hpp \
+Network/MessageClient.hpp \
+Network/NetworkAccessManager.hpp \
+Network/NetworkMessage.hpp \
+Network/NetworkServerLookup.hpp \
+Network/PSKReporter.hpp \
+Network/wsprnet.h
diff --git a/Network/NetworkAccessManager.cpp b/Network/NetworkAccessManager.cpp index e0b06be7..b5592c07 100755 --- a/Network/NetworkAccessManager.cpp +++ b/Network/NetworkAccessManager.cpp @@ -1,62 +1,62 @@ -#include "Network/NetworkAccessManager.hpp" - -#include <QString> -#include <QNetworkReply> - -#include "moc_NetworkAccessManager.cpp" - -NetworkAccessManager::NetworkAccessManager (QWidget * parent) - : QNetworkAccessManager (parent) - , parent_widget_ {parent} -{ - // handle SSL errors that have not been cached as allowed - // exceptions and offer them to the user to add to the ignored - // exception cache - connect (this, &QNetworkAccessManager::sslErrors, this, &NetworkAccessManager::filter_SSL_errors); -} - -void NetworkAccessManager::filter_SSL_errors (QNetworkReply * reply, QList<QSslError> const& errors) -{ - QString message; - QList<QSslError> new_errors; - for (auto const& error: errors) - { - if (!allowed_ssl_errors_.contains (error)) - { - new_errors << error; - message += '\n' + reply->request ().url ().toDisplayString () + ": " + error.errorString (); - } - } - if (new_errors.size ()) - { - QString certs; - for (auto const& cert : reply->sslConfiguration ().peerCertificateChain ()) - { - certs += cert.toText () + '\n'; - } - if (MessageBox::Ignore == MessageBox::query_message (parent_widget_ - , tr ("Network SSL/TLS Errors") - , message, certs - , MessageBox::Abort | MessageBox::Ignore)) - { - // accumulate new SSL error exceptions that have been allowed - allowed_ssl_errors_.append (new_errors); - reply->ignoreSslErrors (allowed_ssl_errors_); - } - } - else - { - // no new exceptions so silently ignore the ones already allowed - reply->ignoreSslErrors (allowed_ssl_errors_); - } -} - -QNetworkReply * NetworkAccessManager::createRequest (Operation operation, QNetworkRequest const& request - , QIODevice * outgoing_data) -{ - auto reply = QNetworkAccessManager::createRequest (operation, request, outgoing_data); - // errors are usually certificate specific so passing all cached - // exceptions here is ok - reply->ignoreSslErrors (allowed_ssl_errors_); - return reply; -} +#include "Network/NetworkAccessManager.hpp"
+
+#include <QString>
+#include <QNetworkReply>
+
+#include "moc_NetworkAccessManager.cpp"
+
+NetworkAccessManager::NetworkAccessManager (QWidget * parent)
+ : QNetworkAccessManager (parent)
+ , parent_widget_ {parent}
+{
+ // handle SSL errors that have not been cached as allowed
+ // exceptions and offer them to the user to add to the ignored
+ // exception cache
+ connect (this, &QNetworkAccessManager::sslErrors, this, &NetworkAccessManager::filter_SSL_errors);
+}
+
+void NetworkAccessManager::filter_SSL_errors (QNetworkReply * reply, QList<QSslError> const& errors)
+{
+ QString message;
+ QList<QSslError> new_errors;
+ for (auto const& error: errors)
+ {
+ if (!allowed_ssl_errors_.contains (error))
+ {
+ new_errors << error;
+ message += '\n' + reply->request ().url ().toDisplayString () + ": " + error.errorString ();
+ }
+ }
+ if (new_errors.size ())
+ {
+ QString certs;
+ for (auto const& cert : reply->sslConfiguration ().peerCertificateChain ())
+ {
+ certs += cert.toText () + '\n';
+ }
+ if (MessageBox::Ignore == MessageBox::query_message (parent_widget_
+ , tr ("Network SSL/TLS Errors")
+ , message, certs
+ , MessageBox::Abort | MessageBox::Ignore))
+ {
+ // accumulate new SSL error exceptions that have been allowed
+ allowed_ssl_errors_.append (new_errors);
+ reply->ignoreSslErrors (allowed_ssl_errors_);
+ }
+ }
+ else
+ {
+ // no new exceptions so silently ignore the ones already allowed
+ reply->ignoreSslErrors (allowed_ssl_errors_);
+ }
+}
+
+QNetworkReply * NetworkAccessManager::createRequest (Operation operation, QNetworkRequest const& request
+ , QIODevice * outgoing_data)
+{
+ auto reply = QNetworkAccessManager::createRequest (operation, request, outgoing_data);
+ // errors are usually certificate specific so passing all cached
+ // exceptions here is ok
+ reply->ignoreSslErrors (allowed_ssl_errors_);
+ return reply;
+}
diff --git a/Network/NetworkAccessManager.hpp b/Network/NetworkAccessManager.hpp index d68ad215..4e4359f6 100755 --- a/Network/NetworkAccessManager.hpp +++ b/Network/NetworkAccessManager.hpp @@ -1,34 +1,34 @@ -#ifndef NETWORK_ACCESS_MANAGER_HPP__ -#define NETWORK_ACCESS_MANAGER_HPP__ - -#include <QNetworkAccessManager> -#include <QList> -#include <QSslError> - -#include "widgets/MessageBox.hpp" - -class QNetworkRequest; -class QIODevice; -class QWidget; - -// sub-class QNAM to keep a list of accepted SSL errors and allow -// them in future replies -class NetworkAccessManager - : public QNetworkAccessManager -{ - Q_OBJECT - -public: - explicit NetworkAccessManager (QWidget * parent); - -protected: - QNetworkReply * createRequest (Operation, QNetworkRequest const&, QIODevice * = nullptr) override; - -private: - void filter_SSL_errors (QNetworkReply * reply, QList<QSslError> const& errors); - - QWidget * parent_widget_; - QList<QSslError> allowed_ssl_errors_; -}; - -#endif +#ifndef NETWORK_ACCESS_MANAGER_HPP__
+#define NETWORK_ACCESS_MANAGER_HPP__
+
+#include <QNetworkAccessManager>
+#include <QList>
+#include <QSslError>
+
+#include "widgets/MessageBox.hpp"
+
+class QNetworkRequest;
+class QIODevice;
+class QWidget;
+
+// sub-class QNAM to keep a list of accepted SSL errors and allow
+// them in future replies
+class NetworkAccessManager
+ : public QNetworkAccessManager
+{
+ Q_OBJECT
+
+public:
+ explicit NetworkAccessManager (QWidget * parent);
+
+protected:
+ QNetworkReply * createRequest (Operation, QNetworkRequest const&, QIODevice * = nullptr) override;
+
+private:
+ void filter_SSL_errors (QNetworkReply * reply, QList<QSslError> const& errors);
+
+ QWidget * parent_widget_;
+ QList<QSslError> allowed_ssl_errors_;
+};
+
+#endif
diff --git a/Network/NetworkMessage.cpp b/Network/NetworkMessage.cpp index a1e7050f..5e2dbb51 100755 --- a/Network/NetworkMessage.cpp +++ b/Network/NetworkMessage.cpp @@ -1,136 +1,136 @@ -#include "NetworkMessage.hpp" - -#include <exception> - -#include <QString> -#include <QByteArray> -#include <QDebug> - -#include "pimpl_impl.hpp" - -namespace NetworkMessage -{ - Builder::Builder (QIODevice * device, Type type, QString const& id, quint32 schema) - : QDataStream {device} - { - common_initialization (type, id, schema); - } - - Builder::Builder (QByteArray * a, Type type, QString const& id, quint32 schema) - : QDataStream {a, QIODevice::WriteOnly} - { - common_initialization (type, id, schema); - } - - void Builder::common_initialization (Type type, QString const& id, quint32 schema) - { - if (schema <= 1) - { - setVersion (QDataStream::Qt_5_0); // Qt schema version - } -#if QT_VERSION >= QT_VERSION_CHECK (5, 2, 0) - else if (schema <= 2) - { - setVersion (QDataStream::Qt_5_2); // Qt schema version - } -#endif -#if QT_VERSION >= QT_VERSION_CHECK (5, 4, 0) - else if (schema <= 3) - { - setVersion (QDataStream::Qt_5_4); // Qt schema version - } -#endif - else - { - throw std::runtime_error {"Unrecognized message schema"}; - } - - // the following two items assume that the quint32 encoding is - // unchanged over QDataStream versions - *this << magic; - *this << schema; - - *this << static_cast<quint32> (type) << id.toUtf8 (); - } - - class Reader::impl - { - public: - void common_initialization (Reader * parent) - { - quint32 magic; - *parent >> magic; - if (magic != Builder::magic) - { - throw std::runtime_error {"Invalid message format"}; - } - *parent >> schema_; - if (schema_ > Builder::schema_number) - { - throw std::runtime_error {"Unrecognized message schema"}; - } - if (schema_ <= 1) - { - parent->setVersion (QDataStream::Qt_5_0); - } -#if QT_VERSION >= QT_VERSION_CHECK (5, 2, 0) - else if (schema_ <= 2) - { - parent->setVersion (QDataStream::Qt_5_2); - } -#endif -#if QT_VERSION >= QT_VERSION_CHECK (5, 4, 0) - else if (schema_ <= 3) - { - parent->setVersion (QDataStream::Qt_5_4); - } -#endif - quint32 type; - *parent >> type >> id_; - if (type >= maximum_message_type_) - { - qDebug () << "Unrecognized message type:" << type << "from id:" << id_; - type_ = maximum_message_type_; - } - else - { - type_ = static_cast<Type> (type); - } - } - - quint32 schema_; - Type type_; - QByteArray id_; - }; - - Reader::Reader (QIODevice * device) - : QDataStream {device} - { - m_->common_initialization (this); - } - - Reader::Reader (QByteArray const& a) - : QDataStream {a} - { - m_->common_initialization (this); - } - - Reader::~Reader () - { - } - - quint32 Reader::schema () const - { - return m_->schema_; - } - - Type Reader::type () const - { - return static_cast<Type> (m_->type_); - } - - QString Reader::id () const - { - return QString::fromUtf8 (m_->id_); - } -} +#include "NetworkMessage.hpp"
+
+#include <exception>
+
+#include <QString>
+#include <QByteArray>
+#include <QDebug>
+
+#include "pimpl_impl.hpp"
+
+namespace NetworkMessage
+{
+ Builder::Builder (QIODevice * device, Type type, QString const& id, quint32 schema)
+ : QDataStream {device}
+ {
+ common_initialization (type, id, schema);
+ }
+
+ Builder::Builder (QByteArray * a, Type type, QString const& id, quint32 schema)
+ : QDataStream {a, QIODevice::WriteOnly}
+ {
+ common_initialization (type, id, schema);
+ }
+
+ void Builder::common_initialization (Type type, QString const& id, quint32 schema)
+ {
+ if (schema <= 1)
+ {
+ setVersion (QDataStream::Qt_5_0); // Qt schema version
+ }
+#if QT_VERSION >= QT_VERSION_CHECK (5, 2, 0)
+ else if (schema <= 2)
+ {
+ setVersion (QDataStream::Qt_5_2); // Qt schema version
+ }
+#endif
+#if QT_VERSION >= QT_VERSION_CHECK (5, 4, 0)
+ else if (schema <= 3)
+ {
+ setVersion (QDataStream::Qt_5_4); // Qt schema version
+ }
+#endif
+ else
+ {
+ throw std::runtime_error {"Unrecognized message schema"};
+ }
+
+ // the following two items assume that the quint32 encoding is
+ // unchanged over QDataStream versions
+ *this << magic;
+ *this << schema;
+
+ *this << static_cast<quint32> (type) << id.toUtf8 ();
+ }
+
+ class Reader::impl
+ {
+ public:
+ void common_initialization (Reader * parent)
+ {
+ quint32 magic;
+ *parent >> magic;
+ if (magic != Builder::magic)
+ {
+ throw std::runtime_error {"Invalid message format"};
+ }
+ *parent >> schema_;
+ if (schema_ > Builder::schema_number)
+ {
+ throw std::runtime_error {"Unrecognized message schema"};
+ }
+ if (schema_ <= 1)
+ {
+ parent->setVersion (QDataStream::Qt_5_0);
+ }
+#if QT_VERSION >= QT_VERSION_CHECK (5, 2, 0)
+ else if (schema_ <= 2)
+ {
+ parent->setVersion (QDataStream::Qt_5_2);
+ }
+#endif
+#if QT_VERSION >= QT_VERSION_CHECK (5, 4, 0)
+ else if (schema_ <= 3)
+ {
+ parent->setVersion (QDataStream::Qt_5_4);
+ }
+#endif
+ quint32 type;
+ *parent >> type >> id_;
+ if (type >= maximum_message_type_)
+ {
+ qDebug () << "Unrecognized message type:" << type << "from id:" << id_;
+ type_ = maximum_message_type_;
+ }
+ else
+ {
+ type_ = static_cast<Type> (type);
+ }
+ }
+
+ quint32 schema_;
+ Type type_;
+ QByteArray id_;
+ };
+
+ Reader::Reader (QIODevice * device)
+ : QDataStream {device}
+ {
+ m_->common_initialization (this);
+ }
+
+ Reader::Reader (QByteArray const& a)
+ : QDataStream {a}
+ {
+ m_->common_initialization (this);
+ }
+
+ Reader::~Reader ()
+ {
+ }
+
+ quint32 Reader::schema () const
+ {
+ return m_->schema_;
+ }
+
+ Type Reader::type () const
+ {
+ return static_cast<Type> (m_->type_);
+ }
+
+ QString Reader::id () const
+ {
+ return QString::fromUtf8 (m_->id_);
+ }
+}
diff --git a/Network/NetworkMessage.hpp b/Network/NetworkMessage.hpp index 74a268fa..c046c3db 100755 --- a/Network/NetworkMessage.hpp +++ b/Network/NetworkMessage.hpp @@ -1,626 +1,626 @@ -#ifndef NETWORK_MESSAGE_HPP__ -#define NETWORK_MESSAGE_HPP__ - -/* - * WSJT-X Message Formats - * ====================== - * - * All messages are written or read using the QDataStream derivatives - * defined below, note that we are using the default for floating - * point precision which means all are double precision i.e. 64-bit - * IEEE format. - * - * Message is big endian format - * - * Header format: - * - * 32-bit unsigned integer magic number 0xadbccbda - * 32-bit unsigned integer schema number - * - * Payload format: - * - * As per the QDataStream format, see below for version used and - * here: - * - * http://doc.qt.io/qt-5/datastreamformat.html - * - * for the serialization details for each type, at the time of - * writing the above document is for Qt_5_0 format which is buggy - * so we use Qt_5_4 format, differences are: - * - * QDateTime: - * QDate qint64 Julian day number - * QTime quint32 Milli-seconds since midnight - * timespec quint8 0=local, 1=UTC, 2=Offset from UTC - * (seconds) - * 3=time zone - * offset qint32 only present if timespec=2 - * timezone several-fields only present if timespec=3 - * - * we will avoid using QDateTime fields with time zones for - * simplicity. - * - * Type utf8 is a utf-8 byte string formatted as a QByteArray for - * serialization purposes (currently a quint32 size followed by size - * bytes, no terminator is present or counted). - * - * The QDataStream format document linked above is not complete for - * the QByteArray serialization format, it is similar to the QString - * serialization format in that it differentiates between empty - * strings and null strings. Empty strings have a length of zero - * whereas null strings have a length field of 0xffffffff. - * - * - * Schema Negotiation - * ------------------ - * - * The NetworkMessage::Builder class specifies a schema number which - * may be incremented from time to time. It represents a version of - * the underlying encoding schemes used to store data items. Since the - * underlying encoding is defined by the Qt project in it's - * QDataStream stream operators, it is essential that clients and - * servers of this protocol can agree on a common scheme. The - * NetworkMessage utility classes below exchange the schema number - * actually used. The handling of the schema is backwards compatible - * to an extent, so long as clients and servers are written - * correctly. For example a server written to any particular schema - * version can communicate with a client written to a later schema. - * - * Schema Version 1:- this schema used the QDataStream::Qt_5_0 version - * which is broken. - * - * Schema Version 2:- this schema uses the QDataStream::Qt_5_2 version. - * - * Schema Version 3:- this schema uses the QDataStream::Qt_5_4 version. - * - * - * Backward Compatibility - * ---------------------- - * - * It is important that applications developed at different times - * remain compatible with this protocol and with older or newer - * versions of WSJT-X. This is achieved by both third-party - * applications and WSJT-X honouring two basic rules. - * - * 1. New message types may be added to the protocol in the future, - * third-party applications and WSJT-X shall ignore silently any - * message types they do not recognize. - * - * 2. New fields may be added to existing message types, they will - * always be added to the end of the existing fields and the number - * and type of existing fields shall not change. If a field type - * must be changed; a new field will be added and the existing - * field will remain. The originator of such a message shall - * populate both the new and old field with reasonable - * values. Third-party applications and WSJT-X shall ignore - * silently any extra data received in datagrams after the fields - * they know about. - * - * Note that these rules are unrelated to the schema number above - * whose purpose is to distinguish between non-compatible encodings of - * field data types. New message types and extra fields in existing - * messages can and will be added without any change in schema number. - * - * - * Message Types - * ------------- - * - * Message Direction Value Type - * ------------- --------- ---------------------- ----------- - * Heartbeat Out/In 0 quint32 - * Id (unique key) utf8 - * Maximum schema number quint32 - * version utf8 - * revision utf8 - * - * The heartbeat message shall be sent on a periodic basis every - * NetworkMessage::pulse seconds (see below), the WSJT-X - * application does that using the MessageClient class. This - * message is intended to be used by servers to detect the presence - * of a client and also the unexpected disappearance of a client - * and by clients to learn the schema negotiated by the server - * after it receives the initial heartbeat message from a client. - * The message_aggregator reference server does just that using the - * MessageServer class. Upon initial startup a client must send a - * heartbeat message as soon as is practical, this message is used - * to negotiate the maximum schema number common to the client and - * server. Note that the server may not be able to support the - * client's requested maximum schema number, in which case the - * first message received from the server will specify a lower - * schema number (never a higher one as that is not allowed). If a - * server replies with a lower schema number then no higher than - * that number shall be used for all further outgoing messages from - * either clients or the server itself. - * - * Note: the "Maximum schema number" field was introduced at the - * same time as schema 3, therefore servers and clients must assume - * schema 2 is the highest schema number supported if the Heartbeat - * message does not contain the "Maximum schema number" field. - * - * - * Status Out 1 quint32 - * Id (unique key) utf8 - * Dial Frequency (Hz) quint64 - * Mode utf8 - * DX call utf8 - * Report utf8 - * Tx Mode utf8 - * Tx Enabled bool - * Transmitting bool - * Decoding bool - * Rx DF quint32 - * Tx DF quint32 - * DE call utf8 - * DE grid utf8 - * DX grid utf8 - * Tx Watchdog bool - * Sub-mode utf8 - * Fast mode bool - * Special Operation Mode quint8 - * Frequency Tolerance quint32 - * T/R Period quint32 - * Configuration Name utf8 - * Tx Message utf8 - * - * WSJT-X sends this status message when various internal state - * changes to allow the server to track the relevant state of each - * client without the need for polling commands. The current state - * changes that generate status messages are: - * - * Application start up, - * "Enable Tx" button status changes, - * dial frequency changes, - * changes to the "DX Call" field, - * operating mode, sub-mode or fast mode changes, - * transmit mode changed (in dual JT9+JT65 mode), - * changes to the "Rpt" spinner, - * after an old decodes replay sequence (see Replay below), - * when switching between Tx and Rx mode, - * at the start and end of decoding, - * when the Rx DF changes, - * when the Tx DF changes, - * when settings are exited, - * when the DX call or grid changes, - * when the Tx watchdog is set or reset, - * when the frequency tolerance is changed, - * when the T/R period is changed, - * when the configuration name changes, - * when the message being transmitted changes. - * - * The Special operation mode is an enumeration that indicates the - * setting selected in the WSJT-X "Settings->Advanced->Special - * operating activity" panel. The values are as follows: - * - * 0 -> NONE - * 1 -> NA VHF - * 2 -> EU VHF - * 3 -> FIELD DAY - * 4 -> RTTY RU - * 5 -> WW DIGI - * 6 -> FOX - * 7 -> HOUND - * 8 -> ARRL DIGI - * - * The Frequency Tolerance and T/R period fields may have a value - * of the maximum quint32 value which implies the field is not - * applicable. - * - * - * Decode Out 2 quint32 - * Id (unique key) utf8 - * New bool - * Time QTime - * snr qint32 - * Delta time (S) float (serialized as double) - * Delta frequency (Hz) quint32 - * Mode utf8 - * Message utf8 - * Low confidence bool - * Off air bool - * - * The decode message is sent when a new decode is completed, in - * this case the 'New' field is true. It is also used in response - * to a "Replay" message where each old decode in the "Band - * activity" window, that has not been erased, is sent in order - * as a one of these messages with the 'New' field set to false. - * See the "Replay" message below for details of usage. Low - * confidence decodes are flagged in protocols where the decoder - * has knows that a decode has a higher than normal probability - * of being false, they should not be reported on publicly - * accessible services without some attached warning or further - * validation. Off air decodes are those that result from playing - * back a .WAV file. - * - * - * Clear Out/In 3 quint32 - * Id (unique key) utf8 - * Window quint8 (In only) - * - * This message is send when all prior "Decode" messages in the - * "Band Activity" window have been discarded and therefore are - * no long available for actioning with a "Reply" message. It is - * sent when the user erases the "Band activity" window and when - * WSJT-X closes down normally. The server should discard all - * decode messages upon receipt of this message. - * - * It may also be sent to a WSJT-X instance in which case it - * clears one or both of the "Band Activity" and "Rx Frequency" - * windows. The Window argument can be one of the following - * values: - * - * 0 - clear the "Band Activity" window (default) - * 1 - clear the "Rx Frequency" window - * 2 - clear both "Band Activity" and "Rx Frequency" windows - * - * - * Reply In 4 quint32 - * Id (target unique key) utf8 - * Time QTime - * snr qint32 - * Delta time (S) float (serialized as double) - * Delta frequency (Hz) quint32 - * Mode utf8 - * Message utf8 - * Low confidence bool - * Modifiers quint8 - * - * In order for a server to provide a useful cooperative service - * to WSJT-X it is possible for it to initiate a QSO by sending - * this message to a client. WSJT-X filters this message and only - * acts upon it if the message exactly describes a prior decode - * and that decode is a CQ or QRZ message. The action taken is - * exactly equivalent to the user double clicking the message in - * the "Band activity" window. The intent of this message is for - * servers to be able to provide an advanced look up of potential - * QSO partners, for example determining if they have been worked - * before or if working them may advance some objective like - * award progress. The intention is not to provide a secondary - * user interface for WSJT-X, it is expected that after QSO - * initiation the rest of the QSO is carried out manually using - * the normal WSJT-X user interface. - * - * The Modifiers field allows the equivalent of keyboard - * modifiers to be sent "as if" those modifier keys where pressed - * while double-clicking the specified decoded message. The - * modifier values (hexadecimal) are as follows: - * - * no modifier 0x00 - * SHIFT 0x02 - * CTRL 0x04 CMD on Mac - * ALT 0x08 - * META 0x10 Windows key on MS Windows - * KEYPAD 0x20 Keypad or arrows - * Group switch 0x40 X11 only - * - * - * QSO Logged Out 5 quint32 - * Id (unique key) utf8 - * Date & Time Off QDateTime - * DX call utf8 - * DX grid utf8 - * Tx frequency (Hz) quint64 - * Mode utf8 - * Report sent utf8 - * Report received utf8 - * Tx power utf8 - * Comments utf8 - * Name utf8 - * Date & Time On QDateTime - * Operator call utf8 - * My call utf8 - * My grid utf8 - * Exchange sent utf8 - * Exchange received utf8 - * ADIF Propagation mode utf8 - * - * The QSO logged message is sent to the server(s) when the - * WSJT-X user accepts the "Log QSO" dialog by clicking the "OK" - * button. - * - * - * Close Out/In 6 quint32 - * Id (unique key) utf8 - * - * Close is sent by a client immediately prior to it shutting - * down gracefully. When sent by a server it requests the target - * client to close down gracefully. - * - * - * Replay In 7 quint32 - * Id (unique key) utf8 - * - * When a server starts it may be useful for it to determine the - * state of preexisting clients. Sending this message to each - * client as it is discovered will cause that client (WSJT-X) to - * send a "Decode" message for each decode currently in its "Band - * activity" window. Each "Decode" message sent will have the - * "New" flag set to false so that they can be distinguished from - * new decodes. After all the old decodes have been broadcast a - * "Status" message is also broadcast. If the server wishes to - * determine the status of a newly discovered client; this - * message should be used. - * - * - * Halt Tx In 8 - * Id (unique key) utf8 - * Auto Tx Only bool - * - * The server may stop a client from transmitting messages either - * immediately or at the end of the current transmission period - * using this message. - * - * - * Free Text In 9 - * Id (unique key) utf8 - * Text utf8 - * Send bool - * - * This message allows the server to set the current free text - * message content. Sending this message with a non-empty "Text" - * field is equivalent to typing a new message (old contents are - * discarded) in to the WSJT-X free text message field or "Tx5" - * field (both are updated) and if the "Send" flag is set then - * clicking the "Now" radio button for the "Tx5" field if tab one - * is current or clicking the "Free msg" radio button if tab two - * is current. - * - * It is the responsibility of the sender to limit the length of - * the message text and to limit it to legal message - * characters. Despite this, it may be difficult for the sender - * to determine the maximum message length without reimplementing - * the complete message encoding protocol. Because of this is may - * be better to allow any reasonable message length and to let - * the WSJT-X application encode and possibly truncate the actual - * on-air message. - * - * If the message text is empty the meaning of the message is - * refined to send the current free text unchanged when the - * "Send" flag is set or to clear the current free text when the - * "Send" flag is unset. Note that this API does not include a - * command to determine the contents of the current free text - * message. - * - * - * WSPRDecode Out 10 quint32 - * Id (unique key) utf8 - * New bool - * Time QTime - * snr qint32 - * Delta time (S) float (serialized as double) - * Frequency (Hz) quint64 - * Drift (Hz) qint32 - * Callsign utf8 - * Grid utf8 - * Power (dBm) qint32 - * Off air bool - * - * The decode message is sent when a new decode is completed, in - * this case the 'New' field is true. It is also used in response - * to a "Replay" message where each old decode in the "Band - * activity" window, that has not been erased, is sent in order - * as a one of these messages with the 'New' field set to - * false. See the "Replay" message below for details of - * usage. The off air field indicates that the decode was decoded - * from a played back recording. - * - * - * Location In 11 - * Id (unique key) utf8 - * Location utf8 - * - * This message allows the server to set the current current - * geographical location of operation. The supplied location is - * not persistent but is used as a session lifetime replacement - * loction that overrides the Maidenhead grid locater set in the - * application settings. The intent is to allow an external - * application to update the operating location dynamically - * during a mobile period of operation. - * - * Currently only Maidenhead grid squares or sub-squares are - * accepted, i.e. 4- or 6-digit locators. Other formats may be - * accepted in future. - * - * - * Logged ADIF Out 12 quint32 - * Id (unique key) utf8 - * ADIF text utf8 - * - * The logged ADIF message is sent to the server(s) when the - * WSJT-X user accepts the "Log QSO" dialog by clicking the "OK" - * button. The "ADIF text" field consists of a valid ADIF file - * such that the WSJT-X UDP header information is encapsulated - * into a valid ADIF header. E.g.: - * - * <magic-number><schema-number><type><id><32-bit-count> # binary encoded fields - * # the remainder is the contents of the ADIF text field - * <adif_ver:5>3.0.7 - * <programid:6>WSJT-X - * <EOH> - * ADIF log data fields ...<EOR> - * - * Note that receiving applications can treat the whole message - * as a valid ADIF file with one record without special parsing. - * - * - * Highlight Callsign In 13 quint32 - * Id (unique key) utf8 - * Callsign utf8 - * Background Color QColor - * Foreground Color QColor - * Highlight last bool - * - * The server may send this message at any time. The message - * specifies the background and foreground color that will be - * used to highlight the specified callsign in the decoded - * messages printed in the Band Activity panel. The WSJT-X - * clients maintain a list of such instructions and apply them to - * all decoded messages in the band activity window. To clear - * and cancel highlighting send an invalid QColor value for - * either or both of the background and foreground fields. When - * using this mode the total number of callsign highlighting - * requests should be limited otherwise the performance of WSJT-X - * decoding may be impacted. A rough rule of thumb might be too - * limit the number of active highlighting requests to no more - * than 100. - * - * Using a callsign of "CLEARALL!" and anything for the - * color values will clear the internal highlighting data. It will - * NOT remove the highlighting on the screen, however. The exclamation - * symbol is used to avoid accidental clearing of all highlighting - * data via a decoded callsign, since an exclamation symbol is not - * a valid character in a callsign. - - * - * The "Highlight last" field allows the sender to request that - * all instances of "Callsign" in the last period only, instead - * of all instances in all periods, be highlighted. - * - * - * SwitchConfiguration In 14 quint32 - * Id (unique key) utf8 - * Configuration Name utf8 - * - * The server may send this message at any time. The message - * specifies the name of the configuration to switch to. The new - * configuration must exist. - * - * - * Configure In 15 quint32 - * Id (unique key) utf8 - * Mode utf8 - * Frequency Tolerance quint32 - * Submode utf8 - * Fast Mode bool - * T/R Period quint32 - * Rx DF quint32 - * DX Call utf8 - * DX Grid utf8 - * Generate Messages bool - * - * The server may send this message at any time. The message - * specifies various configuration options. For utf8 string - * fields an empty value implies no change, for the quint32 Rx DF - * and Frequency Tolerance fields the maximum quint32 value - * implies no change. Invalid or unrecognized values will be - * silently ignored. NOTE that if a mode/submode change occurs and - * the current frequency is NOT in the frequency table for that - * mode, a frequency change (to the default frequency for that band - * and mode) may occur. - * - * AnnotationInfo In 16 quint32 - * Id (unique key) utf8 - * DX Call utf8 - * Sort Order Provided bool - * Sort Order quint32 - * - * The server may send this message at any time. Sort orders can be used - * for sorting hound callers when in Fox mode. A typical usage is to - * "score" callsigns based on number of bands and/or modes worked using - * an external logging program during a DXpedition, to be able to give - * preference to calls that have not been worked before on any other - * band or mode. An external program can watch decodes from wsjt-x, - * then use this message to annotate the calls with a sort order. The - * hound queue can be displayed by that sort order. * - * - * If 'sort order provided' is true, the message also specifies a numeric - * sort order for the DX call. - * - * Invalid or unrecognized values will be silently ignored. A sort-order of - * ffffffff will remove the sort-order value from the internal table. - * Callsigns without a sort order will be valued at zero for sorting purposes - * in the hound display. - */ - -#include <QDataStream> - -#include "pimpl_h.hpp" - -class QIODevice; -class QByteArray; -class QString; - -namespace NetworkMessage -{ - // NEVER DELETE MESSAGE TYPES - enum Type - { - Heartbeat, - Status, - Decode, - Clear, - Reply, - QSOLogged, - Close, - Replay, - HaltTx, - FreeText, - WSPRDecode, - Location, - LoggedADIF, - HighlightCallsign, - SwitchConfiguration, - Configure, - AnnotationInfo, - maximum_message_type_ // ONLY add new message types - // immediately before here - }; - - quint32 constexpr pulse {15}; // seconds - - // - // NetworkMessage::Builder - build a message containing serialized Qt types - // - class Builder - : public QDataStream - { - public: - static quint32 constexpr magic {0xadbccbda}; // never change this - - // increment this if a newer Qt schema is required and add decode - // logic to the Builder and Reader class implementations -#if QT_VERSION >= QT_VERSION_CHECK (5, 4, 0) - static quint32 constexpr schema_number {3}; -#elif QT_VERSION >= QT_VERSION_CHECK (5, 2, 0) - static quint32 constexpr schema_number {2}; -#else - // Schema 1 (Qt_5_0) is broken -#error "Qt version 5.2 or greater required" -#endif - - explicit Builder (QIODevice *, Type, QString const& id, quint32 schema); - explicit Builder (QByteArray *, Type, QString const& id, quint32 schema); - Builder (Builder const&) = delete; - Builder& operator = (Builder const&) = delete; - - private: - void common_initialization (Type type, QString const& id, quint32 schema); - }; - - // - // NetworkMessage::Reader - read a message containing serialized Qt types - // - // Message is as per NetworkMessage::Builder above, the schema() - // member may be used to determine the schema of the original - // message. - // - class Reader - : public QDataStream - { - public: - explicit Reader (QIODevice *); - explicit Reader (QByteArray const&); - Reader (Reader const&) = delete; - Reader& operator = (Reader const&) = delete; - ~Reader (); - - quint32 schema () const; - Type type () const; - QString id () const; - - private: - class impl; - pimpl<impl> m_; - }; -} - -#endif +#ifndef NETWORK_MESSAGE_HPP__
+#define NETWORK_MESSAGE_HPP__
+
+/*
+ * WSJT-X Message Formats
+ * ======================
+ *
+ * All messages are written or read using the QDataStream derivatives
+ * defined below, note that we are using the default for floating
+ * point precision which means all are double precision i.e. 64-bit
+ * IEEE format.
+ *
+ * Message is big endian format
+ *
+ * Header format:
+ *
+ * 32-bit unsigned integer magic number 0xadbccbda
+ * 32-bit unsigned integer schema number
+ *
+ * Payload format:
+ *
+ * As per the QDataStream format, see below for version used and
+ * here:
+ *
+ * http://doc.qt.io/qt-5/datastreamformat.html
+ *
+ * for the serialization details for each type, at the time of
+ * writing the above document is for Qt_5_0 format which is buggy
+ * so we use Qt_5_4 format, differences are:
+ *
+ * QDateTime:
+ * QDate qint64 Julian day number
+ * QTime quint32 Milli-seconds since midnight
+ * timespec quint8 0=local, 1=UTC, 2=Offset from UTC
+ * (seconds)
+ * 3=time zone
+ * offset qint32 only present if timespec=2
+ * timezone several-fields only present if timespec=3
+ *
+ * we will avoid using QDateTime fields with time zones for
+ * simplicity.
+ *
+ * Type utf8 is a utf-8 byte string formatted as a QByteArray for
+ * serialization purposes (currently a quint32 size followed by size
+ * bytes, no terminator is present or counted).
+ *
+ * The QDataStream format document linked above is not complete for
+ * the QByteArray serialization format, it is similar to the QString
+ * serialization format in that it differentiates between empty
+ * strings and null strings. Empty strings have a length of zero
+ * whereas null strings have a length field of 0xffffffff.
+ *
+ *
+ * Schema Negotiation
+ * ------------------
+ *
+ * The NetworkMessage::Builder class specifies a schema number which
+ * may be incremented from time to time. It represents a version of
+ * the underlying encoding schemes used to store data items. Since the
+ * underlying encoding is defined by the Qt project in it's
+ * QDataStream stream operators, it is essential that clients and
+ * servers of this protocol can agree on a common scheme. The
+ * NetworkMessage utility classes below exchange the schema number
+ * actually used. The handling of the schema is backwards compatible
+ * to an extent, so long as clients and servers are written
+ * correctly. For example a server written to any particular schema
+ * version can communicate with a client written to a later schema.
+ *
+ * Schema Version 1:- this schema used the QDataStream::Qt_5_0 version
+ * which is broken.
+ *
+ * Schema Version 2:- this schema uses the QDataStream::Qt_5_2 version.
+ *
+ * Schema Version 3:- this schema uses the QDataStream::Qt_5_4 version.
+ *
+ *
+ * Backward Compatibility
+ * ----------------------
+ *
+ * It is important that applications developed at different times
+ * remain compatible with this protocol and with older or newer
+ * versions of WSJT-X. This is achieved by both third-party
+ * applications and WSJT-X honouring two basic rules.
+ *
+ * 1. New message types may be added to the protocol in the future,
+ * third-party applications and WSJT-X shall ignore silently any
+ * message types they do not recognize.
+ *
+ * 2. New fields may be added to existing message types, they will
+ * always be added to the end of the existing fields and the number
+ * and type of existing fields shall not change. If a field type
+ * must be changed; a new field will be added and the existing
+ * field will remain. The originator of such a message shall
+ * populate both the new and old field with reasonable
+ * values. Third-party applications and WSJT-X shall ignore
+ * silently any extra data received in datagrams after the fields
+ * they know about.
+ *
+ * Note that these rules are unrelated to the schema number above
+ * whose purpose is to distinguish between non-compatible encodings of
+ * field data types. New message types and extra fields in existing
+ * messages can and will be added without any change in schema number.
+ *
+ *
+ * Message Types
+ * -------------
+ *
+ * Message Direction Value Type
+ * ------------- --------- ---------------------- -----------
+ * Heartbeat Out/In 0 quint32
+ * Id (unique key) utf8
+ * Maximum schema number quint32
+ * version utf8
+ * revision utf8
+ *
+ * The heartbeat message shall be sent on a periodic basis every
+ * NetworkMessage::pulse seconds (see below), the WSJT-X
+ * application does that using the MessageClient class. This
+ * message is intended to be used by servers to detect the presence
+ * of a client and also the unexpected disappearance of a client
+ * and by clients to learn the schema negotiated by the server
+ * after it receives the initial heartbeat message from a client.
+ * The message_aggregator reference server does just that using the
+ * MessageServer class. Upon initial startup a client must send a
+ * heartbeat message as soon as is practical, this message is used
+ * to negotiate the maximum schema number common to the client and
+ * server. Note that the server may not be able to support the
+ * client's requested maximum schema number, in which case the
+ * first message received from the server will specify a lower
+ * schema number (never a higher one as that is not allowed). If a
+ * server replies with a lower schema number then no higher than
+ * that number shall be used for all further outgoing messages from
+ * either clients or the server itself.
+ *
+ * Note: the "Maximum schema number" field was introduced at the
+ * same time as schema 3, therefore servers and clients must assume
+ * schema 2 is the highest schema number supported if the Heartbeat
+ * message does not contain the "Maximum schema number" field.
+ *
+ *
+ * Status Out 1 quint32
+ * Id (unique key) utf8
+ * Dial Frequency (Hz) quint64
+ * Mode utf8
+ * DX call utf8
+ * Report utf8
+ * Tx Mode utf8
+ * Tx Enabled bool
+ * Transmitting bool
+ * Decoding bool
+ * Rx DF quint32
+ * Tx DF quint32
+ * DE call utf8
+ * DE grid utf8
+ * DX grid utf8
+ * Tx Watchdog bool
+ * Sub-mode utf8
+ * Fast mode bool
+ * Special Operation Mode quint8
+ * Frequency Tolerance quint32
+ * T/R Period quint32
+ * Configuration Name utf8
+ * Tx Message utf8
+ *
+ * WSJT-X sends this status message when various internal state
+ * changes to allow the server to track the relevant state of each
+ * client without the need for polling commands. The current state
+ * changes that generate status messages are:
+ *
+ * Application start up,
+ * "Enable Tx" button status changes,
+ * dial frequency changes,
+ * changes to the "DX Call" field,
+ * operating mode, sub-mode or fast mode changes,
+ * transmit mode changed (in dual JT9+JT65 mode),
+ * changes to the "Rpt" spinner,
+ * after an old decodes replay sequence (see Replay below),
+ * when switching between Tx and Rx mode,
+ * at the start and end of decoding,
+ * when the Rx DF changes,
+ * when the Tx DF changes,
+ * when settings are exited,
+ * when the DX call or grid changes,
+ * when the Tx watchdog is set or reset,
+ * when the frequency tolerance is changed,
+ * when the T/R period is changed,
+ * when the configuration name changes,
+ * when the message being transmitted changes.
+ *
+ * The Special operation mode is an enumeration that indicates the
+ * setting selected in the WSJT-X "Settings->Advanced->Special
+ * operating activity" panel. The values are as follows:
+ *
+ * 0 -> NONE
+ * 1 -> NA VHF
+ * 2 -> EU VHF
+ * 3 -> FIELD DAY
+ * 4 -> RTTY RU
+ * 5 -> WW DIGI
+ * 6 -> FOX
+ * 7 -> HOUND
+ * 8 -> ARRL DIGI
+ *
+ * The Frequency Tolerance and T/R period fields may have a value
+ * of the maximum quint32 value which implies the field is not
+ * applicable.
+ *
+ *
+ * Decode Out 2 quint32
+ * Id (unique key) utf8
+ * New bool
+ * Time QTime
+ * snr qint32
+ * Delta time (S) float (serialized as double)
+ * Delta frequency (Hz) quint32
+ * Mode utf8
+ * Message utf8
+ * Low confidence bool
+ * Off air bool
+ *
+ * The decode message is sent when a new decode is completed, in
+ * this case the 'New' field is true. It is also used in response
+ * to a "Replay" message where each old decode in the "Band
+ * activity" window, that has not been erased, is sent in order
+ * as a one of these messages with the 'New' field set to false.
+ * See the "Replay" message below for details of usage. Low
+ * confidence decodes are flagged in protocols where the decoder
+ * has knows that a decode has a higher than normal probability
+ * of being false, they should not be reported on publicly
+ * accessible services without some attached warning or further
+ * validation. Off air decodes are those that result from playing
+ * back a .WAV file.
+ *
+ *
+ * Clear Out/In 3 quint32
+ * Id (unique key) utf8
+ * Window quint8 (In only)
+ *
+ * This message is send when all prior "Decode" messages in the
+ * "Band Activity" window have been discarded and therefore are
+ * no long available for actioning with a "Reply" message. It is
+ * sent when the user erases the "Band activity" window and when
+ * WSJT-X closes down normally. The server should discard all
+ * decode messages upon receipt of this message.
+ *
+ * It may also be sent to a WSJT-X instance in which case it
+ * clears one or both of the "Band Activity" and "Rx Frequency"
+ * windows. The Window argument can be one of the following
+ * values:
+ *
+ * 0 - clear the "Band Activity" window (default)
+ * 1 - clear the "Rx Frequency" window
+ * 2 - clear both "Band Activity" and "Rx Frequency" windows
+ *
+ *
+ * Reply In 4 quint32
+ * Id (target unique key) utf8
+ * Time QTime
+ * snr qint32
+ * Delta time (S) float (serialized as double)
+ * Delta frequency (Hz) quint32
+ * Mode utf8
+ * Message utf8
+ * Low confidence bool
+ * Modifiers quint8
+ *
+ * In order for a server to provide a useful cooperative service
+ * to WSJT-X it is possible for it to initiate a QSO by sending
+ * this message to a client. WSJT-X filters this message and only
+ * acts upon it if the message exactly describes a prior decode
+ * and that decode is a CQ or QRZ message. The action taken is
+ * exactly equivalent to the user double clicking the message in
+ * the "Band activity" window. The intent of this message is for
+ * servers to be able to provide an advanced look up of potential
+ * QSO partners, for example determining if they have been worked
+ * before or if working them may advance some objective like
+ * award progress. The intention is not to provide a secondary
+ * user interface for WSJT-X, it is expected that after QSO
+ * initiation the rest of the QSO is carried out manually using
+ * the normal WSJT-X user interface.
+ *
+ * The Modifiers field allows the equivalent of keyboard
+ * modifiers to be sent "as if" those modifier keys where pressed
+ * while double-clicking the specified decoded message. The
+ * modifier values (hexadecimal) are as follows:
+ *
+ * no modifier 0x00
+ * SHIFT 0x02
+ * CTRL 0x04 CMD on Mac
+ * ALT 0x08
+ * META 0x10 Windows key on MS Windows
+ * KEYPAD 0x20 Keypad or arrows
+ * Group switch 0x40 X11 only
+ *
+ *
+ * QSO Logged Out 5 quint32
+ * Id (unique key) utf8
+ * Date & Time Off QDateTime
+ * DX call utf8
+ * DX grid utf8
+ * Tx frequency (Hz) quint64
+ * Mode utf8
+ * Report sent utf8
+ * Report received utf8
+ * Tx power utf8
+ * Comments utf8
+ * Name utf8
+ * Date & Time On QDateTime
+ * Operator call utf8
+ * My call utf8
+ * My grid utf8
+ * Exchange sent utf8
+ * Exchange received utf8
+ * ADIF Propagation mode utf8
+ *
+ * The QSO logged message is sent to the server(s) when the
+ * WSJT-X user accepts the "Log QSO" dialog by clicking the "OK"
+ * button.
+ *
+ *
+ * Close Out/In 6 quint32
+ * Id (unique key) utf8
+ *
+ * Close is sent by a client immediately prior to it shutting
+ * down gracefully. When sent by a server it requests the target
+ * client to close down gracefully.
+ *
+ *
+ * Replay In 7 quint32
+ * Id (unique key) utf8
+ *
+ * When a server starts it may be useful for it to determine the
+ * state of preexisting clients. Sending this message to each
+ * client as it is discovered will cause that client (WSJT-X) to
+ * send a "Decode" message for each decode currently in its "Band
+ * activity" window. Each "Decode" message sent will have the
+ * "New" flag set to false so that they can be distinguished from
+ * new decodes. After all the old decodes have been broadcast a
+ * "Status" message is also broadcast. If the server wishes to
+ * determine the status of a newly discovered client; this
+ * message should be used.
+ *
+ *
+ * Halt Tx In 8
+ * Id (unique key) utf8
+ * Auto Tx Only bool
+ *
+ * The server may stop a client from transmitting messages either
+ * immediately or at the end of the current transmission period
+ * using this message.
+ *
+ *
+ * Free Text In 9
+ * Id (unique key) utf8
+ * Text utf8
+ * Send bool
+ *
+ * This message allows the server to set the current free text
+ * message content. Sending this message with a non-empty "Text"
+ * field is equivalent to typing a new message (old contents are
+ * discarded) in to the WSJT-X free text message field or "Tx5"
+ * field (both are updated) and if the "Send" flag is set then
+ * clicking the "Now" radio button for the "Tx5" field if tab one
+ * is current or clicking the "Free msg" radio button if tab two
+ * is current.
+ *
+ * It is the responsibility of the sender to limit the length of
+ * the message text and to limit it to legal message
+ * characters. Despite this, it may be difficult for the sender
+ * to determine the maximum message length without reimplementing
+ * the complete message encoding protocol. Because of this is may
+ * be better to allow any reasonable message length and to let
+ * the WSJT-X application encode and possibly truncate the actual
+ * on-air message.
+ *
+ * If the message text is empty the meaning of the message is
+ * refined to send the current free text unchanged when the
+ * "Send" flag is set or to clear the current free text when the
+ * "Send" flag is unset. Note that this API does not include a
+ * command to determine the contents of the current free text
+ * message.
+ *
+ *
+ * WSPRDecode Out 10 quint32
+ * Id (unique key) utf8
+ * New bool
+ * Time QTime
+ * snr qint32
+ * Delta time (S) float (serialized as double)
+ * Frequency (Hz) quint64
+ * Drift (Hz) qint32
+ * Callsign utf8
+ * Grid utf8
+ * Power (dBm) qint32
+ * Off air bool
+ *
+ * The decode message is sent when a new decode is completed, in
+ * this case the 'New' field is true. It is also used in response
+ * to a "Replay" message where each old decode in the "Band
+ * activity" window, that has not been erased, is sent in order
+ * as a one of these messages with the 'New' field set to
+ * false. See the "Replay" message below for details of
+ * usage. The off air field indicates that the decode was decoded
+ * from a played back recording.
+ *
+ *
+ * Location In 11
+ * Id (unique key) utf8
+ * Location utf8
+ *
+ * This message allows the server to set the current current
+ * geographical location of operation. The supplied location is
+ * not persistent but is used as a session lifetime replacement
+ * loction that overrides the Maidenhead grid locater set in the
+ * application settings. The intent is to allow an external
+ * application to update the operating location dynamically
+ * during a mobile period of operation.
+ *
+ * Currently only Maidenhead grid squares or sub-squares are
+ * accepted, i.e. 4- or 6-digit locators. Other formats may be
+ * accepted in future.
+ *
+ *
+ * Logged ADIF Out 12 quint32
+ * Id (unique key) utf8
+ * ADIF text utf8
+ *
+ * The logged ADIF message is sent to the server(s) when the
+ * WSJT-X user accepts the "Log QSO" dialog by clicking the "OK"
+ * button. The "ADIF text" field consists of a valid ADIF file
+ * such that the WSJT-X UDP header information is encapsulated
+ * into a valid ADIF header. E.g.:
+ *
+ * <magic-number><schema-number><type><id><32-bit-count> # binary encoded fields
+ * # the remainder is the contents of the ADIF text field
+ * <adif_ver:5>3.0.7
+ * <programid:6>WSJT-X
+ * <EOH>
+ * ADIF log data fields ...<EOR>
+ *
+ * Note that receiving applications can treat the whole message
+ * as a valid ADIF file with one record without special parsing.
+ *
+ *
+ * Highlight Callsign In 13 quint32
+ * Id (unique key) utf8
+ * Callsign utf8
+ * Background Color QColor
+ * Foreground Color QColor
+ * Highlight last bool
+ *
+ * The server may send this message at any time. The message
+ * specifies the background and foreground color that will be
+ * used to highlight the specified callsign in the decoded
+ * messages printed in the Band Activity panel. The WSJT-X
+ * clients maintain a list of such instructions and apply them to
+ * all decoded messages in the band activity window. To clear
+ * and cancel highlighting send an invalid QColor value for
+ * either or both of the background and foreground fields. When
+ * using this mode the total number of callsign highlighting
+ * requests should be limited otherwise the performance of WSJT-X
+ * decoding may be impacted. A rough rule of thumb might be too
+ * limit the number of active highlighting requests to no more
+ * than 100.
+ *
+ * Using a callsign of "CLEARALL!" and anything for the
+ * color values will clear the internal highlighting data. It will
+ * NOT remove the highlighting on the screen, however. The exclamation
+ * symbol is used to avoid accidental clearing of all highlighting
+ * data via a decoded callsign, since an exclamation symbol is not
+ * a valid character in a callsign.
+
+ *
+ * The "Highlight last" field allows the sender to request that
+ * all instances of "Callsign" in the last period only, instead
+ * of all instances in all periods, be highlighted.
+ *
+ *
+ * SwitchConfiguration In 14 quint32
+ * Id (unique key) utf8
+ * Configuration Name utf8
+ *
+ * The server may send this message at any time. The message
+ * specifies the name of the configuration to switch to. The new
+ * configuration must exist.
+ *
+ *
+ * Configure In 15 quint32
+ * Id (unique key) utf8
+ * Mode utf8
+ * Frequency Tolerance quint32
+ * Submode utf8
+ * Fast Mode bool
+ * T/R Period quint32
+ * Rx DF quint32
+ * DX Call utf8
+ * DX Grid utf8
+ * Generate Messages bool
+ *
+ * The server may send this message at any time. The message
+ * specifies various configuration options. For utf8 string
+ * fields an empty value implies no change, for the quint32 Rx DF
+ * and Frequency Tolerance fields the maximum quint32 value
+ * implies no change. Invalid or unrecognized values will be
+ * silently ignored. NOTE that if a mode/submode change occurs and
+ * the current frequency is NOT in the frequency table for that
+ * mode, a frequency change (to the default frequency for that band
+ * and mode) may occur.
+ *
+ * AnnotationInfo In 16 quint32
+ * Id (unique key) utf8
+ * DX Call utf8
+ * Sort Order Provided bool
+ * Sort Order quint32
+ *
+ * The server may send this message at any time. Sort orders can be used
+ * for sorting hound callers when in Fox mode. A typical usage is to
+ * "score" callsigns based on number of bands and/or modes worked using
+ * an external logging program during a DXpedition, to be able to give
+ * preference to calls that have not been worked before on any other
+ * band or mode. An external program can watch decodes from wsjt-x,
+ * then use this message to annotate the calls with a sort order. The
+ * hound queue can be displayed by that sort order. *
+ *
+ * If 'sort order provided' is true, the message also specifies a numeric
+ * sort order for the DX call.
+ *
+ * Invalid or unrecognized values will be silently ignored. A sort-order of
+ * ffffffff will remove the sort-order value from the internal table.
+ * Callsigns without a sort order will be valued at zero for sorting purposes
+ * in the hound display.
+ */
+
+#include <QDataStream>
+
+#include "pimpl_h.hpp"
+
+class QIODevice;
+class QByteArray;
+class QString;
+
+namespace NetworkMessage
+{
+ // NEVER DELETE MESSAGE TYPES
+ enum Type
+ {
+ Heartbeat,
+ Status,
+ Decode,
+ Clear,
+ Reply,
+ QSOLogged,
+ Close,
+ Replay,
+ HaltTx,
+ FreeText,
+ WSPRDecode,
+ Location,
+ LoggedADIF,
+ HighlightCallsign,
+ SwitchConfiguration,
+ Configure,
+ AnnotationInfo,
+ maximum_message_type_ // ONLY add new message types
+ // immediately before here
+ };
+
+ quint32 constexpr pulse {15}; // seconds
+
+ //
+ // NetworkMessage::Builder - build a message containing serialized Qt types
+ //
+ class Builder
+ : public QDataStream
+ {
+ public:
+ static quint32 constexpr magic {0xadbccbda}; // never change this
+
+ // increment this if a newer Qt schema is required and add decode
+ // logic to the Builder and Reader class implementations
+#if QT_VERSION >= QT_VERSION_CHECK (5, 4, 0)
+ static quint32 constexpr schema_number {3};
+#elif QT_VERSION >= QT_VERSION_CHECK (5, 2, 0)
+ static quint32 constexpr schema_number {2};
+#else
+ // Schema 1 (Qt_5_0) is broken
+#error "Qt version 5.2 or greater required"
+#endif
+
+ explicit Builder (QIODevice *, Type, QString const& id, quint32 schema);
+ explicit Builder (QByteArray *, Type, QString const& id, quint32 schema);
+ Builder (Builder const&) = delete;
+ Builder& operator = (Builder const&) = delete;
+
+ private:
+ void common_initialization (Type type, QString const& id, quint32 schema);
+ };
+
+ //
+ // NetworkMessage::Reader - read a message containing serialized Qt types
+ //
+ // Message is as per NetworkMessage::Builder above, the schema()
+ // member may be used to determine the schema of the original
+ // message.
+ //
+ class Reader
+ : public QDataStream
+ {
+ public:
+ explicit Reader (QIODevice *);
+ explicit Reader (QByteArray const&);
+ Reader (Reader const&) = delete;
+ Reader& operator = (Reader const&) = delete;
+ ~Reader ();
+
+ quint32 schema () const;
+ Type type () const;
+ QString id () const;
+
+ private:
+ class impl;
+ pimpl<impl> m_;
+ };
+}
+
+#endif
diff --git a/Network/NetworkServerLookup.cpp b/Network/NetworkServerLookup.cpp index 0d7cd4fe..c516822a 100755 --- a/Network/NetworkServerLookup.cpp +++ b/Network/NetworkServerLookup.cpp @@ -1,85 +1,85 @@ -#include "NetworkServerLookup.hpp" - -#include <stdexcept> - -#include <QHostInfo> -#include <QString> - -std::tuple<QHostAddress, quint16> -network_server_lookup (QString query - , quint16 default_service_port - , QHostAddress default_host_address - , QAbstractSocket::NetworkLayerProtocol required_protocol) -{ - query = query.trimmed (); - - QHostAddress host_address {default_host_address}; - quint16 service_port {default_service_port}; - - QString host_name; - if (!query.isEmpty ()) - { - int port_colon_index {-1}; - - if ('[' == query[0]) - { - // assume IPv6 combined address/port syntax [<address>]:<port> - auto close_bracket_index = query.lastIndexOf (']'); - host_name = query.mid (1, close_bracket_index - 1); - port_colon_index = query.indexOf (':', close_bracket_index); - } - else - { - port_colon_index = query.lastIndexOf (':'); - host_name = query.left (port_colon_index); - } - host_name = host_name.trimmed (); - - if (port_colon_index >= 0) - { - bool ok; - service_port = query.mid (port_colon_index + 1).trimmed ().toUShort (&ok); - if (!ok) - { - throw std::runtime_error {"network server lookup error: invalid port"}; - } - } - } - - if (!host_name.isEmpty ()) - { - auto host_info = QHostInfo::fromName (host_name); - if (host_info.addresses ().isEmpty ()) - { - throw std::runtime_error {"network server lookup error: host name lookup failed"}; - } - - bool found {false}; - for (int i {0}; i < host_info.addresses ().size () && !found; ++i) - { - host_address = host_info.addresses ().at (i); - switch (required_protocol) - { - case QAbstractSocket::IPv4Protocol: - case QAbstractSocket::IPv6Protocol: - if (required_protocol != host_address.protocol ()) - { - break; - } - // fall through - case QAbstractSocket::AnyIPProtocol: - found = true; - break; - - default: - throw std::runtime_error {"network server lookup error: invalid required protocol"}; - } - } - if (!found) - { - throw std::runtime_error {"network server lookup error: no suitable host address found"}; - } - } - - return std::make_tuple (host_address, service_port); -} +#include "NetworkServerLookup.hpp"
+
+#include <stdexcept>
+
+#include <QHostInfo>
+#include <QString>
+
+std::tuple<QHostAddress, quint16>
+network_server_lookup (QString query
+ , quint16 default_service_port
+ , QHostAddress default_host_address
+ , QAbstractSocket::NetworkLayerProtocol required_protocol)
+{
+ query = query.trimmed ();
+
+ QHostAddress host_address {default_host_address};
+ quint16 service_port {default_service_port};
+
+ QString host_name;
+ if (!query.isEmpty ())
+ {
+ int port_colon_index {-1};
+
+ if ('[' == query[0])
+ {
+ // assume IPv6 combined address/port syntax [<address>]:<port>
+ auto close_bracket_index = query.lastIndexOf (']');
+ host_name = query.mid (1, close_bracket_index - 1);
+ port_colon_index = query.indexOf (':', close_bracket_index);
+ }
+ else
+ {
+ port_colon_index = query.lastIndexOf (':');
+ host_name = query.left (port_colon_index);
+ }
+ host_name = host_name.trimmed ();
+
+ if (port_colon_index >= 0)
+ {
+ bool ok;
+ service_port = query.mid (port_colon_index + 1).trimmed ().toUShort (&ok);
+ if (!ok)
+ {
+ throw std::runtime_error {"network server lookup error: invalid port"};
+ }
+ }
+ }
+
+ if (!host_name.isEmpty ())
+ {
+ auto host_info = QHostInfo::fromName (host_name);
+ if (host_info.addresses ().isEmpty ())
+ {
+ throw std::runtime_error {"network server lookup error: host name lookup failed"};
+ }
+
+ bool found {false};
+ for (int i {0}; i < host_info.addresses ().size () && !found; ++i)
+ {
+ host_address = host_info.addresses ().at (i);
+ switch (required_protocol)
+ {
+ case QAbstractSocket::IPv4Protocol:
+ case QAbstractSocket::IPv6Protocol:
+ if (required_protocol != host_address.protocol ())
+ {
+ break;
+ }
+ // fall through
+ case QAbstractSocket::AnyIPProtocol:
+ found = true;
+ break;
+
+ default:
+ throw std::runtime_error {"network server lookup error: invalid required protocol"};
+ }
+ }
+ if (!found)
+ {
+ throw std::runtime_error {"network server lookup error: no suitable host address found"};
+ }
+ }
+
+ return std::make_tuple (host_address, service_port);
+}
diff --git a/Network/NetworkServerLookup.hpp b/Network/NetworkServerLookup.hpp index 7c7c9d11..b3a105d5 100755 --- a/Network/NetworkServerLookup.hpp +++ b/Network/NetworkServerLookup.hpp @@ -1,38 +1,38 @@ -#ifndef NETWORK_SERVER_LOOKUP_HPP__ -#define NETWORK_SERVER_LOOKUP_HPP__ - -#include <tuple> - -#include <QHostAddress> -#include <QAbstractSocket> - -class QString; - -// -// Do a blocking DNS lookup using query as a destination host address -// and port. -// -// query can be one of: -// -// 1) "" (empty string) - use defaults -// 2) ":nnnnn" - override default service port with port nnnnn -// 3) "<valid-host-name>" - override default host address with DNS lookup -// 4) "nnn.nnn.nnn.nnn" - override default host address with the IPv4 address given by nnn.nnn.nnn.nnn -// 5) "[<valid-IPv6-address]" - override default host address with the given IPv6 address -// 6) "<valid-host-name>:nnnnn" - use as per (3) & (2) -// 7) "nnn.nnn.nnn.nnn:nnnnn" - use as per (4) & (2) -// 8) "[<valid-IPv6-address]:nnnnn" - use as per (5) & (2) -// -// The first host address matching the protocol and the service port -// number are returned. -// -// If no suitable host address is found QHostAddress::Null will be -// returned in the first member of the result tuple. -// -std::tuple<QHostAddress, quint16> -network_server_lookup (QString query - , quint16 default_service_port - , QHostAddress default_host_address = QHostAddress::LocalHost - , QAbstractSocket::NetworkLayerProtocol protocol = QAbstractSocket::AnyIPProtocol); - -#endif +#ifndef NETWORK_SERVER_LOOKUP_HPP__
+#define NETWORK_SERVER_LOOKUP_HPP__
+
+#include <tuple>
+
+#include <QHostAddress>
+#include <QAbstractSocket>
+
+class QString;
+
+//
+// Do a blocking DNS lookup using query as a destination host address
+// and port.
+//
+// query can be one of:
+//
+// 1) "" (empty string) - use defaults
+// 2) ":nnnnn" - override default service port with port nnnnn
+// 3) "<valid-host-name>" - override default host address with DNS lookup
+// 4) "nnn.nnn.nnn.nnn" - override default host address with the IPv4 address given by nnn.nnn.nnn.nnn
+// 5) "[<valid-IPv6-address]" - override default host address with the given IPv6 address
+// 6) "<valid-host-name>:nnnnn" - use as per (3) & (2)
+// 7) "nnn.nnn.nnn.nnn:nnnnn" - use as per (4) & (2)
+// 8) "[<valid-IPv6-address]:nnnnn" - use as per (5) & (2)
+//
+// The first host address matching the protocol and the service port
+// number are returned.
+//
+// If no suitable host address is found QHostAddress::Null will be
+// returned in the first member of the result tuple.
+//
+std::tuple<QHostAddress, quint16>
+network_server_lookup (QString query
+ , quint16 default_service_port
+ , QHostAddress default_host_address = QHostAddress::LocalHost
+ , QAbstractSocket::NetworkLayerProtocol protocol = QAbstractSocket::AnyIPProtocol);
+
+#endif
diff --git a/Network/PSKReporter.cpp b/Network/PSKReporter.cpp index d9d65b0e..6e390006 100755 --- a/Network/PSKReporter.cpp +++ b/Network/PSKReporter.cpp @@ -1,696 +1,697 @@ -#include "PSKReporter.hpp" - -// Interface for posting spots to PSK Reporter web site -// Implemented by Edson Pereira PY2SDR -// Updated by Bill Somerville, G4WJS -// -// Reports will be sent in batch mode every 5 minutes. - -#include <fstream> -#include <iostream> -#include <cmath> -#include <QObject> -#include <QString> -#include <QDateTime> -#include <QSharedPointer> -#include <QUdpSocket> -#include <QTcpSocket> -#include <QHostInfo> -#include <QQueue> -#include <QByteArray> -#include <QDataStream> -#include <QTimer> -#include <QDir> -#if QT_VERSION >= QT_VERSION_CHECK(5, 15, 0) -#include <QRandomGenerator> -#endif - -#include "Logger.hpp" -#include "Configuration.hpp" -#include "pimpl_impl.hpp" - - -#include "moc_PSKReporter.cpp" - -#define DEBUGECLIPSE 0 - -namespace -{ - QLatin1String HOST {"report.pskreporter.info"}; - // QLatin1String HOST {"127.0.0.1"}; - quint16 SERVICE_PORT {4739}; - // quint16 SERVICE_PORT {14739}; - int MIN_SEND_INTERVAL {120}; // in seconds - int FLUSH_INTERVAL {MIN_SEND_INTERVAL + 5}; // in send intervals - bool ALIGNMENT_PADDING {true}; - int MIN_PAYLOAD_LENGTH {508}; - int MAX_PAYLOAD_LENGTH {10000}; - int CACHE_TIMEOUT {300}; // default to 5 minutes for repeating spots - QMap<QString, time_t> spot_cache; -} - -static int added; -static int removed; - -class PSKReporter::impl final - : public QObject -{ - Q_OBJECT - - using logger_type = boost::log::sources::severity_channel_logger_mt<boost::log::trivial::severity_level>; - -public: - impl (PSKReporter * self, Configuration const * config, QString const& program_info) - : logger_ {boost::log::keywords::channel = "PSKRPRT"} - , self_ {self} - , config_ {config} - , sequence_number_ {0u} - , send_descriptors_ {0} - , send_receiver_data_ {0} - , flush_counter_ {0u} - , prog_id_ {program_info} - { -#if QT_VERSION < QT_VERSION_CHECK(5, 15, 0) - observation_id_ = qrand(); -#else - observation_id_ = QRandomGenerator::global ()->generate (); -#endif - - // This timer sets the interval to check for spots to send. - connect (&report_timer_, &QTimer::timeout, [this] () {send_report ();}); - - // This timer repeats the sending of IPFIX templates and receiver - // information if we are using UDP, in case server has been - // restarted ans lost cached information. - connect (&descriptor_timer_, &QTimer::timeout, [this] () { - if (socket_ - && QAbstractSocket::UdpSocket == socket_->socketType ()) - { - LOG_LOG_LOCATION (logger_, trace, "enable descriptor resend"); - // send templates again - send_descriptors_ = 3; // three times - // send receiver data set again - send_receiver_data_ = 3; // three times - } - }); - eclipse_load(config->data_dir ().absoluteFilePath ("eclipse.txt")); - } - - void check_connection () - { - if (!socket_ - || QAbstractSocket::UnconnectedState == socket_->state () - || (socket_->socketType () != (config_->psk_reporter_tcpip () ? QAbstractSocket::TcpSocket : QAbstractSocket::UdpSocket))) - { - // we need to create the appropriate socket - if (socket_ - && QAbstractSocket::UnconnectedState != socket_->state () - && QAbstractSocket::ClosingState != socket_->state ()) - { - LOG_LOG_LOCATION (logger_, trace, "create/recreate socket"); - // handle re-opening asynchronously - auto connection = QSharedPointer<QMetaObject::Connection>::create (); - *connection = connect (socket_.data (), &QAbstractSocket::disconnected, [this, connection] () { - disconnect (*connection); - check_connection (); - }); - // close gracefully - send_report (true); - socket_->close (); - } - else - { - reconnect (); - } - } - } - - void handle_socket_error (QAbstractSocket::SocketError e) - { - LOG_LOG_LOCATION (logger_, warning, "socket error: " << socket_->errorString ()); - switch (e) - { - case QAbstractSocket::RemoteHostClosedError: - socket_->disconnectFromHost (); - break; - - case QAbstractSocket::TemporaryError: - break; - - default: - spots_.clear (); - Q_EMIT self_->errorOccurred (socket_->errorString ()); - break; - } - } - - void reconnect () - { - // Using deleteLater for the deleter as we may eventually - // be called from the disconnected handler above. - if (config_->psk_reporter_tcpip ()) - { - LOG_LOG_LOCATION (logger_, trace, "create TCP/IP socket"); - socket_.reset (new QTcpSocket, &QObject::deleteLater); - send_descriptors_ = 1; - send_receiver_data_ = 1; - } - else - { - LOG_LOG_LOCATION (logger_, trace, "create UDP/IP socket"); - socket_.reset (new QUdpSocket, &QObject::deleteLater); - send_descriptors_ = 3; - send_receiver_data_ = 3; - } - -#if QT_VERSION >= QT_VERSION_CHECK(5, 15, 0) - connect (socket_.get (), &QAbstractSocket::errorOccurred, this, &PSKReporter::impl::handle_socket_error); -#elif QT_VERSION >= QT_VERSION_CHECK(5, 7, 0) - connect (socket_.data (), QOverload<QAbstractSocket::SocketError>::of (&QAbstractSocket::error), this, &PSKReporter::impl::handle_socket_error); -#else - connect (socket_.data (), static_cast<void (QAbstractSocket::*) (QAbstractSocket::SocketError)> (&QAbstractSocket::error), this, &PSKReporter::impl::handle_socket_error); -#endif - - // use this for pseudo connection with UDP, allows us to use - // QIODevice::write() instead of QUDPSocket::writeDatagram() - socket_->connectToHost (HOST, SERVICE_PORT, QAbstractSocket::WriteOnly); - LOG_LOG_LOCATION (logger_, debug, "remote host: " << HOST << " port: " << SERVICE_PORT); - - if (!report_timer_.isActive ()) - { - report_timer_.start (MIN_SEND_INTERVAL+1 * 1000); // we add 1 to give some more randomization - } - if (!descriptor_timer_.isActive ()) - { - descriptor_timer_.start (1 * 60 * 60 * 1000); // hourly - } - } - - void stop () - { - if (socket_) - { - LOG_LOG_LOCATION (logger_, trace, "disconnecting"); - socket_->disconnectFromHost (); - } - descriptor_timer_.stop (); - report_timer_.stop (); - } - - void send_report (bool send_residue = false); - void build_preamble (QDataStream&); - void eclipse_load(QString filename); - bool eclipse_active(QDateTime now = QDateTime::currentDateTime()); - - bool flushing () - { - bool flush = FLUSH_INTERVAL && !(++flush_counter_ % FLUSH_INTERVAL); - LOG_LOG_LOCATION (logger_, trace, "flush: " << flush); - return flush; - } - - QString getStringFromQDateTime(const QString& dateTimeString, const QString& format) - { - QDateTime dateTime = QDateTime::fromString(dateTimeString, format); - return dateTime.toString(); - } - - QList<QDateTime> eclipseDates; - - logger_type mutable logger_; - PSKReporter * self_; - Configuration const * config_; - QSharedPointer<QAbstractSocket> socket_; - int dns_lookup_id_; - QByteArray payload_; - quint32 sequence_number_; - int send_descriptors_; - - // Currently PSK Reporter requires that a receiver data set is sent - // in every data flow. This memeber variable can be used to only - // send that information at session start (3 times for UDP), when it - // changes (3 times for UDP), or once per hour (3 times) if using - // UDP. Uncomment the relevant code to enable that fuctionality. - int send_receiver_data_; - - unsigned flush_counter_; - quint32 observation_id_; - QString rx_call_; - QString rx_grid_; - QString rx_ant_; - QString rigInformation_; - QString prog_id_; - QByteArray tx_data_; - QByteArray tx_residue_; - struct Spot - { - bool operator == (Spot const& rhs) - { - return - call_ == rhs.call_ - && grid_ == rhs.grid_ - && mode_ == rhs.mode_ - && std::abs (Radio::FrequencyDelta (freq_ - rhs.freq_)) < 50; - } - - QString call_; - QString grid_; - int snr_; - Radio::Frequency freq_; - QString mode_; - QDateTime time_; - }; - QQueue<Spot> spots_; - QTimer report_timer_; - QTimer descriptor_timer_; -}; - -#include "PSKReporter.moc" - -namespace -{ - void writeUtfString (QDataStream& out, QString const& s) - { - auto const& utf = s.toUtf8 ().left (254); - out << quint8 (utf.size ()); - out.writeRawData (utf, utf.size ()); - } - - int num_pad_bytes (int len) - { - return ALIGNMENT_PADDING ? (4 - len % 4) % 4 : 0; - } - - void set_length (QDataStream& out, QByteArray& b) - { - // pad with nulls modulo 4 - auto pad_len = num_pad_bytes (b.size ()); - out.writeRawData (QByteArray {pad_len, '\0'}.constData (), pad_len); - auto pos = out.device ()->pos (); - out.device ()->seek (sizeof (quint16)); - // insert length - out << static_cast<quint16> (b.size ()); - out.device ()->seek (pos); - } -} - -bool PSKReporter::impl::eclipse_active(QDateTime timeutc) -{ -#ifdef DEBUGECLIPSE - std::ofstream mylog("/temp/eclipse.log", std::ios_base::app); -#endif - QDateTime dateNow = QDateTime::currentDateTimeUtc(); - for (int i=0; i< eclipseDates.size(); ++i) - { - QDateTime check = eclipseDates.at(i); // already in UTC time - // +- 6 hour window - qint64 secondsDiff = qAbs(check.secsTo(dateNow)); - if (secondsDiff <= 3600*6) // 6 hour check - { -#ifdef DEBUGECLIPSE - mylog << dateNow.toString(Qt::ISODate) << " Eclipse! " << "secondsDiff=" << secondsDiff << std::endl; -#endif - return true; - } - } -#ifdef DEBUGECLIPSE - mylog << timeutc.toString("yyyy-MM-dd HH:mm:ss") << " no eclipse" << "\n"; -#endif - return false; -} - -void PSKReporter::impl::eclipse_load(QString eclipse_file) -{ - std::ifstream fs(qPrintable(eclipse_file)); - std::string mydate,mytime,myline; -#ifdef DEBUGECLIPSE - std::ofstream mylog("c:/temp/eclipse.log"); - mylog << "eclipse_file=" << eclipse_file << std::endl; -#endif - if (fs.is_open()) - { - while(!fs.eof()) - { - std::getline(fs, myline); - if (myline[0] != '#' && myline.length() > 2) // make sure to skip blank lines - { - //QString format = "yyyy-MM-dd hh:mm:ss"; - QDateTime qdate = QDateTime::fromString(QString::fromStdString(myline), Qt::ISODate); - QDateTime now = QDateTime::currentDateTimeUtc(); - // only add the date if we can cover the whole 12 hours - //if (now < qdate.toUTC().addSecs(-3600*6)) - eclipseDates.append(qdate); -#ifdef DEBUGECLIPSE - //else - // mylog << "not adding " << myline << std::endl; -#endif - - } -#ifdef DEBUGECLIPSE - mylog << myline << std::endl; -#endif - } - } -#ifdef DEBUGECLIPSE - if (eclipse_active(QDateTime::currentDateTime().toUTC())) mylog << "Eclipse is active" << std::endl; - else mylog << "Eclipse is not active" << std::endl; -#endif -} - -void PSKReporter::impl::build_preamble (QDataStream& message) -{ - // Message Header - message - << quint16 (10u) // Version Number - << quint16 (0u) // Length (place-holder filled in later) - << quint32 (0u) // Export Time (place-holder filled in later) - << ++sequence_number_ // Sequence Number - << observation_id_; // Observation Domain ID - LOG_LOG_LOCATION (logger_, trace, "#: " << sequence_number_); - - if (send_descriptors_) - { - --send_descriptors_; - { - // Sender Information descriptor - QByteArray descriptor; - QDataStream out {&descriptor, QIODevice::WriteOnly}; - out - << quint16 (2u) // Template Set ID - << quint16 (0u) // Length (place-holder) - << quint16 (0x50e3) // Link ID - << quint16 (7u) // Field Count - << quint16 (0x8000 + 1u) // Option 1 Information Element ID (senderCallsign) - << quint16 (0xffff) // Option 1 Field Length (variable) - << quint32 (30351u) // Option 1 Enterprise Number - << quint16 (0x8000 + 5u) // Option 2 Information Element ID (frequency) - << quint16 (5u) // Option 2 Field Length - << quint32 (30351u) // Option 2 Enterprise Number - << quint16 (0x8000 + 6u) // Option 3 Information Element ID (sNR) - << quint16 (1u) // Option 3 Field Length - << quint32 (30351u) // Option 3 Enterprise Number - << quint16 (0x8000 + 10u) // Option 4 Information Element ID (mode) - << quint16 (0xffff) // Option 4 Field Length (variable) - << quint32 (30351u) // Option 4 Enterprise Number - << quint16 (0x8000 + 3u) // Option 5 Information Element ID (senderLocator) - << quint16 (0xffff) // Option 5 Field Length (variable) - << quint32 (30351u) // Option 5 Enterprise Number - << quint16 (0x8000 + 11u) // Option 6 Information Element ID (informationSource) - << quint16 (1u) // Option 6 Field Length - << quint32 (30351u) // Option 6 Enterprise Number - << quint16 (150u) // Option 7 Information Element ID (dateTimeSeconds) - << quint16 (4u); // Option 7 Field Length - // insert Length and move to payload - set_length (out, descriptor); - message.writeRawData (descriptor.constData (), descriptor.size ()); - } - { - // Receiver Information descriptor - QByteArray descriptor; - QDataStream out {&descriptor, QIODevice::WriteOnly}; - out - << quint16 (3u) // Options Template Set ID - << quint16 (0u) // Length (place-holder) - << quint16 (0x50e2) // Link ID - << quint16 (5u) // Field Count - << quint16 (0u) // Scope Field Count - << quint16 (0x8000 + 2u) // Option 1 Information Element ID (receiverCallsign) - << quint16 (0xffff) // Option 1 Field Length (variable) - << quint32 (30351u) // Option 1 Enterprise Number - << quint16 (0x8000 + 4u) // Option 2 Information Element ID (receiverLocator) - << quint16 (0xffff) // Option 2 Field Length (variable) - << quint32 (30351u) // Option 2 Enterprise Number - << quint16 (0x8000 + 8u) // Option 3 Information Element ID (decodingSoftware) - << quint16 (0xffff) // Option 3 Field Length (variable) - << quint32 (30351u) // Option 3 Enterprise Number - << quint16 (0x8000 + 9u) // Option 4 Information Element ID (antennaInformation) - << quint16 (0xffff) // Option 4 Field Length (variable) - << quint32 (30351u) // Option 5 Enterprise Number - << quint16 (0x8000 + 13u)// Option 5 Information Element ID (rigInformation) - << quint16 (0xffff) // Option 5 Field Length (variable) - << quint32 (30351u); // Option 4 Enterprise Number - // insert Length - set_length (out, descriptor); - message.writeRawData (descriptor.constData (), descriptor.size ()); - LOG_LOG_LOCATION (logger_, debug, "sent descriptors"); - } - } - - // if (send_receiver_data_) - { - // --send_receiver_data_; - - // Receiver information - QByteArray data; - QDataStream out {&data, QIODevice::WriteOnly}; - - // Set Header - out - << quint16 (0x50e2) // Template ID - << quint16 (0u); // Length (place-holder) - - // Set data - writeUtfString (out, rx_call_); - writeUtfString (out, rx_grid_); - writeUtfString (out, prog_id_); - writeUtfString (out, rx_ant_); - writeUtfString (out, rigInformation_); - - // insert Length and move to payload - set_length (out, data); - message.writeRawData (data.constData (), data.size ()); - LOG_LOG_LOCATION (logger_, debug, "sent local information"); - } -} - -void PSKReporter::impl::send_report (bool send_residue) -{ - LOG_LOG_LOCATION (logger_, trace, "sending residue: " << send_residue); - if (QAbstractSocket::ConnectedState != socket_->state ()) return; - - QDataStream message {&payload_, QIODevice::WriteOnly | QIODevice::Append}; - QDataStream tx_out {&tx_data_, QIODevice::WriteOnly | QIODevice::Append}; - - if (!payload_.size ()) - { - // Build header, optional descriptors, and receiver information - build_preamble (message); - } - - auto flush = flushing () || send_residue; - while (spots_.size () || flush) - { - if (!payload_.size ()) - { - // Build header, optional descriptors, and receiver information - build_preamble (message); - } - - if (!tx_data_.size () && (spots_.size () || tx_residue_.size ())) - { - // Set Header - tx_out - << quint16 (0x50e3) // Template ID - << quint16 (0u); // Length (place-holder) - } - - // insert any residue - if (tx_residue_.size ()) - { - tx_out.writeRawData (tx_residue_.constData (), tx_residue_.size ()); - LOG_LOG_LOCATION (logger_, debug, "sent residue"); - tx_residue_.clear (); - } - - LOG_LOG_LOCATION (logger_, debug, "pending spots: " << spots_.size ()); - while (spots_.size () || flush) - { - auto tx_data_size = tx_data_.size (); - if (spots_.size ()) - { - auto const& spot = spots_.dequeue (); - - // Sender information - writeUtfString (tx_out, spot.call_); - uint8_t data[5]; - long long int i64 = spot.freq_; - data[0] = ( i64 & 0xff); - data[1] = ((i64 >> 8) & 0xff); - data[2] = ((i64 >> 16) & 0xff); - data[3] = ((i64 >> 24) & 0xff); - data[4] = ((i64 >> 32) & 0xff); - tx_out // BigEndian - << static_cast<uint8_t> (data[4]) - << static_cast<uint8_t> (data[3]) - << static_cast<uint8_t> (data[2]) - << static_cast<uint8_t> (data[1]) - << static_cast<uint8_t> (data[0]) - << static_cast<qint8> (spot.snr_); - writeUtfString (tx_out, spot.mode_); - writeUtfString (tx_out, spot.grid_); - tx_out - << quint8 (1u) // REPORTER_SOURCE_AUTOMATIC - << static_cast<quint32> ( -#if QT_VERSION >= QT_VERSION_CHECK(5, 8, 0) - spot.time_.toSecsSinceEpoch () -#else - spot.time_.toMSecsSinceEpoch () / 1000 -#endif - ); - } - - auto len = payload_.size () + tx_data_.size (); - len += num_pad_bytes (tx_data_.size ()); - len += num_pad_bytes (len); - if (len > MAX_PAYLOAD_LENGTH // our upper datagram size limit - || (!spots_.size () && len > MIN_PAYLOAD_LENGTH) // spots drained and above lower datagram size limit - || (flush && !spots_.size ())) // send what we have, possibly no spots - { - if (tx_data_.size ()) - { - if (len <= MAX_PAYLOAD_LENGTH) - { - tx_data_size = tx_data_.size (); - } - QByteArray tx {tx_data_.left (tx_data_size)}; - QDataStream out {&tx, QIODevice::WriteOnly | QIODevice::Append}; - // insert Length - set_length (out, tx); - message.writeRawData (tx.constData (), tx.size ()); - } - - // insert Length and Export Time - set_length (message, payload_); - message.device ()->seek (2 * sizeof (quint16)); - message << static_cast<quint32> ( -#if QT_VERSION >= QT_VERSION_CHECK(5, 8, 0) - QDateTime::currentDateTime ().toSecsSinceEpoch () -#else - QDateTime::currentDateTime ().toMSecsSinceEpoch () / 1000 -#endif - ); - - // Send data to PSK Reporter site - socket_->write (payload_); // TODO: handle errors - LOG_LOG_LOCATION (logger_, debug, "sent spots"); - flush = false; // break loop - message.device ()->seek (0u); - payload_.clear (); // Fresh message - // Save unsent spots - tx_residue_ = tx_data_.right (tx_data_.size () - tx_data_size); - tx_out.device ()->seek (0u); - tx_data_.clear (); - break; - } - } - LOG_LOG_LOCATION (logger_, debug, "remaining spots: " << spots_.size ()); - } -} - -PSKReporter::PSKReporter (Configuration const * config, QString const& program_info) - : m_ {this, config, program_info} -{ - LOG_LOG_LOCATION (m_->logger_, trace, "Started for: " << program_info); -} - -PSKReporter::~PSKReporter () -{ - // m_->send_report (true); // send any pending spots - LOG_LOG_LOCATION (m_->logger_, trace, "Ended"); -} - -void PSKReporter::reconnect () -{ - LOG_LOG_LOCATION (m_->logger_, trace, ""); - m_->reconnect (); -} - -bool PSKReporter::eclipse_active(QDateTime now) -{ - return m_->eclipse_active(now); -} - -void PSKReporter::setLocalStation (QString const& call, QString const& gridSquare, QString const& antenna, QString const& rigInformation) -{ - LOG_LOG_LOCATION (m_->logger_, trace, "call: " << call << " grid: " << gridSquare << " ant: " << antenna); - m_->check_connection (); - if (call != m_->rx_call_ || gridSquare != m_->rx_grid_ || antenna != m_->rx_ant_) - { - LOG_LOG_LOCATION (m_->logger_, trace, "updating information"); - m_->send_receiver_data_ = m_->socket_ - && QAbstractSocket::UdpSocket == m_->socket_->socketType () ? 3 : 1; - m_->rx_call_ = call; - m_->rx_grid_ = gridSquare; - m_->rx_ant_ = antenna; - m_->rigInformation_ = rigInformation; - } -} - -bool PSKReporter::addRemoteStation (QString const& call, QString const& grid, Radio::Frequency freq - , QString const& mode, int snr) -{ - LOG_LOG_LOCATION (m_->logger_, trace, "call: " << call << " grid: " << grid << " freq: " << freq << " mode: " << mode << " snr: " << snr); - m_->check_connection (); - if (m_->socket_ && m_->socket_->isValid ()) - { - if (QAbstractSocket::UnconnectedState == m_->socket_->state ()) - { - reconnect (); - } - // remove any earlier spots of this call to reduce pskreporter load -#ifdef DEBUGPSK - static std::fstream fs; - if (!fs.is_open()) fs.open("/temp/psk.log", std::fstream::in | std::fstream::out | std::fstream::app); -#endif - added++; - - QDateTime qdateNow = QDateTime::currentDateTime().toUTC(); - // we allow all spots through +/- 6 hours around an eclipse for the HamSCI group - if (!spot_cache.contains(call) || freq > 49000000 || eclipse_active(qdateNow)) // then it's a new spot - { - m_->spots_.enqueue ({call, grid, snr, freq, mode, QDateTime::currentDateTimeUtc ()}); - spot_cache.insert(call, time(NULL)); -#ifdef DEBUGPSK - if (fs.is_open()) fs << "Adding " << call << " freq=" << freq << " " << spot_cache[call] << " count=" << m_->spots_.count() << std::endl; -#endif - } - else if (time(NULL) - spot_cache[call] > CACHE_TIMEOUT) // then the cache has expired - { - m_->spots_.enqueue ({call, grid, snr, freq, mode, QDateTime::currentDateTimeUtc ()}); -#ifdef DEBUGPSK - if (fs.is_open()) fs << "Adding # " << call << spot_cache[call] << " count=" << m_->spots_.count() << std::endl; -#endif - spot_cache[call] = time(NULL); - } - else - { - removed++; -#ifdef DEBUGPSK - if (fs.is_open()) fs << "Removing " << call << " " << time(NULL) << " reduction=" << removed/(double)added*100 << "%" << std::endl; -#endif - } - // remove cached items over 10 minutes old to save a little memory - QMapIterator<QString, time_t> i(spot_cache); - time_t tmptime = time(NULL); - while(i.hasNext()) { - i.next(); - if (tmptime - i.value() > 600) spot_cache.remove(i.key()); - } - return true; - } - return false; -} - -void PSKReporter::sendReport (bool last) -{ - LOG_LOG_LOCATION (m_->logger_, trace, "last: " << last); - m_->check_connection (); - if (m_->socket_ && QAbstractSocket::ConnectedState == m_->socket_->state ()) - { - m_->send_report (true); - } - if (last) - { - m_->stop (); - } -} +#include "PSKReporter.hpp"
+
+// Interface for posting spots to PSK Reporter web site
+// Implemented by Edson Pereira PY2SDR
+// Updated by Bill Somerville, G4WJS
+//
+// Reports will be sent in batch mode every 5 minutes.
+
+#include <fstream>
+#include <iostream>
+#include <cmath>
+#include <QObject>
+#include <QString>
+#include <QDateTime>
+#include <QSharedPointer>
+#include <QUdpSocket>
+#include <QTcpSocket>
+#include <QHostInfo>
+#include <QQueue>
+#include <QByteArray>
+#include <QDataStream>
+#include <QTimer>
+#include <QDir>
+#if QT_VERSION >= QT_VERSION_CHECK(5, 15, 0)
+#include <QRandomGenerator>
+#endif
+
+#include "Logger.hpp"
+#include "Configuration.hpp"
+#include "pimpl_impl.hpp"
+
+
+#include "moc_PSKReporter.cpp"
+
+//#define DEBUGECLIPSE 0
+
+namespace
+{
+ QLatin1String HOST {"report.pskreporter.info"};
+ // QLatin1String HOST {"127.0.0.1"};
+ quint16 SERVICE_PORT {4739};
+ // quint16 SERVICE_PORT {14739};
+ int MIN_SEND_INTERVAL {120}; // in seconds
+ int FLUSH_INTERVAL {MIN_SEND_INTERVAL + 5}; // in send intervals
+ bool ALIGNMENT_PADDING {true};
+ int MIN_PAYLOAD_LENGTH {508};
+ int MAX_PAYLOAD_LENGTH {10000};
+ int CACHE_TIMEOUT {300}; // default to 5 minutes for repeating spots
+ QMap<QString, time_t> spot_cache;
+}
+
+static int added;
+static int removed;
+
+class PSKReporter::impl final
+ : public QObject
+{
+ Q_OBJECT
+
+ using logger_type = boost::log::sources::severity_channel_logger_mt<boost::log::trivial::severity_level>;
+
+public:
+ impl (PSKReporter * self, Configuration const * config, QString const& program_info)
+ : logger_ {boost::log::keywords::channel = "PSKRPRT"}
+ , self_ {self}
+ , config_ {config}
+ , sequence_number_ {0u}
+ , send_descriptors_ {0}
+ , send_receiver_data_ {0}
+ , flush_counter_ {0u}
+ , prog_id_ {program_info}
+ {
+#if QT_VERSION < QT_VERSION_CHECK(5, 15, 0)
+ observation_id_ = qrand();
+#else
+ observation_id_ = QRandomGenerator::global ()->generate ();
+#endif
+
+ // This timer sets the interval to check for spots to send.
+ connect (&report_timer_, &QTimer::timeout, [this] () {send_report ();});
+
+ // This timer repeats the sending of IPFIX templates and receiver
+ // information if we are using UDP, in case server has been
+ // restarted ans lost cached information.
+ connect (&descriptor_timer_, &QTimer::timeout, [this] () {
+ if (socket_
+ && QAbstractSocket::UdpSocket == socket_->socketType ())
+ {
+ LOG_LOG_LOCATION (logger_, trace, "enable descriptor resend");
+ // send templates again
+ send_descriptors_ = 3; // three times
+ // send receiver data set again
+ send_receiver_data_ = 3; // three times
+ }
+ });
+ eclipse_load(config->data_dir ().absoluteFilePath ("eclipse.txt"));
+ }
+
+ void check_connection ()
+ {
+ if (!socket_
+ || QAbstractSocket::UnconnectedState == socket_->state ()
+ || (socket_->socketType () != (config_->psk_reporter_tcpip () ? QAbstractSocket::TcpSocket : QAbstractSocket::UdpSocket)))
+ {
+ // we need to create the appropriate socket
+ if (socket_
+ && QAbstractSocket::UnconnectedState != socket_->state ()
+ && QAbstractSocket::ClosingState != socket_->state ())
+ {
+ LOG_LOG_LOCATION (logger_, trace, "create/recreate socket");
+ // handle re-opening asynchronously
+ auto connection = QSharedPointer<QMetaObject::Connection>::create ();
+ *connection = connect (socket_.data (), &QAbstractSocket::disconnected, [this, connection] () {
+ disconnect (*connection);
+ check_connection ();
+ });
+ // close gracefully
+ send_report (true);
+ socket_->close ();
+ }
+ else
+ {
+ reconnect ();
+ }
+ }
+ }
+
+ void handle_socket_error (QAbstractSocket::SocketError e)
+ {
+ LOG_LOG_LOCATION (logger_, warning, "socket error: " << socket_->errorString ());
+ switch (e)
+ {
+ case QAbstractSocket::RemoteHostClosedError:
+ socket_->disconnectFromHost ();
+ break;
+
+ case QAbstractSocket::TemporaryError:
+ break;
+
+ default:
+ spots_.clear ();
+ Q_EMIT self_->errorOccurred (socket_->errorString ());
+ break;
+ }
+ }
+
+ void reconnect ()
+ {
+ // Using deleteLater for the deleter as we may eventually
+ // be called from the disconnected handler above.
+ if (config_->psk_reporter_tcpip ())
+ {
+ LOG_LOG_LOCATION (logger_, trace, "create TCP/IP socket");
+ socket_.reset (new QTcpSocket, &QObject::deleteLater);
+ send_descriptors_ = 1;
+ send_receiver_data_ = 1;
+ }
+ else
+ {
+ LOG_LOG_LOCATION (logger_, trace, "create UDP/IP socket");
+ socket_.reset (new QUdpSocket, &QObject::deleteLater);
+ send_descriptors_ = 3;
+ send_receiver_data_ = 3;
+ }
+
+#if QT_VERSION >= QT_VERSION_CHECK(5, 15, 0)
+ connect (socket_.get (), &QAbstractSocket::errorOccurred, this, &PSKReporter::impl::handle_socket_error);
+#elif QT_VERSION >= QT_VERSION_CHECK(5, 7, 0)
+ connect (socket_.data (), QOverload<QAbstractSocket::SocketError>::of (&QAbstractSocket::error), this, &PSKReporter::impl::handle_socket_error);
+#else
+ connect (socket_.data (), static_cast<void (QAbstractSocket::*) (QAbstractSocket::SocketError)> (&QAbstractSocket::error), this, &PSKReporter::impl::handle_socket_error);
+#endif
+
+ // use this for pseudo connection with UDP, allows us to use
+ // QIODevice::write() instead of QUDPSocket::writeDatagram()
+ socket_->connectToHost (HOST, SERVICE_PORT, QAbstractSocket::WriteOnly);
+ LOG_LOG_LOCATION (logger_, debug, "remote host: " << HOST << " port: " << SERVICE_PORT);
+
+ if (!report_timer_.isActive ())
+ {
+ report_timer_.start (MIN_SEND_INTERVAL+1 * 1000); // we add 1 to give some more randomization
+ }
+ if (!descriptor_timer_.isActive ())
+ {
+ descriptor_timer_.start (1 * 60 * 60 * 1000); // hourly
+ }
+ }
+
+ void stop ()
+ {
+ if (socket_)
+ {
+ LOG_LOG_LOCATION (logger_, trace, "disconnecting");
+ socket_->disconnectFromHost ();
+ }
+ descriptor_timer_.stop ();
+ report_timer_.stop ();
+ }
+
+ void send_report (bool send_residue = false);
+ void build_preamble (QDataStream&);
+ void eclipse_load(QString filename);
+ bool eclipse_active(QDateTime now = QDateTime::currentDateTime());
+
+ bool flushing ()
+ {
+ bool flush = FLUSH_INTERVAL && !(++flush_counter_ % FLUSH_INTERVAL);
+ LOG_LOG_LOCATION (logger_, trace, "flush: " << flush);
+ return flush;
+ }
+
+ QString getStringFromQDateTime(const QString& dateTimeString, const QString& format)
+ {
+ QDateTime dateTime = QDateTime::fromString(dateTimeString, format);
+ return dateTime.toString();
+ }
+
+ QList<QDateTime> eclipseDates;
+
+ logger_type mutable logger_;
+ PSKReporter * self_;
+ Configuration const * config_;
+ QSharedPointer<QAbstractSocket> socket_;
+ int dns_lookup_id_;
+ QByteArray payload_;
+ quint32 sequence_number_;
+ int send_descriptors_;
+
+ // Currently PSK Reporter requires that a receiver data set is sent
+ // in every data flow. This memeber variable can be used to only
+ // send that information at session start (3 times for UDP), when it
+ // changes (3 times for UDP), or once per hour (3 times) if using
+ // UDP. Uncomment the relevant code to enable that fuctionality.
+ int send_receiver_data_;
+
+ unsigned flush_counter_;
+ quint32 observation_id_;
+ QString rx_call_;
+ QString rx_grid_;
+ QString rx_ant_;
+ QString rigInformation_;
+ QString prog_id_;
+ QByteArray tx_data_;
+ QByteArray tx_residue_;
+ struct Spot
+ {
+ bool operator == (Spot const& rhs)
+ {
+ return
+ call_ == rhs.call_
+ && grid_ == rhs.grid_
+ && mode_ == rhs.mode_
+ && std::abs (Radio::FrequencyDelta (freq_ - rhs.freq_)) < 50;
+ }
+
+ QString call_;
+ QString grid_;
+ int snr_;
+ Radio::Frequency freq_;
+ QString mode_;
+ QDateTime time_;
+ };
+ QQueue<Spot> spots_;
+ QTimer report_timer_;
+ QTimer descriptor_timer_;
+};
+
+#include "PSKReporter.moc"
+
+namespace
+{
+ void writeUtfString (QDataStream& out, QString const& s)
+ {
+ auto const& utf = s.toUtf8 ().left (254);
+ out << quint8 (utf.size ());
+ out.writeRawData (utf, utf.size ());
+ }
+
+ int num_pad_bytes (int len)
+ {
+ return ALIGNMENT_PADDING ? (4 - len % 4) % 4 : 0;
+ }
+
+ void set_length (QDataStream& out, QByteArray& b)
+ {
+ // pad with nulls modulo 4
+ auto pad_len = num_pad_bytes (b.size ());
+ out.writeRawData (QByteArray {pad_len, '\0'}.constData (), pad_len);
+ auto pos = out.device ()->pos ();
+ out.device ()->seek (sizeof (quint16));
+ // insert length
+ out << static_cast<quint16> (b.size ());
+ out.device ()->seek (pos);
+ }
+}
+
+bool PSKReporter::impl::eclipse_active(QDateTime timeutc)
+{
+ qDebug() << timeutc;
+#ifdef DEBUGECLIPSE
+ std::ofstream mylog("/temp/eclipse.log", std::ios_base::app);
+#endif
+ QDateTime dateNow = QDateTime::currentDateTimeUtc();
+ for (int i=0; i< eclipseDates.size(); ++i)
+ {
+ QDateTime check = eclipseDates.at(i); // already in UTC time
+ // +- 6 hour window
+ qint64 secondsDiff = qAbs(check.secsTo(dateNow));
+ if (secondsDiff <= 3600*6) // 6 hour check
+ {
+#ifdef DEBUGECLIPSE
+ mylog << dateNow.toString(Qt::ISODate) << " Eclipse! " << "secondsDiff=" << secondsDiff << std::endl;
+#endif
+ return true;
+ }
+ }
+#ifdef DEBUGECLIPSE
+ mylog << timeutc.toString("yyyy-MM-dd HH:mm:ss") << " no eclipse" << "\n";
+#endif
+ return false;
+}
+
+void PSKReporter::impl::eclipse_load(QString eclipse_file)
+{
+ std::ifstream fs(qPrintable(eclipse_file));
+ std::string mydate,mytime,myline;
+#ifdef DEBUGECLIPSE
+ std::ofstream mylog("c:/temp/eclipse.log");
+ mylog << "eclipse_file=" << eclipse_file << std::endl;
+#endif
+ if (fs.is_open())
+ {
+ while(!fs.eof())
+ {
+ std::getline(fs, myline);
+ if (myline[0] != '#' && myline.length() > 2) // make sure to skip blank lines
+ {
+ //QString format = "yyyy-MM-dd hh:mm:ss";
+ QDateTime qdate = QDateTime::fromString(QString::fromStdString(myline), Qt::ISODate);
+ QDateTime now = QDateTime::currentDateTimeUtc();
+ // only add the date if we can cover the whole 12 hours
+ //if (now < qdate.toUTC().addSecs(-3600*6))
+ eclipseDates.append(qdate);
+#ifdef DEBUGECLIPSE
+ //else
+ // mylog << "not adding " << myline << std::endl;
+#endif
+
+ }
+#ifdef DEBUGECLIPSE
+ mylog << myline << std::endl;
+#endif
+ }
+ }
+#ifdef DEBUGECLIPSE
+ if (eclipse_active(QDateTime::currentDateTime().toUTC())) mylog << "Eclipse is active" << std::endl;
+ else mylog << "Eclipse is not active" << std::endl;
+#endif
+}
+
+void PSKReporter::impl::build_preamble (QDataStream& message)
+{
+ // Message Header
+ message
+ << quint16 (10u) // Version Number
+ << quint16 (0u) // Length (place-holder filled in later)
+ << quint32 (0u) // Export Time (place-holder filled in later)
+ << ++sequence_number_ // Sequence Number
+ << observation_id_; // Observation Domain ID
+ LOG_LOG_LOCATION (logger_, trace, "#: " << sequence_number_);
+
+ if (send_descriptors_)
+ {
+ --send_descriptors_;
+ {
+ // Sender Information descriptor
+ QByteArray descriptor;
+ QDataStream out {&descriptor, QIODevice::WriteOnly};
+ out
+ << quint16 (2u) // Template Set ID
+ << quint16 (0u) // Length (place-holder)
+ << quint16 (0x50e3) // Link ID
+ << quint16 (7u) // Field Count
+ << quint16 (0x8000 + 1u) // Option 1 Information Element ID (senderCallsign)
+ << quint16 (0xffff) // Option 1 Field Length (variable)
+ << quint32 (30351u) // Option 1 Enterprise Number
+ << quint16 (0x8000 + 5u) // Option 2 Information Element ID (frequency)
+ << quint16 (5u) // Option 2 Field Length
+ << quint32 (30351u) // Option 2 Enterprise Number
+ << quint16 (0x8000 + 6u) // Option 3 Information Element ID (sNR)
+ << quint16 (1u) // Option 3 Field Length
+ << quint32 (30351u) // Option 3 Enterprise Number
+ << quint16 (0x8000 + 10u) // Option 4 Information Element ID (mode)
+ << quint16 (0xffff) // Option 4 Field Length (variable)
+ << quint32 (30351u) // Option 4 Enterprise Number
+ << quint16 (0x8000 + 3u) // Option 5 Information Element ID (senderLocator)
+ << quint16 (0xffff) // Option 5 Field Length (variable)
+ << quint32 (30351u) // Option 5 Enterprise Number
+ << quint16 (0x8000 + 11u) // Option 6 Information Element ID (informationSource)
+ << quint16 (1u) // Option 6 Field Length
+ << quint32 (30351u) // Option 6 Enterprise Number
+ << quint16 (150u) // Option 7 Information Element ID (dateTimeSeconds)
+ << quint16 (4u); // Option 7 Field Length
+ // insert Length and move to payload
+ set_length (out, descriptor);
+ message.writeRawData (descriptor.constData (), descriptor.size ());
+ }
+ {
+ // Receiver Information descriptor
+ QByteArray descriptor;
+ QDataStream out {&descriptor, QIODevice::WriteOnly};
+ out
+ << quint16 (3u) // Options Template Set ID
+ << quint16 (0u) // Length (place-holder)
+ << quint16 (0x50e2) // Link ID
+ << quint16 (5u) // Field Count
+ << quint16 (0u) // Scope Field Count
+ << quint16 (0x8000 + 2u) // Option 1 Information Element ID (receiverCallsign)
+ << quint16 (0xffff) // Option 1 Field Length (variable)
+ << quint32 (30351u) // Option 1 Enterprise Number
+ << quint16 (0x8000 + 4u) // Option 2 Information Element ID (receiverLocator)
+ << quint16 (0xffff) // Option 2 Field Length (variable)
+ << quint32 (30351u) // Option 2 Enterprise Number
+ << quint16 (0x8000 + 8u) // Option 3 Information Element ID (decodingSoftware)
+ << quint16 (0xffff) // Option 3 Field Length (variable)
+ << quint32 (30351u) // Option 3 Enterprise Number
+ << quint16 (0x8000 + 9u) // Option 4 Information Element ID (antennaInformation)
+ << quint16 (0xffff) // Option 4 Field Length (variable)
+ << quint32 (30351u) // Option 5 Enterprise Number
+ << quint16 (0x8000 + 13u)// Option 5 Information Element ID (rigInformation)
+ << quint16 (0xffff) // Option 5 Field Length (variable)
+ << quint32 (30351u); // Option 4 Enterprise Number
+ // insert Length
+ set_length (out, descriptor);
+ message.writeRawData (descriptor.constData (), descriptor.size ());
+ LOG_LOG_LOCATION (logger_, debug, "sent descriptors");
+ }
+ }
+
+ // if (send_receiver_data_)
+ {
+ // --send_receiver_data_;
+
+ // Receiver information
+ QByteArray data;
+ QDataStream out {&data, QIODevice::WriteOnly};
+
+ // Set Header
+ out
+ << quint16 (0x50e2) // Template ID
+ << quint16 (0u); // Length (place-holder)
+
+ // Set data
+ writeUtfString (out, rx_call_);
+ writeUtfString (out, rx_grid_);
+ writeUtfString (out, prog_id_);
+ writeUtfString (out, rx_ant_);
+ writeUtfString (out, rigInformation_);
+
+ // insert Length and move to payload
+ set_length (out, data);
+ message.writeRawData (data.constData (), data.size ());
+ LOG_LOG_LOCATION (logger_, debug, "sent local information");
+ }
+}
+
+void PSKReporter::impl::send_report (bool send_residue)
+{
+ LOG_LOG_LOCATION (logger_, trace, "sending residue: " << send_residue);
+ if (QAbstractSocket::ConnectedState != socket_->state ()) return;
+
+ QDataStream message {&payload_, QIODevice::WriteOnly | QIODevice::Append};
+ QDataStream tx_out {&tx_data_, QIODevice::WriteOnly | QIODevice::Append};
+
+ if (!payload_.size ())
+ {
+ // Build header, optional descriptors, and receiver information
+ build_preamble (message);
+ }
+
+ auto flush = flushing () || send_residue;
+ while (spots_.size () || flush)
+ {
+ if (!payload_.size ())
+ {
+ // Build header, optional descriptors, and receiver information
+ build_preamble (message);
+ }
+
+ if (!tx_data_.size () && (spots_.size () || tx_residue_.size ()))
+ {
+ // Set Header
+ tx_out
+ << quint16 (0x50e3) // Template ID
+ << quint16 (0u); // Length (place-holder)
+ }
+
+ // insert any residue
+ if (tx_residue_.size ())
+ {
+ tx_out.writeRawData (tx_residue_.constData (), tx_residue_.size ());
+ LOG_LOG_LOCATION (logger_, debug, "sent residue");
+ tx_residue_.clear ();
+ }
+
+ LOG_LOG_LOCATION (logger_, debug, "pending spots: " << spots_.size ());
+ while (spots_.size () || flush)
+ {
+ auto tx_data_size = tx_data_.size ();
+ if (spots_.size ())
+ {
+ auto const& spot = spots_.dequeue ();
+
+ // Sender information
+ writeUtfString (tx_out, spot.call_);
+ uint8_t data[5];
+ long long int i64 = spot.freq_;
+ data[0] = ( i64 & 0xff);
+ data[1] = ((i64 >> 8) & 0xff);
+ data[2] = ((i64 >> 16) & 0xff);
+ data[3] = ((i64 >> 24) & 0xff);
+ data[4] = ((i64 >> 32) & 0xff);
+ tx_out // BigEndian
+ << static_cast<uint8_t> (data[4])
+ << static_cast<uint8_t> (data[3])
+ << static_cast<uint8_t> (data[2])
+ << static_cast<uint8_t> (data[1])
+ << static_cast<uint8_t> (data[0])
+ << static_cast<qint8> (spot.snr_);
+ writeUtfString (tx_out, spot.mode_);
+ writeUtfString (tx_out, spot.grid_);
+ tx_out
+ << quint8 (1u) // REPORTER_SOURCE_AUTOMATIC
+ << static_cast<quint32> (
+#if QT_VERSION >= QT_VERSION_CHECK(5, 8, 0)
+ spot.time_.toSecsSinceEpoch ()
+#else
+ spot.time_.toMSecsSinceEpoch () / 1000
+#endif
+ );
+ }
+
+ auto len = payload_.size () + tx_data_.size ();
+ len += num_pad_bytes (tx_data_.size ());
+ len += num_pad_bytes (len);
+ if (len > MAX_PAYLOAD_LENGTH // our upper datagram size limit
+ || (!spots_.size () && len > MIN_PAYLOAD_LENGTH) // spots drained and above lower datagram size limit
+ || (flush && !spots_.size ())) // send what we have, possibly no spots
+ {
+ if (tx_data_.size ())
+ {
+ if (len <= MAX_PAYLOAD_LENGTH)
+ {
+ tx_data_size = tx_data_.size ();
+ }
+ QByteArray tx {tx_data_.left (tx_data_size)};
+ QDataStream out {&tx, QIODevice::WriteOnly | QIODevice::Append};
+ // insert Length
+ set_length (out, tx);
+ message.writeRawData (tx.constData (), tx.size ());
+ }
+
+ // insert Length and Export Time
+ set_length (message, payload_);
+ message.device ()->seek (2 * sizeof (quint16));
+ message << static_cast<quint32> (
+#if QT_VERSION >= QT_VERSION_CHECK(5, 8, 0)
+ QDateTime::currentDateTime ().toSecsSinceEpoch ()
+#else
+ QDateTime::currentDateTime ().toMSecsSinceEpoch () / 1000
+#endif
+ );
+
+ // Send data to PSK Reporter site
+ socket_->write (payload_); // TODO: handle errors
+ LOG_LOG_LOCATION (logger_, debug, "sent spots");
+ flush = false; // break loop
+ message.device ()->seek (0u);
+ payload_.clear (); // Fresh message
+ // Save unsent spots
+ tx_residue_ = tx_data_.right (tx_data_.size () - tx_data_size);
+ tx_out.device ()->seek (0u);
+ tx_data_.clear ();
+ break;
+ }
+ }
+ LOG_LOG_LOCATION (logger_, debug, "remaining spots: " << spots_.size ());
+ }
+}
+
+PSKReporter::PSKReporter (Configuration const * config, QString const& program_info)
+ : m_ {this, config, program_info}
+{
+ LOG_LOG_LOCATION (m_->logger_, trace, "Started for: " << program_info);
+}
+
+PSKReporter::~PSKReporter ()
+{
+ // m_->send_report (true); // send any pending spots
+ LOG_LOG_LOCATION (m_->logger_, trace, "Ended");
+}
+
+void PSKReporter::reconnect ()
+{
+ LOG_LOG_LOCATION (m_->logger_, trace, "");
+ m_->reconnect ();
+}
+
+bool PSKReporter::eclipse_active(QDateTime now)
+{
+ return m_->eclipse_active(now);
+}
+
+void PSKReporter::setLocalStation (QString const& call, QString const& gridSquare, QString const& antenna, QString const& rigInformation)
+{
+ LOG_LOG_LOCATION (m_->logger_, trace, "call: " << call << " grid: " << gridSquare << " ant: " << antenna);
+ m_->check_connection ();
+ if (call != m_->rx_call_ || gridSquare != m_->rx_grid_ || antenna != m_->rx_ant_)
+ {
+ LOG_LOG_LOCATION (m_->logger_, trace, "updating information");
+ m_->send_receiver_data_ = m_->socket_
+ && QAbstractSocket::UdpSocket == m_->socket_->socketType () ? 3 : 1;
+ m_->rx_call_ = call;
+ m_->rx_grid_ = gridSquare;
+ m_->rx_ant_ = antenna;
+ m_->rigInformation_ = rigInformation;
+ }
+}
+
+bool PSKReporter::addRemoteStation (QString const& call, QString const& grid, Radio::Frequency freq
+ , QString const& mode, int snr)
+{
+ LOG_LOG_LOCATION (m_->logger_, trace, "call: " << call << " grid: " << grid << " freq: " << freq << " mode: " << mode << " snr: " << snr);
+ m_->check_connection ();
+ if (m_->socket_ && m_->socket_->isValid ())
+ {
+ if (QAbstractSocket::UnconnectedState == m_->socket_->state ())
+ {
+ reconnect ();
+ }
+ // remove any earlier spots of this call to reduce pskreporter load
+#ifdef DEBUGPSK
+ static std::fstream fs;
+ if (!fs.is_open()) fs.open("/temp/psk.log", std::fstream::in | std::fstream::out | std::fstream::app);
+#endif
+ added++;
+
+ QDateTime qdateNow = QDateTime::currentDateTime().toUTC();
+ // we allow all spots through +/- 6 hours around an eclipse for the HamSCI group
+ if (!spot_cache.contains(call) || freq > 49000000 || eclipse_active(qdateNow)) // then it's a new spot
+ {
+ m_->spots_.enqueue ({call, grid, snr, freq, mode, QDateTime::currentDateTimeUtc ()});
+ spot_cache.insert(call, time(NULL));
+#ifdef DEBUGPSK
+ if (fs.is_open()) fs << "Adding " << call << " freq=" << freq << " " << spot_cache[call] << " count=" << m_->spots_.count() << std::endl;
+#endif
+ }
+ else if (time(NULL) - spot_cache[call] > CACHE_TIMEOUT) // then the cache has expired
+ {
+ m_->spots_.enqueue ({call, grid, snr, freq, mode, QDateTime::currentDateTimeUtc ()});
+#ifdef DEBUGPSK
+ if (fs.is_open()) fs << "Adding # " << call << spot_cache[call] << " count=" << m_->spots_.count() << std::endl;
+#endif
+ spot_cache[call] = time(NULL);
+ }
+ else
+ {
+ removed++;
+#ifdef DEBUGPSK
+ if (fs.is_open()) fs << "Removing " << call << " " << time(NULL) << " reduction=" << removed/(double)added*100 << "%" << std::endl;
+#endif
+ }
+ // remove cached items over 10 minutes old to save a little memory
+ QMapIterator<QString, time_t> i(spot_cache);
+ time_t tmptime = time(NULL);
+ while(i.hasNext()) {
+ i.next();
+ if (tmptime - i.value() > 600) spot_cache.remove(i.key());
+ }
+ return true;
+ }
+ return false;
+}
+
+void PSKReporter::sendReport (bool last)
+{
+ LOG_LOG_LOCATION (m_->logger_, trace, "last: " << last);
+ m_->check_connection ();
+ if (m_->socket_ && QAbstractSocket::ConnectedState == m_->socket_->state ())
+ {
+ m_->send_report (true);
+ }
+ if (last)
+ {
+ m_->stop ();
+ }
+}
diff --git a/Network/PSKReporter.hpp b/Network/PSKReporter.hpp index 93a8367d..25006de0 100755 --- a/Network/PSKReporter.hpp +++ b/Network/PSKReporter.hpp @@ -1,45 +1,45 @@ -#ifndef PSK_REPORTER_HPP_ -#define PSK_REPORTER_HPP_ - -#include <QObject> -#include "Radio.hpp" -#include "pimpl_h.hpp" - -class QString; -class Configuration; - -class PSKReporter final - : public QObject -{ - Q_OBJECT - -public: - explicit PSKReporter (Configuration const *, QString const& program_info); - ~PSKReporter (); - - void reconnect (); - - void setLocalStation (QString const& call, QString const& grid, QString const& antenna, QString const& rigInformation); - - // - // Returns false if PSK Reporter connection is not available - // - bool addRemoteStation (QString const& call, QString const& grid, Radio::Frequency freq, QString const& mode, int snr); - - // - // Flush any pending spots to PSK Reporter - // - void sendReport (bool last = false); - - // - // True if current time falls withing a +/- window of a solar eclipse for HamSCI use - bool eclipse_active(QDateTime now); - - Q_SIGNAL void errorOccurred (QString const& reason); - -private: - class impl; - pimpl<impl> m_; -}; - -#endif +#ifndef PSK_REPORTER_HPP_
+#define PSK_REPORTER_HPP_
+
+#include <QObject>
+#include "Radio.hpp"
+#include "pimpl_h.hpp"
+
+class QString;
+class Configuration;
+
+class PSKReporter final
+ : public QObject
+{
+ Q_OBJECT
+
+public:
+ explicit PSKReporter (Configuration const *, QString const& program_info);
+ ~PSKReporter ();
+
+ void reconnect ();
+
+ void setLocalStation (QString const& call, QString const& grid, QString const& antenna, QString const& rigInformation);
+
+ //
+ // Returns false if PSK Reporter connection is not available
+ //
+ bool addRemoteStation (QString const& call, QString const& grid, Radio::Frequency freq, QString const& mode, int snr);
+
+ //
+ // Flush any pending spots to PSK Reporter
+ //
+ void sendReport (bool last = false);
+
+ //
+ // True if current time falls withing a +/- window of a solar eclipse for HamSCI use
+ bool eclipse_active(QDateTime now);
+
+ Q_SIGNAL void errorOccurred (QString const& reason);
+
+private:
+ class impl;
+ pimpl<impl> m_;
+};
+
+#endif
diff --git a/Network/tests/PSKReporter/PSKReporter.IESpec b/Network/tests/PSKReporter/PSKReporter.IESpec index 8e95ffd0..c16130aa 100755 --- a/Network/tests/PSKReporter/PSKReporter.IESpec +++ b/Network/tests/PSKReporter/PSKReporter.IESpec @@ -1,12 +1,12 @@ -senderCallsign(30351/1)<string>[65535] -receiverCallsign(30351/2)<string>[65535] -senderLocator(30351/3)<string>[65535] -receiverLocator(30351/4)<string>[65535] -frequency(30351/5)<unsigned32>[4] -sNR(30351/6)<signed8>[1] -iMD(30351/7)<signed8>[1] -decoderSoftware(30351/8)<string>[65535] -antennaInformation(30351/9)<string>[65535] -mode(30351/10)<string>[65535] -informationSource(30351/11)<signed8>[1] -persistentIdentifier(30351/12)<string>[65535] +senderCallsign(30351/1)<string>[65535]
+receiverCallsign(30351/2)<string>[65535]
+senderLocator(30351/3)<string>[65535]
+receiverLocator(30351/4)<string>[65535]
+frequency(30351/5)<unsigned32>[4]
+sNR(30351/6)<signed8>[1]
+iMD(30351/7)<signed8>[1]
+decoderSoftware(30351/8)<string>[65535]
+antennaInformation(30351/9)<string>[65535]
+mode(30351/10)<string>[65535]
+informationSource(30351/11)<signed8>[1]
+persistentIdentifier(30351/12)<string>[65535]
diff --git a/Network/tests/PSKReporter/listener.py b/Network/tests/PSKReporter/listener.py index 4cc0e29c..ea129726 100755 --- a/Network/tests/PSKReporter/listener.py +++ b/Network/tests/PSKReporter/listener.py @@ -1,94 +1,94 @@ -from __future__ import unicode_literals -import sys -import argparse -import logging -import time -import threading -import ipfix.ie -import ipfix.reader -import ipfix.message -import socketserver -import socket - -class IPFixDatagramHandler (socketserver.DatagramRequestHandler): - - def handle (self): - logging.info (f'Connection from {self.client_address}') - try: - self.server.msg_buffer.from_bytes (self.packet) - for rec in self.server.msg_buffer.namedict_iterator (): - logging.info (f't: {self.server.msg_buffer.get_export_time()}: {rec}') - except: - logging.error ('Unexpected exception:', sys.exc_info ()[0]) - - -class IPFixUdpServer (socketserver.UDPServer): - - def __init__ (self, *args, **kwargs): - - self.msg_buffer = ipfix.message.MessageBuffer () - super ().__init__ (*args, **kwargs) - -class IPFixStreamHandler (socketserver.StreamRequestHandler): - - def handle (self): - logging.info (f'Connection from {self.client_address}') - try: - msg_reader = ipfix.reader.from_stream (self.rfile) - for rec in msg_reader.namedict_iterator (): - logging.info (f't: {msg_reader.msg.get_export_time()}: {rec}') - logging.info (f'{self.client_address} closed their connection') - except ConnectionResetError: - logging.info (f'{self.client_address} connection reset') - except TimeoutError: - logging.info (f'{self.client_address} connection timed out') - except: - logging.error ('Unexpected exception:', sys.exc_info ()[0]) - - -if __name__ == "__main__": - INTERFACE, PORT = '', 4739 - - ap = argparse.ArgumentParser (description='Dump IPFIX data collected over UDP') - ap.add_argument ('-l', '--log', metavar='loglevel', default='WARNING', help='logging level') - ap.add_argument ('-s', '--spec', metavar='specfile', help='iespec file to read') - args = ap.parse_args () - - log_level = getattr (logging, args.log.upper (), None) - if not isinstance (log_level, int): - raise ValueError (f'Invalif log level: {log_level}') - logging.basicConfig ( - level=log_level - , format='[%(levelname)s] (%(threadName)-10s) %(message)s' - , - ) - - logging.info (f'Starting IPFix servers on service port: {PORT}') - - ipfix.ie.use_iana_default () - ipfix.ie.use_5103_default () - if args.spec: - ipfix.ie.use_specfile (args.spec) - - udp_server = IPFixUdpServer ((INTERFACE, PORT), IPFixDatagramHandler) - udp_thread = threading.Thread (name='UDP Server', target=udp_server.serve_forever) - - tcp_server = socketserver.TCPServer ((INTERFACE, PORT), IPFixStreamHandler) - tcp_server.allow_reuse_address = True - tcp_server.socket.setsockopt (socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1) - tcp_thread = threading.Thread (name='TCP/IP Server', target=tcp_server.serve_forever) - - udp_thread.start () - tcp_thread.start () - - try: - while True: - time.sleep (1000) - except KeyboardInterrupt: - logging.warning ('Closing down servers') - udp_server.shutdown () - tcp_server.shutdown () - - udp_thread.join () - tcp_thread.join () - logging.info ('Servers closed') +from __future__ import unicode_literals
+import sys
+import argparse
+import logging
+import time
+import threading
+import ipfix.ie
+import ipfix.reader
+import ipfix.message
+import socketserver
+import socket
+
+class IPFixDatagramHandler (socketserver.DatagramRequestHandler):
+
+ def handle (self):
+ logging.info (f'Connection from {self.client_address}')
+ try:
+ self.server.msg_buffer.from_bytes (self.packet)
+ for rec in self.server.msg_buffer.namedict_iterator ():
+ logging.info (f't: {self.server.msg_buffer.get_export_time()}: {rec}')
+ except:
+ logging.error ('Unexpected exception:', sys.exc_info ()[0])
+
+
+class IPFixUdpServer (socketserver.UDPServer):
+
+ def __init__ (self, *args, **kwargs):
+
+ self.msg_buffer = ipfix.message.MessageBuffer ()
+ super ().__init__ (*args, **kwargs)
+
+class IPFixStreamHandler (socketserver.StreamRequestHandler):
+
+ def handle (self):
+ logging.info (f'Connection from {self.client_address}')
+ try:
+ msg_reader = ipfix.reader.from_stream (self.rfile)
+ for rec in msg_reader.namedict_iterator ():
+ logging.info (f't: {msg_reader.msg.get_export_time()}: {rec}')
+ logging.info (f'{self.client_address} closed their connection')
+ except ConnectionResetError:
+ logging.info (f'{self.client_address} connection reset')
+ except TimeoutError:
+ logging.info (f'{self.client_address} connection timed out')
+ except:
+ logging.error ('Unexpected exception:', sys.exc_info ()[0])
+
+
+if __name__ == "__main__":
+ INTERFACE, PORT = '', 4739
+
+ ap = argparse.ArgumentParser (description='Dump IPFIX data collected over UDP')
+ ap.add_argument ('-l', '--log', metavar='loglevel', default='WARNING', help='logging level')
+ ap.add_argument ('-s', '--spec', metavar='specfile', help='iespec file to read')
+ args = ap.parse_args ()
+
+ log_level = getattr (logging, args.log.upper (), None)
+ if not isinstance (log_level, int):
+ raise ValueError (f'Invalif log level: {log_level}')
+ logging.basicConfig (
+ level=log_level
+ , format='[%(levelname)s] (%(threadName)-10s) %(message)s'
+ ,
+ )
+
+ logging.info (f'Starting IPFix servers on service port: {PORT}')
+
+ ipfix.ie.use_iana_default ()
+ ipfix.ie.use_5103_default ()
+ if args.spec:
+ ipfix.ie.use_specfile (args.spec)
+
+ udp_server = IPFixUdpServer ((INTERFACE, PORT), IPFixDatagramHandler)
+ udp_thread = threading.Thread (name='UDP Server', target=udp_server.serve_forever)
+
+ tcp_server = socketserver.TCPServer ((INTERFACE, PORT), IPFixStreamHandler)
+ tcp_server.allow_reuse_address = True
+ tcp_server.socket.setsockopt (socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
+ tcp_thread = threading.Thread (name='TCP/IP Server', target=tcp_server.serve_forever)
+
+ udp_thread.start ()
+ tcp_thread.start ()
+
+ try:
+ while True:
+ time.sleep (1000)
+ except KeyboardInterrupt:
+ logging.warning ('Closing down servers')
+ udp_server.shutdown ()
+ tcp_server.shutdown ()
+
+ udp_thread.join ()
+ tcp_thread.join ()
+ logging.info ('Servers closed')
diff --git a/Network/tests/PSKReporter/python-ipfix.patch b/Network/tests/PSKReporter/python-ipfix.patch index cb679709..2ccbcd5f 100755 --- a/Network/tests/PSKReporter/python-ipfix.patch +++ b/Network/tests/PSKReporter/python-ipfix.patch @@ -1,64 +1,64 @@ -The following changes since commit e487dfbead9965c1a251d110dc55039a7ba4afef: - - sphinx doc update (2017-09-20 16:07:22 +0200) - -are available in the Git repository at: - - git@github.com:g4wjs/python-ipfix.git varlen-and-padding - -for you to fetch changes up to 6dcc106f22d25ac21b27f8ccb9b82be12e7eb18e: - - Parse and emit data elements correctly when variable length items included (2020-06-19 19:53:33 +0100) - ----------------------------------------------------------------- -Bill Somerville (2): - Allow for alignment padding when parsing sets - Parse and emit data elements correctly when variable length items included - - ipfix/message.py | 3 ++- - ipfix/template.py | 4 ++-- - 2 files changed, 4 insertions(+), 3 deletions(-) - -diff --git a/ipfix/message.py b/ipfix/message.py -index 0af2fad..71c1328 100644 ---- a/ipfix/message.py -+++ b/ipfix/message.py -@@ -398,7 +398,7 @@ class MessageBuffer(object): - offset += _sethdr_st.size # skip set header in decode - if setid == template.TEMPLATE_SET_ID or\ - setid == template.OPTIONS_SET_ID: -- while offset < setend: -+ while offset + 4 < setend: # allow for padding up to 4 byte alignment - (tmpl, offset) = template.decode_template_from( - self.mbuf, offset, setid) - # FIXME handle withdrawal -@@ -431,6 +431,7 @@ class MessageBuffer(object): - # KeyError on template lookup - unknown data set - self.unknown_data_set_hook(self, - self.mbuf[offset-_sethdr_st.size:setend]) -+ offset = setend # real end may be greater that accumulated offset - - def namedict_iterator(self): - """ -diff --git a/ipfix/template.py b/ipfix/template.py -index 1203e55..26cd8c1 100644 ---- a/ipfix/template.py -+++ b/ipfix/template.py -@@ -187,7 +187,7 @@ class Template(object): - offset += packplan.st.size - - # short circuit on no varlen -- if not self.varlenslice: -+ if self.varlenslice is None: - return (vals, offset) - - # direct iteration over remaining IEs -@@ -239,7 +239,7 @@ class Template(object): - offset += packplan.st.size - - # shortcircuit no varlen -- if not self.varlenslice: -+ if self.varlenslice is None: - return offset - - # direct iteration over remaining IEs +The following changes since commit e487dfbead9965c1a251d110dc55039a7ba4afef:
+
+ sphinx doc update (2017-09-20 16:07:22 +0200)
+
+are available in the Git repository at:
+
+ git@github.com:g4wjs/python-ipfix.git varlen-and-padding
+
+for you to fetch changes up to 6dcc106f22d25ac21b27f8ccb9b82be12e7eb18e:
+
+ Parse and emit data elements correctly when variable length items included (2020-06-19 19:53:33 +0100)
+
+----------------------------------------------------------------
+Bill Somerville (2):
+ Allow for alignment padding when parsing sets
+ Parse and emit data elements correctly when variable length items included
+
+ ipfix/message.py | 3 ++-
+ ipfix/template.py | 4 ++--
+ 2 files changed, 4 insertions(+), 3 deletions(-)
+
+diff --git a/ipfix/message.py b/ipfix/message.py
+index 0af2fad..71c1328 100644
+--- a/ipfix/message.py
++++ b/ipfix/message.py
+@@ -398,7 +398,7 @@ class MessageBuffer(object):
+ offset += _sethdr_st.size # skip set header in decode
+ if setid == template.TEMPLATE_SET_ID or\
+ setid == template.OPTIONS_SET_ID:
+- while offset < setend:
++ while offset + 4 < setend: # allow for padding up to 4 byte alignment
+ (tmpl, offset) = template.decode_template_from(
+ self.mbuf, offset, setid)
+ # FIXME handle withdrawal
+@@ -431,6 +431,7 @@ class MessageBuffer(object):
+ # KeyError on template lookup - unknown data set
+ self.unknown_data_set_hook(self,
+ self.mbuf[offset-_sethdr_st.size:setend])
++ offset = setend # real end may be greater that accumulated offset
+
+ def namedict_iterator(self):
+ """
+diff --git a/ipfix/template.py b/ipfix/template.py
+index 1203e55..26cd8c1 100644
+--- a/ipfix/template.py
++++ b/ipfix/template.py
+@@ -187,7 +187,7 @@ class Template(object):
+ offset += packplan.st.size
+
+ # short circuit on no varlen
+- if not self.varlenslice:
++ if self.varlenslice is None:
+ return (vals, offset)
+
+ # direct iteration over remaining IEs
+@@ -239,7 +239,7 @@ class Template(object):
+ offset += packplan.st.size
+
+ # shortcircuit no varlen
+- if not self.varlenslice:
++ if self.varlenslice is None:
+ return offset
+
+ # direct iteration over remaining IEs
diff --git a/Network/wsprnet.cpp b/Network/wsprnet.cpp index 903c8236..ec4ed9e4 100755 --- a/Network/wsprnet.cpp +++ b/Network/wsprnet.cpp @@ -1,343 +1,343 @@ -// Interface to WSPRnet website -// -// by Edson Pereira - PY2SDR - -#include "wsprnet.h" - -#include <cmath> - -#include <QTimer> -#include <QFile> -#include <QRegExp> -#include <QRegularExpression> -#include <QNetworkAccessManager> -#include <QNetworkRequest> -#include <QNetworkReply> -#include <QUrl> -#include <QDebug> - -#include "moc_wsprnet.cpp" - -namespace -{ - char const * const wsprNetUrl = "http://wsprnet.org/post/"; - //char const * const wsprNetUrl = "http://127.0.0.1:5000/post/"; - - // - // tested with this python REST mock of WSPRNet.org - // - /* -# Mock WSPRNet.org RESTful API -from flask import Flask, request, url_for -from flask_restful import Resource, Api - -app = Flask(__name__) - -@app.route ('/post/', methods=['GET', 'POST']) -def spot (): - if request.method == 'POST': - print (request.form) - return "1 spot(s) added" - -with app.test_request_context (): - print (url_for ('spot')) - */ - - // regexp to parse FST4W decodes - QRegularExpression fst4_re {R"( - (?<time>\d{4}) - \s+(?<db>[-+]?\d+) - \s+(?<dt>[-+]?\d+\.\d+) - \s+(?<freq>\d+) - \s+` - \s+<?(?<call>[A-Z0-9/]+)>?(?:\s(?<grid>[A-R]{2}[0-9]{2}(?:[A-X]{2})?))?(?:\s+(?<dBm>\d+))? -)", QRegularExpression::ExtendedPatternSyntaxOption}; - - // regexp to parse wspr_spots.txt from wsprd - // - // 130223 2256 7 -21 -0.3 14.097090 DU1MGA PK04 37 0 40 0 - // Date Time Sync dBm DT Freq Msg - // 1 2 3 4 5 6 -------7------ 8 9 10 - QRegularExpression wspr_re(R"(^(\d+)\s+(\d+)\s+(\d+)\s+([+-]?\d+)\s+([+-]?\d+\.\d+)\s+(\d+\.\d+)\s+([^ ].*[^ ])\s+([+-]?\d+)\s+([+-]?\d+)\s+([+-]?\d+))"); -}; - -WSPRNet::WSPRNet (QNetworkAccessManager * manager, QObject *parent) - : QObject {parent} - , network_manager_ {manager} - , spots_to_send_ {0} -{ - connect (network_manager_, &QNetworkAccessManager::finished, this, &WSPRNet::networkReply); - connect (&upload_timer_, &QTimer::timeout, this, &WSPRNet::work); -} - -void WSPRNet::upload (QString const& call, QString const& grid, QString const& rfreq, QString const& tfreq, - QString const& mode, float TR_period, QString const& tpct, QString const& dbm, - QString const& version, QString const& fileName) -{ - m_call = call; - m_grid = grid; - m_rfreq = rfreq; - m_tfreq = tfreq; - m_mode = mode; - TR_period_ = TR_period; - m_tpct = tpct; - m_dbm = dbm; - m_vers = version; - m_file = fileName; - - // Open the wsprd.out file - if (m_uploadType != 3) - { - QFile wsprdOutFile (fileName); - if (!wsprdOutFile.open (QIODevice::ReadOnly | QIODevice::Text) || !wsprdOutFile.size ()) - { - spot_queue_.enqueue (urlEncodeNoSpot ()); - m_uploadType = 1; - } - else - { - // Read the contents - while (!wsprdOutFile.atEnd()) - { - SpotQueue::value_type query; - if (decodeLine (wsprdOutFile.readLine(), query)) - { - // Prevent reporting data ouside of the current frequency band - float f = fabs (m_rfreq.toFloat() - query.queryItemValue ("tqrg", QUrl::FullyDecoded).toFloat()); - if (f < 0.01) // MHz - { - spot_queue_.enqueue(urlEncodeSpot (query)); - m_uploadType = 2; - } - } - } - } - } - spots_to_send_ = spot_queue_.size (); - upload_timer_.start (200); -} - -void WSPRNet::post (QString const& call, QString const& grid, QString const& rfreq, QString const& tfreq, - QString const& mode, float TR_period, QString const& tpct, QString const& dbm, - QString const& version, QString const& decode_text) -{ - m_call = call; - m_grid = grid; - m_rfreq = rfreq; - m_tfreq = tfreq; - m_mode = mode; - TR_period_ = TR_period; - m_tpct = tpct; - m_dbm = dbm; - m_vers = version; - - if (!decode_text.size ()) - { - if (!spot_queue_.size ()) - { - spot_queue_.enqueue (urlEncodeNoSpot ()); - m_uploadType = 3; - } - } - else - { - auto const& match = fst4_re.match (decode_text); - if (match.hasMatch ()) - { - SpotQueue::value_type query; - // Prevent reporting data ouside of the current frequency - // band - removed by G4WJS to accommodate FST4W spots - // outside of WSPR segments - auto tqrg = match.captured ("freq").toInt (); - // if (tqrg >= 1400 && tqrg <= 1600) - { - query.addQueryItem ("function", "wspr"); - // use time as at 3/4 of T/R period before current to - // ensure date is in Rx period - auto const& date = QDateTime::currentDateTimeUtc ().addSecs (-TR_period * 3. / 4.).date (); - query.addQueryItem ("date", date.toString ("yyMMdd")); - query.addQueryItem ("time", match.captured ("time")); - query.addQueryItem ("sig", match.captured ("db")); - query.addQueryItem ("dt", match.captured ("dt")); - query.addQueryItem ("tqrg", QString::number (rfreq.toDouble () + (tqrg - 1500) / 1e6, 'f', 6)); - query.addQueryItem ("tcall", match.captured ("call")); - query.addQueryItem ("drift", "0"); - query.addQueryItem ("tgrid", match.captured ("grid")); - query.addQueryItem ("dbm", match.captured ("dBm")); - spot_queue_.enqueue (urlEncodeSpot (query)); - m_uploadType = 2; - } - } - } -} - -void WSPRNet::networkReply (QNetworkReply * reply) -{ - // check if request was ours - if (m_outstandingRequests.removeOne (reply)) - { - if (QNetworkReply::NoError != reply->error ()) - { - Q_EMIT uploadStatus (QString {"Error: %1"}.arg (reply->error ())); - // not clearing queue or halting queuing as it may be a - // transient one off request error - } - else - { - QString serverResponse = reply->readAll (); - if (m_uploadType == 2) - { - if (!serverResponse.contains(QRegExp("spot\\(s\\) added"))) - { - Q_EMIT uploadStatus (QString {"Upload Failed: %1"}.arg (serverResponse)); - spot_queue_.clear (); - upload_timer_.stop (); - } - } - - if (!spot_queue_.size ()) - { - Q_EMIT uploadStatus("done"); - QFile f {m_file}; - if (f.exists ()) f.remove (); - upload_timer_.stop (); - } - } - - qDebug () << QString {"WSPRnet.org %1 outstanding requests"}.arg (m_outstandingRequests.size ()); - - // delete request object instance on return to the event loop otherwise it is leaked - reply->deleteLater (); - } -} - -bool WSPRNet::decodeLine (QString const& line, SpotQueue::value_type& query) const -{ - auto const& rx_match = wspr_re.match (line); - if (rx_match.hasMatch ()) { - int msgType = 0; - QString msg = rx_match.captured (7); - QString call, grid, dbm; - QRegularExpression msgRx; - - // Check for Message Type 1 - msgRx.setPattern(R"(^([A-Z0-9]{3,6})\s+([A-R]{2}\d{2})\s+(\d+))"); - auto match = msgRx.match (msg); - if (match.hasMatch ()) { - msgType = 1; - call = match.captured (1); - grid = match.captured (2); - dbm = match.captured (3); - } - - // Check for Message Type 2 - msgRx.setPattern(R"(^([A-Z0-9/]+)\s+(\d+))"); - match = msgRx.match (msg); - if (match.hasMatch ()) { - msgType = 2; - call = match.captured (1); - grid = ""; - dbm = match.captured (2); - } - - // Check for Message Type 3 - msgRx.setPattern(R"(^<([A-Z0-9/]+)>\s+([A-R]{2}\d{2}[A-X]{2})\s+(\d+))"); - match = msgRx.match (msg); - if (match.hasMatch ()) { - msgType = 3; - call = match.captured (1); - grid = match.captured (2); - dbm = match.captured (3); - } - - // Unknown message format - if (!msgType) { - return false; - } - - query.addQueryItem ("function", "wspr"); - query.addQueryItem ("date", rx_match.captured (1)); - query.addQueryItem ("time", rx_match.captured (2)); - query.addQueryItem ("sig", rx_match.captured (4)); - query.addQueryItem ("dt", rx_match.captured(5)); - query.addQueryItem ("drift", rx_match.captured(8)); - query.addQueryItem ("tqrg", rx_match.captured(6)); - query.addQueryItem ("tcall", call); - query.addQueryItem ("tgrid", grid); - query.addQueryItem ("dbm", dbm); - } else { - return false; - } - return true; -} - -QString WSPRNet::encode_mode () const -{ - if (m_mode == "WSPR") return "2"; - if (m_mode == "WSPR-15") return "15"; - if (m_mode == "FST4W") - { - auto tr = static_cast<int> ((TR_period_ / 60.)+.5); -// if (2 == tr || 15 == tr) - if (2 == tr) - { - tr += 1; // distinguish from WSPR-2 - } - return QString::number (tr); - } - return ""; -} - -auto WSPRNet::urlEncodeNoSpot () const -> SpotQueue::value_type -{ - SpotQueue::value_type query; - query.addQueryItem ("function", "wsprstat"); - query.addQueryItem ("rcall", m_call); - query.addQueryItem ("rgrid", m_grid); - query.addQueryItem ("rqrg", m_rfreq); - query.addQueryItem ("tpct", m_tpct); - query.addQueryItem ("tqrg", m_tfreq); - query.addQueryItem ("dbm", m_dbm); - query.addQueryItem ("version", m_vers); - query.addQueryItem ("mode", encode_mode ()); - return query;; -} - -auto WSPRNet::urlEncodeSpot (SpotQueue::value_type& query) const -> SpotQueue::value_type -{ - query.addQueryItem ("version", m_vers); - query.addQueryItem ("rcall", m_call); - query.addQueryItem ("rgrid", m_grid); - query.addQueryItem ("rqrg", m_rfreq); - query.addQueryItem ("mode", encode_mode ()); - return query; -} - -void WSPRNet::work() -{ - if (spots_to_send_ && spot_queue_.size ()) - { -#if QT_VERSION < QT_VERSION_CHECK (5, 15, 0) - if (QNetworkAccessManager::Accessible != network_manager_->networkAccessible ()) { - // try and recover network access for QNAM - network_manager_->setNetworkAccessible (QNetworkAccessManager::Accessible); - } -#endif - QNetworkRequest request (QUrl {wsprNetUrl}); - request.setHeader (QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded"); - auto const& spot = spot_queue_.dequeue (); - m_outstandingRequests << network_manager_->post (request, spot.query (QUrl::FullyEncoded).toUtf8 ()); - Q_EMIT uploadStatus(QString {"Uploading Spot %1/%2"}.arg (spots_to_send_ - spot_queue_.size()).arg (spots_to_send_)); - } - else - { - upload_timer_.stop (); - } -} - -void WSPRNet::abortOutstandingRequests () { - spot_queue_.clear (); - for (auto& request : m_outstandingRequests) { - request->abort (); - } -} +// Interface to WSPRnet website
+//
+// by Edson Pereira - PY2SDR
+
+#include "wsprnet.h"
+
+#include <cmath>
+
+#include <QTimer>
+#include <QFile>
+#include <QRegExp>
+#include <QRegularExpression>
+#include <QNetworkAccessManager>
+#include <QNetworkRequest>
+#include <QNetworkReply>
+#include <QUrl>
+#include <QDebug>
+
+#include "moc_wsprnet.cpp"
+
+namespace
+{
+ char const * const wsprNetUrl = "http://wsprnet.org/post/";
+ //char const * const wsprNetUrl = "http://127.0.0.1:5000/post/";
+
+ //
+ // tested with this python REST mock of WSPRNet.org
+ //
+ /*
+# Mock WSPRNet.org RESTful API
+from flask import Flask, request, url_for
+from flask_restful import Resource, Api
+
+app = Flask(__name__)
+
+@app.route ('/post/', methods=['GET', 'POST'])
+def spot ():
+ if request.method == 'POST':
+ print (request.form)
+ return "1 spot(s) added"
+
+with app.test_request_context ():
+ print (url_for ('spot'))
+ */
+
+ // regexp to parse FST4W decodes
+ QRegularExpression fst4_re {R"(
+ (?<time>\d{4})
+ \s+(?<db>[-+]?\d+)
+ \s+(?<dt>[-+]?\d+\.\d+)
+ \s+(?<freq>\d+)
+ \s+`
+ \s+<?(?<call>[A-Z0-9/]+)>?(?:\s(?<grid>[A-R]{2}[0-9]{2}(?:[A-X]{2})?))?(?:\s+(?<dBm>\d+))?
+)", QRegularExpression::ExtendedPatternSyntaxOption};
+
+ // regexp to parse wspr_spots.txt from wsprd
+ //
+ // 130223 2256 7 -21 -0.3 14.097090 DU1MGA PK04 37 0 40 0
+ // Date Time Sync dBm DT Freq Msg
+ // 1 2 3 4 5 6 -------7------ 8 9 10
+ QRegularExpression wspr_re(R"(^(\d+)\s+(\d+)\s+(\d+)\s+([+-]?\d+)\s+([+-]?\d+\.\d+)\s+(\d+\.\d+)\s+([^ ].*[^ ])\s+([+-]?\d+)\s+([+-]?\d+)\s+([+-]?\d+))");
+};
+
+WSPRNet::WSPRNet (QNetworkAccessManager * manager, QObject *parent)
+ : QObject {parent}
+ , network_manager_ {manager}
+ , spots_to_send_ {0}
+{
+ connect (network_manager_, &QNetworkAccessManager::finished, this, &WSPRNet::networkReply);
+ connect (&upload_timer_, &QTimer::timeout, this, &WSPRNet::work);
+}
+
+void WSPRNet::upload (QString const& call, QString const& grid, QString const& rfreq, QString const& tfreq,
+ QString const& mode, float TR_period, QString const& tpct, QString const& dbm,
+ QString const& version, QString const& fileName)
+{
+ m_call = call;
+ m_grid = grid;
+ m_rfreq = rfreq;
+ m_tfreq = tfreq;
+ m_mode = mode;
+ TR_period_ = TR_period;
+ m_tpct = tpct;
+ m_dbm = dbm;
+ m_vers = version;
+ m_file = fileName;
+
+ // Open the wsprd.out file
+ if (m_uploadType != 3)
+ {
+ QFile wsprdOutFile (fileName);
+ if (!wsprdOutFile.open (QIODevice::ReadOnly | QIODevice::Text) || !wsprdOutFile.size ())
+ {
+ spot_queue_.enqueue (urlEncodeNoSpot ());
+ m_uploadType = 1;
+ }
+ else
+ {
+ // Read the contents
+ while (!wsprdOutFile.atEnd())
+ {
+ SpotQueue::value_type query;
+ if (decodeLine (wsprdOutFile.readLine(), query))
+ {
+ // Prevent reporting data ouside of the current frequency band
+ float f = fabs (m_rfreq.toFloat() - query.queryItemValue ("tqrg", QUrl::FullyDecoded).toFloat());
+ if (f < 0.01) // MHz
+ {
+ spot_queue_.enqueue(urlEncodeSpot (query));
+ m_uploadType = 2;
+ }
+ }
+ }
+ }
+ }
+ spots_to_send_ = spot_queue_.size ();
+ upload_timer_.start (200);
+}
+
+void WSPRNet::post (QString const& call, QString const& grid, QString const& rfreq, QString const& tfreq,
+ QString const& mode, float TR_period, QString const& tpct, QString const& dbm,
+ QString const& version, QString const& decode_text)
+{
+ m_call = call;
+ m_grid = grid;
+ m_rfreq = rfreq;
+ m_tfreq = tfreq;
+ m_mode = mode;
+ TR_period_ = TR_period;
+ m_tpct = tpct;
+ m_dbm = dbm;
+ m_vers = version;
+
+ if (!decode_text.size ())
+ {
+ if (!spot_queue_.size ())
+ {
+ spot_queue_.enqueue (urlEncodeNoSpot ());
+ m_uploadType = 3;
+ }
+ }
+ else
+ {
+ auto const& match = fst4_re.match (decode_text);
+ if (match.hasMatch ())
+ {
+ SpotQueue::value_type query;
+ // Prevent reporting data ouside of the current frequency
+ // band - removed by G4WJS to accommodate FST4W spots
+ // outside of WSPR segments
+ auto tqrg = match.captured ("freq").toInt ();
+ // if (tqrg >= 1400 && tqrg <= 1600)
+ {
+ query.addQueryItem ("function", "wspr");
+ // use time as at 3/4 of T/R period before current to
+ // ensure date is in Rx period
+ auto const& date = QDateTime::currentDateTimeUtc ().addSecs (-TR_period * 3. / 4.).date ();
+ query.addQueryItem ("date", date.toString ("yyMMdd"));
+ query.addQueryItem ("time", match.captured ("time"));
+ query.addQueryItem ("sig", match.captured ("db"));
+ query.addQueryItem ("dt", match.captured ("dt"));
+ query.addQueryItem ("tqrg", QString::number (rfreq.toDouble () + (tqrg - 1500) / 1e6, 'f', 6));
+ query.addQueryItem ("tcall", match.captured ("call"));
+ query.addQueryItem ("drift", "0");
+ query.addQueryItem ("tgrid", match.captured ("grid"));
+ query.addQueryItem ("dbm", match.captured ("dBm"));
+ spot_queue_.enqueue (urlEncodeSpot (query));
+ m_uploadType = 2;
+ }
+ }
+ }
+}
+
+void WSPRNet::networkReply (QNetworkReply * reply)
+{
+ // check if request was ours
+ if (m_outstandingRequests.removeOne (reply))
+ {
+ if (QNetworkReply::NoError != reply->error ())
+ {
+ Q_EMIT uploadStatus (QString {"Error: %1"}.arg (reply->error ()));
+ // not clearing queue or halting queuing as it may be a
+ // transient one off request error
+ }
+ else
+ {
+ QString serverResponse = reply->readAll ();
+ if (m_uploadType == 2)
+ {
+ if (!serverResponse.contains(QRegExp("spot\\(s\\) added")))
+ {
+ Q_EMIT uploadStatus (QString {"Upload Failed: %1"}.arg (serverResponse));
+ spot_queue_.clear ();
+ upload_timer_.stop ();
+ }
+ }
+
+ if (!spot_queue_.size ())
+ {
+ Q_EMIT uploadStatus("done");
+ QFile f {m_file};
+ if (f.exists ()) f.remove ();
+ upload_timer_.stop ();
+ }
+ }
+
+ qDebug () << QString {"WSPRnet.org %1 outstanding requests"}.arg (m_outstandingRequests.size ());
+
+ // delete request object instance on return to the event loop otherwise it is leaked
+ reply->deleteLater ();
+ }
+}
+
+bool WSPRNet::decodeLine (QString const& line, SpotQueue::value_type& query) const
+{
+ auto const& rx_match = wspr_re.match (line);
+ if (rx_match.hasMatch ()) {
+ int msgType = 0;
+ QString msg = rx_match.captured (7);
+ QString call, grid, dbm;
+ QRegularExpression msgRx;
+
+ // Check for Message Type 1
+ msgRx.setPattern(R"(^([A-Z0-9]{3,6})\s+([A-R]{2}\d{2})\s+(\d+))");
+ auto match = msgRx.match (msg);
+ if (match.hasMatch ()) {
+ msgType = 1;
+ call = match.captured (1);
+ grid = match.captured (2);
+ dbm = match.captured (3);
+ }
+
+ // Check for Message Type 2
+ msgRx.setPattern(R"(^([A-Z0-9/]+)\s+(\d+))");
+ match = msgRx.match (msg);
+ if (match.hasMatch ()) {
+ msgType = 2;
+ call = match.captured (1);
+ grid = "";
+ dbm = match.captured (2);
+ }
+
+ // Check for Message Type 3
+ msgRx.setPattern(R"(^<([A-Z0-9/]+)>\s+([A-R]{2}\d{2}[A-X]{2})\s+(\d+))");
+ match = msgRx.match (msg);
+ if (match.hasMatch ()) {
+ msgType = 3;
+ call = match.captured (1);
+ grid = match.captured (2);
+ dbm = match.captured (3);
+ }
+
+ // Unknown message format
+ if (!msgType) {
+ return false;
+ }
+
+ query.addQueryItem ("function", "wspr");
+ query.addQueryItem ("date", rx_match.captured (1));
+ query.addQueryItem ("time", rx_match.captured (2));
+ query.addQueryItem ("sig", rx_match.captured (4));
+ query.addQueryItem ("dt", rx_match.captured(5));
+ query.addQueryItem ("drift", rx_match.captured(8));
+ query.addQueryItem ("tqrg", rx_match.captured(6));
+ query.addQueryItem ("tcall", call);
+ query.addQueryItem ("tgrid", grid);
+ query.addQueryItem ("dbm", dbm);
+ } else {
+ return false;
+ }
+ return true;
+}
+
+QString WSPRNet::encode_mode () const
+{
+ if (m_mode == "WSPR") return "2";
+ if (m_mode == "WSPR-15") return "15";
+ if (m_mode == "FST4W")
+ {
+ auto tr = static_cast<int> ((TR_period_ / 60.)+.5);
+// if (2 == tr || 15 == tr)
+ if (2 == tr)
+ {
+ tr += 1; // distinguish from WSPR-2
+ }
+ return QString::number (tr);
+ }
+ return "";
+}
+
+auto WSPRNet::urlEncodeNoSpot () const -> SpotQueue::value_type
+{
+ SpotQueue::value_type query;
+ query.addQueryItem ("function", "wsprstat");
+ query.addQueryItem ("rcall", m_call);
+ query.addQueryItem ("rgrid", m_grid);
+ query.addQueryItem ("rqrg", m_rfreq);
+ query.addQueryItem ("tpct", m_tpct);
+ query.addQueryItem ("tqrg", m_tfreq);
+ query.addQueryItem ("dbm", m_dbm);
+ query.addQueryItem ("version", m_vers);
+ query.addQueryItem ("mode", encode_mode ());
+ return query;;
+}
+
+auto WSPRNet::urlEncodeSpot (SpotQueue::value_type& query) const -> SpotQueue::value_type
+{
+ query.addQueryItem ("version", m_vers);
+ query.addQueryItem ("rcall", m_call);
+ query.addQueryItem ("rgrid", m_grid);
+ query.addQueryItem ("rqrg", m_rfreq);
+ query.addQueryItem ("mode", encode_mode ());
+ return query;
+}
+
+void WSPRNet::work()
+{
+ if (spots_to_send_ && spot_queue_.size ())
+ {
+#if QT_VERSION < QT_VERSION_CHECK (5, 15, 0)
+ if (QNetworkAccessManager::Accessible != network_manager_->networkAccessible ()) {
+ // try and recover network access for QNAM
+ network_manager_->setNetworkAccessible (QNetworkAccessManager::Accessible);
+ }
+#endif
+ QNetworkRequest request (QUrl {wsprNetUrl});
+ request.setHeader (QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");
+ auto const& spot = spot_queue_.dequeue ();
+ m_outstandingRequests << network_manager_->post (request, spot.query (QUrl::FullyEncoded).toUtf8 ());
+ Q_EMIT uploadStatus(QString {"Uploading Spot %1/%2"}.arg (spots_to_send_ - spot_queue_.size()).arg (spots_to_send_));
+ }
+ else
+ {
+ upload_timer_.stop ();
+ }
+}
+
+void WSPRNet::abortOutstandingRequests () {
+ spot_queue_.clear ();
+ for (auto& request : m_outstandingRequests) {
+ request->abort ();
+ }
+}
diff --git a/Network/wsprnet.h b/Network/wsprnet.h index a450d582..38a3cd8f 100755 --- a/Network/wsprnet.h +++ b/Network/wsprnet.h @@ -1,60 +1,60 @@ -#ifndef WSPRNET_H -#define WSPRNET_H - -#include <QObject> -#include <QTimer> -#include <QString> -#include <QList> -#include <QUrlQuery> -#include <QQueue> - -class QNetworkAccessManager; -class QNetworkReply; - -class WSPRNet : public QObject -{ - Q_OBJECT - - using SpotQueue = QQueue<QUrlQuery>; - -public: - explicit WSPRNet (QNetworkAccessManager *, QObject *parent = nullptr); - void upload (QString const& call, QString const& grid, QString const& rfreq, QString const& tfreq, - QString const& mode, float TR_peirod, QString const& tpct, QString const& dbm, - QString const& version, QString const& fileName); - void post (QString const& call, QString const& grid, QString const& rfreq, QString const& tfreq, - QString const& mode, float TR_period, QString const& tpct, QString const& dbm, - QString const& version, QString const& decode_text = QString {}); -signals: - void uploadStatus (QString); - -public slots: - void networkReply (QNetworkReply *); - void work (); - void abortOutstandingRequests (); - -private: - bool decodeLine (QString const& line, SpotQueue::value_type& query) const; - SpotQueue::value_type urlEncodeNoSpot () const; - SpotQueue::value_type urlEncodeSpot (SpotQueue::value_type& spot) const; - QString encode_mode () const; - - QNetworkAccessManager * network_manager_; - QList<QNetworkReply *> m_outstandingRequests; - QString m_call; - QString m_grid;; - QString m_rfreq; - QString m_tfreq; - QString m_mode; - QString m_tpct; - QString m_dbm; - QString m_vers; - QString m_file; - float TR_period_; - int spots_to_send_; - SpotQueue spot_queue_; - QTimer upload_timer_; - int m_uploadType; -}; - -#endif // WSPRNET_H +#ifndef WSPRNET_H
+#define WSPRNET_H
+
+#include <QObject>
+#include <QTimer>
+#include <QString>
+#include <QList>
+#include <QUrlQuery>
+#include <QQueue>
+
+class QNetworkAccessManager;
+class QNetworkReply;
+
+class WSPRNet : public QObject
+{
+ Q_OBJECT
+
+ using SpotQueue = QQueue<QUrlQuery>;
+
+public:
+ explicit WSPRNet (QNetworkAccessManager *, QObject *parent = nullptr);
+ void upload (QString const& call, QString const& grid, QString const& rfreq, QString const& tfreq,
+ QString const& mode, float TR_peirod, QString const& tpct, QString const& dbm,
+ QString const& version, QString const& fileName);
+ void post (QString const& call, QString const& grid, QString const& rfreq, QString const& tfreq,
+ QString const& mode, float TR_period, QString const& tpct, QString const& dbm,
+ QString const& version, QString const& decode_text = QString {});
+signals:
+ void uploadStatus (QString);
+
+public slots:
+ void networkReply (QNetworkReply *);
+ void work ();
+ void abortOutstandingRequests ();
+
+private:
+ bool decodeLine (QString const& line, SpotQueue::value_type& query) const;
+ SpotQueue::value_type urlEncodeNoSpot () const;
+ SpotQueue::value_type urlEncodeSpot (SpotQueue::value_type& spot) const;
+ QString encode_mode () const;
+
+ QNetworkAccessManager * network_manager_;
+ QList<QNetworkReply *> m_outstandingRequests;
+ QString m_call;
+ QString m_grid;;
+ QString m_rfreq;
+ QString m_tfreq;
+ QString m_mode;
+ QString m_tpct;
+ QString m_dbm;
+ QString m_vers;
+ QString m_file;
+ float TR_period_;
+ int spots_to_send_;
+ SpotQueue spot_queue_;
+ QTimer upload_timer_;
+ int m_uploadType;
+};
+
+#endif // WSPRNET_H
|
