-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwifi.cpp
1615 lines (1383 loc) · 44.7 KB
/
wifi.cpp
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
/* use wifi for NTP and scraping web sites.
* call updateClocks() during lengthy operations, particularly after making new connections.
*/
#include "HamClock.h"
// agent
#if defined(__linux__)
static const char agent[] = "HamClock-linux";
#elif defined (__APPLE__)
static const char agent[] = "MacHamClock-apple";
#else
static const char agent[] = "ESPHamClock";
#endif
// RSS info
#define RSS_DEFINT 15000 // default update interval, millis()
static uint16_t rss_interval = RSS_DEFINT; // working interval
static const char rss_page[] = "/ham/HamClock/RSS/web15rss.pl";
#define NRSS 15 // max number RSS entries to cache
// kp historical and predicted info, new data posted every 3 hours
#define KP_INTERVAL 3500000UL // polling period, millis()
#define KP_COLOR RA8875_YELLOW // loading message text color
static const char kp_page[] = "/ham/HamClock/geomag/kindex.txt";
// xray info, new data posted every 10 minutes
#define XRAY_INTERVAL 600000UL // polling interval, millis()
#define XRAY_LCOLOR RGB565(255,50,50) // long wavelength plot color, reddish
#define XRAY_SCOLOR RGB565(50,50,255) // short wavelength plot color, blueish
static const char xray_page[] = "/ham/HamClock/xray/xray.txt";
// sunspot info, new data posted daily
#define SSPOT_INTERVAL 3400000UL // polling interval, millis()
#define SSPOT_COLOR RGB565(100,100,255) // loading message text color
static const char sspot_page[] = "/ham/HamClock/ssn/ssn.txt";
// solar flux info, new data posted three times a day
#define FLUX_INTERVAL 3300000UL // polling interval, millis()
#define FLUX_COLOR RA8875_GREEN // loading message text color
static const char sf_page[] = "/ham/HamClock/solar-flux/solarflux.txt";
// band conditions, voacap model changes every hour
#define BC_INTERVAL 1800000UL // polling interval, millis()
static const char bc_page[] = "/ham/HamClock/fetchBandConditions.pl";
static bool bc_reverting; // set while waiting for BC after WX
static uint16_t bc_power; // VOACAP power setting
// geolocation web page
static const char locip_page[] = "/ham/HamClock/fetchIPGeoloc.pl";
// SDO images
#define SDO_INTERVAL 3200000UL // polling interval, millis()
#define SDO_COLOR RA8875_MAGENTA // loading message text color
static struct {
const char *read_msg;
const char *file_name;
} sdo_images[] = {
#if defined(_CLOCK_1600x960)
{ "Reading SDO composite", "/ham/HamClock/SDO/f_211_193_171_340.bmp"},
{ "Reading SDO 6173 A", "/ham/HamClock/SDO/latest_340_HMIIC.bmp"},
{ "Reading SDO magnetogram", "/ham/HamClock/SDO/latest_340_HMIB.bmp"}
#elif defined(_CLOCK_2400x1440)
{ "Reading SDO composite", "/ham/HamClock/SDO/f_211_193_171_510.bmp"},
{ "Reading SDO 6173 A", "/ham/HamClock/SDO/latest_510_HMIIC.bmp"},
{ "Reading SDO magnetogram", "/ham/HamClock/SDO/latest_510_HMIB.bmp"}
#elif defined(_CLOCK_3200x1920)
{ "Reading SDO composite", "/ham/HamClock/SDO/f_211_193_171_680.bmp"},
{ "Reading SDO 6173 A", "/ham/HamClock/SDO/latest_680_HMIIC.bmp"},
{ "Reading SDO magnetogram", "/ham/HamClock/SDO/latest_680_HMIB.bmp"}
#else
{ "Reading SDO composite", "/ham/HamClock/SDO/f_211_193_171_170.bmp"},
{ "Reading SDO 6173 A", "/ham/HamClock/SDO/latest_170_HMIIC.bmp"},
{ "Reading SDO magnetogram", "/ham/HamClock/SDO/latest_170_HMIB.bmp"}
#endif
};
// web site retry interval, millis()
#define WIFI_RETRY 10000UL
// millis() of last attempts
static uint32_t last_wifi;
static uint32_t last_flux;
static uint32_t last_ssn;
static uint32_t last_xray;
static uint32_t last_kp;
static uint32_t last_rss;
static uint32_t last_sdo;
static uint32_t last_bc;
// local funcs
static bool updateKp(SBox &b);
static bool updateXRay(void);
static bool updateSDO(void);
static bool updateSunSpots(void);
static bool updateSolarFlux(void);
static bool updateBandConditions(SBox &box);
static uint32_t crackBE32 (uint8_t bp[]);
/* it is MUCH faster to print F() strings in a String than using them directly.
* see esp8266/2.3.0/cores/esp8266/Print.cpp::print(const __FlashStringHelper *ifsh) to see why.
*/
void FWIFIPR (WiFiClient &client, const __FlashStringHelper *str)
{
String _sp(str);
client.print(_sp);
}
void FWIFIPRLN (WiFiClient &client, const __FlashStringHelper *str)
{
String _sp(str);
client.println(_sp);
}
// handy wifi health check
bool wifiOk()
{
if (WiFi.status() == WL_CONNECTED)
return (true);
// retry occasionally
uint32_t t0 = millis();
if (t0 - last_wifi > WIFI_RETRY) {
last_wifi = t0;
initWiFi(false);
return (WiFi.status() == WL_CONNECTED);
} else
return (false);
}
/* reset the wifi retry flags so they all refresh again
*/
void initWiFiRetry()
{
last_wifi = 0;
last_flux = 0;
last_ssn = 0;
last_xray = 0;
last_kp = 0;
last_rss = 0;
last_sdo = 0;
last_bc = 0;
}
/* called to potentially update band conditions.
* if BC is on plot1_b just wait for revert if in progress else update immediately.
* if BC is on plot2_b arrange to update it immediately.
*/
void newBC()
{
if ((plot1_ch == PLOT1_BC && !bc_reverting) || plot2_ch == PLOT2_BC)
last_bc = 0;
}
/* set de_ll.lat_d and de_ll.lng_d from our public ip.
* report status via tftMsg if verbose.
*/
static void geolocateIP (bool verbose)
{
WiFiClient iploc_client; // wifi client connection
float lat, lng;
char llline[80];
char ipline[80];
char credline[80];
int nlines = 0;
Serial.println(locip_page);
resetWatchdog();
if (wifiOk() && iploc_client.connect(svr_host, HTTPPORT)) {
httpGET (iploc_client, svr_host, locip_page);
if (!httpSkipHeader (iploc_client))
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 = myatof (llline+4);
if (!getTCPLine (iploc_client, llline, sizeof(llline), NULL))
goto out;
nlines++;
lng = myatof (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
if (verbose)
tftMsg ("IP %s geolocation courtesy %s", ipline+3, credline+7);
de_ll.lat_d = lat;
de_ll.lng_d = lng;
normalizeLL (de_ll);
setMaidenhead(NV_DE_GRID, de_ll);
NVWriteFloat (NV_DE_LAT, de_ll.lat_d);
NVWriteFloat (NV_DE_LNG, de_ll.lng_d);
} else {
// trouble, error message if 1 line
if (verbose) {
if (nlines == 1)
tftMsg ("IP geolocation err: %s", llline);
else
tftMsg ("IP geolocation failed");
}
}
iploc_client.stop();
resetWatchdog();
printFreeHeap (F("geolocateIP"));
}
/* init and connect, inform via tftMsg() if verbose.
* non-verbose is used for automatic retries that should not clobber the display.
*/
void initWiFi (bool verbose)
{
// N.B. look at the usages and make sure this is "big enough"
static const char dots[] = ".........................................";
if (verbose) tftMsg("Starting Network:");
resetWatchdog();
// we only want station mode, not access too
WiFi.mode(WIFI_STA);
// show connection status
char *ssid = getWiFiSSID();
WiFi.begin (ssid, getWiFiPW()); // non-blocking, poll with status()
resetWatchdog();
uint32_t t0 = millis();
uint32_t timeout = verbose ? 30000UL : 3000UL; // it is much faster when trying to reconnect
uint16_t wn = 1;
if (verbose) tftMsg ("MAC addr: %s", WiFi.macAddress().c_str());
if (verbose && ssid) tftMsg (""); // prep for connection countdown
do {
if (verbose && ssid) tftMsg ("Connecting to %s %.*s\r", ssid, wn++, dots);
resetWatchdog();
Serial.println (F("Trying network"));
if (millis() - t0 > timeout || wn == sizeof(dots)) {
if (verbose) {
tftMsg ("Connection failed .. check connections and credentials.");
tftMsg ("Continuing degraded but will keep trying.");
wdDelay(5000);
}
return;
}
wdDelay(1000);
} while (WiFi.status() != WL_CONNECTED);
// success -- init retry times
resetWatchdog();
initWiFiRetry();
if (verbose) {
IPAddress ip;
ip = WiFi.localIP();
tftMsg ("IP: %d.%d.%d.%d", ip[0], ip[1], ip[2], ip[3]);
ip = WiFi.subnetMask();
tftMsg ("Mask: %d.%d.%d.%d", ip[0], ip[1], ip[2], ip[3]);
ip = WiFi.gatewayIP();
tftMsg ("GW: %d.%d.%d.%d", ip[0], ip[1], ip[2], ip[3]);
ip = WiFi.dnsIP();
tftMsg ("DNS: %d.%d.%d.%d", ip[0], ip[1], ip[2], ip[3]);
tftMsg ("Hostname: %s", WiFi.hostname().c_str());
if (WiFi.RSSI() < 10) {
tftMsg ("Signal strength : %d dBm", WiFi.RSSI());
tftMsg ("Channel : %d", WiFi.channel());
}
tftMsg ("S/N: %u", ESP.getChipId());
}
// set location from IP if desired
resetWatchdog();
if (useGeoIP())
geolocateIP (verbose);
// start web server for screen captures (no return status to report)
initWebServer();
// final report and time to peruse or skip
if (verbose) {
static const SBox skip_b = {730,10,55,35}; // skip box, nice if same as sat ok
selectFontStyle (BOLD_FONT, SMALL_FONT);
drawStringInBox ("Skip", skip_b, false, RA8875_WHITE);
tftMsg ("");
#define TO_DS 50 // timeout delay, decaseconds
uint8_t s_left = TO_DS/10; // seconds remaining
uint32_t t0 = millis();
drainTouch();
for (uint8_t ds_left = TO_DS; ds_left > 0; --ds_left) {
SCoord s;
if (readCalTouch(s) != TT_NONE && inBox(s, skip_b)) {
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
char buf[30];
sprintf (buf, "Network ready ... %d\r", s_left--);
tftMsg (buf);
}
wdDelay(100);
}
}
// handy init bc_power
if (bc_power == 0 && !NVReadUInt16 (NV_BCPOWER, &bc_power))
bc_power = 100;
}
/* if s is in ll corner of b, rotate bc_power, update NV and return true; else return false.
* N.B. we assume s is already somewhere within b.
*/
static bool rotateBCPower (const SCoord &s, const SBox &b)
{
// done if not in ll corner
if (s.x > b.x + b.w/3 || s.y < b.y + 4*b.h/5)
return (false);
// rotate
switch (bc_power) {
case 1: bc_power = 10; break;
case 10: bc_power = 100; break;
case 100: bc_power = 1000; break;
default: bc_power = 1; break;
}
// persist
NVWriteUInt16 (NV_BCPOWER, bc_power);
// good
return (true);
}
/* arrange to resume plot1 after dt
*/
void revertPlot1 (uint32_t dt)
{
switch (plot1_ch) {
case PLOT1_SSN:
last_ssn = millis() - SSPOT_INTERVAL + dt;
break;
case PLOT1_FLUX:
last_flux = millis() - FLUX_INTERVAL + dt;
break;
case PLOT1_BC:
last_bc = millis() - BC_INTERVAL + dt;
bc_reverting = true;
break;
case PLOT1_N: // lint
break;
}
}
/* check if it is time to update any info via wifi.
* really should be called updatePlots()
*/
void updateWiFi(void)
{
resetWatchdog();
// time now
uint32_t t0 = millis();
// proceed even if no wifi to allow subsystems to display their error messages
// freshen plot1 contents
switch (plot1_ch) {
case PLOT1_SSN:
if (!last_ssn || t0 - last_ssn > SSPOT_INTERVAL) {
if (updateSunSpots())
last_ssn = t0;
else
last_ssn = t0 - SSPOT_INTERVAL + WIFI_RETRY;
}
break;
case PLOT1_FLUX:
if (!last_flux || t0 - last_flux > FLUX_INTERVAL) {
if (updateSolarFlux())
last_flux = t0;
else
last_flux = t0 - FLUX_INTERVAL + WIFI_RETRY;
}
break;
case PLOT1_BC:
if (!last_bc || t0 - last_bc > BC_INTERVAL) {
if (updateBandConditions(plot1_b))
last_bc = t0;
else
last_bc = t0 - BC_INTERVAL + WIFI_RETRY;
}
break;
case PLOT1_N: // lint
break;
}
// freshen plot2 contents
switch (plot2_ch) {
case PLOT2_KP:
if (!last_kp || t0 - last_kp > KP_INTERVAL) {
if (updateKp(plot2_b))
last_kp = t0;
else
last_kp = t0 - KP_INTERVAL + WIFI_RETRY;
}
break;
case PLOT2_XRAY:
if (!last_xray || t0 - last_xray > XRAY_INTERVAL) {
if (updateXRay())
last_xray = t0;
else
last_xray = t0 - XRAY_INTERVAL + WIFI_RETRY;
}
break;
case PLOT2_BC:
if (!last_bc || t0 - last_bc > BC_INTERVAL) {
if (updateBandConditions(plot2_b))
last_bc = t0;
else
last_bc = t0 - BC_INTERVAL + WIFI_RETRY;
}
break;
case PLOT2_DX:
updateDXCluster();
break;
case PLOT2_N: // lint
break;
}
// freshen plot3 contents
switch (plot3_ch) {
case PLOT3_SDO_1: // fallthru
case PLOT3_SDO_2: // fallthru
case PLOT3_SDO_3:
if (!last_sdo || t0 - last_sdo > SDO_INTERVAL) {
if (updateSDO())
last_sdo = t0;
else
last_sdo = t0 - SDO_INTERVAL + WIFI_RETRY;
}
break;
case PLOT3_GIMBAL:
updateGimbal();
break;
case PLOT3_KP:
if (!last_kp || t0 - last_kp > KP_INTERVAL) {
if (updateKp(plot3_b))
last_kp = t0;
else
last_kp = t0 - KP_INTERVAL + WIFI_RETRY;
}
break;
case PLOT3_N:
break;
}
// freshen RSS
if (!last_rss || t0 - last_rss > rss_interval) {
if (updateRSS())
last_rss = t0;
else
last_rss = t0 - rss_interval + WIFI_RETRY;
}
// check for server commands
checkWebServer();
}
/* check if the given touch coord is inside plot1_b.
* if so, rotate to next type, reset its new last_X counter and return true, else return false.
*/
bool checkPlot1Touch (const SCoord &s)
{
if (!inBox (s, plot1_b))
return (false);
// rotate
switch (plot1_ch) {
case PLOT1_SSN:
plot1_ch = PLOT1_FLUX;
last_flux = millis() - FLUX_INTERVAL; // force new fetch in next updateWiFi()
break;
case PLOT1_FLUX:
if (plot2_ch == PLOT2_BC) {
plot1_ch = PLOT1_SSN; // dont duplicate BC
last_ssn = millis() - SSPOT_INTERVAL; // force new fetch in next updateWiFi()
} else {
plot1_ch = PLOT1_BC;
last_bc = millis() - BC_INTERVAL; // force new fetch in next updateWiFi()
}
break;
case PLOT1_BC:
if (rotateBCPower (s, plot1_b)) {
// stay with BC, just update with new power setting
updateBandConditions(plot1_b);
} else {
plot1_ch = PLOT1_SSN;
last_ssn = millis() - SSPOT_INTERVAL; // force new fetch in next updateWiFi()
}
break;
case PLOT1_N: // lint
break;
}
// persist
NVWriteUInt8 (NV_PLOT_1, plot1_ch);
// ok
return (true);
}
/* check if the given touch coord is inside plot2_b.
* if so, rotate to next type, reset its new last_X counter and return true, else return false.
*/
bool checkPlot2Touch (const SCoord &s)
{
if (!inBox (s, plot2_b))
return (false);
// rotate
switch (plot2_ch) {
case PLOT2_KP:
plot2_ch = PLOT2_XRAY;
last_xray = millis() - XRAY_INTERVAL; // force new fetch in next updateWiFi()
break;
case PLOT2_XRAY:
if (plot1_ch != PLOT1_BC) {
plot2_ch = PLOT2_BC;
last_bc = millis() - BC_INTERVAL; // force new fetch in next updateWiFi()
} else if (useDXCluster()) {
plot2_ch = PLOT2_DX;
initDXCluster();
} else if (plot3_ch != PLOT3_KP) {
plot2_ch = PLOT2_KP;
last_kp = millis() - KP_INTERVAL; // force new fetch in next updateWiFi()
} // nothing else eligible
break;
case PLOT2_BC:
if (rotateBCPower (s, plot2_b)) {
// stay with BC, just update with new power setting
updateBandConditions(plot2_b);
} else if (useDXCluster()) {
plot2_ch = PLOT2_DX;
initDXCluster();
} else if (plot3_ch != PLOT3_KP) {
plot2_ch = PLOT2_KP;
last_kp = millis() - KP_INTERVAL; // force new fetch in next updateWiFi()
} else {
plot2_ch = PLOT2_XRAY;
last_xray = millis() - XRAY_INTERVAL; // force new fetch in next updateWiFi()
}
break;
case PLOT2_DX:
// first check if user has tapped a dx, else assume they want to roll to next pane
if (!checkDXTouch(s)) {
closeDXCluster();
if (plot3_ch != PLOT3_KP) {
plot2_ch = PLOT2_KP;
last_kp = millis() - KP_INTERVAL; // force new fetch in next updateWiFi()
} else {
plot2_ch = PLOT2_XRAY;
last_xray = millis() - XRAY_INTERVAL; // force new fetch in next updateWiFi()
}
}
break;
case PLOT2_N: // lint
break;
}
// persist
NVWriteUInt8 (NV_PLOT_2, plot2_ch);
// ok
return (true);
}
/* handle plot3 touch, return whether ours.
* handle all but SDO immediately.
*/
bool checkPlot3Touch (const SCoord &s)
{
// check whether in box at all
if (!inBox (s, plot3_b))
return (false);
// check gimbal first
if (checkGimbalTouch(s))
return (true);
// handy top half check
SBox top_b = plot3_b;
top_b.h /= 2;
// roll depending on tap and state
if (bme280_connected && !inBox (s, top_b)) {
// in bottom half with sensor: roll sensor plot
switch (plot3_ch) {
case PLOT3_TEMP: plot3_ch = PLOT3_PRESSURE; break;
case PLOT3_PRESSURE: plot3_ch = PLOT3_HUMIDITY; break;
case PLOT3_HUMIDITY: plot3_ch = PLOT3_DEWPOINT; break;
case PLOT3_DEWPOINT: plot3_ch = PLOT3_TEMP; break;
default: plot3_ch = PLOT3_TEMP; break;
}
plotBME280();
} else {
// in top half or no sensor: roll to next pane type
switch (plot3_ch) {
case PLOT3_SDO_1:
plot3_ch = PLOT3_SDO_2;
last_sdo = millis() - SDO_INTERVAL; // force new fetch in next updateWiFi()
break;
case PLOT3_SDO_2:
plot3_ch = PLOT3_SDO_3;
last_sdo = millis() - SDO_INTERVAL; // force new fetch in next updateWiFi()
break;
case PLOT3_SDO_3:
if (haveGimbal()) {
plot3_ch = PLOT3_GIMBAL;
initGimbalGUI();
} else if (plot2_ch != PLOT2_KP) {
plot3_ch = PLOT3_KP;
last_kp = millis() - KP_INTERVAL; // force new fetch in next updateWiFi()
} else {
plot3_ch = PLOT3_SDO_1;
last_sdo = millis() - SDO_INTERVAL; // force new fetch in next updateWiFi()
}
break;
case PLOT3_GIMBAL:
closeGimbal();
// fallthru
default:
plot3_ch = PLOT3_SDO_1;
last_sdo = millis() - SDO_INTERVAL; // force new fetch in next updateWiFi()
break;
}
}
// persist
NVWriteUInt8 (NV_PLOT_3, plot3_ch);
// ours
return (true);
}
/* NTP time server query.
* returns UNIX time, or 0 if trouble.
* for NTP packet description see
* http://www.cisco.com
* /c/en/us/about/press/internet-protocol-journal/back-issues/table-contents-58/154-ntp.html
*/
time_t getNTPUTC(void)
{
static const char *ntp_list[] = {
"time.google.com",
"pool.ntp.org",
"time.apple.com",
};
#define NNTP (sizeof(ntp_list)/sizeof(ntp_list[0]))
static uint8_t ntp_i = 0;
static const uint8_t timeReqA[] = { 0xE3, 0x00, 0x06, 0xEC };
static const uint8_t timeReqB[] = { 0x31, 0x4E, 0x31, 0x34 };
// need wifi
if (!wifiOk())
return (0);
// need udp
WiFiUDP ntp_udp;
if (!ntp_udp.begin(1234)) { // any local port
Serial.println (F("UDP startup failed"));
return (0);
}
// NTP buffer and timers
uint8_t buf[48];
uint32_t tx_ms, rx_ms;
// Assemble request packet
memset(buf, 0, sizeof(buf));
memcpy(buf, timeReqA, sizeof(timeReqA));
memcpy(&buf[12], timeReqB, sizeof(timeReqB));
// send
Serial.print(F("Issuing NTP request to ")); Serial.println(ntp_list[ntp_i]);
ntp_udp.beginPacket (ntp_list[ntp_i], 123); // NTP uses port 123
ntp_udp.write(buf, sizeof(buf));
tx_ms = millis(); // record when packet sent
if (!ntp_udp.endPacket()) {
Serial.println (F("UDP write failed"));
ntp_i = (ntp_i+1)%NNTP; // try different server next time
ntp_udp.stop();
return (0UL);
}
// Serial.print (F("Sent 48 ... "));
resetWatchdog();
// receive response
// Serial.print(F("Awaiting response ... "));
memset(buf, 0, sizeof(buf));
uint32_t t0 = millis();
while (!ntp_udp.parsePacket()) {
if (millis() - t0 > 3000U) {
Serial.println(F("UDP timed out"));
ntp_i = (ntp_i+1)%NNTP; // try different server next time
ntp_udp.stop();
return (0UL);
}
resetWatchdog();
wdDelay(10);
}
rx_ms = millis(); // record when packet arrived
resetWatchdog();
// read response
if (ntp_udp.read (buf, sizeof(buf)) != sizeof(buf)) {
Serial.println (F("UDP read failed"));
ntp_i = (ntp_i+1)%NNTP; // try different server next time
ntp_udp.stop();
return (0UL);
}
// IPAddress from = ntp_udp.remoteIP();
// Serial.printf ("received 48 from %d.%d.%d.%d\n", from[0], from[1], from[2], from[3]);
// only accept server responses which are mode 4
uint8_t mode = buf[0] & 0x7;
if (mode != 4) { // insure server packet
Serial.print (F("RX mode should be 4 but it is ")); Serial.println (mode);
ntp_udp.stop();
return (0UL);
}
// crack and advance to next whole second
time_t unix_s = crackBE32 (&buf[40]) - 2208988800UL; // packet transmit time - (1970 - 1900)
if ((uint32_t)unix_s > 0x7FFFFFFFUL) { // sanity check beyond unsigned value
Serial.print (F("crazy large UNIX time: ")); Serial.println ((uint32_t)unix_s);
ntp_udp.stop();
return (0UL);
}
uint32_t fraction_more = crackBE32 (&buf[44]); // x / 10^32 additional second
uint16_t ms_more = 1000UL*(fraction_more>>22)/1024UL; // 10 MSB to ms
uint16_t transit_time = (rx_ms - tx_ms)/2; // transit = half the round-trip time
if (transit_time < 1) { // don't trust unless finite
Serial.println (F("too fast"));
ntp_udp.stop();
return (0UL);
}
ms_more += transit_time; // with transit now = unix_s + ms_more
uint16_t sec_more = ms_more/1000U+1U; // whole seconds behind rounded up
wdDelay (sec_more*1000U - ms_more); // wait to next whole second
unix_s += sec_more; // account for delay
// Serial.print (F("Fraction ")); Serial.print(ms_more);
// Serial.print (F(", transit ")); Serial.print(transit_time);
// Serial.print (F(", seconds ")); Serial.print(sec_more);
// Serial.print (F(", UNIX ")); Serial.print (unix_s); Serial.println();
resetWatchdog();
Serial.println (F("NTP ok"));
ntp_udp.stop();
printFreeHeap (F("NTP"));
return (unix_s);
}
/* read next char from client.
* return whether another character was in fact available.
*/
bool getChar (WiFiClient &client, char *cp)
{
#define GET_TO 5000 // millis()
resetWatchdog();
// wait for char
uint32_t t0 = millis();
while (!client.available()) {
resetWatchdog();
if (!client.connected())
return (false);
if (millis() - t0 > GET_TO)
return (false);
wdDelay(10);
}
// read, which has another way to indicate failure
int c = client.read();
if (c < 0) {
Serial.println (F("bad read"));
return (false);
}
// got one
*cp = (char)c;
return (true);
}
/* send User-Agent to client
*/
void sendUserAgent (WiFiClient &client)
{
// format
char ua[100];
snprintf (ua, sizeof(ua), "User-Agent: %s/%s (id %u up %ld)\r\n",
agent, VERSION, ESP.getChipId(), getUptime(NULL,NULL,NULL,NULL));
// send
client.print(ua);
}
/* issue an HTTP Get
*/
void httpGET (WiFiClient &client, const char *server, const char *page)
{
resetWatchdog();
FWIFIPR (client, F("GET ")); client.print(page); FWIFIPRLN (client, F(" HTTP/1.0"));
FWIFIPR (client, F("Host: ")); client.println (server);
sendUserAgent (client);
FWIFIPRLN (client, F("Connection: close\r\n"));
resetWatchdog();
}
/* skip the given wifi client stream ahead to just after the first blank line, return whether ok.
* this is often used so subsequent stop() on client doesn't slam door in client's face with RST
*/
bool httpSkipHeader (WiFiClient &client)
{
char line[512];
do {
if (!getTCPLine (client, line, sizeof(line), NULL))
return (false);
// Serial.println (line);
} while (line[0] != '\0'); // getTCPLine absorbs \r\n so this tests for a blank line
return (true);
}
/* retrieve and plot latest and predicted kp indices, return whether all ok
*/
static bool updateKp(SBox &b)
{
// data are provided every 3 hours == 8/day. collect 7 days of history + 2 days of predictions
#define NHKP (8*7) // N historical Kp values
#define NPKP (8*2) // N predicted Kp values
#define NKP (NHKP+NPKP) // N total Kp values
uint8_t kp[NKP]; // kp collection
uint8_t kp_i = 0; // next kp index to use
char line[100]; // text line
WiFiClient kp_client; // wifi client connection
bool ok = false; // set iff all ok
plotMessage (b, KP_COLOR, "Reading kpmag data...");
Serial.println(kp_page);
resetWatchdog();
if (wifiOk() && kp_client.connect(svr_host, HTTPPORT)) {
updateClocks(false);
resetWatchdog();
// query web page
httpGET (kp_client, svr_host, kp_page);
// skip response header
if (!httpSkipHeader (kp_client))
goto out;
// read lines into kp array
// Serial.println(F("reading k indices"));
for (kp_i = 0; kp_i < NKP && getTCPLine (kp_client, line, sizeof(line), NULL); kp_i++) {
// Serial.print(kp_i); Serial.print("\t"); Serial.println(line);
kp[kp_i] = myatof(line);
}
} else {
Serial.println (F("connection failed"));
}
// require all
ok = (kp_i == NKP);
out:
// plot
if (ok)
plotKp (b, kp, NHKP, NPKP, KP_COLOR);
else
plotMessage (b, KP_COLOR, "No Kp data");
// clean up
kp_client.stop();
resetWatchdog();
printFreeHeap (F("Kp"));
return (ok);
}
/* given a GOES XRAY Flux value, return its event level designation in buf.
*/
static char *xrayLevel (float flux, char *buf)
{
if (flux < 1e-8)
strcpy (buf, "A0.0");
else {
static const char levels[] = "ABCMX";
int power = floorf(log10f(flux));
if (power > -4)
power = -4;
float mantissa = flux*powf(10.0F,-power);
char alevel = levels[8+power];
sprintf (buf, "%c%.1f", alevel, mantissa);
}
return (buf);
}
// retrieve and plot latest xray indices, return whether all ok
static bool updateXRay()
{
#define NXRAY 150 // n lines to collect = 25 hours @ 10 mins per line
float lxray[NXRAY], sxray[NXRAY]; // long and short wavelength values
uint8_t xray_i; // next index
char line[100];
uint16_t ll;
bool ok = false;
WiFiClient xray_client;
plotMessage (plot2_b, XRAY_LCOLOR, "Reading XRay data...");
Serial.println(xray_page);
resetWatchdog();
if (wifiOk() && xray_client.connect(svr_host, HTTPPORT)) {
updateClocks(false);
// query web page
httpGET (xray_client, svr_host, xray_page);
// soak up remaining header
(void) httpSkipHeader (xray_client);
// collect content lines and extract both wavelength intensities
xray_i = 0;
float current_flux = 1;
while (xray_i < NXRAY && getTCPLine (xray_client, line, sizeof(line), &ll)) {
// Serial.println(line);
if (line[0] == '2' && ll >= 56) {
float s = myatof(line+35);
if (s <= 0) // missing values are set to -1.00e+05, also guard 0
s = 1e-9;
sxray[xray_i] = log10f(s);
float l = myatof(line+47);
if (l <= 0) // missing values are set to -1.00e+05, also guard 0
l = 1e-9;
lxray[xray_i] = log10f(l);
// Serial.print(l); Serial.print('\t'); Serial.println (s);
xray_i++;
if (xray_i == NXRAY)
current_flux = l;
}
}
// proceed iff we found all
if (xray_i == NXRAY) {
resetWatchdog();