-
Notifications
You must be signed in to change notification settings - Fork 0
/
A.ino
2841 lines (2508 loc) · 92.4 KB
/
A.ino
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
//Joseph Hewitt 2023
//This code is for the ESP32 "Side A" of the wardriver hardware revision 3.
const String VERSION = "1.2.0b3";
#include <GParser.h>
#include <MicroNMEA.h>
#include "FS.h"
#include "SD.h"
#include "SPI.h"
#include <WiFi.h>
#include <Preferences.h>
#include <time.h>
#include <Update.h>
#include "mbedtls/sha256.h"
#include "mbedtls/md.h"
#include <WiFiClientSecure.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#define SCREEN_WIDTH 128 // OLED display width, in pixels
#define SCREEN_HEIGHT 32 // OLED display height, in pixels
#define OLED_RESET -1 // Reset pin # (or -1 if sharing Arduino reset pin)
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);
//The stack size is insufficient for the OTA hashing calls. This is 10K, instead of the default 8K.
SET_LOOP_TASK_STACK_SIZE(10240);
//These variables are used for buffering/caching GPS data.
char nmeaBuffer[100];
MicroNMEA nmea(nmeaBuffer, sizeof(nmeaBuffer));
unsigned long lastgps = 0;
String last_dt_string = "";
String last_lats = "";
String last_lons = "";
//Automatically set by the OTA update check with the latest version numbers.
String ota_latest_stable = "";
String ota_latest_beta = "";
//Automatically set to true if a blocklist was loaded.
boolean use_blocklist = false;
//millis() when the last block happened.
unsigned long ble_block_at = 0;
unsigned long wifi_block_at = 0;
//These variables are used to populate the LCD with statistics.
float temperature;
unsigned int ble_count;
unsigned int count_5ghz;
unsigned int gsm_count;
unsigned int wifi_count;
unsigned int disp_gsm_count;
unsigned int disp_wifi_count;
boolean is_5ghz = false;
uint32_t chip_id;
File filewriter;
Preferences preferences;
unsigned long bootcount = 0;
String default_ssid = "wardriver.uk";
const char* default_psk = "wardriver.uk";
/* The recently seen MAC addresses and cell towers are saved into these arrays so that the
* wardriver can detect if they have already been written to the Wigle CSV file.
* These _len definitions define how large those arrays should be. Larger is better but consumes more RAM.
*/
#define mac_history_len 512
#define cell_history_len 128
#define blocklist_len 20
//Max blocklist entry length. 32 = max SSID len.
#define blocklist_str_len 32
struct mac_addr {
unsigned char bytes[6];
};
struct coordinates {
double lat;
double lon;
int acc;
};
struct cell_tower {
int mcc;
int mnc;
int lac;
int cellid;
unsigned long seenat;
int strength;
struct coordinates pos;
};
struct block_str {
char characters[blocklist_str_len];
};
struct mac_addr mac_history[mac_history_len];
unsigned int mac_history_cursor = 0;
struct cell_tower cell_history[cell_history_len];
unsigned int cell_history_cursor = 0;
struct block_str block_list[blocklist_len];
unsigned long lcd_last_updated;
#define YEAR_2020 1577836800 //epoch value for 1st Jan 2020; dates older than this are considered wrong (this code was written after 2020).
unsigned long epoch;
unsigned long epoch_updated_at;
const char* ntpServer = "pool.ntp.org";
TaskHandle_t primary_scan_loop_handle;
boolean b_working = false; //Set to true when we receive some valid data from side B.
boolean ota_optout = false; //Set in the web interface
#define DEVICE_UNKNOWN 254
#define DEVICE_CUSTOM 0
#define DEVICE_REV3 1
#define DEVICE_REV3_5 2
#define DEVICE_REV4 3
#define DEVICE_REV3_5GM 4
byte DEVICE_TYPE = DEVICE_UNKNOWN;
#define HTTP_TIMEOUT_MS 750
//Change these in cfg.txt instead of editing this source code.
int gps_baud_rate = 9600;
boolean rotate_display = false;
boolean block_resets = false;
boolean block_reconfigure = false;
int web_timeout = 60000; //ms to spend hosting the web interface before booting.
int gps_allow_stale_time = 60000;
boolean enforce_valid_binary_checksums = true; //Lookup OTA binary checksums online, prevent installation if no match found
boolean use_fallback_cert = false;
// CERTIFICATES
// These certs are used for HTTPS comms to the OTA backend.
// By hardcoding them, we are asserting trust. CAs are not used.
// They will be rotated regularly.
static const char *PRIMARY_OTA_CERT = R"EOF(
-----BEGIN CERTIFICATE-----
MIIDeTCCAmGgAwIBAgIUbrbwBJuNsr7DeScXZxaUynePHfowDQYJKoZIhvcNAQEL
BQAwTDELMAkGA1UEBhMCTkwxCzAJBgNVBAgMAlpIMRUwEwYDVQQKDAx3YXJkcml2
ZXIudWsxGTAXBgNVBAMMEG90YS53YX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Z
/pVgZwdi/DGnFk7hn9s9A5+regXDRnUt36TDH2ArAdGHJIl64n+UtpOCoYUIbRA+
XECvNDA4pMiGiTyH3kPsCeoVK+PY7YX1TMg9gY3QbobSHh4LJ2zH6I+kqDhej/Nr
f0PDdGbXj3H6v/r3fk8syofQM1stfmta/HVCBAo=
-----END CERTIFICATE-----
)EOF";
// END CERTIFICATES
String ota_get_url(String url, String write_to=""){
if (ota_optout){
Serial.println("OTA optout");
return "";
}
clear_display();
display.println("Contacting server");
display.display();
Serial.print("Contacting OTA server -> ");
Serial.println(url);
WiFiClientSecure httpsclient;
if (use_fallback_cert){
Serial.println("fallback cert");
httpsclient.setCACert(FALLBACK_OTA_CERT);
} else {
Serial.println("primary cert");
httpsclient.setCACert(PRIMARY_OTA_CERT);
}
if (!httpsclient.connect("ota.wardriver.uk", 443)){
Serial.println("failed");
if (!use_fallback_cert){
Serial.println("Will retry using fallback cert");
use_fallback_cert = true;
return ota_get_url(url);
} else {
return "";
}
} else {
httpsclient.print("GET ");
httpsclient.print(url);
httpsclient.println(" HTTP/1.0");
httpsclient.println("Host: ota.wardriver.uk");
httpsclient.println("Connection: close");
httpsclient.print("User-Agent: ");
httpsclient.print(device_type_string());
httpsclient.print(" / ");
httpsclient.println(VERSION);
httpsclient.println();
}
String return_out = "";
boolean headers_ended = false;
unsigned long content_length_long = 0;
while (httpsclient.connected()){
String buff = httpsclient.readStringUntil('\n');
if (!headers_ended){
Serial.println(buff);
}
if (buff == "\r" || buff == "\n" || buff.length() == 0){
headers_ended = true;
Serial.println("END OF HEADER^");
if (write_to == ""){
continue;
}
}
if (!headers_ended){
int clpos = buff.indexOf("Content-Length: ");
if (clpos > -1){
String content_length = buff.substring(clpos+16);
Serial.print("CL:");
Serial.println(content_length);
content_length_long = content_length.toInt();
}
}
if (headers_ended){
if (write_to == ""){
return_out.concat(buff);
return_out.concat('\n');
if (return_out.length() > 1024){
return return_out;
}
} else {
SD.remove(write_to);
File fw_writer = SD.open(write_to, FILE_WRITE);
unsigned long lastbyte = millis();
unsigned long bytecounter = 0;
while (httpsclient.connected() && (millis() - lastbyte) < 10000){
if (httpsclient.available()){
byte c = httpsclient.read();
bytecounter++;
fw_writer.write(c);
lastbyte = millis();
float percent = ((float)bytecounter / (float)content_length_long) * 100;
if (bytecounter % 6000 == 0){
clear_display();
display.print("Downloading ");
display.println(write_to);
display.print(percent);
display.println("%");
display.display();
}
}
}
fw_writer.flush();
fw_writer.close();
}
}
}
Serial.println("OTA contact end");
return return_out;
}
boolean check_for_updates(boolean stable=true, boolean download_now=false){
String res = ota_get_url("/latest.txt");
Serial.println("Update list res:");
Serial.println(res);
int cur = 0;
String partbuf = "";
boolean reading_stable = false;
int linecount = 0;
int partcount = 0;
boolean update_available = false;
while (cur <= res.length()){
char c = res.charAt(cur);
if (c == '>' || c == '\n'){
//Handle partbuf.
Serial.print("PBUF");
Serial.print(linecount);
Serial.print("/");
Serial.print(partcount);
Serial.print(":");
Serial.println(partbuf);
if (partbuf == "SR"){
reading_stable = true;
}
if (partbuf == "PR"){
reading_stable = false;
}
if (partcount == 1){
if (reading_stable){
ota_latest_stable = partbuf;
} else {
ota_latest_beta = partbuf;
}
}
if (stable == reading_stable){
//This is the branch we are interested in
if (partcount == 1){
//VERSION
if (partbuf != VERSION){
update_available = true;
}
}
if (update_available){
if (partcount == 5){
if (download_now){
ota_get_url(partbuf, "/A.bin");
}
}
if (partcount == 6){
if (download_now){
ota_get_url(partbuf, "/B.bin");
}
}
}
}
partbuf = "";
partcount++;
if (c == '\n'){
linecount++;
partcount = 0;
}
} else {
partbuf.concat(c);
}
cur++;
}
return update_available;
}
void setup_wifi(){
//Gets the WiFi ready for scanning by disconnecting from networks and changing mode.
WiFi.mode(WIFI_STA);
WiFi.disconnect();
}
void clear_display(){
//Clears the LCD and resets the cursor.
display.clearDisplay();
display.setCursor(0, 0);
}
int get_config_int(String key, int def=0){
String res = get_config_option(key);
if (res == ""){
return def;
}
return res.toInt();
}
String file_hash(String filename, boolean update_lcd=true, String lcd_prompt="Wardriver busy"){
File reader = SD.open(filename, FILE_READ);
//Setup a hash context, and somewhere to keep the output.
unsigned char genhash[32];
byte bbuf[2] = {0x00, 0x00};
mbedtls_sha256_context ctx;
mbedtls_sha256_init(&ctx);
mbedtls_sha256_starts(&ctx, 0);
int i = 0;
while (reader.available()){
byte c = reader.read();
bbuf[0] = c;
mbedtls_sha256_update(&ctx, bbuf, 1);
i++;
if (i > 1800){
i = 0;
if (update_lcd){
clear_display();
display.println(lcd_prompt);
float percent = ((float)reader.position() / (float)reader.size()) * 100;
display.print(percent);
display.println("%");
display.display();
}
}
}
mbedtls_sha256_finish(&ctx, genhash);
return hex_str(genhash, sizeof genhash);
}
static void print_hex(const char *title, const unsigned char buf[], size_t len)
{
Serial.printf("%s: ", title);
for (size_t i = 0; i < len; i++) {
if (buf[i] < 0xF) {
Serial.printf("0%x", buf[i]);
} else {
Serial.printf("%x", buf[i]);
}
}
Serial.println();
}
String html_escape(String ret){
ret.replace("<","<");
ret.replace(">",">");
ret.replace("&","&");
ret.replace("\"",""");
ret.replace("'","'");
return ret;
}
String online_hash_check(String check_hash){
//Return "" for invalid hashes, or a human-readable message about the release.
String url = "/hashes/";
url.concat(check_hash);
url.concat(".txt");
String result = ota_get_url(url);
Serial.println("Got OTA hash check response:");
Serial.println(result);
if (result == ""){
return "";
}
String checkfor = "OKHASH>";
checkfor.concat(check_hash);
if (result.indexOf(checkfor) > -1){
int version_pos = result.indexOf("VERS>")+5;
int date_pos = result.indexOf("DATE>")+5;
String retmsg = "Valid official release ";
if (version_pos > -1 && date_pos > -1){
int version_end_pos = result.indexOf("\n",version_pos);
int date_end_pos = result.indexOf("\n",date_pos);
String release_version = result.substring(version_pos, version_end_pos);
String release_datetime = result.substring(date_pos, date_end_pos);
release_version = html_escape(release_version);
release_datetime = html_escape(release_datetime);
retmsg.concat(release_version);
retmsg.concat(" from ");
retmsg.concat(release_datetime);
retmsg.concat(". ");
if (release_version != ota_latest_stable && release_version != ota_latest_beta){
retmsg.concat("<a href=\"/repupdate\">Newer version available</a>");
}
}
return retmsg;
} else {
return "";
}
return "";
}
boolean install_firmware(String filepath, String expect_hash = "") {
//Install a .bin binary to the local device.
//If expect_hash is not empty, the hash will be validated first.
if (!SD.exists(filepath)) {
Serial.print("File not found: ");
Serial.println(filepath);
return false;
}
Serial.println("Validating firmware");
String actual_hash = file_hash(filepath, true, "Validating firmware");
if (expect_hash.length() > 0) {
if (expect_hash != actual_hash) {
Serial.println("Local checksum mismatch");
return false;
}
}
if (enforce_valid_binary_checksums) {
//At this point, make a HTTPS request to an API which can validate the .bin checksum.
//Fail here if the checksum is a mismatch.
String check_result = online_hash_check(actual_hash);
if (check_result == ""){
Serial.println("Strict online hash check mismatch, aborting");
return false;
}
}
if (filepath == "/A.bin"){
clear_display();
display.println("Installing update");
display.display();
File binreader = SD.open(filepath, FILE_READ);
#define binbuflen 4096
uint8_t binbuf[binbuflen] = { 0x00 };
Update.begin(binreader.size());
int counter = 0;
while (binreader.available()) {
byte c = binreader.read();
binbuf[counter] = c;
counter++;
if (counter == binbuflen){
Update.write(binbuf,counter);
counter = 0;
memset(binbuf, 'f', binbuflen);
clear_display();
display.print("Installing: ");
float percent = ((float)binreader.position() / (float)binreader.size()) * 100;
display.print(percent);
display.println("%");
display.println("DO NOT POWER OFF");
display.display();
}
}
if (counter != 0){
Update.write(binbuf,counter);
}
Update.end(true);
clear_display();
display.println("Update installed");
display.println("Restarting now");
display.display();
delay(1000);
SD.remove("/A.bin");
ESP.restart();
return true;
}
if (filepath == "/B.bin"){
Serial.println("Firmware update for side B");
boolean update_ready = false;
Serial1.flush();
String b_buff = "";
int ready_failures = 0;
clear_display();
display.println("Getting B ready");
display.display();
while (!update_ready){
Serial.println("Getting B ready");
Serial1.print("FWUP:");
Serial1.print(actual_hash);
Serial1.print("\n");
Serial1.flush();
int linecounter = 0;
while (linecounter < 5){
String buff = Serial1.readStringUntil('\n');
if (buff.indexOf(actual_hash) > -1){
update_ready = true;
break;
}
Serial.print("Unwanted: ");
Serial.println(buff);
buff = "";
linecounter++;
clear_display();
display.println("Getting B ready");
display.print("Attempt: ");
display.println(ready_failures);
display.display();
}
if (!update_ready){
ready_failures++;
}
if (ready_failures > 99){
Serial.println("Unable to configure B!");
Serial.println("Likely B is outdated, does not support OTA, and must be updated manually");
clear_display();
display.println("FAILURE");
display.println("Update B manually!");
display.println("OTA not supported");
display.display();
delay(10000);
return false;
}
}
//At this point, B side is in update mode.
Serial.println("B is ready");
//0xE9 is the binary header, let's spam something else to be sure we're clear of junk
for(int i=0; i<3000; i++){
Serial1.write(0xFF);
Serial1.flush();
if (i % 100 == 0 || i < 2){
clear_display();
display.println("B is ready");
display.println("Please wait");
display.print(i);
display.print(" / ");
display.println("3000");
display.display();
}
delay(1);
}
//B will sense 0xFF -> 0xE9 and start the update.
//START UPDATE
File binreader = SD.open(filepath, FILE_READ);
int counter = 0;
int pause_byte_counter = 0;
while (binreader.available()) {
byte c = binreader.read();
Serial1.write(c);
counter++;
pause_byte_counter++;
while (Serial1.available()){
//We don't care what B says, just clear the RX buffer
Serial1.read();
}
if (pause_byte_counter >= 110){
//If we stop, B will send us a message when it wants more.
while (!Serial1.available()){
yield();
}
pause_byte_counter = 0;
}
if (counter > 5000 || binreader.position() <= 1){
counter = 0;
clear_display();
display.print("Installing: ");
float percent = ((float)binreader.position() / (float)binreader.size()) * 100;
display.print(percent);
display.println("%");
display.println("DO NOT POWER OFF");
display.display();
}
}
Serial1.flush();
clear_display();
display.println("Completing install");
display.println("Please wait");
display.println("DO NOT POWER OFF");
display.display();
int tocounter = 0;
boolean did_update = false;
boolean transfer_success = false;
while (!did_update){
String buff = Serial1.readStringUntil('\n');
clear_display();
if (!transfer_success){
display.println("Verifying..");
} else {
display.println("Finalizing..");
}
display.println("DO NOT POWER OFF");
display.print("Count:");
tocounter++;
display.println(tocounter);
display.display();
if (buff.indexOf(actual_hash) > -1){
Serial.println("Update transfer verified");
transfer_success = true;
tocounter = 0;
}
if (buff.indexOf("FAILURE") > -1){
Serial.println("B confirmed failure");
clear_display();
display.println("FAILURE");
display.println("Hash mismatch");
display.display();
delay(10000);
return false;
}
if (transfer_success == true && tocounter > 3){
Serial.println("Update complete");
clear_display();
display.println("Update complete");
display.display();
delay(4000);
did_update = true;
SD.remove("/B.bin");
return true;
}
if (transfer_success == false && tocounter > 40){
Serial.println("Update failed");
clear_display();
display.println("!FAILURE!");
display.println("Try again");
display.display();
delay(7500);
return false;
}
}
}
return true;
}
String hex_str(const unsigned char buf[], size_t len)
{
String outstr;
char outchr[6];
for (size_t i = 0; i < len; i++) {
if (buf[i] <= 0xF) {
sprintf(outchr, "0%x", buf[i]);
} else {
sprintf(outchr, "%x", buf[i]);
}
outstr = outstr + outchr;
}
return outstr;
}
boolean get_config_bool(String key, boolean def=false){
String res = get_config_option(key);
if (res == "true" || res == "yes"){
return true;
}
if (res == "false" || res == "no"){
return false;
}
return def;
}
String get_config_string(String key, String def=""){
String res = get_config_option(key);
if (res == ""){
return def;
}
return res;
}
void boot_config(){
//Load configuration variables and perform first time setup if required.
Serial.println("Setting/loading boot config..");
gps_baud_rate = get_config_int("gps_baud_rate", gps_baud_rate);
rotate_display = get_config_bool("rotate_display", rotate_display);
block_resets = get_config_bool("block_resets", block_resets);
block_reconfigure = get_config_bool("block_reconfigure", block_reconfigure);
web_timeout = get_config_int("web_timeout", web_timeout);
gps_allow_stale_time = get_config_int("gps_allow_stale_time", gps_allow_stale_time);
enforce_valid_binary_checksums = get_config_bool("enforce_checksums", enforce_valid_binary_checksums);
boolean sb_bw16 = get_config_bool("sb_bw16", false);
if (sb_bw16){
is_5ghz = true;
}
preferences.begin("wardriver", false);
ota_optout = preferences.getBool("ota_optout", false);
bool firstrun = preferences.getBool("first", true);
if (block_reconfigure){
firstrun = false;
}
bool doreset = preferences.getBool("reset", false);
if (block_resets){
doreset = false;
}
bootcount = preferences.getULong("bootcount", 0);
Serial.println("Loaded variables");
DEVICE_TYPE = preferences.getShort("model", DEVICE_UNKNOWN);
DEVICE_TYPE = identify_model();
preferences.putShort("model", DEVICE_TYPE);
if (doreset){
Serial.println("resetting");
clear_display();
display.println("RESET");
display.display();
preferences.clear();
delay(2000);
firstrun = true;
}
if (!firstrun && !block_resets){
preferences.putBool("reset", true);
preferences.end();
clear_display();
display.println("Power cycle now");
display.println("to factory reset");
display.display();
delay(1250);
preferences.begin("wardriver", false);
preferences.putBool("reset", false);
clear_display();
}
if (firstrun){
Serial.println("Begin first time setup..");
int n = WiFi.scanNetworks(false,false,false,150);
Serial.print("Scan result is ");
Serial.println(n);
Serial.print("Connect to: ");
Serial.println(default_ssid);
WiFi.softAP(default_ssid.c_str(), default_psk);
IPAddress IP = WiFi.softAPIP();
clear_display();
display.println("Connect to:");
display.println(default_ssid);
display.println(IP);
display.display();
WiFiServer server(80);
server.begin();
boolean newline = false;
String buff;
while (firstrun){
WiFiClient client = server.available();
if (client){
Serial.println("client connected");
clear_display();
display.println("Client connected");
display.display();
}
while (client.connected()){
if (client.available()){
char c = client.read();
Serial.write(c);
buff += c;
if (c == '\n'){
if (newline){
Serial.println("End of message");
Serial.println(buff);
client.println("HTTP/1.1 200 OK");
client.println("Content-type: text/html");
client.println("Connection: close");
client.println();
if (buff.indexOf("GET / HTTP") > -1) {
Serial.println("Sending FTS homepage");
client.print("<style>html{font-size:21px;text-align:center;padding:20px}input[type=text],input[type=password],input[type=submit],select{padding:5px;width:100%;max-width:1000px}form{padding-top:10px}br{display:block;margin:5px 0}</style>");
client.print("<html><head><meta name=\"viewport\" content=\"width=device-width, initial-scale=1, maximum-scale=1\"><h1>wardriver.uk " + device_type_string() + " by Joseph Hewitt</h1><h2>First time setup</h2>");
client.print("<p>Please provide the credentials of your WiFi network to get started.</p>");
client.print("<p>You can use this network to get your captured data, sync the date/time, and to download updates</p><br>");
if (n > 0){
client.println("<script>function ssid_selected(obj){");
client.println("document.getElementById(\"ssid\").value = obj.value;");
client.println("}</script>");
client.println("<select onchange=\"ssid_selected(this)\" name=\"ssid\" id=\"ssid_select\">");
client.println("<option value=\"Select your network\">Select your network</option>");
for (int i = 0; i < n; i++) {
client.print("<option value=\"");
client.print(WiFi.SSID(i));
client.print("\">");
client.print(WiFi.SSID(i));
client.println("</option>");
}
client.println("</select>");
}
client.print("<form method=\"get\" action=\"/wifi\">WiFi Name (SSID):<input type=\"text\" name=\"ssid\" id=\"ssid\"><br>WiFi Password (PSK):<input type=\"password\" name=\"psk\" id=\"psk\"><br><br><input type=\"submit\" value=\"Submit\"><p><label for=\"otaoptout\"><input type=\"checkbox\" id=\"otaoptout\" name=\"otaoptout\" value=\"otaoptout\"> Disable OTA updates*</label></p></form>");
client.print("<a href=\"/wifi?ssid=&psk=\">Continue without network</a>");
client.print("<br><hr>Additional help is available at https://wardriver.uk<br>v");
client.print(VERSION);
client.print("<br><p>*Please see https://wardriver.uk/ota for more information about the OTA update function. Disabling it is not recommended.</p>");
}
if (buff.indexOf("GET /wifi?") > -1){
Serial.println("Got WiFi config");
if (buff.indexOf("&otaoptout=otaoptout") > -1){
ota_optout = true;
//This only makes me want to switch to POST even more.
buff.replace("&otaoptout=otaoptout","");
preferences.putBool("ota_optout", true);
Serial.println("OTA opt out selected");
}
int startpos = buff.indexOf("?ssid=")+6;
int endpos = buff.indexOf("&");
String new_ssid = GP_urldecode(buff.substring(startpos,endpos));
startpos = buff.indexOf("&psk=")+5;
endpos = buff.indexOf(" HTTP");
String new_psk = GP_urldecode(buff.substring(startpos,endpos));
Serial.println(new_ssid);
preferences.putString("ssid", new_ssid);
Serial.println(new_psk);
preferences.putString("psk", new_psk);
client.print("<h1>Thanks!</h1>Please wait. <meta http-equiv=\"refresh\" content=\"1; URL=/step2\" />");
}
if (buff.indexOf("GET /step2 HTTP") > -1){
Serial.println("Starting step2");
client.print("<style>html{font-size:21px;text-align:center;padding:20px}input,select{padding:5px;width:100%;max-width:1000px}form{padding-top:10px}br{display:block;margin:5px 0}</style>");
client.print("<html><head><meta name=\"viewport\" content=\"width=device-width, initial-scale=1, maximum-scale=1\"><h1>wardriver.uk " + device_type_string() + " by Joseph Hewitt</h1><h2>Fallback network setup</h2>");
client.print("If your wardriver is unable to connect to your main network it will create a network which your device can join. Please provide some credentials for this fallback network.<br>");
client.print("<form method=\"get\" action=\"/fbwifi\">SSID:<input type=\"text\" name=\"ssid\" id=\"ssid\"><br>PSK:<input type=\"password\" name=\"psk\" id=\"psk\"><br><input type=\"submit\" value=\"Submit\"></form>");
client.print("<a href=\"/fbwifi?ssid=&psk=\">Continue without fallback network</a>");
client.print("<br><hr>Additional help is available at http:https://wardriver.uk<br>v");
client.print(VERSION);
}
if (buff.indexOf("GET /fbwifi?") > -1){
Serial.println("Got WiFi (fallback) config");
int startpos = buff.indexOf("?ssid=")+6;
int endpos = buff.indexOf("&");
String new_ssid = GP_urldecode(buff.substring(startpos,endpos));
startpos = buff.indexOf("&psk=")+5;
endpos = buff.indexOf(" HTTP");
String new_psk = GP_urldecode(buff.substring(startpos,endpos));
Serial.println(new_ssid);
preferences.putString("fbssid", new_ssid);
Serial.println(new_psk);
preferences.putString("fbpsk", new_psk);
client.print("<h1>Thanks!</h1>Your wardriver is now getting ready. <meta http-equiv=\"refresh\" content=\"1; URL=/done\" />");
}
if (buff.indexOf("GET /done HTTP") > -1){
Serial.println("Setup complete");
client.print("<h1>Setup complete!</h1>Your wardriver will now boot normally.");
client.print("\n\r\n\r");
client.flush();
delay(800);
client.stop();
preferences.putBool("first", false);
firstrun = false;
break;
}
client.print("\n\r\n\r");
client.flush();
delay(5);
client.stop();
buff = "";
}
newline = true;
} else {
if (c != '\r'){
newline = false;
}
}
}
}//client
} //firstrun
}
setup_wifi();
bootcount++;
preferences.putULong("bootcount", bootcount);
String con_ssid = GP_urldecode(preferences.getString("ssid",""));
String con_psk = GP_urldecode(preferences.getString("psk",""));
con_ssid = get_config_string("con_ssid", con_ssid);
con_psk = get_config_string("con_psk", con_psk);
String fb_ssid = GP_urldecode(preferences.getString("fbssid",""));
String fb_psk = GP_urldecode(preferences.getString("fbpsk",""));
fb_ssid = get_config_string("fb_ssid", fb_ssid);
fb_psk = get_config_string("fb_psk", fb_psk);
boolean created_network = false; //Set to true automatically when the fallback network is created.