Repository navigation
Expand file tree
/
Copy pathmain.cpp
More file actions
executable file
·2135 lines (1968 loc) · 68.8 KB
/
Copy pathmain.cpp
File metadata and controls
executable file
·2135 lines (1968 loc) · 68.8 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
/* OpenGarage Firmware
*
* Main loop
* Mar 2016 @ OpenGarage.io
*
* This file is part of the OpenGarage library
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see
* <http://www.gnu.org/licenses/>.
*/
#if defined(SERIAL_DEBUG)
#define BLYNK_DEBUG
#define BLYNK_PRINT Serial
#endif
#include <BlynkSimpleEsp8266.h>
#include <DNSServer.h>
#include <PubSubClient.h>
#include <OpenThingsFramework.h>
#include <Request.h>
#include <Response.h>
#include "pitches.h"
#include "OpenGarage.h"
#include "espconnect.h"
OpenGarage og;
OTF::OpenThingsFramework *otf = NULL;
ESP8266WebServer *updateServer = NULL;
DNSServer *dns = NULL;
WidgetLED blynk_door(BLYNK_PIN_DOOR);
WidgetLED blynk_car(BLYNK_PIN_CAR);
WidgetLED blynk_dval(BLYNK_PIN_DVAL);
static Ticker aux_ticker;
static Ticker ip_ticker;
static Ticker restart_ticker;
static WiFiClient wificlient;
static WiFiClient httpclient;
PubSubClient mqttclient(wificlient);
String mqtt_topic;
String mqtt_id;
static String scanned_ssids;
static byte read_cnt = 0;
static uint distance = 0;
static byte sn2_value = 0;
static float tempC = 0;
static float humid = 0;
static byte door_status = DOOR_STATUS_UNKNOWN; //door_status enum
static byte last_door_status = DOOR_STATUS_UNKNOWN;
static byte secplus_door_status = DOOR_STATUS_UNKNOWN;
static byte door_status_hist = 0;
static bool light_status = 0;
static bool lock_status = 0;
static bool obstruction_status = 0;
static uint16_t opening_count = 0;
static int vehicle_status = OG_VEH_ABSENT;
static uint led_blink_ms = LED_FAST_BLINK;
static ulong justopen_timestamp = 0;
static byte curr_mode;
extern bool fullbuffer;
// this is one byte storing the door status histogram
// maximum 8 bits
static ulong start_utc_time = 0;
static ulong curr_utc_time = 0;
static ulong curr_utc_hour= 0;
static HTTPClient http;
static bool light_blink_enabled = true;
// security+ objects
SecPlus1::Garage secplus1_garage(PIN_SW_RX, PIN_SW_TX);
#include "secplus2_identity_store.h"
#include "body_device_key.h"
#include "health_stats.h"
#include "audio_timing.h"
struct BuzzerSink {
void note(unsigned frequency, unsigned duration) { tone(PIN_BUZZER, frequency, duration); }
void silence() { noTone(PIN_BUZZER); }
};
static BuzzerSink buzzer;
static og_audio::Warning<BuzzerSink> warning_audio(buzzer);
static og_audio::Melody<BuzzerSink> startup_audio(buzzer);
static bool ip_audio_active=false, setup_reboot_pending=false;
static byte ip_note=0, ip_digit=0;
void cancel_diagnostic_audio() {
startup_audio.cancel();
ip_ticker.detach();
if (ip_audio_active) buzzer.silence();
ip_audio_active=false; ip_note=ip_digit=0;
}
void start_tune(og_audio::Tune tune) {
if (!og.alarm && !ip_audio_active) startup_audio.start(millis(),tune);
}
static HealthStats health_stats;
struct LoopMeasurement {
uint32_t started=micros();
LoopMeasurement() { health_stats.enter(millis()); }
~LoopMeasurement() { health_stats.finish(started,micros(),ESP.getFreeHeap()); }
};
static uint32_t secplus2_client_id = 0;
static bool secplus2_identity_ready = false;
static bool identity_restart_pending = false;
SecPlus2::Garage secplus2_garage(0, PIN_SW_RX, PIN_SW_TX);
void do_setup();
void otf_send_html_P(OTF::Response &res, const __FlashStringHelper *content) {
res.writeStatus(200, F("OK"));
res.writeHeader(F("Content-Type"), F("text/html"));
res.writeHeader(F("Access-Control-Allow-Origin"), F("*")); // from esp8266 2.4 this has to be sent explicitly
res.writeHeader(F("Content-Length"), strlen_P((char *) content));
res.writeHeader(F("Connection"), F("close"));
res.writeBodyData(content, strlen_P((char*)content));
DEBUG_PRINT(strlen_P((char *) content));
DEBUG_PRINTLN(F(" bytes sent."));
}
void otf_send_compressed_P(OTF::Response& res, const __FlashStringHelper* content, size_t len) {
res.writeStatus(200, F("OK"));
res.writeHeader(F("Content-Type"), F("text/html; charset=utf-8"));
res.writeHeader(F("Access-Control-Allow-Origin"), F("*")); // from esp8266 2.4 this has to be sent explicitly
res.writeHeader(F("Content-Length"), len);
res.writeHeader(F("Vary"), F("Accept-Encoding"));
res.writeHeader(F("Content-Encoding"), F("gzip"));
res.writeHeader(F("Cache-Control"), F("public, max-age=86400"));
res.writeHeader(F("Connection"), F("close"));
res.writeBodyData(content, len);
DEBUG_PRINT(len);
DEBUG_PRINTLN(F(" bytes sent."));
}
void otf_send_json(OTF::Response &res, String json) {
res.writeStatus(200, F("OK"));
res.writeHeader(F("Content-Type"), F("application/json"));
res.writeHeader(F("Access-Control-Allow-Origin"), F("*")); // from esp8266 2.4 this has to be sent explicitly
res.writeHeader(F("Content-Length"), json.length());
res.writeHeader(F("Connection"), F("close"));
res.writeBodyData(json.c_str(), json.length());
}
void otf_send_result(OTF::Response &res, byte code, const char *item = NULL) {
String json = F("{\"result\":");
json += code;
if (!item) item = "";
json += F(",\"item\":\"");
json += item;
json += F("\"");
json += F("}");
otf_send_json(res, json);
}
void updateserver_send_result(byte code, const char* item = NULL) {
String json = F("{\"result\":");
json += code;
if (!item) item = "";
json += F(",\"item\":\"");
json += item;
json += F("\"");
json += F("}");
updateServer->sendHeader("Access-Control-Allow-Origin", "*"); // from esp8266 2.4 this has to be sent explicitly
updateServer->send(200, "application/json", json);
}
// this is simplified version to check if MQTT / NTP server is valid domain name
bool valid_url(String s) {
return (s.length()>0 && s[0]!='-' && s.indexOf('.')>0);
}
String ipString;
static void append_age(String &json, uint32_t age) {
if (age==UINT32_MAX) json += F("-1");
else json += age;
}
static void append_health_json(String &json) {
json += F(",\"active_security_protocol\":"); json += og.options[OPTION_SECV].ival;
json += F(",\"free_heap\":"); json += ESP.getFreeHeap();
json += F(",\"reset_reason\":\""); json += ESP.getResetReason(); json += F("\"");
json += F(",\"reset_reason_code\":"); json += ESP.getResetInfoPtr()->reason;
json += F(",\"uptime_s\":"); json += health_stats.uptime_s();
json += F(",\"min_free_heap\":");
if (health_stats.min_heap()==UINT32_MAX) json += ESP.getFreeHeap();
else json += health_stats.min_heap();
json += F(",\"max_loop_us\":"); json += health_stats.max_loop_us();
if (!og.has_swrx) return;
if (og.options[OPTION_SECV].ival == 1) {
json += F(",\"secplus1_parity_errors\":"); json += secplus1_garage.get_parity_errors();
json += F(",\"secplus1_invalid_frames\":"); json += secplus1_garage.get_invalid_frames();
json += F(",\"secplus1_rx_overflows\":"); json += secplus1_garage.get_overflows();
json += F(",\"secplus1_tx_deferrals\":"); json += secplus1_garage.get_tx_deferrals();
json += F(",\"secplus1_expired_commands\":"); json += secplus1_garage.get_expired_commands();
json += F(",\"secplus1_door_age_ms\":"); append_age(json,secplus1_garage.get_door_age());
json += F(",\"secplus1_light_lock_age_ms\":"); append_age(json,secplus1_garage.get_light_lock_age());
#ifdef OG_SEC1_DIAGNOSTICS
const auto &gap=secplus1_garage.diagnostic_gap();
const auto &gd=gap.diagnostic;
const auto &td=secplus1_garage.diagnostic;
json += F(",\"secplus1_diag\":{\"exchanges\":"); json += gd.exchanges;
json += F(",\"resets\":"); json += gd.resets;
json += F(",\"bad_latency\":"); json += gd.bad_latency;
json += F(",\"zero_latency\":"); json += gd.zero_latency;
json += F(",\"bad_interval\":"); json += gd.bad_interval;
json += F(",\"last_latency_ms\":"); json += gd.latency;
json += F(",\"last_interval_ms\":"); json += gd.interval;
json += F(",\"learned_count\":"); json += gap.learned_count();
json += F(",\"max_learned_count\":"); json += gd.max_count;
json += F(",\"minimum_ms\":"); json += gap.learned_minimum();
json += F(",\"maximum_ms\":"); json += gap.learned_maximum();
json += F(",\"reply_age_ms\":"); append_age(json,gap.reply_age(millis()));
json += F(",\"loops\":"); json += td.loops;
json += F(",\"gap_ready_loops\":"); json += td.gap_ready_loops;
json += F(",\"last_block\":"); json += td.last_block;
json += F(",\"blocked\":[");
for(unsigned i=0;i<9;++i) { if(i) json += ','; json += td.blocked[i]; }
json += F("]}");
#endif
} else if (og.options[OPTION_SECV].ival == 2) {
json += F(",\"secplus2_status_age_ms\":"); append_age(json,secplus2_garage.get_status_age());
json += F(",\"secplus2_query_failures\":"); json += secplus2_garage.get_query_failures();
json += F(",\"secplus2_action_write_failures\":"); json += secplus2_garage.get_write_failures();
json += F(",\"secplus2_tx_deferrals\":"); json += secplus2_garage.get_tx_deferrals();
json += F(",\"secplus2_expired_commands\":"); json += secplus2_garage.get_expired_commands();
json += F(",\"secplus2_control_fault\":"); json += secplus2_garage.controls_faulted() ? 1 : 0;
json += F(",\"secplus2_recovery\":\""); json += secplus2_garage.recovery_status(); json += F("\"");
}
}
void report_ip() {
static uint notes[] = {NOTE_C4, NOTE_CS4, NOTE_D4, NOTE_DS4, NOTE_E4, NOTE_F4, NOTE_FS4, NOTE_G4, NOTE_GS4, NOTE_A4};
if (!ip_audio_active || og.alarm) return;
byte ¬e=ip_note, &digit=ip_digit;
if(digit == ipString.length()) { // play ending note
og.play_note(NOTE_C6); digit++; note=0;
ip_ticker.once_ms(1000, report_ip);
return;
} else if(digit == ipString.length()+1) { // end
og.play_note(0); note=0; digit=0;
ip_audio_active=false;
return;
}
char c = ipString.charAt(digit);
if (c==' ') {
og.play_note(0); digit++; note=0;
ip_ticker.once_ms(1000, report_ip);
} else if (c=='.') {
og.play_note(NOTE_C5);
digit++; note=0;
ip_ticker.once_ms(500, report_ip);
} else if (c>='0' && c<='9') {
byte idx=9; // '0' maps to index 9;
if(c>='1') idx=c-'1';
if(note==idx+1) {
og.play_note(0); note++;
ip_ticker.once_ms(1000, report_ip);
} else if(note==idx+2) {
digit++; note=0;
ip_ticker.once_ms(100, report_ip);
} else {
og.play_note(notes[note]);
note++;
ip_ticker.once_ms(500, report_ip);
}
}
}
void restart_in(uint32_t ms) {
if(og.state != OG_STATE_WAIT_RESTART) {
og.state = OG_STATE_WAIT_RESTART;
DEBUG_PRINTLN(F("Prepare to restart..."));
restart_ticker.once_ms(ms, og.restart);
}
}
// Both the provisioning poll and the normal loop can notice association first.
// Persist once, play the complete success tune, then restart to enter STA mode.
void complete_ap_setup() {
if (setup_reboot_pending || og.options[OPTION_MOD].ival==OG_MOD_STA) return;
og.options[OPTION_MOD].ival=OG_MOD_STA;
og.options_save();
setup_reboot_pending=true;
start_tune(og_audio::Tune::SETUP_SUCCESS);
}
void on_home(const OTF::Request &req, OTF::Response &res) {
if(curr_mode == OG_MOD_AP) {
otf_send_compressed_P(res, (const __FlashStringHelper*)ap_home_html_gz, ap_home_html_gz_len);
} else {
otf_send_compressed_P(res, (const __FlashStringHelper*)sta_home_html_gz, sta_home_html_gz_len);
}
}
void on_sta_view_options(const OTF::Request &req, OTF::Response &res) {
otf_send_compressed_P(res, (const __FlashStringHelper*)sta_options_html_gz, sta_options_html_gz_len);
}
void on_sta_view_logs(const OTF::Request &req, OTF::Response &res) {
otf_send_compressed_P(res, (const __FlashStringHelper*)sta_logs_html_gz, sta_logs_html_gz_len);
}
char dec2hexchar(byte dec) {
if(dec<10) return '0'+dec;
else return 'A'+(dec-10);
}
String get_mac() {
static String hex = "";
if(!hex.length()) {
byte mac[6];
WiFi.macAddress(mac);
for(byte i=0;i<6;i++) {
hex += dec2hexchar((mac[i]>>4)&0x0F);
hex += dec2hexchar(mac[i]&0x0F);
if(i!=5) hex += ":";
}
}
return hex;
}
String get_ap_ssid() {
static String ap_ssid = "";
if(!ap_ssid.length()) {
byte mac[6];
WiFi.macAddress(mac);
ap_ssid = "OG_";
for(byte i=3;i<6;i++) {
ap_ssid += dec2hexchar((mac[i]>>4)&0x0F);
ap_ssid += dec2hexchar(mac[i]&0x0F);
}
}
return ap_ssid;
}
String get_ip() {
IPAddress _ip = WiFi.localIP();
String ip = String(_ip[0]);
ip += ".";
ip += _ip[1];
ip += ".";
ip += _ip[2];
ip += ".";
ip += _ip[3];
return ip;
}
void sta_controller_fill_json(String& json) {
json.reserve(STRING_RESERVE_SIZE);
json = "";
json += F("{\"dist\":");
json += distance;
if(og.options[OPTION_SN2].ival>OG_SN2_NONE) {
json += F(",\"sn2\":");
json += sn2_value;
}
json += F(",\"secv\":");
json += og.options[OPTION_SECV].ival;
json += F(",\"door\":");
json += door_status;
json += F(",\"vehicle\":");
json += vehicle_status;
json += F(",\"rcnt\":");
json += read_cnt;
json += F(",\"fwv\":");
json += og.options[OPTION_FWV].ival;
json += F(",\"has_swrx\":");
json += og.has_swrx;
if(og.has_swrx) {
if(og.options[OPTION_SECV].ival>=1) {
json += F(",\"light\":");
json += light_status;
json += F(",\"lock\":");
json += lock_status;
json += F(",\"obstruct\":");
json += obstruction_status;
if(og.options[OPTION_SECV].ival==2) {
const bool valid=secplus2_garage.status_valid();
json += F(",\"door_valid\":"); json += valid ? 1 : 0;
json += F(",\"light_lock_valid\":"); json += valid ? 1 : 0;
json += F(",\"obstruct_valid\":"); json += valid ? 1 : 0;
json += F(",\"recovery_status\":\"");
json += secplus2_garage.recovery_status(); json += F("\"");
json += F(",\"control_fault\":"); json += secplus2_garage.controls_faulted() ? 1 : 0;
json += F(",\"nopenings\":");
json += opening_count;
}
if(og.options[OPTION_SECV].ival==1) {
json += F(",\"door_valid\":");
json += secplus1_garage.door_valid() ? 1 : 0;
json += F(",\"light_lock_valid\":");
json += secplus1_garage.light_lock_valid() ? 1 : 0;
json += F(",\"obstruct_valid\":");
json += secplus1_garage.obstruction_valid() ? 1 : 0;
json += F(",\"panel_status\":\"");
json += secplus1_garage.get_panel_description();
json += F("\",\"command_status\":\"");
json += secplus1_garage.get_action_result();
json += F("\"");
json += F(",\"pemu\":");
json += secplus1_garage.get_panel_emu_status();
}
}
}
json += F(",\"name\":\"");
json += og.options[OPTION_NAME].sval;
json += F("\",\"mac\":\"");
json += get_mac();
json += F("\",\"cid\":");
json += ESP.getChipId();
json += F(",\"rssi\":");
json += (int16_t)WiFi.RSSI();
json += F(",\"cld\":");
byte cld = og.options[OPTION_CLD].ival;
json += cld;
if(cld>CLOUD_NONE) {
json += F(",\"clds\":");
if(cld==CLOUD_BLYNK) json += (Blynk.connected()?1:0);
else if(cld==CLOUD_OTC) json += (otf->getCloudStatus());
else json += "0";
}
if(og.options[OPTION_TSN].ival) {
json += F(",\"temp\":");
json += tempC;
json += F(",\"humid\":");
json += humid;
}
json += F("}");
}
void on_sta_controller(const OTF::Request &req, OTF::Response &res) {
if(curr_mode == OG_MOD_AP) return;
String json;
sta_controller_fill_json(json);
otf_send_json(res, json);
}
static void append_debug_details(const OTF::Request &req, String &json) {
const char *verbose = req.getQueryParameter("verbose");
if (!verbose || strcmp(verbose, "1") != 0) return;
if (og.has_swrx && og.options[OPTION_SECV].ival == 2) {
json += F(",\"secplus2_client_id\":\"0x");
json += String(secplus2_client_id, HEX);
json += F("\"");
json += F(",\"secplus2_identity_ready\":");
json += secplus2_identity_ready ? F("true") : F("false");
}
append_health_json(json);
}
void on_sta_debug(const OTF::Request &req, OTF::Response &res) {
String json = "";
json.reserve(STRING_RESERVE_SIZE);
json += F("{");
json += F("\"rcnt\":");
json += read_cnt;
json += F(",\"fwv\":");
json += og.options[OPTION_FWV].ival;
json += F(",\"name\":\"");
json += og.options[OPTION_NAME].sval;
json += F("\",\"mac\":\"");
json += get_mac();
json += F("\",\"mqtt_topic\":\"");
json += mqtt_topic;
json += F("\",\"devip\":\"");
json += WiFi.localIP().toString();
json += F("\",\"cid\":");
json += ESP.getChipId();
append_debug_details(req, json);
json += F(",\"rssi\":");
json += (int16_t)WiFi.RSSI();
json += F(",\"bssid\":\"");
json += WiFi.BSSIDstr();
json += F("\",\"build\":\"");
json += (F(__DATE__));
json += F("\",\"Freeheap\":");
json += (uint16_t)ESP.getFreeHeap();
json += F(",\"flash_size\":");
json += (uint32_t)ESP.getFlashChipRealSize();
json += F(",\"has_swrx\":");
json += og.has_swrx;
json += F("}");
otf_send_json(res, json);
}
void sta_logs_fill_json(String& json, OTF::Response &res) {
json = "";
json.reserve(2048); // reserve capacity to reduce the overhead of String's +=
json += F("{\"name\":\"");
json += og.options[OPTION_NAME].sval;
json += F("\",\"starttime\":");
json += start_utc_time;
json += F(",\"time\":");
json += curr_utc_time;
json += F(",\"ncols\":");
json += og.options[OPTION_SN2].ival>OG_SN2_NONE ? 4 : 3;
json += F(",\"logs\":[");
if(!og.read_log_start()) {
json += F("]}");
return;
}
LogStruct l;
for(uint i=0;i<og.options[OPTION_LSZ].ival;i++) {
if(!og.read_log_next(l)) break;
if(!l.tstamp) continue;
json += F("[");
json += l.tstamp;
json += F(",");
json += l.status;
json += F(",");
json += l.dist;
if(og.options[OPTION_SN2].ival>OG_SN2_NONE) {
json += F(",");
json += l.sn2;
}
json += F("],");
}
og.read_log_end();
json.remove(json.length()-1); // remove the extra ,
json += F("]}");
}
void on_sta_logs(const OTF::Request &req, OTF::Response &res) {
if(curr_mode == OG_MOD_AP) return;
String json;
sta_logs_fill_json(json, res);
otf_send_json(res, json);
}
bool verify_device_key(const OTF::Request &req) {
if(req.isCloudRequest()){ // no need for dkey if this is coming from cloud connection
return true;
}
const char *dkey = req.getQueryParameter("dkey");
if(dkey != NULL && strcmp(dkey, og.options[OPTION_DKEY].sval.c_str()) == 0)
return true;
return false;
}
void on_reset_all(const OTF::Request &req, OTF::Response &res){
if(!verify_device_key(req)) {
otf_send_result(res, HTML_UNAUTHORIZED, nullptr);
return;
}
og.state = OG_STATE_RESET;
otf_send_result(res, HTML_SUCCESS, nullptr);
}
// POST only. Keep credentials out of URLs and require a key even over OTC.
void on_regenerate_secplus2_id(const OTF::Request &req, OTF::Response &res) {
if (!body_device_key_matches(req.getBody(), req.getBodyLength(), og.options[OPTION_DKEY].sval.c_str())) {
otf_send_result(res, HTML_UNAUTHORIZED, nullptr);
return;
}
if (og.options[OPTION_SECV].ival != 2) {
otf_send_json(res, F("{\"result\":0,\"message\":\"Select and save Security+ 2.0 first.\"}"));
return;
}
if (identity_restart_pending || og.state != OG_STATE_CONNECTED || og.alarm || secplus2_garage.command_pending()) {
otf_send_json(res, F("{\"result\":0,\"message\":\"Device busy. Wait for the pending action to finish, then retry.\"}"));
return;
}
// No pending actuation: stop the old identity before touching storage. Inhibit
// all further work until reboot, including on a failed/uncertain flash write.
identity_restart_pending = true;
secplus2_garage.stop();
Secplus2IdentityStore store;
uint32_t replacement = 0;
const bool saved = og_identity::load(store, []() -> uint32_t { return ESP.random(); }, true, replacement);
if (saved) {
String json = F("{\"result\":1,\"client_id\":\"0x");
json += String(replacement, HEX);
json += F("\",\"message\":\"New client ID saved. Restarting; WiFi and other settings are unchanged.\"}");
otf_send_json(res, json);
} else {
otf_send_json(res, F("{\"result\":0,\"message\":\"Could not verify the new ID. Restarting; check identity diagnostics before using controls.\"}"));
}
restart_in(1000);
}
void on_clear_log(const OTF::Request &req, OTF::Response &res) {
if(!verify_device_key(req)) {
otf_send_result(res, HTML_UNAUTHORIZED, nullptr);
return;
}
og.log_reset();
otf_send_result(res, HTML_SUCCESS, nullptr);
}
void secplus_update_door(SecPlusCommon::DoorStatus door_state) {
switch (door_state) {
case SecPlusCommon::DoorStatus::OPEN:
secplus_door_status = DOOR_STATUS_OPEN;
break;
case SecPlusCommon::DoorStatus::CLOSED:
secplus_door_status = DOOR_STATUS_CLOSED;
break;
case SecPlusCommon::DoorStatus::STOPPED:
secplus_door_status = DOOR_STATUS_STOPPED;
break;
case SecPlusCommon::DoorStatus::OPENING:
secplus_door_status = DOOR_STATUS_OPENING;
break;
case SecPlusCommon::DoorStatus::CLOSING:
secplus_door_status = DOOR_STATUS_CLOSING;
break;
default:
secplus_door_status = DOOR_STATUS_UNKNOWN;
}
}
void secplus1_state_callback(SecPlus1::state_struct_t state) {
secplus_update_door(state.door_state);
light_status = state.light_state;
lock_status = state.lock_state;
obstruction_status = state.obstruction_state;
}
void secplus2_state_callback(SecPlus2::state_struct_t state) {
secplus_update_door(state.door_state);
light_status = state.light_state;
lock_status = state.lock_state;
obstruction_status = state.obstruction_state;
opening_count = state.openings;
}
int run_auto_detect() {
secplus2_garage.stop();
secplus1_garage.stop(); // finish any possibly dispatched Sec+ 1.0 release tail
// Try Sec+ 2.0 first
if (secplus2_garage.detect()) {
return 2;
}
// If that fails, try Sec+ 1.0
if (secplus1_garage.detect()) {
return 1;
}
return 0; // Detected nothing
}
void on_auto_detect(const OTF::Request &req, OTF::Response &res) {
int detected_version = run_auto_detect();
String json = "{\"version\": " + String(detected_version) + "}";
otf_send_json(res, json);
}
void performDoorAction(uint8_t action, bool force_alarm_off = false) {
if (identity_restart_pending) return;
// Check if the requested action is valid based on the current door state
bool isValidAction = false;
if((og.options[OPTION_SECV].ival == 2) || // For Sec+ 2.0, open/close commands are always valid
(action == ACTION_TOGGLE) || // toggle action is always valid
(action == ACTION_OPEN && (door_status == DOOR_STATUS_CLOSED || door_status == DOOR_STATUS_CLOSING)) || // can only open from CLOSED or CLOSING states
(action == ACTION_CLOSE && (door_status == DOOR_STATUS_OPEN || door_status == DOOR_STATUS_STOPPED))) {
isValidAction = true;
}
if (!isValidAction) {
DEBUG_PRINTLN(F("Requested command not valid, or door already in requested state"));
return;
}
cancel_diagnostic_audio();
// This is the core logic for deciding whether to trigger the alarm or the door directly.
bool shouldTriggerAlarm = true;
if (force_alarm_off || // override is on
(!og.options[OPTION_ALM].ival) || // alarm not enabled
(og.options[OPTION_AOO].ival && (door_status==DOOR_STATUS_CLOSED || door_status==DOOR_STATUS_CLOSING || door_status==DOOR_STATUS_OPENING))) { shouldTriggerAlarm = false;
}
if (shouldTriggerAlarm) { // if using alarm
if (og.options[OPTION_SECV].ival == 2) {
og.set_alarm(0, action);
} else {
og.set_alarm();
}
return;
}
// no alarm
switch (og.options[OPTION_SECV].ival) {
case 2: // SecPlus 2.0
if (action == ACTION_OPEN) secplus2_garage.open_door();
else if (action == ACTION_CLOSE) secplus2_garage.close_door();
else secplus2_garage.toggle_door();
break;
case 1: // SecPlus 1.0
secplus1_garage.toggle_door();
break;
default: // No SecPlus (standard relay)
og.click_relay();
break;
}
}
void performLightAction(uint8_t action) {
switch(action) {
case ACTION_TOGGLE:
switch (og.options[OPTION_SECV].ival) {
case 2: // SecPlus 2
secplus2_garage.toggle_light();
break;
case 1: // SecPlus 1
secplus1_garage.toggle_light();
break;
default: // No secplus
DEBUG_PRINTLN(F("Command request not valid, light requires secplus"));
}
break;
case ACTION_OPEN: // TODO
case ACTION_CLOSE:
break;
}
}
void performLockAction(uint8_t action) {
switch(action) {
case ACTION_TOGGLE:
switch (og.options[OPTION_SECV].ival) {
case 2: // SecPlus 2
secplus2_garage.toggle_lock();
break;
case 1: // SecPlus 1
secplus1_garage.toggle_lock();
break;
default: // No secplus
DEBUG_PRINTLN(F("Command request not valid, light requires secplus"));
}
break;
case ACTION_OPEN: // TODO
case ACTION_CLOSE:
break;
}
}
void sta_change_controller_main(const OTF::Request &req, OTF::Response &res) {
if(curr_mode == OG_MOD_AP) return;
if(!verify_device_key(req)) {
otf_send_result(res, HTML_UNAUTHORIZED, nullptr);
return;
}
uint8_t action = 255;
if((bool)req.getQueryParameter("click")) { action = ACTION_TOGGLE; }
else if((bool)req.getQueryParameter("close")) { action = ACTION_CLOSE; }
else if((bool)req.getQueryParameter("open")) { action = ACTION_OPEN; }
char* light = req.getQueryParameter("light");
char* lock = req.getQueryParameter("lock");
if(action < 255) {
otf_send_result(res, HTML_SUCCESS, nullptr);
performDoorAction(action);
return;
}
if(light) {
otf_send_result(res, HTML_SUCCESS, nullptr);
if(strcmp(light, "toggle")==0) {
performLightAction(ACTION_TOGGLE);
}
return;
}
if(lock) {
otf_send_result(res, HTML_SUCCESS, nullptr);
if(strcmp(lock, "toggle")==0) {
performLockAction(ACTION_TOGGLE);
}
return;
}
if(req.getQueryParameter("reboot") != NULL) {
otf_send_result(res, HTML_SUCCESS, nullptr);
restart_in(1000);
} else if(req.getQueryParameter("apmode") != NULL) {
otf_send_result(res, HTML_SUCCESS, nullptr);
og.reset_to_ap();
} else {
otf_send_result(res, HTML_NOT_PERMITTED, nullptr);
}
}
void on_sta_change_controller(const OTF::Request &req, OTF::Response &res) {
sta_change_controller_main(req, res);
}
void sta_change_options_main(const OTF::Request &req, OTF::Response &res) {
if(curr_mode == OG_MOD_AP) return;
if(!verify_device_key(req)) {
otf_send_result(res, HTML_UNAUTHORIZED, nullptr);
return;
}
byte i;
OptionStruct *o = og.options;
byte usi = 0;
char *pem_value = req.getQueryParameter("pem");
if (pem_value != NULL) {
const char *requested_secv = req.getQueryParameter("secv");
const bool secplus1_selected = requested_secv ? strcmp(requested_secv, "1") == 0 : og.options[OPTION_SECV].ival == 1;
if (!og.has_swrx || !secplus1_selected ||
(strcmp(pem_value, "0") != 0 && strcmp(pem_value, "1") != 0)) {
otf_send_result(res, HTML_DATA_OUTOFBOUND, "pem");
return;
}
}
// FIRST ROUND: check option validity
// do not save option values yet
for(i=0;i<NUM_OPTIONS;i++,o++) {
const char *key = o->name.c_str();
// these options cannot be modified here
if(i==OPTION_FWV || i==OPTION_MOD || i==OPTION_SSID ||
i==OPTION_PASS || i==OPTION_DKEY)
continue;
if(o->max) { // integer options
char *sval = req.getQueryParameter(key);
if(sval != NULL) {
uint ival = String(sval).toInt();
if(ival>o->max) { // check max limit
otf_send_result(res, HTML_DATA_OUTOFBOUND, key);
return;
}
// check min limit
if(i==OPTION_DRI && ival < 50) {
otf_send_result(res, HTML_DATA_OUTOFBOUND, key);
return;
}
if(i==OPTION_RIV && ival < 1) {
otf_send_result(res, HTML_DATA_OUTOFBOUND, key);
return;
}
if(i==OPTION_LSZ && ival < 20) {
// minimal log size is 20
otf_send_result(res, HTML_DATA_OUTOFBOUND, key);
return;
}
if(i==OPTION_CDT && ival < 50) {
// click delay time should be at least 50 ms
otf_send_result(res, HTML_DATA_OUTOFBOUND, key);
return;
}
if(i==OPTION_USI && ival==1) {
// mark device IP and gateway IP change
usi = 1;
}
}
}
}
// Check device IP and gateway IP changes
const char* _dvip = "dvip";
const char* _gwip = "gwip";
const char* _subn = "subn";
const char* _dns1 = "dns1";
String dvip = req.getQueryParameter(_dvip);
String gwip = req.getQueryParameter(_gwip);
String subn = req.getQueryParameter(_subn);
String dns1 = req.getQueryParameter(_dns1);
if(usi) {
if(dvip != NULL) {
if(gwip != NULL) {
// check validity of IP address
IPAddress ip;
if(!ip.fromString(dvip)) { otf_send_result(res, HTML_DATA_FORMATERROR, _dvip); return;}
if(!ip.fromString(gwip)) { otf_send_result(res, HTML_DATA_FORMATERROR, _gwip); return;}
if(subn != NULL) {
if(!ip.fromString(subn)) {
otf_send_result(res, HTML_DATA_FORMATERROR, _subn);
return;
}
}
if(dns1 != NULL) {
if(!ip.fromString(dns1)) {
otf_send_result(res, HTML_DATA_FORMATERROR, _dns1);
return;
}
}
} else {
otf_send_result(res, HTML_DATA_MISSING, _gwip);
return;
}
} else {
otf_send_result(res, HTML_DATA_MISSING, _dvip);
return;
}
}
// Check device key change
const char* _nkey = "nkey";
const char* _ckey = "ckey";
char* nkey = req.getQueryParameter(_nkey);
char* ckey = req.getQueryParameter(_ckey);
if(nkey != NULL) {
if(ckey != NULL) {
if(strcmp(nkey,ckey)!=0) {
otf_send_result(res, HTML_MISMATCH, _ckey);
return;
}
} else {
otf_send_result(res, HTML_DATA_MISSING, _ckey);
return;
}
}
// SECOND ROUND: change option values
uint old_secv = og.options[OPTION_SECV].ival;
uint old_pem = og.options[OPTION_PEM].ival;
o = og.options;
for(i=0;i<NUM_OPTIONS;i++,o++) {
const char *key = o->name.c_str();
// these options cannot be modified here
if(i==OPTION_FWV || i==OPTION_MOD || i==OPTION_SSID ||
i==OPTION_PASS || i==OPTION_DKEY)
continue;
char *sval = req.getQueryParameter(key);
if(sval != NULL) {
if (o->max) { // integer options
uint ival = String(sval).toInt();
o->ival = ival;
} else {
o->sval = String(sval);
}
}
}
if(usi) {
og.options[OPTION_DVIP].sval = dvip;
og.options[OPTION_GWIP].sval = gwip;
if(subn != NULL) {
og.options[OPTION_SUBN].sval = subn;
}
if(dns1 != NULL) {
og.options[OPTION_DNS1].sval = dns1;
}
}
if(nkey != NULL) {
og.options[OPTION_DKEY].sval = nkey;
}
og.options_save();
uint new_secv = og.options[OPTION_SECV].ival;
secplus1_garage.set_panel_emulation_disabled(og.options[OPTION_PEM].ival != 0);
if(old_secv != new_secv) { // sec+ version changed
if (old_secv == 2) secplus2_garage.stop();
if (old_secv == 1) secplus1_garage.stop();
switch(new_secv) {
case 2:
secplus2_garage.begin();
secplus2_garage.reset_state();
secplus_door_status = DOOR_STATUS_UNKNOWN;
secplus2_garage.enable_callback(secplus2_state_callback);
break;
case 1:
secplus1_garage.begin();
secplus1_garage.reset_state();
secplus_door_status = DOOR_STATUS_UNKNOWN;
secplus1_garage.enable_callback(secplus1_state_callback);
break;
}
} else if (new_secv == 1 && old_pem != og.options[OPTION_PEM].ival) {
secplus1_garage.reset_state();
secplus_door_status = DOOR_STATUS_UNKNOWN;
}
otf_send_result(res, HTML_SUCCESS, nullptr);
}
void on_sta_change_options(const OTF::Request &req, OTF::Response &res) {
sta_change_options_main(req, res);
}
void sta_options_fill_json(String& json) {
json.reserve(STRING_RESERVE_SIZE*2); // reserve capacity to reduce the overhead of String's +=
json = "{";