-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwifi.cpp
More file actions
2507 lines (2096 loc) · 79.2 KB
/
wifi.cpp
File metadata and controls
2507 lines (2096 loc) · 79.2 KB
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
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* manage most wifi uses, including pane and map updates.
*/
#include "HamClock.h"
// host name and port of backend server
const char *backend_host = "clearskyinstitute.com";
int backend_port = 80;
// IP where server thinks we came from
char remote_addr[16]; // INET_ADDRSTRLEN
// user's date and time, UNIX only
time_t usr_datetime;
// ADIF pane
#define ADIF_INTERVAL 2 // polling interval, secs
// DX Cluster update
#define DXC_INTERVAL 1 // update interval, secs
// env sensor
#define ENV_INTERVAL 20 // update interval, secs
// SDO own rotation period when panes are not rotating
#define SDO_INTERVAL 60 // update interval, secs
// band conditions and voacap map, models change each hour
uint16_t bc_powers[] = {1, 5, 10, 50, 100, 500, 1000};
const int n_bc_powers = NARRAY(bc_powers);
static const char bc_page[] = "/fetchBandConditions.pl";
static time_t bc_time; // nowWO() when bc_matrix was loaded
BandCdtnMatrix bc_matrix; // percentage reliability for each band
uint16_t bc_power; // VOACAP power setting
float bc_toa; // VOACAP take off angle
uint8_t bc_utc_tl; // label band conditions timeline in utc else DE local
uint8_t bc_modevalue; // VOACAP sensitivity value
// N.B. these must match the tables in fetchBandConditions.pl etc
const BCModeSetting bc_modes[N_BCMODES] {
{"CW", 19},
{"RTTY", 22},
{"SSB", 38},
{"AM", 49},
{"WSPR", 3},
{"FT8", 13},
{"FT4", 17}
};
uint8_t findBCModeValue (const char *name) // find value give name, else 0
{
for (int i = 0; i < N_BCMODES; i++)
if (strcmp (name, bc_modes[i].name) == 0)
return (bc_modes[i].value);
return (0);
}
const char *findBCModeName (uint8_t value) // find name given value, else NULL
{
for (int i = 0; i < N_BCMODES; i++)
if (bc_modes[i].value == value)
return (bc_modes[i].name);
return (NULL);
}
// geolocation web page
static const char locip_page[] = "/fetchIPGeoloc.pl";
// moon display
#define MOON_INTERVAL 50 // annotation update interval, secs
// list of default NTP servers unless user has set their own
static NTPServer ntp_list[] = { // init times to 0 insures all get tried initially
{"time.google.com", NTP_TOO_LONG},
{"time.apple.com", NTP_TOO_LONG},
{"pool.ntp.org", NTP_TOO_LONG},
{"europe.pool.ntp.org", NTP_TOO_LONG},
{"asia.pool.ntp.org", NTP_TOO_LONG},
{"time.nist.gov", NTP_TOO_LONG},
};
#define N_NTP NARRAY(ntp_list) // number of possible servers
// web site retry interval and max, secs
#define WIFI_RETRY (15)
#define WIFI_MAXRETRY (5*60)
/* "reverting" refers to restoring PANE_1 after temporarily forced to show DE or DX weather.
*/
static time_t revert_time; // when to resume normal pane operation
static PlotPane revert_pane; // which pane is being temporarily reverted
/* rotation time control.
* 0 will refresh immediately.
* reset all in initWiFiRetry()
*/
static time_t next_rotation[PANE_N]; // next pane rotation
time_t next_update[PANE_N]; // next function call
static time_t next_map; // next map check
static time_t map_time; // nowWO() when map was loaded
static bool fresh_redraw[PLOT_CH_N]; // whether full pane redraw is required
/* return absolute difference in two time_t regardless of time_t implementation is signed or unsigned.
*/
static time_t tdiff (const time_t t1, const time_t t2)
{
if (t1 > t2)
return (t1 - t2);
if (t2 > t1)
return (t2 - t1);
return (0);
}
/* return the next retry time_t.
* retries are spaced out every WIFI_RETRY but never more than WIFI_MAXRETRY
*/
static time_t nextWiFiRetry (void)
{
// set and save next retry time
static time_t prev_try;
time_t now = myNow();
time_t next_t0 = now + WIFI_RETRY; // basic interval after now
time_t next_try = prev_try + WIFI_RETRY; // interval extension after prev
if (next_try > now + WIFI_MAXRETRY)
next_try = now + WIFI_MAXRETRY; // but clamp to WIFI_MAXRETRY
prev_try = next_try > next_t0 ? next_try : next_t0; // use whichever is later
return (prev_try);
}
/* calls nextWiFiRetry() and logs the given string
*/
time_t nextWiFiRetry (const char *str)
{
time_t next_try = nextWiFiRetry();
int dt = next_try - myNow();
int nm = millis()/1000+dt;
Serial.printf ("Next %s retry in %d sec at %d\n", str, dt, nm);
return (next_try);
}
/* calls nextWiFiRetry() and logs the given plot choice.
*/
time_t nextWiFiRetry (PlotChoice pc)
{
return (nextWiFiRetry (plot_names[pc]));
}
/* given a plot choice return time of its next update.
* if choice is in play and rotating use pane rotation time else the given interval.
*/
static time_t nextPaneUpdate (PlotChoice pc, int interval)
{
PlotPane pp = findPaneForChoice (pc);
if (pp == PANE_NONE)
fatalError ("nextPaneUpdate %s PANE_NONE", plot_names[pc]);
time_t t0 = myNow();
time_t next = t0 + interval;
int dt = next - t0;
int at = millis()/1000+dt;
if (interval > 60)
Serial.printf ("Pane %d now showing %s updates in %d sec at %d\n", pp, plot_names[pc], dt, at);
return (next);
}
/* return time of next rotation for pane pp or brb_next_update if pp == PANE_NONE.
*/
time_t nextRotation (PlotPane pp)
{
// find latest of all currently scheduled rotations
time_t latest_rot = 0;
for (int i = 0; i < PANE_N; i++)
if ((isPaneRotating(pp) || isSpecialPaneRotating(pp)) && next_rotation[i] > latest_rot)
latest_rot = next_rotation[i];
if (BRBIsRotating() && brb_next_update > latest_rot)
latest_rot = brb_next_update;
// bring up to present if all old
time_t t0 = myNow();
if (latest_rot < t0)
latest_rot = t0;
// next rotation follows
time_t next_rot;
if (pp == PANE_NONE) {
next_rot = brb_next_update = latest_rot + ROTATION_INTERVAL;
int dt = next_rot - t0;
if (dt > 5) { // reduce mog noise when rotating quickly
int at = millis()/1000+dt;
if (BRBIsRotating())
Serial.printf ("BRB: next rotation in %d sec at %d\n", dt, at);
else
Serial.printf ("BRB: next update in %d sec at %d\n", dt, at);
}
} else {
next_rot = next_rotation[pp] = latest_rot + ROTATION_INTERVAL;
int dt = next_rot - t0;
if (dt > 5) { // reduce mog noise when rotating quickly
int at = millis()/1000+dt;
Serial.printf ("Pane %d now %s next rotation in %d sec at %d\n", pp, plot_names[plot_ch[pp]],
dt, at);
}
}
return (next_rot);
}
/* set de_ll.lat_d and de_ll.lng_d from the given ip else our public ip.
* report status via tftMsg
*/
static void geolocateIP (const char *ip)
{
WiFiClient iploc_client; // wifi client connection
float lat, lng;
char llline[80];
char ipline[80];
char credline[80];
int nlines = 0;
if (iploc_client.connect(backend_host, backend_port)) {
// create proper query
strcpy (llline, locip_page);
size_t l = sizeof(locip_page) - 1; // not EOS
if (ip) // else locip_page will use client IP
l += snprintf (llline+l, sizeof(llline)-l, "?IP=%s", ip);
Serial.println(llline);
// send
httpHCGET (iploc_client, backend_host, llline);
if (!httpSkipHeader (iploc_client)) {
Serial.println ("geoIP header short");
goto out;
}
// expect 4 lines: LAT=, LNG=, IP= and CREDIT=, anything else first line is error message
if (!getTCPLine (iploc_client, llline, sizeof(llline), NULL))
goto out;
nlines++;
lat = atof (llline+4);
if (!getTCPLine (iploc_client, llline, sizeof(llline), NULL))
goto out;
nlines++;
lng = atof (llline+4);
if (!getTCPLine (iploc_client, ipline, sizeof(ipline), NULL))
goto out;
nlines++;
if (!getTCPLine (iploc_client, credline, sizeof(credline), NULL))
goto out;
nlines++;
}
out:
if (nlines == 4) {
// ok
tftMsg (true, 0, "IP %s geolocation", ipline+3);
tftMsg (true, 0, " by %s", credline+7);
tftMsg (true, 0, " %.2f%c %.2f%c", fabsf(lat), lat < 0 ? 'S' : 'N',
fabsf(lng), lng < 0 ? 'W' : 'E');
de_ll.lat_d = lat;
de_ll.lng_d = lng;
de_ll.normalize();
NVWriteFloat (NV_DE_LAT, de_ll.lat_d);
NVWriteFloat (NV_DE_LNG, de_ll.lng_d);
setNVMaidenhead (NV_DE_GRID, de_ll);
setTZAuto (de_tz);
NVWriteTZ (NV_DE_TZ, de_tz);
} else {
// trouble, error message if 1 line
if (nlines == 1) {
tftMsg (true, 0, "IP geolocation err:");
tftMsg (true, 1000, " %s", llline);
} else
tftMsg (true, 1000, "IP geolocation failed");
}
iploc_client.stop();
}
/* return best ntp server.
* if user has set their own then always return that one;
* else search ntp_list for the fastest so far, if all look bad then just roll through.
* N.B. never return NULL
*/
NTPServer *findBestNTP()
{
static NTPServer user_server;
static uint8_t prev_fixed;
// user's first
if (useLocalNTPHost()) {
user_server.server = getLocalNTPHost();
return (&user_server);
}
// else look through ntp_list
NTPServer *best_ntp = &ntp_list[0];
int rsp_min = ntp_list[0].rsp_time;
for (int i = 1; i < N_NTP; i++) {
NTPServer *np = &ntp_list[i];
if (np->rsp_time < rsp_min) {
best_ntp = np;
rsp_min = np->rsp_time;
}
}
// if nothing good there just roll through
if (rsp_min == NTP_TOO_LONG) {
prev_fixed = (prev_fixed+1) % N_NTP;
best_ntp = &ntp_list[prev_fixed];
}
return (best_ntp);
}
/* init and connect, inform via tftMsg() if verbose.
* non-verbose is used for automatic retries that should not clobber the display.
*/
static void initWiFi (bool verbose)
{
// N.B. look at the usages and make sure this is "big enough"
static const char dots[] = ".........................................";
// probable mac when only localhost -- used to detect LAN but no WLAN
const char *mac_lh = "FF:FF:FF:FF:FF:FF";
// begin
// N.B. ESP seems to reconnect much faster if avoid begin() unless creds change
// N.B. non-RPi UNIX systems return NULL from getWiFI*()
WiFi.mode(WIFI_STA);
const char *myssid = getWiFiSSID();
const char *mypw = getWiFiPW();
if (myssid && mypw && (strcmp (WiFi.SSID().c_str(), myssid) || strcmp (WiFi.psk().c_str(), mypw)))
WiFi.begin ((char*)myssid, (char*)mypw);
// prep
uint32_t t0 = millis();
uint32_t timeout = verbose ? 30000UL : 3000UL; // dont wait nearly as long for a retry, millis
uint16_t ndots = 0; // progress counter
char mac[30];
strcpy (mac, WiFi.macAddress().c_str());
tftMsg (verbose, 0, "MAC addr: %s", mac);
// wait for connection
if (myssid)
tftMsg (verbose, 0, "\r"); // init overwrite
do {
if (myssid)
tftMsg (verbose, 0, "Connecting to %s %.*s\r", myssid, ndots, dots);
Serial.printf ("Trying network %d\n", ndots);
if (timesUp(&t0,timeout) || ndots == (sizeof(dots)-1)) {
if (myssid)
tftMsg (verbose, 1000, "WiFi failed -- signal? credentials?");
else
tftMsg (verbose, 1000, "Network connection attempt failed");
return;
}
wdDelay(1000);
ndots++;
// WiFi.printDiag(Serial);
} while (strcmp (mac, mac_lh) && (WiFi.status() != WL_CONNECTED));
// init retry times
initWiFiRetry();
// report stats
if (WiFi.status() == WL_CONNECTED) {
// just to get remote_addr
char line[50];
(void)newVersionIsAvailable (line, sizeof(line));
IPAddress ip = WiFi.localIP();
tftMsg (verbose, 0, "Local IP: %d.%d.%d.%d", ip[0], ip[1], ip[2], ip[3]);
tftMsg (verbose, 0, "Public IP: %s", remote_addr);
ip = WiFi.subnetMask();
tftMsg (verbose, 0, "Mask: %d.%d.%d.%d", ip[0], ip[1], ip[2], ip[3]);
ip = WiFi.gatewayIP();
tftMsg (verbose, 0, "GW: %d.%d.%d.%d", ip[0], ip[1], ip[2], ip[3]);
ip = WiFi.dnsIP();
tftMsg (verbose, 0, "DNS: %d.%d.%d.%d", ip[0], ip[1], ip[2], ip[3]);
int rssi;
bool is_dbm;
if (readWiFiRSSI(rssi,is_dbm)) {
tftMsg (verbose, 0, "Signal strength: %d %s", rssi, is_dbm ? "dBm" : "%");
tftMsg (verbose, 0, "Channel: %d", WiFi.channel());
}
tftMsg (verbose, 0, "S/N: %u", ESP.getChipId());
}
}
/* call exactly once to init wifi, maps and maybe time and location.
* report on initial startup screen with tftMsg.
*/
void initSys()
{
// "Skip" tooltip text
static const char skip_ttt[] = "click to proceed immediately to HamClock";
// insure core_map is defined -- N.B. before initWiFi calls sendUserAgent()
initCoreMaps();
// start/check WLAN
initWiFi(true);
// start web servers
initWebServer();
initLiveWeb(true);
// init location if desired
if (useGeoIP() || init_iploc || init_locip) {
if (WiFi.status() == WL_CONNECTED)
geolocateIP (init_locip);
else
tftMsg (true, 0, "no network for geo IP");
} else if (useGPSDLoc()) {
LatLong ll;
if (getGPSDLatLong(&ll)) {
// good -- set de_ll
de_ll = ll;
de_ll.normalize();
NVWriteFloat (NV_DE_LAT, de_ll.lat_d);
NVWriteFloat (NV_DE_LNG, de_ll.lng_d);
setNVMaidenhead(NV_DE_GRID, de_ll);
// leave user's tz offset
// de_tz.tz_secs = getTZ (de_ll);
// NVWriteInt32(NV_DE_TZ, de_tz.tz_secs);
tftMsg (true, 0, "GPSD: %.2f%c %.2f%c",
fabsf(de_ll.lat_d), de_ll.lat_d < 0 ? 'S' : 'N',
fabsf(de_ll.lng_d), de_ll.lng_d < 0 ? 'W' : 'E');
} else
tftMsg (true, 1000, "GPSD: no Lat/Long");
} else if (useNMEALoc()) {
LatLong ll;
if (getNMEALatLong(ll)) {
// good -- set de_ll
de_ll = ll;
de_ll.normalize();
NVWriteFloat (NV_DE_LAT, de_ll.lat_d);
NVWriteFloat (NV_DE_LNG, de_ll.lng_d);
setNVMaidenhead(NV_DE_GRID, de_ll);
// leave user's tz offset
// de_tz.tz_secs = getTZ (de_ll);
// NVWriteInt32(NV_DE_TZ, de_tz.tz_secs);
tftMsg (true, 0, "NMEA: %.2f%c %.2f%c",
fabsf(de_ll.lat_d), de_ll.lat_d < 0 ? 'S' : 'N',
fabsf(de_ll.lng_d), de_ll.lng_d < 0 ? 'W' : 'E');
} else
tftMsg (true, 1000, "NMEA: no Lat/Long");
}
// skip box
selectFontStyle (LIGHT_FONT, SMALL_FONT);
drawStringInBox ("Skip", skip_b, false, RA8875_WHITE);
bool skipped_here = false;
// init time service as desired
if (useGPSDTime()) {
if (getGPSDUTC())
tftMsg (true, 0, "GPSD: time ok");
else
tftMsg (true, 1000, "GPSD: no time");
} else if (useNMEATime()) {
if (getNMEAUTC())
tftMsg (true, 0, "NMEA: time ok");
else
tftMsg (true, 1000, "NMEA: no time");
} else if (useOSTime()) {
tftMsg (true, 0, "Time is from computer");
} else if (WiFi.status() == WL_CONNECTED) {
if (useLocalNTPHost()) {
// test user choice
NTPServer *user_ntp = findBestNTP(); // will always return user's ntp
if (getNTPUTC(user_ntp))
tftMsg (true, 0, "NTP %s: %d ms\r", user_ntp->server, user_ntp->rsp_time);
else
tftMsg (true, 0, "NTP %s: fail\r", user_ntp->server);
} else {
// try all the NTP servers to find the fastest (with sneaky way out)
SCoord s;
drainTouch();
tftMsg (true, 0, "Finding best NTP ...");
NTPServer *best_ntp = NULL;
for (int i = 0; i < N_NTP; i++) {
NTPServer *np = &ntp_list[i];
// measure the next. N.B. assumes we stay in sync
if (getNTPUTC(np) == 0)
tftMsg (true, 0, "%s: err\r", np->server);
else {
tftMsg (true, 0, "%s: %d ms\r", np->server, np->rsp_time);
if (!best_ntp || np->rsp_time < best_ntp->rsp_time)
best_ntp = np;
}
// cancel scan if found at least one good and tapped or typed
TouchType tt = TT_NONE;
if (best_ntp && (skip_skip || tft.getChar(NULL,NULL)
|| ((tt = readCalTouchWS(s)) != TT_NONE && inBox (s, skip_b)))) {
if (tt == TT_TAP_BX)
tooltip (s, skip_ttt);
else {
drawStringInBox ("Skip", skip_b, true, RA8875_WHITE);
Serial.printf ("NTP search cancelled with %s\n", best_ntp->server);
skipped_here = true;
break;
}
}
}
if (!skip_skip)
wdDelay(800); // linger to show last time
if (best_ntp)
tftMsg (true, 0, "Best NTP: %s %d ms\r", best_ntp->server, best_ntp->rsp_time);
else
tftMsg (true, 0, "No NTP\r");
drainTouch();
}
tftMsg (true, 0, NULL); // next row
} else {
tftMsg (true, 0, "No time");
}
// go
initTime();
// track from user's time if set
if (usr_datetime > 0)
setTime (usr_datetime);
// init bc_power, bc_toa, bc_utc_tl and bc_modevalue
if (!NVReadUInt16 (NV_BCPOWER, &bc_power)) {
bc_power = 100;
NVWriteUInt16 (NV_BCPOWER, bc_power);
}
if (!NVReadFloat (NV_BCTOA, &bc_toa)) {
bc_toa = 3;
NVWriteFloat (NV_BCTOA, bc_toa);
}
if (!NVReadUInt8 (NV_BC_UTCTIMELINE, &bc_utc_tl)) {
bc_utc_tl = 0; // default to local time line
NVWriteUInt8 (NV_BC_UTCTIMELINE, bc_utc_tl);
}
if (!NVReadUInt8 (NV_BCMODE, &bc_modevalue)) {
bc_modevalue = findBCModeValue("CW"); // default to CW
NVWriteUInt8 (NV_BCMODE, bc_modevalue);
}
// init space wx
initSpaceWX();
// offer time to peruse unless alreay opted to skip
if (!skipped_here) {
#define TO_DS 50 // timeout delay, decaseconds
drawStringInBox ("Skip", skip_b, false, RA8875_WHITE);
uint8_t s_left = TO_DS/10; // seconds remaining
uint32_t t0 = millis();
drainTouch();
for (uint8_t ds_left = TO_DS; !skip_skip && ds_left > 0; --ds_left) {
SCoord s;
TouchType tt = TT_NONE;
if (tft.getChar(NULL,NULL) || ((tt = readCalTouchWS(s)) != TT_NONE && inBox(s, skip_b))) {
if (tt == TT_TAP_BX)
tooltip (s, skip_ttt);
else {
drawStringInBox ("Skip", skip_b, true, RA8875_WHITE);
break;
}
}
if ((TO_DS - (millis() - t0)/100)/10 < s_left) {
// just printing every ds_left/10 is too slow due to overhead
tftMsg (true, 0, "Ready ... %d\r", s_left--);
}
wdDelay(100);
}
}
}
/* perform the active algorithm for the given autoMap.
* turn on if passes above hi threshold and saw_lo, turn off if passes below lo threshold and saw_hi.
*/
static void doAutoMap (CoreMaps cm, float value_now, float thresh_hi, float thresh_lo)
{
CoreMapInfo &cmi = cm_info[cm];
if (value_now > thresh_hi) {
if (!cmi.saw_hi && cmi.saw_lo) {
// just went hi and came up from lo so turn on
if (IS_CMROT(cm)) {
Serial.printf ("AUTOMAP: %s already on: %g > %g > %g\n",
cmi.name, value_now, thresh_hi, thresh_lo);
} else {
Serial.printf ("AUTOMAP: turning on %s: %g > %g > %g\n",
cmi.name, value_now, thresh_hi, thresh_lo);
scheduleNewCoreMap (cm);
}
}
// update state
cmi.saw_hi = true;
cmi.saw_lo = false; // require a new transition
} else if (value_now < thresh_lo) {
if (!cmi.saw_lo && cmi.saw_hi) {
// just went lo and came down from hi so turn off but beware edge cases
if (!IS_CMROT(cm)) {
Serial.printf ("AUTOMAP: %s already off: %g < %g < %g\n",
cmi.name, value_now, thresh_lo, thresh_hi);
} else if (mapIsRotating()) {
// turn off cm but make sure there's still at least one on
RM_CMROT (cm);
insureCoreMap();
scheduleNewCoreMap (core_map);
Serial.printf ("AUTOMAP: turning off %s: %g < %g\n", cmi.name, value_now, thresh_lo);
} else {
Serial.printf ("AUTOMAP: leaving lone %s on: %g < %g < %g\n",
cmi.name, value_now, thresh_lo, thresh_hi);
}
}
// update state
cmi.saw_lo = true;
cmi.saw_hi = false; // require a new transition
}
}
/* manage maps associated with high levels of space weather indices.
*/
static void checkAutoMap()
{
// out fast if not on
if (!autoMap())
return;
DRAPData drap;
if (retrieveDRAP(drap) && space_wx[SPCWX_DRAP].value_ok)
doAutoMap (CM_DRAP, space_wx[SPCWX_DRAP].value, DRAP_AUTOMAP_ON, DRAP_AUTOMAP_OFF);
AuroraData a;
if (retrieveAurora(a) && space_wx[SPCWX_AURORA].value_ok)
doAutoMap (CM_AURORA, space_wx[SPCWX_AURORA].value, AURORA_AUTOMAP_ON, AURORA_AUTOMAP_OFF);
}
/* check if time to update background map, either rotating or stale
*/
void checkBGMap(void)
{
// check for any auto maps
checkAutoMap();
// for sure update if later than next_map; there are other reasons too
bool time_to_refresh = myNow() > next_map;
// check for rotating, but not if just scheduled
if (next_map != 0 && time_to_refresh && mapIsRotating())
rotateNextMap();
// note whether BC is up
PlotPane bc_pp = findPaneChoiceNow (PLOT_CH_BC);
bool bc_up = bc_pp != PANE_NONE && bc_matrix.ok && myNow() > revert_time;
// note whether core_map is one of the BC maps and whether it's time for it to update
bool bc_map = CM_PMACTIVE();
bool bc_now = bc_up && bc_map && tdiff(map_time,bc_time) >= 3600;
// update if time or to stay in sync with BC or it's been over an hour
if (time_to_refresh || bc_now || tdiff(nowWO(),map_time)>=3600) {
// show busy if BC up and we are updating its map
if (bc_up && bc_map)
plotBandConditions (plot_b[bc_pp], 1, NULL, NULL);
// update map, schedule next
bool ok = installFreshMaps();
if (ok) {
if (core_map == CM_DRAP)
next_map = nextMapUpdate(DRAPMAP_INTERVAL);
else if (core_map == CM_MUF_RT)
next_map = nextMapUpdate(MUF_RT_INTERVAL);
else if (bc_map)
next_map = nextMapUpdate(VOACAP_INTERVAL);
else
next_map = nextMapUpdate(OTHER_MAPS_INTERVAL);
// fresh
map_time = nowWO(); // map is now current
initEarthMap(); // restart fresh
} else {
next_map = nextWiFiRetry (cm_info[core_map].name); // schedule retry
if (bc_map)
map_time = bc_time; // match bc to avoid immediate retry
else
map_time = nowWO()+10; // avoid immediate retry
}
// show result of effort if BC up even if not now a BC map
if (bc_up)
plotBandConditions (plot_b[bc_pp], ok ? 0 : -1, NULL, NULL);
time_t dt = next_map - myNow();
Serial.printf ("Next %s map check in %ld s at %ld\n", cm_info[core_map].name,
(long)dt, (long)(millis()/1000+dt));
}
}
/* given a GOES XRAY Flux value, return its event level designation in buf.
*/
char *xrayLevel (char *buf, const SpaceWeather_t &xray)
{
if (!xray.value_ok)
strcpy (buf, "Err");
else if (xray.value < 1e-8)
strcpy (buf, "A0.0");
else {
static const char levels[] = "ABCMX";
int power = floorf(log10f(xray.value));
if (power > -4)
power = -4;
float mantissa = xray.value*powf(10.0F,-power);
char alevel = levels[8+power];
snprintf (buf, 10, "%c%.1f", alevel, mantissa);
}
return (buf);
}
/* retrieve bc_matrix and optional config line underneath PLOT_CH_BC.
* return whether at least config line was received (even if data was not)
*/
static bool retrieveBandConditions (char *config)
{
WiFiClient bc_client;
bool ok = false;
// init data unknown
bc_matrix.ok = false;
// start by cleaning cache.
// N.B. make sure search string match name we use below
(void) cleanCache ("bc-", BC_INTERVAL);
// build query
time_t t = nowWO();
char query[sizeof(bc_page) + 200];
snprintf (query, sizeof(query),
"%s?YEAR=%d&MONTH=%d&RXLAT=%.3f&RXLNG=%.3f&TXLAT=%.3f&TXLNG=%.3f&UTC=%d&PATH=%d&POW=%d&MODE=%d&TOA=%.1f",
bc_page, year(t), month(t), dx_ll.lat_d, dx_ll.lng_d, de_ll.lat_d, de_ll.lng_d,
hour(t), show_lp, bc_power, bc_modevalue, bc_toa);
// build local cache file name
char cache_fn[100];
snprintf (cache_fn, sizeof(cache_fn), "bc-%010u.txt", stringHash(query)); // N.B. see cleanCache() above
// open cache or get fresh
FILE *fp = openCachedFile (cache_fn, query, 12*3600L, 100);
if (fp) {
char buf[100];
// first line is CSV path reliability for the requested time between DX and DE, 9 bands 80-10m
if (!fgets (buf, sizeof(buf), fp)) {
Serial.println ("BC: No CSV");
goto out;
}
// next line is configuration summary, save if interested
if (!fgets (buf, sizeof(buf), fp)) {
Serial.println ("BC: No config line");
goto out;
}
if (config) {
chompString (buf);
strcpy (config, buf);
}
// transaction for at least config is ok
ok = true;
// next 24 lines are reliability matrix.
// N.B. col 1 is UTC but runs from 1 .. 24, 24 is really 0
// lines include data for 9 bands, 80-10, but we drop 60 for BandCdtnMatrix
float rel[BMTRX_COLS]; // values are path reliability 0 .. 1
for (int r = 0; r < BMTRX_ROWS; r++) {
// read next row
if (!fgets (buf, sizeof(buf), fp)) {
Serial.printf ("BC: fail row %d\n", r);
goto out;
}
// crack row, skipping 60 m
int utc_hr;
if (sscanf(buf, "%d %f,%*f,%f,%f,%f,%f,%f,%f,%f", &utc_hr,
&rel[0], &rel[1], &rel[2], &rel[3], &rel[4], &rel[5], &rel[6], &rel[7])
!= BMTRX_COLS + 1) {
Serial.printf ("BC: bad matrix line: %s\n", buf);
goto out;
}
// insure correct utc
utc_hr %= 24;
// add to bc_matrix as integer percent
for (int c = 0; c < BMTRX_COLS; c++)
bc_matrix.m[utc_hr][c] = (uint8_t)(100*rel[c]);
}
// #define _TEST_BAND_MATRIX
#if defined(_TEST_BAND_MATRIX)
for (int r = 0; r < BMTRX_ROWS; r++) // time 0 .. 23
for (int c = 0; c < BMTRX_COLS; c++) // band 80 .. 10
bc_matrix.m[r][c] = 100*r*c/BMTRX_ROWS/BMTRX_COLS;
#endif
// matrix ok
bc_matrix.ok = true;
// finished with file
fclose(fp);
} else {
Serial.println ("VOACAP connection failed");
}
out:
// out
return (ok);
}
/* convert an array of 4 big-endian network-order bytes into a uint32_t
*/
static uint32_t crackBE32 (uint8_t bp[])
{
union {
uint32_t be;
uint8_t ba[4];
} be4;
be4.ba[3] = bp[0];
be4.ba[2] = bp[1];
be4.ba[1] = bp[2];
be4.ba[0] = bp[3];
return (be4.be);
}
/* keep the NCDXF_b up to date.
* N.B. this is called often so do minimal work.
*/
static void checkBRB (time_t t)
{
// routine update of NCFDX map beacons
updateBeacons (false);
// see if it's time to rotate
if (t > brb_next_update) {
// move brb_mode to next rotset if rotating
if (BRBIsRotating()) {
for (int i = 1; i < BRB_N; i++) {
int next_mode = (brb_mode + i) % BRB_N;
if (brb_rotset & (1 << next_mode)) {
brb_mode = next_mode;
Serial.printf ("BRB: rotating to mode \"%s\"\n", brb_names[brb_mode]);
break;
}
}
}
// update brb_mode
if (drawNCDXFBox()) {
brb_next_update = nextRotation(PANE_NONE);
} else {
// trouble
brb_next_update = nextWiFiRetry("BRB");
}
} else {
// check a few that need spontaneous updating
switch (brb_mode) {
case BRB_SHOW_BME76:
case BRB_SHOW_BME77:
// only if new BME
if (newBME280data())
(void) drawNCDXFBox();
break;
case BRB_SHOW_SWSTATS:
// only if new space stats
if (checkForNewSpaceWx())
(void) drawNCDXFBox();
break;
case BRB_SHOW_DEWX:
case BRB_SHOW_DXWX:
// routine drawNCDXFBox() are enough
break;
case BRB_SHOW_PHOT:
case BRB_SHOW_BR:
// these are updated from followBrightness() in main loop()
break;
}
}
}
/* insure the given plot choice is visible in some pane by itself.
* N.B. never use PANE_0
*/
void setPlotVisible (PlotChoice pc)
{
// done if the choice is already on display
if (findPaneChoiceNow (pc) != PANE_NONE)
return;
// not on display now but maybe in rotation, else just pick one
PlotPane pp = findPaneForChoice (pc);
if (pp == PANE_NONE)
pp = PANE_3;
// install as the only choice
(void) setPlotChoice (pp, pc);
plot_rotset[pp] = 1 << pc;
savePlotOps();
}
/* set the given pane to the given plot choice now.
* return whether successful.
* N.B. we might change plot_ch but we NEVER change plot_rotset here
* N.B. it's harmless to set pane to same choice again.
*/
bool setPlotChoice (PlotPane pp, PlotChoice pc)
{
// ignore if new choice is already in some other pane
PlotPane pp_now = findPaneForChoice (pc);
if (pp_now != PANE_NONE && pp_now != pp)
return (false);
// display box
const SBox &box = plot_b[pp];
// first check a few plot types that require extra tests or processing.
switch (pc) {
case PLOT_CH_DXCLUSTER:
if (!useDXCluster())
return (false);
break;