diff options
| author | Christoph Berg <myon@debian.org> | 2020-09-28 23:28:13 +0200 |
|---|---|---|
| committer | Christoph Berg <myon@debian.org> | 2020-09-28 23:28:13 +0200 |
| commit | 7aa3c56b01768ba7d38fccedc17b30a4046b3fbb (patch) | |
| tree | da509a2cf3667b6f9855ea811f4a1f95d9e6f5ef /Network | |
| parent | 28f34ff4908a90b1a7323b2988c33cdb1779fa06 (diff) | |
New upstream version 2.3.0~rc1+repackupstream/2.3.0_rc1+repack
Diffstat (limited to 'Network')
| -rw-r--r-- | Network/MessageClient.cpp | 78 | ||||
| -rw-r--r-- | Network/MessageClient.hpp | 12 | ||||
| -rw-r--r-- | Network/NetworkAccessManager.cpp | 62 | ||||
| -rw-r--r-- | Network/NetworkAccessManager.hpp | 56 | ||||
| -rw-r--r-- | Network/NetworkMessage.hpp | 1 | ||||
| -rw-r--r-- | Network/PSKReporter.cpp | 521 | ||||
| -rw-r--r-- | Network/PSKReporter.hpp | 41 | ||||
| -rw-r--r-- | Network/psk_reporter.cpp | 140 | ||||
| -rw-r--r-- | Network/psk_reporter.h | 54 | ||||
| -rw-r--r-- | Network/tests/PSKReporter/PSKReporter.IESpec | 12 | ||||
| -rw-r--r-- | Network/tests/PSKReporter/listener.py | 94 | ||||
| -rw-r--r-- | Network/tests/PSKReporter/python-ipfix.patch | 64 | ||||
| -rw-r--r-- | Network/wsprnet.cpp | 435 | ||||
| -rw-r--r-- | Network/wsprnet.h | 59 |
14 files changed, 1140 insertions, 489 deletions
diff --git a/Network/MessageClient.cpp b/Network/MessageClient.cpp index d33b2a63..3c208fd3 100644 --- a/Network/MessageClient.cpp +++ b/Network/MessageClient.cpp @@ -36,6 +36,7 @@ public: impl (QString const& id, QString const& version, QString const& revision, port_type server_port, MessageClient * self) : self_ {self} + , dns_lookup_id_ {0} , enabled_ {false} , id_ {id} , version_ {version} @@ -81,6 +82,7 @@ public: Q_SLOT void host_info_results (QHostInfo); MessageClient * self_; + int dns_lookup_id_; bool enabled_; QString id_; QString version_; @@ -101,6 +103,7 @@ public: void MessageClient::impl::host_info_results (QHostInfo host_info) { + if (host_info.lookupId () != dns_lookup_id_) return; if (QHostInfo::NoError != host_info.error ()) { Q_EMIT self_->error ("UDP server lookup failed:\n" + host_info.errorString ()); @@ -187,7 +190,13 @@ void MessageClient::impl::parse_message (QByteArray const& msg) 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" << hex << 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 @@ -423,30 +432,24 @@ MessageClient::MessageClient (QString const& id, QString const& version, QString : QObject {self} , m_ {id, version, revision, server_port, this} { + connect (&*m_ #if QT_VERSION < QT_VERSION_CHECK(5, 15, 0) - connect (&*m_, static_cast<void (impl::*) (impl::SocketError)> (&impl::error) - , [this] (impl::SocketError e) - { -#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 + , static_cast<void (impl::*) (impl::SocketError)> (&impl::error), [this] (impl::SocketError e) #else - Q_UNUSED (e); + , &impl::errorOccurred, [this] (impl::SocketError e) #endif - { - Q_EMIT error (m_->errorString ()); - } - }); + { +#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 - connect (&*m_, &impl::errorOccurred, [this] (impl::SocketError) { - Q_EMIT error (m_->errorString ()); - }); + { + Q_UNUSED (e); #endif + Q_EMIT error (m_->errorString ()); + } + }); set_server (server); } @@ -464,11 +467,15 @@ void MessageClient::set_server (QString const& server) { m_->server_.clear (); m_->server_string_ = server; - if (!server.isEmpty ()) + if (server.size ()) { // queue a host address lookup TRACE_UDP ("server host DNS lookup:" << server); - QHostInfo::lookupHost (server, &*m_, SLOT (host_info_results (QHostInfo))); +#if QT_VERSION >= QT_VERSION_CHECK(5, 9, 0) + m_->dns_lookup_id_ = QHostInfo::lookupHost (server, &*m_, &MessageClient::impl::host_info_results); +#else + m_->dns_lookup_id_ = QHostInfo::lookupHost (server, &*m_, SLOT (host_info_results (QHostInfo))); +#endif } } @@ -477,27 +484,6 @@ void MessageClient::set_server_port (port_type server_port) m_->server_port_ = server_port; } -qint64 MessageClient::send_raw_datagram (QByteArray const& message, QHostAddress const& dest_address - , port_type dest_port) -{ - if (dest_port && !dest_address.isNull ()) - { - return m_->writeDatagram (message, dest_address, dest_port); - } - return 0; -} - -void MessageClient::add_blocked_destination (QHostAddress const& a) -{ - m_->blocked_addresses_.push_back (a); - if (a == m_->server_) - { - m_->server_.clear (); - Q_EMIT error ("UDP server blocked, please try another"); - m_->pending_messages_.clear (); // discard - } -} - void MessageClient::enable (bool flag) { m_->enabled_ = flag; @@ -573,7 +559,7 @@ void MessageClient::qso_logged (QDateTime time_off, QString const& dx_call, QStr , 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& exchange_rcvd, QString const& propmode) { if (m_->server_port_ && !m_->server_string_.isEmpty ()) { @@ -582,8 +568,8 @@ void MessageClient::qso_logged (QDateTime time_off, QString const& dx_call, QStr 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 (); - 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); + << 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); } } diff --git a/Network/MessageClient.hpp b/Network/MessageClient.hpp index 20f39b01..afe361fa 100644 --- a/Network/MessageClient.hpp +++ b/Network/MessageClient.hpp @@ -69,21 +69,13 @@ public: , 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& 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 may be used to send arbitrary UDP datagrams to and - // destination allowing the underlying socket to be used for general - // UDP messaging if desired - qint64 send_raw_datagram (QByteArray const&, QHostAddress const& dest_address, port_type dest_port); - - // disallowed message destination (does not block datagrams sent - // with send_raw_datagram() above) - Q_SLOT void add_blocked_destination (QHostAddress const&); - // this signal is emitted if the server has requested a decode // window clear action Q_SIGNAL void clear_decodes (quint8 window); diff --git a/Network/NetworkAccessManager.cpp b/Network/NetworkAccessManager.cpp new file mode 100644 index 00000000..e0b06be7 --- /dev/null +++ b/Network/NetworkAccessManager.cpp @@ -0,0 +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; +} diff --git a/Network/NetworkAccessManager.hpp b/Network/NetworkAccessManager.hpp index 1d1b79bc..d68ad215 100644 --- a/Network/NetworkAccessManager.hpp +++ b/Network/NetworkAccessManager.hpp @@ -4,8 +4,6 @@ #include <QNetworkAccessManager> #include <QList> #include <QSslError> -#include <QNetworkReply> -#include <QString> #include "widgets/MessageBox.hpp" @@ -18,58 +16,18 @@ class QWidget; class NetworkAccessManager : public QNetworkAccessManager { + Q_OBJECT + public: - NetworkAccessManager (QWidget * parent) - : QNetworkAccessManager (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, &parent] (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, tr ("Network SSL 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_); - } - }); - } + explicit NetworkAccessManager (QWidget * parent); protected: - QNetworkReply * createRequest (Operation operation, QNetworkRequest const& request, QIODevice * outgoing_data = nullptr) override - { - 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; - } + 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_; }; diff --git a/Network/NetworkMessage.hpp b/Network/NetworkMessage.hpp index 3c5c9268..c484efb2 100644 --- a/Network/NetworkMessage.hpp +++ b/Network/NetworkMessage.hpp @@ -308,6 +308,7 @@ * 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" diff --git a/Network/PSKReporter.cpp b/Network/PSKReporter.cpp new file mode 100644 index 00000000..fcdebf2c --- /dev/null +++ b/Network/PSKReporter.cpp @@ -0,0 +1,521 @@ +#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 <cmath> +#include <QObject> +#include <QString> +#include <QDateTime> +#include <QSharedPointer> +#include <QUdpSocket> +#include <QTcpSocket> +#include <QHostInfo> +#include <QQueue> +#include <QByteArray> +#include <QDataStream> +#include <QTimer> +#if QT_VERSION >= QT_VERSION_CHECK(5, 15, 0) +#include <QRandomGenerator> +#endif + +#include "Configuration.hpp" +#include "pimpl_impl.hpp" + + +#include "moc_PSKReporter.cpp" + +namespace +{ + QLatin1String HOST {"report.pskreporter.info"}; + // QLatin1String HOST {"127.0.0.1"}; + quint16 SERVICE_PORT {4739}; + // quint16 SERVICE_PORT {14739}; + int MIN_SEND_INTERVAL {15}; // in seconds + int FLUSH_INTERVAL {4 * 5}; // in send intervals + bool ALIGNMENT_PADDING {true}; + int MIN_PAYLOAD_LENGTH {508}; + int MAX_PAYLOAD_LENGTH {1400}; +} + +class PSKReporter::impl final + : public QObject +{ + Q_OBJECT + +public: + impl (PSKReporter * self, Configuration const * config, QString const& program_info) + : 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 ()) + { + // send templates again + send_descriptors_ = 3; // three times + // send receiver data set again + send_receiver_data_ = 3; // three times + } + }); + } + + 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 ()) + { + // 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) + { + 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 ()) + { + socket_.reset (new QTcpSocket, &QObject::deleteLater); + send_descriptors_ = 1; + send_receiver_data_ = 1; + } + else + { + 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); +#else + connect (socket_.data (), QOverload<QAbstractSocket::SocketError>::of (&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); + + if (!report_timer_.isActive ()) + { + report_timer_.start (MIN_SEND_INTERVAL * 1000); + } + if (!descriptor_timer_.isActive ()) + { + descriptor_timer_.start (1 * 60 * 60 * 1000); // hourly + } + } + + void stop () + { + if (socket_) + { + socket_->disconnectFromHost (); + } + descriptor_timer_.stop (); + report_timer_.stop (); + } + + void send_report (bool send_residue = false); + void build_preamble (QDataStream&); + + bool flushing () + { + return FLUSH_INTERVAL && !(++flush_counter_ % FLUSH_INTERVAL); + } + + 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 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); + } +} + +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 + + 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 (4u) // 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 (4u) // 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 4 Enterprise Number + // insert Length + set_length (out, descriptor); + message.writeRawData (descriptor.constData (), descriptor.size ()); + } + } + + // 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_); + + // insert Length and move to payload + set_length (out, data); + message.writeRawData (data.constData (), data.size ()); + } +} + +void PSKReporter::impl::send_report (bool 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 ()); + tx_residue_.clear (); + } + + 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_); + tx_out + << static_cast<quint32> (spot.freq_) + << 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 + 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; + } + } + } +} + +PSKReporter::PSKReporter (Configuration const * config, QString const& program_info) + : m_ {this, config, program_info} +{ +} + +PSKReporter::~PSKReporter () +{ + // m_->send_report (true); // send any pending spots +} + +void PSKReporter::reconnect () +{ + m_->reconnect (); +} + +void PSKReporter::setLocalStation (QString const& call, QString const& gridSquare, QString const& antenna) +{ + m_->check_connection (); + if (call != m_->rx_call_ || gridSquare != m_->rx_grid_ || antenna != m_->rx_ant_) + { + 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; + } +} + +bool PSKReporter::addRemoteStation (QString const& call, QString const& grid, Radio::Frequency freq + , QString const& mode, int snr) +{ + m_->check_connection (); + if (m_->socket_ && m_->socket_->isValid ()) + { + if (QAbstractSocket::UnconnectedState == m_->socket_->state ()) + { + reconnect (); + } + m_->spots_.enqueue ({call, grid, snr, freq, mode, QDateTime::currentDateTimeUtc ()}); + return true; + } + return false; +} + +void PSKReporter::sendReport (bool 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 new file mode 100644 index 00000000..1757e63a --- /dev/null +++ b/Network/PSKReporter.hpp @@ -0,0 +1,41 @@ +#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); + + // + // 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); + + Q_SIGNAL void errorOccurred (QString const& reason); + +private: + class impl; + pimpl<impl> m_; +}; + +#endif diff --git a/Network/psk_reporter.cpp b/Network/psk_reporter.cpp deleted file mode 100644 index f84da5ec..00000000 --- a/Network/psk_reporter.cpp +++ /dev/null @@ -1,140 +0,0 @@ -// KISS Interface for posting spots to PSK Reporter web site -// Implemented by Edson Pereira PY2SDR -// -// Reports will be sent in batch mode every 5 minutes. - -#include "psk_reporter.h" - -#include <QHostInfo> -#include <QTimer> -#if QT_VERSION >= QT_VERSION_CHECK(5, 15, 0) -#include <QRandomGenerator> -#endif - -#include "Network/MessageClient.hpp" - -#include "moc_psk_reporter.cpp" - -namespace -{ - int constexpr MAX_PAYLOAD_LENGTH {1400}; -} - -PSK_Reporter::PSK_Reporter(MessageClient * message_client, QObject *parent) : - QObject {parent}, - m_messageClient {message_client}, - reportTimer {new QTimer {this}}, - m_sequenceNumber {0} -{ - m_header_h = "000Allllttttttttssssssssiiiiiiii"; - - // We use 50E2 and 50E3 for link Id - m_rxInfoDescriptor_h = "0003002C50E200040000" - "8002FFFF0000768F" // 2. Rx Call - "8004FFFF0000768F" // 4. Rx Grid - "8008FFFF0000768F" // 8. Rx Soft - "8009FFFF0000768F" // 9. Rx Antenna - "0000"; - - m_txInfoDescriptor_h = "0002003C50E30007" - "8001FFFF0000768F" // 1. Tx Call - "800500040000768F" // 5. Tx Freq - "800600010000768F" // 6. Tx snr - "800AFFFF0000768F" // 10. Tx Mode - "8003FFFF0000768F" // 3. Tx Grid - "800B00010000768F" // 11. Tx info src - "00960004"; // Report time - - -#if QT_VERSION < QT_VERSION_CHECK(5, 15, 0) - m_randomId_h = QString("%1").arg(qrand(),8,16,QChar('0')); -#else - m_randomId_h = QString("%1").arg(QRandomGenerator::global ()->generate (), 8, 16, QChar('0')); -#endif - - QHostInfo::lookupHost("report.pskreporter.info", this, SLOT(dnsLookupResult(QHostInfo))); - - connect(reportTimer, SIGNAL(timeout()), this, SLOT(sendReport())); - reportTimer->start(5*60*1000); // 5 minutes; -} - -void PSK_Reporter::setLocalStation(QString call, QString gridSquare, QString antenna, QString programInfo) -{ - m_rxCall = call; - m_rxGrid = gridSquare; - m_rxAnt = antenna; - m_progId = programInfo; -} - -void PSK_Reporter::addRemoteStation(QString call, QString grid, QString freq, QString mode, QString snr, QString time ) -{ - QHash<QString,QString> spot; - spot["call"] = call; - spot["grid"] = grid; - spot["snr"] = snr; - spot["freq"] = freq; - spot["mode"] = mode; - spot["time"] = time; - m_spotQueue.enqueue(spot); -} - -void PSK_Reporter::sendReport() -{ - while (!m_spotQueue.isEmpty()) { - QString report_h; - - // Header - QString header_h = m_header_h; - header_h.replace("tttttttt", QString("%1").arg(QDateTime::currentDateTime().toTime_t(),8,16,QChar('0'))); - header_h.replace("ssssssss", QString("%1").arg(++m_sequenceNumber,8,16,QChar('0'))); - header_h.replace("iiiiiiii", m_randomId_h); - - // Receiver information - QString rxInfoData_h = "50E2llll"; - rxInfoData_h += QString("%1").arg(m_rxCall.length(),2,16,QChar('0')) + m_rxCall.toUtf8().toHex(); - rxInfoData_h += QString("%1").arg(m_rxGrid.length(),2,16,QChar('0')) + m_rxGrid.toUtf8().toHex(); - rxInfoData_h += QString("%1").arg(m_progId.length(),2,16,QChar('0')) + m_progId.toUtf8().toHex(); - rxInfoData_h += QString("%1").arg(m_rxAnt.length(),2,16,QChar('0')) + m_rxAnt.toUtf8().toHex(); - rxInfoData_h += "0000"; - rxInfoData_h.replace("50E2llll", "50E2" + QString("%1").arg(rxInfoData_h.length()/2,4,16,QChar('0'))); - - // Sender information - QString txInfoData_h = "50E3llll"; - while (!m_spotQueue.isEmpty() - && (header_h.size () + m_rxInfoDescriptor_h.size () + m_txInfoDescriptor_h.size () + rxInfoData_h.size () + txInfoData_h.size ()) / 2 < MAX_PAYLOAD_LENGTH) { - QHash<QString,QString> spot = m_spotQueue.dequeue(); - txInfoData_h += QString("%1").arg(spot["call"].length(),2,16,QChar('0')) + spot["call"].toUtf8().toHex(); - txInfoData_h += QString("%1").arg(spot["freq"].toLongLong(),8,16,QChar('0')); - txInfoData_h += QString("%1").arg(spot["snr"].toInt(),8,16,QChar('0')).right(2); - txInfoData_h += QString("%1").arg(spot["mode"].length(),2,16,QChar('0')) + spot["mode"].toUtf8().toHex(); - txInfoData_h += QString("%1").arg(spot["grid"].length(),2,16,QChar('0')) + spot["grid"].toUtf8().toHex(); - txInfoData_h += QString("%1").arg(1,2,16,QChar('0')); // REPORTER_SOURCE_AUTOMATIC - txInfoData_h += QString("%1").arg(spot["time"].toInt(),8,16,QChar('0')); - } - txInfoData_h += "0000"; - txInfoData_h.replace("50E3llll", "50E3" + QString("%1").arg(txInfoData_h.length()/2,4,16,QChar('0'))); - report_h = header_h + m_rxInfoDescriptor_h + m_txInfoDescriptor_h + rxInfoData_h + txInfoData_h; - //qDebug() << "Sending Report TX: "; - - report_h.replace("000Allll", "000A" + QString("%1").arg(report_h.length()/2,4,16,QChar('0'))); - QByteArray report = QByteArray::fromHex(report_h.toUtf8()); - - // Send data to PSK Reporter site - if (!m_pskReporterAddress.isNull()) { - m_messageClient->send_raw_datagram (report, m_pskReporterAddress, 4739); - } - } -} - -void PSK_Reporter::dnsLookupResult(QHostInfo info) -{ - if (!info.addresses().isEmpty()) { - m_pskReporterAddress = info.addresses().at(0); - // qDebug() << "PSK Reporter IP: " << m_pskReporterAddress; - - // deal with miss-configured settings that attempt to set a - // Pskreporter Internet address for the WSJT-X UDP protocol - // server address - m_messageClient->add_blocked_destination (m_pskReporterAddress); - } -} diff --git a/Network/psk_reporter.h b/Network/psk_reporter.h deleted file mode 100644 index 16afcf43..00000000 --- a/Network/psk_reporter.h +++ /dev/null @@ -1,54 +0,0 @@ -// -*- Mode: C++ -*- -#ifndef PSK_REPORTER_H -#define PSK_REPORTER_H - -#include <QObject> -#include <QString> -#include <QHostAddress> -#include <QQueue> -#include <QHash> - -class MessageClient; -class QTimer; -class QHostInfo; - -class PSK_Reporter : public QObject -{ - Q_OBJECT -public: - explicit PSK_Reporter(MessageClient *, QObject *parent = nullptr); - void setLocalStation(QString call, QString grid, QString antenna, QString programInfo); - void addRemoteStation(QString call, QString grid, QString freq, QString mode, QString snr, QString time); - -signals: - -public slots: - void sendReport(); - -private slots: - void dnsLookupResult(QHostInfo info); - -private: - QString m_header_h; - QString m_rxInfoDescriptor_h; - QString m_txInfoDescriptor_h; - QString m_randomId_h; - QString m_linkId_h; - - QString m_rxCall; - QString m_rxGrid; - QString m_rxAnt; - QString m_progId; - - QHostAddress m_pskReporterAddress; - - QQueue< QHash<QString,QString> > m_spotQueue; - - MessageClient * m_messageClient; - - QTimer *reportTimer; - - int m_sequenceNumber; -}; - -#endif // PSK_REPORTER_H diff --git a/Network/tests/PSKReporter/PSKReporter.IESpec b/Network/tests/PSKReporter/PSKReporter.IESpec new file mode 100644 index 00000000..8e95ffd0 --- /dev/null +++ b/Network/tests/PSKReporter/PSKReporter.IESpec @@ -0,0 +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] diff --git a/Network/tests/PSKReporter/listener.py b/Network/tests/PSKReporter/listener.py new file mode 100644 index 00000000..b2e830e3 --- /dev/null +++ b/Network/tests/PSKReporter/listener.py @@ -0,0 +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 collectedover 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 new file mode 100644 index 00000000..cb679709 --- /dev/null +++ b/Network/tests/PSKReporter/python-ipfix.patch @@ -0,0 +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 diff --git a/Network/wsprnet.cpp b/Network/wsprnet.cpp index cdfed768..669ab155 100644 --- a/Network/wsprnet.cpp +++ b/Network/wsprnet.cpp @@ -8,6 +8,8 @@ #include <QTimer> #include <QFile> +#include <QRegExp> +#include <QRegularExpression> #include <QNetworkAccessManager> #include <QNetworkRequest> #include <QNetworkReply> @@ -18,215 +20,314 @@ namespace { - char const * const wsprNetUrl = "http://wsprnet.org/post?"; - // char const * const wsprNetUrl = "http://127.0.0.1/post?"; + 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} - , networkManager {manager} - , uploadTimer {new QTimer {this}} - , m_urlQueueSize {0} +WSPRNet::WSPRNet (QNetworkAccessManager * manager, QObject *parent) + : QObject {parent} + , network_manager_ {manager} + , spots_to_send_ {0} { - connect(networkManager, SIGNAL(finished(QNetworkReply*)), this, SLOT(networkReply(QNetworkReply*))); - connect( uploadTimer, SIGNAL(timeout()), this, SLOT(work())); + 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, QString const& tpct, QString const& dbm, QString const& version, - QString const& fileName) +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; - m_tpct = tpct; - m_dbm = dbm; - m_vers = version; - m_file = fileName; - - // Open the wsprd.out file - QFile wsprdOutFile(fileName); - if (!wsprdOutFile.open(QIODevice::ReadOnly | QIODevice::Text) || - wsprdOutFile.size() == 0) { - urlQueue.enqueue( wsprNetUrl + urlEncodeNoSpot()); - m_uploadType = 1; - uploadTimer->start(200); - return; + 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 + 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.0002) + { + spot_queue_.enqueue(urlEncodeSpot (query)); + m_uploadType = 2; + } + } + } + } + spots_to_send_ = spot_queue_.size (); + upload_timer_.start (200); +} - // Read the contents - while (!wsprdOutFile.atEnd()) { - QHash<QString,QString> query; - if ( decodeLine(wsprdOutFile.readLine(), query) ) { - // Prevent reporting data ouside of the current frequency band - float f = fabs(m_rfreq.toFloat() - query["tqrg"].toFloat()); - if (f < 0.0002) { - urlQueue.enqueue( wsprNetUrl + urlEncodeSpot(query)); - m_uploadType = 2; +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 = 1; + } + spots_to_send_ = spot_queue_.size (); + upload_timer_.start (200); + } + 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 + 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; + } } - } } - m_urlQueueSize = urlQueue.size(); - uploadTimer->start(200); } -void WSPRNet::networkReply(QNetworkReply *reply) +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"))) { - emit uploadStatus(QString {"Upload Failed: %1"}.arg (serverResponse)); - urlQueue.clear(); - uploadTimer->stop(); + 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 (urlQueue.isEmpty()) { - emit uploadStatus("done"); - QFile::remove(m_file); - uploadTimer->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 ()); + 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 (); - } + // delete request object instance on return to the event loop otherwise it is leaked + reply->deleteLater (); + } } -bool WSPRNet::decodeLine(QString const& line, QHash<QString,QString> &query) +bool WSPRNet::decodeLine (QString const& line, SpotQueue::value_type& query) { - // 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 - QRegExp rx("^(\\d+)\\s+(\\d+)\\s+(\\d+)\\s+([+-]?\\d+)\\s+([+-]?\\d+\\.\\d+)\\s+(\\d+\\.\\d+)\\s+(.*)\\s+([+-]?\\d+)\\s+([+-]?\\d+)\\s+([+-]?\\d+)"); - if (rx.indexIn(line) != -1) { - int msgType = 0; - QString msg = rx.cap(7); - msg.remove(QRegExp("\\s+$")); - msg.remove(QRegExp("^\\s+")); - QString call, grid, dbm; - QRegExp msgRx; - - // Check for Message Type 1 - msgRx.setPattern("^([A-Z0-9]{3,6})\\s+([A-Z]{2}\\d{2})\\s+(\\d+)"); - if (msgRx.indexIn(msg) != -1) { - msgType = 1; - call = msgRx.cap(1); - grid = msgRx.cap(2); - dbm = msgRx.cap(3); - } + 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 2 - msgRx.setPattern("^([A-Z0-9/]+)\\s+(\\d+)"); - if (msgRx.indexIn(msg) != -1) { - msgType = 2; - call = msgRx.cap(1); - grid = ""; - dbm = msgRx.cap(2); - } + // 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 3 - msgRx.setPattern("^<([A-Z0-9/]+)>\\s+([A-Z]{2}\\d{2}[A-Z]{2})\\s+(\\d+)"); - if (msgRx.indexIn(msg) != -1) { - msgType = 3; - call = msgRx.cap(1); - grid = msgRx.cap(2); - dbm = msgRx.cap(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); + } - // Unknown message format - if (!msgType) { - return false; - } + // 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); + } - query["function"] = "wspr"; - query["date"] = rx.cap(1); - query["time"] = rx.cap(2); - query["sig"] = rx.cap(4); - query["dt"] = rx.cap(5); - query["drift"] = rx.cap(8); - query["tqrg"] = rx.cap(6); - query["tcall"] = call; - query["tgrid"] = grid; - query["dbm"] = dbm; - } else { - return false; + // Unknown message format + if (!msgType) { + return false; } - return true; + + 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::urlEncodeNoSpot() +auto WSPRNet::urlEncodeNoSpot () -> SpotQueue::value_type { - QString queryString; - queryString += "function=wsprstat&"; - queryString += "rcall=" + m_call + "&"; - queryString += "rgrid=" + m_grid + "&"; - queryString += "rqrg=" + m_rfreq + "&"; - queryString += "tpct=" + m_tpct + "&"; - queryString += "tqrg=" + m_tfreq + "&"; - queryString += "dbm=" + m_dbm + "&"; - queryString += "version=" + m_vers; - if(m_mode=="WSPR") queryString += "&mode=2"; - if(m_mode=="WSPR-15") queryString += "&mode=15"; - return queryString;; + 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); + if (m_mode == "WSPR") query.addQueryItem ("mode", "2"); + if (m_mode == "WSPR-15") query.addQueryItem ("mode", "15"); + if (m_mode == "FST4W") + { + query.addQueryItem ("mode", QString::number (static_cast<int> ((TR_period_ / 60.)+.5))); + } + return query;; } -QString WSPRNet::urlEncodeSpot(QHash<QString,QString> const& query) +auto WSPRNet::urlEncodeSpot (SpotQueue::value_type& query) -> SpotQueue::value_type { - QString queryString; - queryString += "function=" + query["function"] + "&"; - queryString += "rcall=" + m_call + "&"; - queryString += "rgrid=" + m_grid + "&"; - queryString += "rqrg=" + m_rfreq + "&"; - queryString += "date=" + query["date"] + "&"; - queryString += "time=" + query["time"] + "&"; - queryString += "sig=" + query["sig"] + "&"; - queryString += "dt=" + query["dt"] + "&"; - queryString += "drift=" + query["drift"] + "&"; - queryString += "tqrg=" + query["tqrg"] + "&"; - queryString += "tcall=" + query["tcall"] + "&"; - queryString += "tgrid=" + query["tgrid"] + "&"; - queryString += "dbm=" + query["dbm"] + "&"; - queryString += "version=" + m_vers; - if(m_mode=="WSPR") queryString += "&mode=2"; - if(m_mode=="WSPR-15") queryString += "&mode=15"; - return queryString; + query.addQueryItem ("version", m_vers); + query.addQueryItem ("rcall", m_call); + query.addQueryItem ("rgrid", m_grid); + query.addQueryItem ("rqrg", m_rfreq); + if (m_mode == "WSPR") query.addQueryItem ("mode", "2"); + if (m_mode == "WSPR-15") query.addQueryItem ("mode", "15"); + if (m_mode == "FST4W") + { + query.addQueryItem ("mode", QString::number (static_cast<int> ((TR_period_ / 60.)+.5))); + } + return query; } void WSPRNet::work() { - if (!urlQueue.isEmpty()) { + if (spots_to_send_ && spot_queue_.size ()) + { #if QT_VERSION < QT_VERSION_CHECK (5, 15, 0) - if (QNetworkAccessManager::Accessible != networkManager->networkAccessible ()) { - // try and recover network access for QNAM - networkManager->setNetworkAccessible (QNetworkAccessManager::Accessible); - } + if (QNetworkAccessManager::Accessible != network_manager_->networkAccessible ()) { + // try and recover network access for QNAM + network_manager_->setNetworkAccessible (QNetworkAccessManager::Accessible); + } #endif - QUrl url(urlQueue.dequeue()); - QNetworkRequest request(url); - m_outstandingRequests << networkManager->get(request); - emit uploadStatus(QString {"Uploading Spot %1/%2"}.arg (m_urlQueueSize - urlQueue.size()).arg (m_urlQueueSize)); - } else { - uploadTimer->stop(); - } + 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 () { - urlQueue.clear (); + spot_queue_.clear (); for (auto& request : m_outstandingRequests) { request->abort (); } - m_urlQueueSize = 0; } diff --git a/Network/wsprnet.h b/Network/wsprnet.h index d712d527..29e5e58f 100644 --- a/Network/wsprnet.h +++ b/Network/wsprnet.h @@ -2,45 +2,58 @@ #define WSPRNET_H #include <QObject> +#include <QTimer> #include <QString> #include <QList> -#include <QHash> +#include <QUrlQuery> #include <QQueue> class QNetworkAccessManager; -class QTimer; class QNetworkReply; class WSPRNet : public QObject { - Q_OBJECT; + Q_OBJECT -public: - explicit WSPRNet(QNetworkAccessManager *, QObject *parent = nullptr); - void upload(QString const& call, QString const& grid, QString const& rfreq, QString const& tfreq, - QString const& mode, QString const& tpct, QString const& dbm, QString const& version, - QString const& fileName); - static bool decodeLine(QString const& line, QHash<QString,QString> &query); + 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); + void uploadStatus (QString); public slots: - void networkReply(QNetworkReply *); - void work(); - void abortOutstandingRequests (); + void networkReply (QNetworkReply *); + void work (); + void abortOutstandingRequests (); private: - QNetworkAccessManager *networkManager; - QList<QNetworkReply *> m_outstandingRequests; - QString m_call, m_grid, m_rfreq, m_tfreq, m_mode, m_tpct, m_dbm, m_vers, m_file; - QQueue<QString> urlQueue; - QTimer *uploadTimer; - int m_urlQueueSize; - int m_uploadType; - - QString urlEncodeNoSpot(); - QString urlEncodeSpot(QHash<QString,QString> const& spot); + bool decodeLine (QString const& line, SpotQueue::value_type& query); + SpotQueue::value_type urlEncodeNoSpot (); + SpotQueue::value_type urlEncodeSpot (SpotQueue::value_type& spot); + + 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 |
