-
Notifications
You must be signed in to change notification settings - Fork 30
Expand file tree
/
Copy pathconfigServer.cpp
More file actions
2211 lines (1987 loc) · 85.2 KB
/
configServer.cpp
File metadata and controls
2211 lines (1987 loc) · 85.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
/*
* Copyright (C) 2019-2021 OpenBikeSensor Contributors
* Contact: https://openbikesensor.org
*
* This file is part of the OpenBikeSensor firmware.
*
* The OpenBikeSensor firmware is free software: you can
* redistribute it and/or modify it under the terms of the GNU
* Lesser General Public License as published by the Free Software
* Foundation, either version 3 of the License, or (at your option)
* any later version.
*
* OpenBikeSensor firmware is distributed in the hope that
* it will be useful, but WITHOUT ANY WARRANTY; without even the
* implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
* PURPOSE. See the GNU Lesser General Public License for more
* details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with the OpenBikeSensor firmware. If not,
* see <http://www.gnu.org/licenses/>.
*/
// Based on https://lastminuteengineers.com/esp32-ota-web-updater-arduino-ide/
// The information provided on the LastMinuteEngineers.com may be used, copied,
// remix, transform, build upon the material and distributed for any purposes
// only if provided appropriate credit to the author and link to the original article.
#include <configServer.h>
#include <OpenBikeSensorFirmware.h>
#include <uploader.h>
#include <HTTPURLEncodedBodyParser.hpp>
#include <esp_ota_ops.h>
#include <esp_partition.h>
#include <DNSServer.h>
#include "SPIFFS.h"
#include "HTTPMultipartBodyParser.hpp"
#include "Firmware.h"
#include "utils/https.h"
#include "utils/timeutils.h"
#include "obsimprov.h"
#include <esp_system.h>
using namespace httpsserver;
static const char *const HTML_ENTITY_FAILED_CROSS = "❌";
static const char *const HTML_ENTITY_OK_MARK = "✅";
static const char *const HTML_ENTITY_WASTEBASKET = "🗑";
static const char *const HTTP_GET = "GET";
static const char *const HTTP_POST = "POST";
static const size_t HTTP_UPLOAD_BUFLEN = 1024; // TODO: refine
static ObsConfig *theObsConfig;
static HTTPSServer * server;
static HTTPServer * insecureServer;
static SSLCert * serverSslCert;
static String OBS_ID;
static String OBS_ID_SHORT;
static DNSServer *dnsServer;
static ObsImprov *obsImprov = nullptr;
// TODO
// - Fix CSS Style for mobile && desktop
// - a vs. button
// - back navigation after save
static const char* const header =
"<!DOCTYPE html>\n"
"<html lang='en'><head><meta charset='utf-8'/><title>{title}</title>"
// STYLE
"<style>"
"#file-input,input, button {width:100%;height:44px;border-radius:4px;margin:10px auto;font-size:15px;}"
".small {height:12px;width:12px;margin:2px}"
"input, button, a.back {background:#f1f1f1;border:0;padding:0;text-align:center;}"
"body {background:#3498db;font-family:'Open Sans',sans-serif;font-size:12px;color:#777}"
"#file-input {padding:0 5px;border:1px solid #ddd;line-height:44px;text-align:left;display:block;cursor:pointer}"
"#bar,#prgbar {background-color:#f1f1f1;border-radius:10px}"
"#bar {background-color:#3498db;width:0%;height:10px}"
"form {background:#fff;max-width:258px;margin:75px auto;padding:30px;border-radius:5px;text-align:center}"
".btn {background:#3498db;color:#fff;cursor:pointer}"
"h1,h2, h3 {padding:0;margin:0;}"
"h3 {padding:10px 0;margin-top:10px;margin-bottom:10px;border-top:3px solid #3498db;border-bottom:3px solid #3498db;}"
"h1 a {color:#777}"
"h2 {margin-top:5px}"
"hr { border-top:1px solid #CCC;margin-left:10px;margin-right:10px;}"
".deletePrivacyArea, a.back {color: black; text-decoration: none; font-size: x-large;}"
".deletePrivacyArea:hover {color: red;}"
"a.previous {text-decoration: none; display: inline-block; padding: 8px 16px;background-color: #f1f1f1; color: black;border-radius: 50%; font-family: 'Open Sans', sans-serif; font-size: 18px}"
"a.previous:hover {background-color: #ddd; color: black;}"
"ul.directory-listing {list-style: none; text-align: left; padding: 0; margin: 0; line-height: 1.5;}"
"li.directory a {text-decoration: none; font-weight: bold;}"
"li.file a {text-decoration: none;}"
"</style>"
"<link rel='icon' href='data:;base64,iVBORw0KGgo=' />"
"<script>"
"window.onload = function() {"
" if (window.location.pathname == '/') {"
" document.querySelectorAll('.previous')[0].style.display = 'none';"
" } else {"
" document.querySelectorAll('.previous')[0].style.display = '';"
" }"
"}"
"</script></head><body>"
""
"<form action='{action}' method='POST'>"
"<h1><a href='/'>OpenBikeSensor</a></h1>"
"<h2>{subtitle}</h2>"
"<p>Firmware version: {version}</p>"
"<a href=\"javascript:history.back()\" class='previous'>‹</a>";
static const char* const footer = "</form></body></html>";
// #########################################
// Upload form
// #########################################
static const char* const xhrUpload =
"<input type='file' name='upload' id='file' accept='{accept}'>"
"<label id='file-input' for='file'>Choose file...</label>"
"<input id='btn' type='submit' class=btn value='Upload'>"
"<br><br>"
"<div id='prg'></div>"
"<br><div id='prgbar'><div id='bar'></div></div><br>" // </form>"
"<script>"
""
"function hide(x) { x.style.display = 'none'; }"
"function show(x) { x.style.display = 'block'; }"
""
"hide(document.getElementById('file'));"
"hide(document.getElementById('prgbar'));"
"hide(document.getElementById('prg'));"
""
"var fileName = '';"
"document.getElementById('file').addEventListener('change', function(e){"
"fileNameParts = e.target.value.split('\\\\');"
"fileName = fileNameParts[fileNameParts.length-1];"
"console.log(fileName);"
"document.getElementById('file-input').innerHTML = fileName;"
"});"
""
"document.getElementById('btn').addEventListener('click', function(e){"
"e.preventDefault();"
"if (fileName == '') { alert('No file chosen'); return; }"
"console.log('Start upload...');"
""
"var form = document.getElementsByTagName('form')[0];"
"var data = new FormData(form);"
"console.log(data);"
//https://developer.mozilla.org/en-US/docs/Web/API/FormData/values
"for (var v of data.values()) { console.log(v); }"
""
"hide(document.getElementById('file-input'));"
"hide(document.getElementById('btn'));"
"show(document.getElementById('prgbar'));"
"show(document.getElementById('prg'));"
""
"var xhr = new XMLHttpRequest();"
"xhr.open( 'POST', '{method}', true );"
"xhr.onreadystatechange = function(s) {"
"console.log(xhr.responseText);"
"if (xhr.readyState == 4 && xhr.status == 200) {"
"document.getElementById('prg').innerHTML = xhr.responseText;"
"} else if (xhr.readyState == 4 && xhr.status == 500) {"
"document.getElementById('prg').innerHTML = 'Upload error:' + xhr.responseText;"
"} else {"
"document.getElementById('prg').innerHTML = 'Unknown error';"
"}"
"};"
"xhr.upload.addEventListener('progress', function(evt) {"
"if (evt.lengthComputable) {"
"var per = Math.round((evt.loaded * 100) / evt.total);"
"if(per == 100) document.getElementById('prg').innerHTML = 'Updating...';"
"else document.getElementById('prg').innerHTML = 'Upload progress: ' + per + '%';"
"document.getElementById('bar').style.width = per + '%';"
"}"
"}, false);"
"xhr.send( data );"
"});" // btn click
""
"</script>";
// #########################################
// Navigation
// #########################################
static const char* const navigationIndex =
"<input type=button onclick=\"window.location.href='/upload'\" class=btn value='Upload Tracks'>"
"<h3>Settings</h3>"
"<input type=button onclick=\"window.location.href='/settings/general'\" class=btn value='General'>"
"<input type=button onclick=\"window.location.href='/settings/privacy'\" class=btn value='Privacy Zones'>"
"<input type=button onclick=\"window.location.href='/settings/wifi'\" class=btn value='Wifi'>"
"<input type=button onclick=\"window.location.href='/settings/backup'\" class=btn value='Backup & Restore'>"
"<input type=button onclick=\"window.location.href='/settings/security'\" class=btn value='Security'>"
"<h3>Maintenance</h3>"
"<input type=button onclick=\"window.location.href='/updatesd'\" class=btn value='Update Firmware'>"
"<input type=button onclick=\"window.location.href='/updateFlash'\" class=btn value='Update Flash App'>"
"<input type=button onclick=\"window.location.href='/sd'\" class=btn value='Show SD Card Contents'>"
"<input type=button onclick=\"window.location.href='/about'\" class=btn value='About'>"
"<input type=button onclick=\"window.location.href='/delete'\" class=btn value='Delete'>"
"<input type=button onclick=\"window.location.href='/reboot'\" class=btn value='Reboot'>";
static const char* const httpsRedirect =
"<h3>HTTPS</h3>"
"You need to access the obs via secure https. If not done already, you also need to "
"accept the self signed cert from the OBS after pressing 'Goto https'. Login is 'obs' "
"and the up to 6 digit pin displayed "
"on the OBS."
"<input type=button onclick=\"window.location.href='https://{host}'\" class=btn value='Goto https'>"
"<input type=button onclick=\"window.location.href='/cert'\" class=btn value='Download Cert'>"
"<hr/>If you are in a local network under your control with no risk of hostile external access, "
"you can enable unencrypted access."
"<input type='submit' name='http' id='http' class=btn value='Enable unencrypted access' />";
// #########################################
// Development
// #########################################
static const char* const development =
"<h3>Development</h3>"
"<input type=button onclick=\"window.location.href='/settings/development'\" class=btn value='Development'>";
// #########################################
// Reboot
// #########################################
static const char* const rebootIndex =
"<h3>Device reboots now.</h3>";
// #########################################
// Wifi
// #########################################
static const char* const wifiSettingsIndex =
"<script>"
"function resetPassword() { document.getElementById('pass').value = ''; }"
"</script>"
"<h3>Settings</h3>"
"SSID"
"<input name=ssid placeholder='ssid' value='{ssid}'>"
"Password"
"<input id=pass name=pass placeholder='password' type='Password' value='{password}' onclick='resetPassword()'>"
"<input type=submit class=btn value=Save>";
static const char* const backupIndex =
"<p>This backups and restores the device configuration incl. the Basic Config, Privacy Zones and Wifi Settings.</p>"
"<h3>Backup</h3>"
"<input type='button' onclick=\"window.location.href='/settings/backup.json'\" class=btn value='Download' />"
"<h3>Restore</h3>";
static const char* const updateSdIndex = R""""(
<p>{description}</p>
<h3>From Github (preferred)</h3>
List also pre-releases<br><input type='checkbox' id='preReleases' onchange='selectFirmware()'>
<script>
let availableReleases;
async function updateFirmwareList() {
(await fetch('{releaseApiUrl}')).json().then(res => {
availableReleases = res;
selectFirmware();
})
}
function selectFirmware() {
const displayPreReleases = (document.getElementById('preReleases').checked == true);
url = "";
version = "";
availableReleases.filter(r => displayPreReleases || !r.prerelease).forEach(release => {
release.assets.filter(asset => asset.name.endsWith(".bin")).forEach(
asset => {
if (!url) {
version = release.name;
url = asset.browser_download_url;
}
}
)
}
)
if (url) {
document.getElementById('version').value = "Update to " + version;
document.getElementById('version').disabled = false;
document.getElementById('downloadUrl').value = url;
} else {
document.getElementById('version').value = "No version found";
document.getElementById('version').disabled = true;
document.getElementById('downloadUrl').value = "";
}
}
updateFirmwareList();
</script>
<input type='hidden' name='downloadUrl' id='downloadUrl' value=''/>
<input type='submit' name='version' id='version' class=btn value='Update' />
<h3>File Upload</h3>
)"""";
// #########################################
// Config
// #########################################
static const char* const configIndex =
"<h3>Sensor</h3>"
"Offset Sensor Left<input name='offsetS1' placeholder='Offset Sensor Left' value='{offset1}'>"
"<hr>"
"Offset Sensor Right<input name='offsetS2' placeholder='Offset Sensor Right' value='{offset2}'>"
"<hr>"
"Swap Sensors (Left ⇔ Right)<input type='checkbox' name='displaySwapSensors' {displaySwapSensors}>"
""
"<h3>Generic Display</h3>"
"Invert<br>(black ⇔ white)<input type='checkbox' name='displayInvert' {displayInvert}>"
"<hr>"
"Flip<br>(upside down ⇕)<input type='checkbox' name='displayFlip' {displayFlip}>"
""
"<h3>Measurement Display</h3>"
"Confirmation Time Window<br>(time in seconds to confirm until a new measurement starts)<input name='confirmationTimeWindow' placeholder='Seconds' value='{confirmationTimeWindow}'>"
"<hr>"
"Simple Mode<br>(all measurement display options below are ignored)<input type='checkbox' name='displaySimple' {displaySimple}>"
"<hr>"
"Show Left Measurement<input type='checkbox' name='displayLeft' {displayLeft}>"
"<hr>"
"Show Right Measurement<input type='checkbox' name='displayRight' {displayRight}>"
"<hr>"
"Show Satellites<input type='checkbox' name='displayGPS' {displayGPS}>"
"<hr>"
"Show Velocity<input type='checkbox' name='displayVELO' {displayVELO}>"
"<hr>"
"Show Confirmation Stats<input type='checkbox' name='displayNumConfirmed' {displayNumConfirmed}>"
"<hr>"
"Show raw details for distance sensors <input type='checkbox' name='displayDistanceDetail' {displayDistanceDetail}>"
"<small>Displays raw, unfiltered distance sensor reading in cm (L=left/R=right) "
"and reading-cycles per second (F) in the form <code>LLL|FF|RRR</code> in the 2nd display line.</small>"
"<h3>Privacy Options</h3>"
"<label for='absolutePrivacy'>Dont record at all in privacy areas</label>"
"<input type='radio' id='absolutePrivacy' name='privacyOptions' value='absolutePrivacy' {absolutePrivacy}>"
"<hr>"
"<label for='noPosition'>Dont record position in privacy areas</label>"
"<input type='radio' id='noPosition' name='privacyOptions' value='noPosition' {noPosition}>"
"<hr>"
"<label for='noPrivacy'>Record even in privacy areas</label>"
"<input type='radio' id='noPrivacy' name='privacyOptions' value='noPrivacy' {noPrivacy}>"
"<hr>"
"Override Privacy when Pushing the Button<input type='checkbox' name='overridePrivacy' {overridePrivacy}>"
"<h3>Upload User Data</h3>"
"<input name='hostname' placeholder='API URL' value='{hostname}'>"
"<hr>"
"<input name='obsUserID' placeholder='API Key' value='{userId}' >"
"<h3>Operation</h3>"
"Enable Bluetooth <input type='checkbox' name='bluetooth' {bluetooth}>"
"<hr>"
"SimRa Mode <input type='checkbox' name='simRaMode' {simRaMode}>"
"<input type=submit class=btn value=Save>";
static const char* const privacyIndexPostfix =
"<input type='submit' class='btn' value='Save'>"
"<hr>"
"Location: <div id='gps'>{gps}</div> <a href='javascript:window.location.reload()'>↻</a>"
"<input type='submit' name='addCurrent' id='addCurrent' class=btn value='Add current location' />"
"<script>"
"async function updateLocation() {"
" if (document.readyState == 'complete') {"
" const gps = await fetch('/gps').then(res => res.text());"
" document.getElementById('gps').innerHTML = gps;"
" }"
" setTimeout(updateLocation, 1000);"
"}"
"setTimeout(updateLocation, 1000);"
"</script>"
;
static const char* const deleteIndex =
"<h3>Flash</h3>"
"<p>Flash stores ssl certificate and configuration.</p>"
"<label for='flash'>Format flash</label>"
"<input type='checkbox' id='flash' name='flash' "
"onchange=\"document.getElementById('flashCert').checked = document.getElementById('flashConfig').checked = document.getElementById('flash').checked;\">"
"<label for='flashCert'>Delete ssl certificate, a new one will be created at the next start.</label>"
// Link https://support.mozilla.org/en-US/kb/Certificate-contains-the-same-serial-number-as-another-certificate ?
"<input type='checkbox' id='flashCert' name='flashCert'>"
"<label for='flashConfig'>Delete configuration, default settings will be used at the next start,"
" consider storing a <a href='/settings/backup.json'>Backup</a> 1st.</label>"
"<input type='checkbox' id='flashConfig' name='flashConfig'>"
"<h3>Memory</h3>"
"<label for='config'>Clear current configuration, wifi connection will stay.</label>"
"<input type='checkbox' id='config' name='config'>"
"<h3>SD Card</h3>"
"<label for='sdcard'>Delete OBS related content (aid_ini.ubx, tracknumber.txt, current_14d.*, "
"*.obsdata.csv, sdflash/*, trash/*, uploaded/*). The files are just removed from to filesystem "
"part of the data might be still read from the card. Be patient.</label>"
"<input type='checkbox' id='sdcard' name='sdcard'>"
"<input type='submit' class='btn' value='Delete' onclick=\"return confirm('Are you sure?')\" />";
static const char* const settingsSecurityIndex =
"<h3>Http</h3>"
"<label for='pin'>Wish pin for http access, the pin will still be displayed on"
" the OBS display. Pin must consist out of 3-8 numeric digits.</label>"
"<input name='pin' type='number' value='{pin}' maxlength='8'>"
// "<label for='httpAccess'>Allow full access via http. Do this only in networks you"
// " have control over. All data send or retrieved from the OBS can be intercepted"
// " from within your network as well as everybody in this network has full access to"
// " your OBS. The setting wil be reset if you change the WiFi settings.</label>"
// "<input type='checkbox' id='httpAccess' name='httpAccess' />"
"<input type=submit class=btn value='Save'>"
// "<h3>OBS SSL Cert</h3>"
// "<label for='flashCert'>Delete ssl certificate, a new one will be created at the next start.</label>"
// "<input type=button onclick=\"window.location.href='/settings/deleteSslCert'\" class=btn value='Renew SSL Cert'>"
// "<h3>CA Cert Management</h3>"
// "For outgoing https connections the OBS has to trust different authorities (CA). "
// "The OBS can not hold all well known authorities like your browser does "
// "here you can add or remove the CAs your OBS trusts, usually you do not need "
// "to modify this. You can not remove CAs trusted by the OBS by default, but "
// "you can add additional CAs to trust here."
// "{caList}";
;
// #########################################
static String getParameter(const std::vector<std::pair<String,String>> ¶ms, const String& name, const String& def = "") {
for (const auto& param : params) {
if (param.first == name) {
return param.second;
}
}
return def;
}
static String getParameter(HTTPRequest *req, const String& name, const String& def = "") {
std::string value;
if (req->getParams()->getQueryParameter(name.c_str(), value)) {
return String(value.c_str());
}
return def;
}
static String replacePlain(const String &body, const String &key, const String &value) {
String str(body);
str.replace(key, value);
return str;
}
static String replaceHtml(const String &body, const String &key, const String &value) {
return replacePlain(body, key, ObsUtils::encodeForXmlAttribute(value));
}
static std::vector<std::pair<String,String>> extractParameters(HTTPRequest *req);
static void handleNotFound(HTTPRequest * req, HTTPResponse * res);
static void handleIndex(HTTPRequest * req, HTTPResponse * res);
static void handleAbout(HTTPRequest * req, HTTPResponse * res);
static void handleReboot(HTTPRequest * req, HTTPResponse * res);
static void handleBackup(HTTPRequest * req, HTTPResponse * res);
static void handleBackupDownload(HTTPRequest * req, HTTPResponse * res);
static void handleBackupRestore(HTTPRequest * req, HTTPResponse * res);
static void handleWifi(HTTPRequest * req, HTTPResponse * res);
static void handleWifiSave(HTTPRequest * req, HTTPResponse * res);
static void handleConfig(HTTPRequest * req, HTTPResponse * res);
static void handleConfigSave(HTTPRequest * req, HTTPResponse * res);
static void handleFirmwareUpdateSd(HTTPRequest * req, HTTPResponse * res);
static void handleFirmwareUpdateSdAction(HTTPRequest * req, HTTPResponse * res);
static void handleFirmwareUpdateSdUrlAction(HTTPRequest * req, HTTPResponse * res);
static void handleFlashUpdate(HTTPRequest * req, HTTPResponse * res);
static void handleFlashFileUpdateAction(HTTPRequest * req, HTTPResponse * res);
static void handleFlashUpdateUrlAction(HTTPRequest * req, HTTPResponse * res);
#ifdef DEVELOP
static void handleDev(HTTPRequest * req, HTTPResponse * res);
static void handleDevAction(HTTPRequest * req, HTTPResponse * res);
#endif
static void handlePrivacyAction(HTTPRequest * req, HTTPResponse * res);
static void handleGps(HTTPRequest * req, HTTPResponse * res);
static void handleUpload(HTTPRequest * req, HTTPResponse * res);
static void handlePrivacy(HTTPRequest *req, HTTPResponse *res);
static void handlePrivacyDeleteAction(HTTPRequest *req, HTTPResponse *res);
static void handleSd(HTTPRequest *req, HTTPResponse *res);
static void handleDeleteFiles(HTTPRequest *req, HTTPResponse *res);
static void handleDelete(HTTPRequest *req, HTTPResponse *res);
static void handleDeleteAction(HTTPRequest *req, HTTPResponse *res);
static void handleDownloadCert(HTTPRequest *req, HTTPResponse * res);
static void handleSettingSecurity(HTTPRequest *, HTTPResponse * res);
static void handleSettingSecurityAction(HTTPRequest * req, HTTPResponse * res);
static void handleHttpsRedirect(HTTPRequest *req, HTTPResponse *res);
static void handleHttpAction(HTTPRequest *req, HTTPResponse *res);
static void accessFilter(HTTPRequest * req, HTTPResponse * res, std::function<void()> next);
bool configServerWasConnectedViaHttpFlag = false;
static void tryWiFiConnect();
static uint16_t countFilesInRoot();
static String ensureSdIsAvailable();
static void moveToUploaded(const String &fileName);
String getIp() {
if (WiFiClass::status() != WL_CONNECTED) {
return WiFi.softAPIP().toString();
} else {
return WiFi.localIP().toString();
}
}
void updateDisplay(SSD1306DisplayDevice * const display, String action = "") {
if (action.isEmpty()) {
display->showTextOnGrid(0, 0, "Ver.:");
display->showTextOnGrid(1, 0, OBSVersion);
if (WiFiClass::status() == WL_CONNECTED) {
display->showTextOnGrid(0, 1, "SSID:");
display->showTextOnGrid(1, 1, WiFi.SSID());
display->showTextOnGrid(0, 2, "IP:");
display->showTextOnGrid(1, 2, WiFi.localIP().toString());
} else if (WiFiGenericClass::getMode() == WIFI_MODE_AP || WiFiGenericClass::getMode() == WIFI_MODE_APSTA) {
// OK??
display->showTextOnGrid(0, 1, "AP: " + WiFi.softAPSSID());
display->showTextOnGrid(0, 2, "IP:");
display->showTextOnGrid(1, 2, WiFi.softAPIP().toString());
display->showTextOnGrid(0, 3, "Pass:");
display->showTextOnGrid(1, 3, "12345678");
} else {
log_w("Unexpected wifi mode %d ", WiFiGenericClass::getMode());
}
} else {
displayTest->showTextOnGrid(0, 0,
theObsConfig->getProperty<String>(ObsConfig::PROPERTY_OBS_NAME));
displayTest->showTextOnGrid(0, 1, "IP:");
display->showTextOnGrid(1, 1, getIp());
displayTest->showTextOnGrid(1, 2, "");
displayTest->showTextOnGrid(0, 2, action);
displayTest->showTextOnGrid(0, 3, "");
displayTest->showTextOnGrid(1, 3, "");
}
}
void registerPages(HTTPServer * httpServer) {
httpServer->setDefaultNode(new ResourceNode("", HTTP_GET, handleNotFound));
httpServer->registerNode(new ResourceNode("/", HTTP_GET, handleIndex));
httpServer->registerNode(new ResourceNode("/about", HTTP_GET, handleAbout));
httpServer->registerNode(new ResourceNode("/reboot", HTTP_GET, handleReboot));
httpServer->registerNode(new ResourceNode("/settings/backup", HTTP_GET, handleBackup));
httpServer->registerNode(new ResourceNode("/settings/backup.json", HTTP_GET, handleBackupDownload));
httpServer->registerNode(new ResourceNode("/settings/restore", HTTP_POST, handleBackupRestore));
httpServer->registerNode(new ResourceNode("/settings/wifi", HTTP_GET, handleWifi));
httpServer->registerNode(new ResourceNode("/settings/wifi/action", HTTP_POST, handleWifiSave));
httpServer->registerNode(new ResourceNode("/settings/general", HTTP_GET, handleConfig));
httpServer->registerNode(new ResourceNode("/settings/general/action", HTTP_POST, handleConfigSave));
httpServer->registerNode(new ResourceNode("/updateFlash", HTTP_GET, handleFlashUpdate));
httpServer->registerNode(new ResourceNode("/updateFlash", HTTP_POST, handleFlashFileUpdateAction));
httpServer->registerNode(new ResourceNode("/updateFlashUrl", HTTP_POST, handleFlashUpdateUrlAction));
httpServer->registerNode(new ResourceNode("/updatesd", HTTP_GET, handleFirmwareUpdateSd));
httpServer->registerNode(new ResourceNode("/updatesd", HTTP_POST, handleFirmwareUpdateSdAction));
httpServer->registerNode(new ResourceNode("/updateSdUrl", HTTP_POST, handleFirmwareUpdateSdUrlAction));
httpServer->registerNode(new ResourceNode("/delete", HTTP_GET, handleDelete));
httpServer->registerNode(new ResourceNode("/delete", HTTP_POST, handleDeleteAction));
httpServer->registerNode(new ResourceNode("/privacy_action", HTTP_POST, handlePrivacyAction));
httpServer->registerNode(new ResourceNode("/gps", HTTP_GET, handleGps));
httpServer->registerNode(new ResourceNode("/upload", HTTP_GET, handleUpload));
httpServer->registerNode(new ResourceNode("/settings/privacy", HTTP_GET, handlePrivacy));
httpServer->registerNode(new ResourceNode("/privacy_delete", HTTP_GET, handlePrivacyDeleteAction));
httpServer->registerNode(new ResourceNode("/sd", HTTP_GET, handleSd));
httpServer->registerNode(new ResourceNode("/deleteFiles", HTTP_POST, handleDeleteFiles));
httpServer->registerNode(new ResourceNode("/cert", HTTP_GET, handleDownloadCert));
httpServer->registerNode(new ResourceNode("/settings/security", HTTP_GET, handleSettingSecurity));
httpServer->registerNode(new ResourceNode("/settings/security", HTTP_POST, handleSettingSecurityAction));
httpServer->addMiddleware(&accessFilter);
httpServer->setDefaultHeader("Server", std::string("OBS/") + OBSVersion);
}
void beginPages() {
registerPages(server);
insecureServer->registerNode(new ResourceNode("/cert", HTTP_GET, handleDownloadCert));
insecureServer->registerNode(new ResourceNode("/http", HTTP_POST, handleHttpAction));
insecureServer->setDefaultNode(new ResourceNode("", HTTP_GET, handleHttpsRedirect));
insecureServer->setDefaultHeader("Server", std::string("OBS/") + OBSVersion);
}
static int ticks;
static void progressTick() {
displayTest->drawWaitBar(5, ticks++);
}
static void createHttpServer() {
log_i("About to create http server.");
if (!Https::existsCertificate()) {
displayTest->clear();
displayTest->showTextOnGrid(0, 2, "Creating ssl cert,");
displayTest->showTextOnGrid(0, 3, "be patient.");
}
serverSslCert = Https::getCertificate(progressTick);
server = new HTTPSServer(serverSslCert, 443, 2);
displayTest->clear();
updateDisplay(displayTest);
insecureServer = new HTTPServer(80, 2);
beginPages();
log_i("Starting http(s) servers.");
server->start();
insecureServer->start();
}
bool configServerWasConnectedViaHttp() {
return configServerWasConnectedViaHttpFlag;
}
void touchConfigServerHttp() {
configServerWasConnectedViaHttpFlag = true;
}
String createPage(const String& content, const String& additionalContent = "") {
configServerWasConnectedViaHttpFlag = true;
String result;
result += header;
result += content;
result += additionalContent;
result += footer;
return result;
}
String replaceDefault(String html, const String& subTitle, const String& action = "#") {
configServerWasConnectedViaHttpFlag = true;
html = replaceHtml(html, "{title}",OBS_ID_SHORT + " - " + subTitle);
html = replaceHtml(html, "{version}", OBSVersion);
html = replaceHtml(html, "{subtitle}", subTitle);
html = replaceHtml(html, "{action}", action);
displayTest->clear();
updateDisplay(displayTest, "Menu: " + subTitle);
return html;
}
static void sendPlainText(HTTPResponse * res, const String& data) {
res->setHeader("Content-Type", "text/plain");
res->setHeader("Connection", "keep-alive");
res->print(data);
}
static void sendHtml(HTTPResponse * res, const String& data) {
res->setHeader("Content-Type", "text/html");
res->print(data);
}
static void sendHtml(HTTPResponse * res, const char * data) {
res->setHeader("Content-Type", "text/html");
res->print(data);
}
static void sendRedirect(HTTPResponse * res, const String& location) {
res->setHeader("Location", location.c_str());
res->setStatusCode(302);
res->finalize();
}
static void handleNotFound(HTTPRequest * req, HTTPResponse * res) {
// Discard request body, if we received any
// We do this, as this is the default node and may also server POST/PUT requests
req->discardRequestBody();
// Set the response status
res->setStatusCode(404);
res->setStatusText("Not Found");
sendHtml(res, replaceDefault(header, "Not Found"));
res->println("<h3>404 Not Found</h3><p>The requested resource was not found on this server.</p>");
res->println("<input type=button onclick=\"window.location.href='/'\" class='btn' value='Home' />");
res->print(footer);
}
bool CreateWifiSoftAP() {
bool softAccOK;
WiFi.disconnect();
log_i("Initialize SoftAP");
String apName = OBS_ID;
String APPassword = "12345678";
softAccOK = WiFi.softAP(apName.c_str(), APPassword.c_str(), 1, 0, 1);
delay(2000); // Without delay I've seen the IP address blank
/* Soft AP network parameters */
IPAddress apIP(172, 20, 0, 1);
IPAddress netMsk(255, 255, 255, 0);
WiFi.softAPConfig(apIP, apIP, netMsk);
if (softAccOK) {
dnsServer = new DNSServer();
// with "*" we get a lot of requests from all sort of apps,
// use obs.local here
dnsServer->start(53, "obs.local", apIP);
log_i("AP successful IP: %s", apIP.toString().c_str());
} else {
log_e("Soft AP Error. Name: %s Pass: %s", apName.c_str(), APPassword.c_str());
}
updateDisplay(displayTest);
return softAccOK;
}
/* Actions to be taken when we get internet. */
static void wifiConectedActions() {
log_i("Connected to %s, IP: %s",
WiFi.SSID().c_str(), WiFi.localIP().toString().c_str());
if (dnsServer) { // was used to announce AP ip
dnsServer->start(53, "obs.local", WiFi.localIP());
}
updateDisplay(displayTest);
MDNS.begin("obs");
TimeUtils::setClockByNtp(WiFi.gatewayIP().toString().c_str());
if (SD.begin() && WiFiClass::status() == WL_CONNECTED) {
AlpData::update(displayTest);
}
}
/* callback function called if wifi data is received via improv */
bool initWifi(const std::string & ssid, const std::string & password) {
log_i("Received WiFi credentials for SSID '%s'", ssid.c_str());
theObsConfig->setProperty(0, ObsConfig::PROPERTY_WIFI_SSID, ssid);
theObsConfig->setProperty(0, ObsConfig::PROPERTY_WIFI_PASSWORD, password);
displayTest->clear();
displayTest->showTextOnGrid(0, 1, "SSID:");
displayTest->showTextOnGrid(1, 1, ssid.c_str());
displayTest->showTextOnGrid(0, 2, "Connecting (IMPROV)...");
WiFi.disconnect();
tryWiFiConnect();
bool connected = WiFiClass::status() == WL_CONNECTED;
if (connected) {
theObsConfig->saveConfig();
wifiConectedActions();
} else {
CreateWifiSoftAP();
displayTest->showTextOnGrid(0, 4, "Connect failed.");
}
return connected;
}
/* Callback for improv - status of device */
static ObsImprov::State improvCallbackGetWifiStatus() {
ObsImprov::State result;
if (WiFiClass::status() == WL_CONNECTED) {
result = ObsImprov::State::PROVISIONED;
} else { // not sure for STATE_PROVISIONING
result = ObsImprov::State::READY;
}
return result;
}
static std::string improvCallbackGetDeviceUrl() {
std::string url = "";
if (WiFiClass::status() == WL_CONNECTED) {
theObsConfig->saveConfig();
url += "http://";
url += WiFi.localIP().toString().c_str();
url += + "/";
}
log_d("Device URL: '%s'", url.c_str());
return url;
}
static void createImprovServer() {
obsImprov = new ObsImprov(initWifi,
improvCallbackGetWifiStatus,
improvCallbackGetDeviceUrl,
&Serial);
obsImprov->setDeviceInfo("OpenBikeSensor", OBSVersion,
ESP.getChipModel(),
OBS_ID.c_str());
}
void startServer(ObsConfig *obsConfig) {
theObsConfig = obsConfig;
uint8_t mac[6];
esp_efuse_mac_get_default(mac);
char ssid[28];
snprintf(ssid, sizeof(ssid), "OpenBikeSensor-%02X%02X%02X%02X%02X%02X", mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
OBS_ID = String(ssid);
OBS_ID_SHORT = "OBS-" + OBS_ID.substring(15,19);
displayTest->clear();
displayTest->showTextOnGrid(0, 0, "Ver.:");
displayTest->showTextOnGrid(1, 0, OBSVersion);
displayTest->showTextOnGrid(0, 1, "SSID:");
displayTest->showTextOnGrid(1, 1,
theObsConfig->getProperty<String>(ObsConfig::PROPERTY_WIFI_SSID));
tryWiFiConnect();
if (WiFiClass::status() != WL_CONNECTED) {
CreateWifiSoftAP();
touchConfigServerHttp(); // side effect do not allow track upload via button
MDNS.begin("obs");
} else {
wifiConectedActions();
}
createHttpServer();
createImprovServer();
}
static void tryWiFiConnect() {
if (!WiFiGenericClass::mode(WIFI_MODE_STA)) {
log_e("Failed to enable WiFi station mode.");
}
if (!WiFi.setHostname("obs")) {
log_e("Failed to set hostname to 'obs'.");
}
if (theObsConfig->getProperty<String>(ObsConfig::PROPERTY_WIFI_SSID).isEmpty()) {
log_w("No wifi SID set - will not try to connect.");
return;
}
const auto startTime = millis();
const uint16_t timeout = 10000;
// Connect to WiFi network
while ((WiFiClass::status() != WL_CONNECTED) && (( millis() - startTime) <= timeout)) {
log_i("Trying to connect to %s",
theObsConfig->getProperty<const char *>(ObsConfig::PROPERTY_WIFI_SSID));
wl_status_t status = WiFi.begin(
theObsConfig->getProperty<const char *>(ObsConfig::PROPERTY_WIFI_SSID),
theObsConfig->getProperty<const char *>(ObsConfig::PROPERTY_WIFI_PASSWORD));
log_d("WiFi status after begin is %d", status);
status = static_cast<wl_status_t>(WiFi.waitForConnectResult());
while(status != WL_CONNECTED && (( millis() - startTime) <= timeout)) {
log_d("WiFi status after wait is %d", status);
if (status >= WL_CONNECT_FAILED) {
log_i("WiFi resetting connection for retry. (status 0x%02x))", status);
WiFi.disconnect(true, true);
break;
} else if (status == WL_NO_SSID_AVAIL) {
log_i("WiFi SSID not found - delay (status 0x%02x))", status);
delay(250);// WiFi.scanNetworks(false);
}
delay(250);
status = static_cast<wl_status_t>(WiFi.waitForConnectResult());
}
}
}
static void handleIndex(HTTPRequest *, HTTPResponse * res) {
// ###############################################################
// ### Index ###
// ###############################################################
String html = createPage(navigationIndex);
html = replaceDefault(html, "Navigation");
sendHtml(res, html);
}
static String keyValue(const String& key, const String& value, const String& suffix = "") {
return "<b>" + ObsUtils::encodeForXmlText(key) + ":</b> " + value + suffix + "<br />";
}
static String keyValue(const String& key, const uint32_t value, const String& suffix = "") {
return keyValue(key, String(value), suffix);
}
static String keyValue(const String& key, const int32_t value, const String& suffix = "") {
return keyValue(key, String(value), suffix);
}
static String keyValue(const String& key, const uint64_t value, const String& suffix = "") {
// is long this sufficient?
return keyValue(key, String((unsigned long) value), suffix);
}
static String appVersion(const esp_partition_t *partition) {
esp_app_desc_t app_desc;
esp_err_t ret = ESP_ERROR_CHECK_WITHOUT_ABORT(esp_ota_get_partition_description(partition, &app_desc));
if (ret == ESP_OK) {
char buffer[256];
snprintf(buffer, sizeof(buffer),
"App '%s', Version: '%s', IDF-Version: '%s', sha-256: %s, date: '%s', time: '%s'",
app_desc.project_name, app_desc.version, app_desc.idf_ver,
ObsUtils::sha256ToString(app_desc.app_elf_sha256).substring(0, 24).c_str(),
app_desc.date, app_desc.time);
return String(buffer);
} else {
return String("No app (") + String(esp_err_to_name(ret)) + String(")");
}
}
static void handleAbout(HTTPRequest *req, HTTPResponse * res) {
res->setHeader("Content-Type", "text/html");
res->print(replaceDefault(header, "About"));
String page;
gps.pollStatistics(); // takes ~100ms!
res->print("<h3>ESP32</h3>");
res->print(keyValue("Chip Model", ESP.getChipModel()));
res->print(keyValue("Chip Revision", ESP.getChipRevision()));
res->print(keyValue("Heap size", ObsUtils::toScaledByteString(ESP.getHeapSize())));
res->print(keyValue("Free heap", ObsUtils::toScaledByteString(ESP.getFreeHeap())));
res->print(keyValue("Min. free heap", ObsUtils::toScaledByteString(ESP.getMinFreeHeap())));
String chipId = String((uint32_t) ESP.getEfuseMac(), HEX) + String((uint32_t) (ESP.getEfuseMac() >> 32), HEX);
chipId.toUpperCase();
res->print(keyValue("Chip id", chipId));
res->print(keyValue("FlashApp Version", Firmware::getFlashAppVersion()));
res->print(keyValue("IDF Version", esp_get_idf_version()));
res->print(keyValue("App size", ObsUtils::toScaledByteString(ESP.getSketchSize())));
res->print(keyValue("App space", ObsUtils::toScaledByteString(ESP.getFreeSketchSpace())));
page += keyValue("App 'DEVELOP'",
#ifdef DEVELOP
"true"
#else
"false"
#endif
);
#ifdef CONFIG_LOG_DEFAULT_LEVEL
page += keyValue("Log default level", String(CONFIG_LOG_DEFAULT_LEVEL));
#endif
#ifdef CORE_DEBUG_LEVEL
page += keyValue("Core debug level", String(CORE_DEBUG_LEVEL));
#endif
res->print(page);
page.clear();
page += keyValue("Cores", ESP.getChipCores());
page += keyValue("CPU frequency", ESP.getCpuFreqMHz(), "MHz");
page += keyValue("SPIFFS size", ObsUtils::toScaledByteString(SPIFFS.totalBytes()));
page += keyValue("SPIFFS used", ObsUtils::toScaledByteString(SPIFFS.usedBytes()));
String files;
auto dir = SPIFFS.open("/");
auto file = dir.openNextFile();
while(file) {
files += "<br />";
files += file.name();
files += " ";
files += ObsUtils::toScaledByteString(file.size());
files += " ";
files += TimeUtils::dateTimeToString(file.getLastWrite());
file.close();
file = dir.openNextFile();
}
dir.close();
page += keyValue("SPIFFS files", files);
page += keyValue("System date time", TimeUtils::dateTimeToString(file.getLastWrite()));
page += keyValue("System millis", String(millis()));
if (voltageMeter) {
page += keyValue("Battery voltage", String(voltageMeter->read(), 2), "V");
}
res->print(page);
page.clear();
page += "<h3>App Partitions</h3>";
const esp_partition_t *running = esp_ota_get_running_partition();
page += keyValue("Current Partition", running->label);
const esp_partition_t *ota0 = esp_partition_find_first(ESP_PARTITION_TYPE_APP, ESP_PARTITION_SUBTYPE_APP_OTA_0,
nullptr);
page += keyValue("OTA-0 Partition", ota0->label);
page += keyValue("OTA-0 Partition Size", ObsUtils::toScaledByteString(ota0->size));
page += keyValue("OTA-0 App", appVersion(ota0));
const esp_partition_t *ota1 = esp_partition_find_first(ESP_PARTITION_TYPE_APP, ESP_PARTITION_SUBTYPE_APP_OTA_1,
nullptr);
page += keyValue("OTA-1 Partition", ota1->label);
page += keyValue("OTA-1 Partition Size", ObsUtils::toScaledByteString(ota1->size));
page += keyValue("OTA-1 App", appVersion(ota1));
res->print(page);
page.clear();
page += "<h3>SD Card</h3>";
page += keyValue("SD card size", ObsUtils::toScaledByteString(SD.cardSize()));
String sdCardType;
switch (SD.cardType()) {
case CARD_NONE: sdCardType = "NONE"; break;
case CARD_MMC: sdCardType = "MMC"; break;
case CARD_SD: sdCardType = "SD"; break;
case CARD_SDHC: sdCardType = "SDHC"; break;
default: sdCardType = "UNKNOWN"; break;
}
page += keyValue("SD card type", sdCardType);
page += keyValue("SD fs size", ObsUtils::toScaledByteString(SD.totalBytes()));
page += keyValue("SD fs used", ObsUtils::toScaledByteString(SD.usedBytes()));
page += "<h3>TOF Sensors</h3>";
page += keyValue("Left Sensor raw", sensorManager->getRawMedianDistance(LEFT_SENSOR_ID), "cm");
page += keyValue("Left Sensor max duration", sensorManager->getMaxDurationUs(LEFT_SENSOR_ID), "µs");
page += keyValue("Left Sensor min duration", sensorManager->getMinDurationUs(LEFT_SENSOR_ID), "µs");
page += keyValue("Left Sensor last start delay", sensorManager->getLastDelayTillStartUs(LEFT_SENSOR_ID), "µs");
page += keyValue("Left Sensor signal errors", sensorManager->getNoSignalReadings(LEFT_SENSOR_ID));
page += keyValue("Right Sensor raw", sensorManager->getRawMedianDistance(RIGHT_SENSOR_ID), "cm");
page += keyValue("Right Sensor max duration", sensorManager->getMaxDurationUs(RIGHT_SENSOR_ID), "µs");
page += keyValue("Right Sensor min duration", sensorManager->getMinDurationUs(RIGHT_SENSOR_ID), "µs");
page += keyValue("Right Sensor last start delay", sensorManager->getLastDelayTillStartUs(RIGHT_SENSOR_ID), "µs");
page += keyValue("Right Sensor signal errors", sensorManager->getNoSignalReadings(RIGHT_SENSOR_ID));
res->print(page);
page.clear();
page += "<h3>GPS</h3>";
page += keyValue("GPS valid checksum", gps.getValidMessageCount());
page += keyValue("GPS failed checksum", gps.getMessagesWithFailedCrcCount());
page += keyValue("GPS unexpected chars", gps.getUnexpectedCharReceivedCount());
page += keyValue("GPS hdop", gps.getCurrentGpsRecord().getHdopString());
page += keyValue("GPS fix", String(gps.getCurrentGpsRecord().getFixStatus(), 16));