1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
|
// Interface to WSPRnet website
//
// by Edson Pereira - PY2SDR
#include "wsprnet.h"
#include <cmath>
#include <limits>
#include <QTimer>
#include <QFile>
#include <QRegExp>
#include <QRegularExpression>
#include <QNetworkAccessManager>
#include <QNetworkRequest>
#include <QNetworkReply>
#include <QUrl>
#include <QDebug>
#include <QtGlobal>
#include <QCryptographicHash>
#if QT_VERSION >= QT_VERSION_CHECK (5, 10, 0)
#include <QRandomGenerator>
#endif
#include "moc_wsprnet.cpp"
namespace
{
class QNetworkAccessManagerTransport final
: public QObject
, public WSPRNet::Transport
{
public:
explicit QNetworkAccessManagerTransport (QObject *parent = nullptr)
: QObject {parent}
, network_manager_ {new QNetworkAccessManager {this}}
{
}
QNetworkReply *post (QNetworkRequest const& request, QByteArray const& body) override
{
#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
return network_manager_->post (request, body);
}
private:
QNetworkAccessManager * network_manager_;
};
char const * const wsprNetUrl = "http://wsprnet.org/post/";
char const * const wsprNetUrl2 = "http://wsprnet.eu:3000/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(QObject *parent)
: WSPRNet {nullptr, RetryPolicy {}, false, parent}
{
}
WSPRNet::WSPRNet (Transport *transport, RetryPolicy retry_policy,
bool take_transport_ownership, QObject *parent)
: QObject {parent}
, transport_ {transport ? transport : new QNetworkAccessManagerTransport {this}}
, owns_transport_ {transport && take_transport_ownership}
, retry_policy_ {retry_policy}
, TR_period_ {0.F}
, uploads_started_ {0}
, next_file_batch_id_ {1}
, next_logical_upload_id_ {1}
, upload_session_active_ {false}
{
upload_timer_.setSingleShot (true);
connect (&upload_timer_, &QTimer::timeout, this, &WSPRNet::work);
}
WSPRNet::~WSPRNet ()
{
if (owns_transport_)
{
delete transport_;
}
}
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)
{
StationContext context {call, grid, rfreq, tfreq, mode, TR_period, tpct, dbm, version};
queueWsprFile (context, fileName);
flush (context);
}
void WSPRNet::queueWsprFile (StationContext const& context, QString const& file_name)
{
applyContext (context);
auto const snapshot = snapshotFile (file_name);
auto const file_batch_id = beginFileBatch (snapshot);
QFile wsprdOutFile (file_name);
if (!wsprdOutFile.open (QIODevice::ReadOnly | QIODevice::Text) || !wsprdOutFile.size ())
{
enqueueUpload (urlEncodeNoSpot (), UploadSource::File, PayloadKind::Status, file_name, file_batch_id);
}
else
{
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
{
enqueueUpload (urlEncodeSpot (query), UploadSource::File, PayloadKind::Spot, file_name, file_batch_id);
}
}
}
}
if (file_uploads_.value (file_batch_id).total == 0)
{
file_uploads_.remove (file_batch_id);
}
}
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)
{
StationContext context {call, grid, rfreq, tfreq, mode, TR_period, tpct, dbm, version};
if (!decode_text.size ())
{
flush (context);
}
else
{
queueFst4wDecode (context, decode_text);
}
}
void WSPRNet::queueFst4wDecode (StationContext const& context, QString const& decode_text)
{
applyContext (context);
auto const& match = fst4_re.match (decode_text);
if (match.hasMatch ())
{
SpotQueue::value_type query;
auto tqrg = match.captured ("freq").toInt ();
query.addQueryItem ("function", "wspr");
// FST4W reports are intentionally not constrained to WSPR sub-bands.
auto const& date = QDateTime::currentDateTimeUtc ().addSecs (-context.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 (context.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"));
enqueueUpload (urlEncodeSpot (query), UploadSource::Direct, PayloadKind::Spot);
}
}
void WSPRNet::flush (StationContext const& context)
{
applyContext (context);
if (pending_primary_uploads_.isEmpty () && !hasOutstanding (UploadTarget::Primary))
{
enqueueUpload (urlEncodeNoSpot (), UploadSource::Direct, PayloadKind::Status);
}
startUploadSession ();
}
void WSPRNet::applyContext (StationContext const& context)
{
m_call = context.call;
m_grid = context.grid;
m_rfreq = context.rfreq;
m_tfreq = context.tfreq;
m_mode = context.mode;
TR_period_ = context.TR_period;
m_tpct = context.tpct;
m_dbm = context.dbm;
m_vers = context.version;
}
auto WSPRNet::snapshotFile (QString const& file_name) const -> FileSnapshot
{
FileSnapshot snapshot;
snapshot.path = file_name;
QFile file {file_name};
if (!file.open (QIODevice::ReadOnly))
{
return snapshot;
}
auto const contents = file.readAll ();
snapshot.size = contents.size ();
snapshot.hash = QCryptographicHash::hash (contents, QCryptographicHash::Sha256);
return snapshot;
}
bool WSPRNet::fileMatchesSnapshot (FileSnapshot const& snapshot) const
{
if (snapshot.path.isEmpty () || snapshot.size < 0)
{
return false;
}
QFile file {snapshot.path};
if (!file.open (QIODevice::ReadOnly))
{
return false;
}
auto const contents = file.readAll ();
if (contents.size () != snapshot.size)
{
return false;
}
return QCryptographicHash::hash (contents, QCryptographicHash::Sha256) == snapshot.hash;
}
bool WSPRNet::hasPendingFileLeg (int file_batch_id, int logical_upload_id) const
{
auto is_file_leg = [file_batch_id, logical_upload_id](PendingUpload const& upload)
{
return UploadSource::File == upload.source
&& upload.file_batch_id == file_batch_id
&& upload.logical_upload_id == logical_upload_id;
};
for (auto const& upload : pending_primary_uploads_)
{
if (is_file_leg (upload))
{
return true;
}
}
for (auto const& upload : pending_alternate_uploads_)
{
if (is_file_leg (upload))
{
return true;
}
}
for (auto const& upload : outstanding_requests_)
{
if (is_file_leg (upload))
{
return true;
}
}
return false;
}
bool WSPRNet::hasOutstanding (UploadTarget target) const
{
for (auto const& upload : outstanding_requests_)
{
if (upload.target == target)
{
return true;
}
}
return false;
}
void WSPRNet::networkReply (QNetworkReply * reply)
{
if (!outstanding_requests_.contains (reply))
{
reply->deleteLater ();
return;
}
auto upload = outstanding_requests_.take (reply);
QString server_response;
if (replyAccepted (upload, reply, server_response))
{
markAccepted (upload);
}
else
{
auto const now = QDateTime::currentDateTimeUtc ();
if (QNetworkReply::NoError != reply->error ())
{
Q_EMIT uploadStatus (QString {"Error: %1"}.arg (reply->errorString ()));
}
else
{
Q_EMIT uploadStatus (QString {"Upload Failed: %1"}.arg (server_response));
}
auto const retry_delay_ms = retryDelayMs (upload);
if (canRetry (upload, now, retry_delay_ms))
{
retryUpload (upload, now, retry_delay_ms);
}
else
{
markFailed (upload);
}
}
qDebug () << QString {"WSPRnet.org %1 outstanding requests"}.arg (outstanding_requests_.size ());
// delete request object instance on return to the event loop otherwise it is leaked
reply->deleteLater ();
scheduleWork ();
maybeFinalize ();
}
void WSPRNet::enqueueUpload (QUrlQuery const& query, UploadSource source, PayloadKind kind, QString const& source_file, int file_batch_id)
{
auto const now = QDateTime::currentDateTimeUtc ();
auto const logical_upload_id = UploadSource::File == source ? next_logical_upload_id_++ : 0;
if (UploadSource::File == source)
{
auto& state = file_uploads_[file_batch_id];
++state.total;
}
auto enqueue_for_target = [this, &query, source, kind, &source_file, file_batch_id,
logical_upload_id, now](UploadTarget target)
{
auto& uploads = target == UploadTarget::Primary
? pending_primary_uploads_ : pending_alternate_uploads_;
uploads.enqueue ({query, source, kind, source_file, file_batch_id, now,
now.addMSecs (retry_policy_.ttl_ms), now, 0, target,
logical_upload_id});
};
enqueue_for_target (UploadTarget::Primary);
if (PayloadKind::Spot == kind
&& !query.queryItemValue ("tgrid", QUrl::FullyDecoded).isEmpty ())
{
enqueue_for_target (UploadTarget::Alternate);
}
pruneExpiredUploads (now);
enforcePendingLimit ();
}
int WSPRNet::beginFileBatch (FileSnapshot const& snapshot)
{
auto const file_batch_id = next_file_batch_id_++;
auto& state = file_uploads_[file_batch_id];
state.snapshot = snapshot;
return file_batch_id;
}
void WSPRNet::startUploadSession ()
{
upload_session_active_ = true;
uploads_started_ = outstanding_requests_.size ();
scheduleWork ();
maybeFinalize ();
}
void WSPRNet::scheduleWork ()
{
if (!upload_session_active_)
{
return;
}
auto const now = QDateTime::currentDateTimeUtc ();
pruneExpiredUploads (now);
QDateTime next_attempt_at;
auto have_next_attempt = false;
auto consider_queue = [this, &next_attempt_at, &have_next_attempt]
(QQueue<PendingUpload> const& uploads, UploadTarget target)
{
if (hasOutstanding (target))
{
return;
}
for (auto const& upload : uploads)
{
if (!have_next_attempt || upload.next_attempt_at < next_attempt_at)
{
next_attempt_at = upload.next_attempt_at;
have_next_attempt = true;
}
}
};
consider_queue (pending_primary_uploads_, UploadTarget::Primary);
consider_queue (pending_alternate_uploads_, UploadTarget::Alternate);
if (!have_next_attempt)
{
upload_timer_.stop ();
return;
}
auto const delay = qMax<qint64> (0, now.msecsTo (next_attempt_at));
upload_timer_.start (static_cast<int> (qMin<qint64> (delay, std::numeric_limits<int>::max ())));
}
void WSPRNet::pruneExpiredUploads (QDateTime const& now)
{
int dropped = 0;
auto prune_queue = [this, &now, &dropped](QQueue<PendingUpload>& uploads)
{
for (int i = 0; i < uploads.size ();)
{
if (uploads[i].expires_at <= now)
{
markFailed (uploads.takeAt (i));
++dropped;
}
else
{
++i;
}
}
};
prune_queue (pending_primary_uploads_);
prune_queue (pending_alternate_uploads_);
if (dropped)
{
Q_EMIT uploadStatus (QString {"Dropped %1 expired WSPRNet upload(s)"}.arg (dropped));
}
}
void WSPRNet::enforcePendingLimit ()
{
auto const max_pending = qMax (1, retry_policy_.max_pending);
auto const now = QDateTime::currentDateTimeUtc ();
pruneExpiredUploads (now);
int dropped = 0;
auto enforce_queue_limit = [this, max_pending, &dropped](QQueue<PendingUpload>& uploads)
{
while (uploads.size () > max_pending)
{
markFailed (uploads.dequeue ());
++dropped;
}
};
enforce_queue_limit (pending_primary_uploads_);
enforce_queue_limit (pending_alternate_uploads_);
if (dropped)
{
Q_EMIT uploadStatus (QString {"Dropped %1 oldest pending WSPRNet upload(s)"}.arg (dropped));
}
}
void WSPRNet::sendUpload (PendingUpload upload)
{
auto const url = upload.target == UploadTarget::Primary ? wsprNetUrl : wsprNetUrl2;
QNetworkRequest request (QUrl {url});
request.setHeader (QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");
if (!upload.attempts)
{
++uploads_started_;
}
++upload.attempts;
QNetworkReply *reply = transport_->post (request, upload.query.query (QUrl::FullyEncoded).toUtf8 ());
connect (reply, &QNetworkReply::finished, this, [this, reply]() { networkReply (reply); });
outstanding_requests_.insert (reply, upload);
Q_EMIT uploadStatus (QString {"Uploading Spot %1/%2"}.arg (uploads_started_).arg (uploadsToSend ()));
}
bool WSPRNet::replyAccepted (PendingUpload const& upload, QNetworkReply *reply, QString& server_response) const
{
if (QNetworkReply::NoError != reply->error ())
{
return false;
}
server_response = reply->readAll ();
return PayloadKind::Status == upload.kind
|| server_response.contains (QRegExp ("spot\\(s\\) added"));
}
bool WSPRNet::canRetry (PendingUpload const& upload, QDateTime const& now, int retry_delay_ms) const
{
return upload.attempts < retry_policy_.max_attempts
&& now.addMSecs (retry_delay_ms) < upload.expires_at;
}
int WSPRNet::retryDelayMs (PendingUpload const& upload) const
{
int delay = 0;
if (!retry_policy_.retry_delays_ms.isEmpty ())
{
auto const index = qMin (upload.attempts - 1, retry_policy_.retry_delays_ms.size () - 1);
delay = retry_policy_.retry_delays_ms[qMax (0, index)];
}
if (delay <= 0 || retry_policy_.jitter_fraction <= 0.)
{
return qMax (0, delay);
}
#if QT_VERSION >= QT_VERSION_CHECK (5, 10, 0)
auto const random = QRandomGenerator::global ()->generateDouble ();
#else
auto const random = qrand () / (RAND_MAX + 1.0);
#endif
auto const factor = 1. - retry_policy_.jitter_fraction
+ random * retry_policy_.jitter_fraction * 2.;
return qMax (0, static_cast<int> (delay * factor));
}
int WSPRNet::uploadsToSend () const
{
auto total = uploads_started_;
auto count_unstarted = [&total](QQueue<PendingUpload> const& uploads)
{
for (auto const& upload : uploads)
{
if (!upload.attempts)
{
++total;
}
}
};
count_unstarted (pending_primary_uploads_);
count_unstarted (pending_alternate_uploads_);
return qMax (uploads_started_, total);
}
void WSPRNet::retryUpload (PendingUpload upload, QDateTime const& now, int retry_delay_ms)
{
upload.next_attempt_at = now.addMSecs (retry_delay_ms);
auto& uploads = upload.target == UploadTarget::Primary
? pending_primary_uploads_ : pending_alternate_uploads_;
uploads.enqueue (upload);
Q_EMIT uploadStatus (QString {"Retrying WSPRNet upload in %1 ms"}.arg (retry_delay_ms));
enforcePendingLimit ();
}
void WSPRNet::markAccepted (PendingUpload const& upload)
{
if (UploadSource::File == upload.source)
{
auto state = file_uploads_.find (upload.file_batch_id);
if (state == file_uploads_.end ())
{
return;
}
state->accepted.insert (upload.logical_upload_id);
state->failed.remove (upload.logical_upload_id);
maybeRemoveCompletedFile (upload.file_batch_id);
maybeRemoveFailedFileBatch (upload.file_batch_id);
}
}
void WSPRNet::markFailed (PendingUpload const& upload)
{
if (UploadSource::File == upload.source)
{
auto state = file_uploads_.find (upload.file_batch_id);
if (state == file_uploads_.end () || state->accepted.contains (upload.logical_upload_id))
{
return;
}
if (!hasPendingFileLeg (upload.file_batch_id, upload.logical_upload_id))
{
state->failed.insert (upload.logical_upload_id);
}
maybeRemoveFailedFileBatch (upload.file_batch_id);
}
}
void WSPRNet::maybeRemoveFailedFileBatch (int file_batch_id)
{
auto const state = file_uploads_.constFind (file_batch_id);
if (state == file_uploads_.constEnd () || state->failed.isEmpty ())
{
return;
}
if (state->accepted.size () + state->failed.size () >= state->total)
{
file_uploads_.remove (file_batch_id);
}
}
void WSPRNet::maybeRemoveCompletedFile (int file_batch_id)
{
if (!file_uploads_.contains (file_batch_id))
{
return;
}
auto const state = file_uploads_.value (file_batch_id);
if (state.total > 0 && state.accepted.size () == state.total)
{
QFile f {state.snapshot.path};
// wsprd can rewrite this scratch file between the check and remove.
// The snapshot guard prevents deleting known-new contents.
if (f.exists () && fileMatchesSnapshot (state.snapshot))
{
f.remove ();
}
file_uploads_.remove (file_batch_id);
}
}
void WSPRNet::maybeFinalize ()
{
if (!upload_session_active_)
{
return;
}
if (pending_primary_uploads_.isEmpty () && pending_alternate_uploads_.isEmpty ()
&& outstanding_requests_.isEmpty ())
{
uploads_started_ = 0;
upload_session_active_ = false;
upload_timer_.stop ();
Q_EMIT uploadStatus ("done");
}
}
bool WSPRNet::decodeLine (QString const& line, SpotQueue::value_type& query) const
{
auto const& rx_match = wspr_re.match (line);
if (rx_match.hasMatch ()) {
if (line.contains ("<...>")) {
return false;
}
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()
{
auto const now = QDateTime::currentDateTimeUtc ();
pruneExpiredUploads (now);
auto send_ready_upload = [this, &now](QQueue<PendingUpload>& uploads, UploadTarget target)
{
if (hasOutstanding (target))
{
return;
}
for (int i = 0; i < uploads.size (); ++i)
{
if (uploads[i].next_attempt_at <= now)
{
sendUpload (uploads.takeAt (i));
return;
}
}
};
send_ready_upload (pending_primary_uploads_, UploadTarget::Primary);
send_ready_upload (pending_alternate_uploads_, UploadTarget::Alternate);
scheduleWork ();
maybeFinalize ();
}
void WSPRNet::abortOutstandingRequests () {
upload_timer_.stop ();
pending_primary_uploads_.clear ();
pending_alternate_uploads_.clear ();
file_uploads_.clear ();
uploads_started_ = 0;
upload_session_active_ = false;
auto const requests = outstanding_requests_.keys ();
outstanding_requests_.clear ();
for (auto& request : requests) {
request->abort ();
}
}
|