forked from Cantata-Communication-Solutions/KinkonyAGFW
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHaptique_AGFW.ino
More file actions
3185 lines (2684 loc) · 92.5 KB
/
Copy pathHaptique_AGFW.ino
File metadata and controls
3185 lines (2684 loc) · 92.5 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
/*
ESP32 IR/RF GATEWAY + COMMAND STORAGE v1.1.2
============================================
RF Command Storage:
POST /api/rf/save Save last received RF with name
GET /api/rf/saved List all saved RF commands
POST /api/rf/send/name Send saved RF by name
DELETE /api/rf/delete Delete saved RF command
IR Command Storage:
POST /api/ir/save Save last received IR with name (combined frame)
GET /api/ir/saved List all saved IR commands
POST /api/ir/send/name Send saved IR by name
DELETE /api/ir/delete Delete saved IR command
*/
/*
IR:
TX (LEDC) : GPIO2
RX (RMT0) : GPIO23 (TSOP active-low)
RF 433MHz:
RX : GPIO13
TX : GPIO22
Web API:
GET / -> "OK"
GET /api/status
GET /api/hostname
POST /api/hostname {"hostname":"haptique-extender","instance":"Haptique Extender"}
GET /api/wifi/status
POST /api/wifi/save {"ssid":"...","pass":"..."}
POST /api/wifi/forget
GET /api/wifi/scan
GET /api/ir/test ?ms=800
POST /api/ir/send {"freq_khz":38,"duty":33,"repeat":1,"raw":[...]}
GET /api/ir/last
GET /api/rf/last -> Get last RF received
POST /api/rf/send {"code":12345,"bits":24,"protocol":1,"repeat":10}
GET /api/rf/status -> RF module status
OTA:
GET /api/ota/status
GET /api/ota/config
POST /api/ota/config
GET /api/ota/manifest
POST /api/ota/check
POST /api/ota/url
Challenge-Response Auth:
POST /api/auth/challenge/setup -> Setup PIN
GET /api/auth/challenge/get -> Get challenge + MAC
POST /api/auth/challenge/verify -> Verify response & get token
POST /api/auth/challenge/reset -> Reset PIN
GET /api/auth/challenge/status -> Get auth status
*/
#include <WiFi.h>
#include <WebServer.h>
#include <Preferences.h>
#include <ESPmDNS.h>
#include <ArduinoJson.h>
#include <esp_wifi.h>
#include <esp_err.h>
#include <driver/ledc.h>
#include <driver/rmt.h>
#include <RCSwitch.h>
#include "esp_log.h"
#include "esp_wifi_types.h"
// OTA
#include <HTTPClient.h>
#include <WiFiClientSecure.h>
#include <Update.h>
// Challenge-Response
#include "mbedtls/md.h"
#include "mbedtls/sha256.h"
// ======= VERSION =======
#define FIRMWARE_VERSION "1.1.2"
#define MANUFACTURE "KINCONY"
#define MODEL "KC868-AG"
// ======= Pins =======
#define IR_TX_PIN 2
#define IR_RX_PIN 23
#define IR_RX_ACTIVE_LOW 1
// ======= RF 433MHz Pins =======
#define RF_RX_PIN 13
#define RF_TX_PIN 22
// ======= Factory reset =======
#define FACTORY_BTN_PIN 0
#define FACTORY_ACTIVE_LOW 1
#define FACTORY_HOLD_MS 10000
#define OTA_API_URL "https://app.cantatacs.com/remote/ir-extender/software/update/get"
// ======= Storage Limits =======
#define MAX_RF_COMMANDS 100
#define MAX_IR_COMMANDS 50
#define MAX_NAME_LENGTH 32
#define MAX_IR_RAW_STORE 512 // Limit stored IR raw data
#define MAX_INDEX_SIZE 2048 // Max size for name index string
struct Manifest;
struct OtaInfo {
String version;
String url;
size_t size;
String md5;
bool force;
String notes;
};
// ======= Stored Command Structures =======
struct RfCommand {
char name[MAX_NAME_LENGTH];
uint32_t code;
uint8_t bits;
uint8_t protocol;
uint16_t pulseLen;
};
/*
* The IR command structure persists captured IR timings to flash via the
* Preferences (NVS) API. Previous versions of this sketch stored the
* pulse durations as an array of 32‑bit values. Unfortunately NVS has
* a practical limit on the size of a single value (roughly <2 kB). A
* struct holding 512 × 32‑bit values (~2088 bytes) would exceed that limit
* when combined with the other fields, causing `prefs.putBytes()` to
* silently fail. To avoid this problem while still supporting long
* sequences, the durations are now stored in compressed form. Each
* microsecond value is divided by IR_STORE_DIV (currently 10) and the
* result rounded to the nearest integer. The result fits into a 16‑bit
* integer, reducing the overall size of the struct to ~1064 bytes and
* keeping it well within the NVS per‑value limit. When reading the
* command back the values are multiplied by the same divisor to restore
* the original timing in microseconds. This introduces a maximum
* rounding error of ±(IR_STORE_DIV/2) microseconds, which is well within
* the tolerances of typical IR receivers.
*/
#define IR_STORE_DIV 10
struct IrCommand {
char name[MAX_NAME_LENGTH]; // sanitized command name
uint32_t freqHz; // carrier frequency (Hz)
uint8_t duty; // duty cycle percent
uint16_t count; // number of timing values
uint16_t raw[MAX_IR_RAW_STORE]; // compressed durations (µs / IR_STORE_DIV)
};
// ======= AP =======
static const char* AP_SSID = "HAP_IRHUB";
static const char* AP_PASS = "12345678";
// ======= Hostname =======
static const char* DEFAULT_HOSTNAME = "haptique-extender";
static const char* DEFAULT_INSTANCE = "Haptique Extender";
// ======= IR TX =======
#define IR_MODE LEDC_LOW_SPEED_MODE
#define IR_TIMER LEDC_TIMER_0
#define IR_CHANNEL LEDC_CHANNEL_0
#define IR_DUTY_RES LEDC_TIMER_10_BIT
#define IR_DUTY_MAX ((1U << IR_DUTY_RES) - 1U)
// ======= IR RX =======
#define IR_RMT_CHANNEL RMT_CHANNEL_0
#define RMT_CLK_DIV 80
#define IR_RX_FILTER_US 100
#define IR_RX_IDLE_US 18000
#define DEFAULT_RX_FREQ_KHZ 38
#define WAIT_FOR_B_MS 350
#define WINDOW_QUIET_MS 220
#define WINDOW_TOTAL_MS 800
#define DEFAULT_AB_GAP_US 30000
#define IR_RAW_MAX 2048
// AP auto-recover
static bool apEnabled = false;
static uint32_t apReenableAtMs = 0;
static const uint32_t AP_REENABLE_DELAY_MS = 20000;
// Globals
Preferences prefs;
WebServer server(80);
String gHostname = DEFAULT_HOSTNAME;
String gInstance = DEFAULT_INSTANCE;
bool mdnsStarted = false;
String staSsid, staPass;
bool staHaveCreds = false;
volatile bool staConnected = false;
volatile bool staConnecting = false;
volatile uint32_t irFreqHz = 38000; // update at capture
volatile uint8_t irDuty = 33; // update at capture
// ================== AUTH: globals ==================
String gAuthToken = "";
bool gAuthTokenSet = false;
// Challenge-Response globals
String userPIN = "";
bool pinConfigured = false;
String currentChallenge = "";
uint32_t challengeExpiry = 0;
uint32_t lastChallengeCheck = 0;
#define CHALLENGE_DIGITS 6
#define CHALLENGE_EXPIRY_MS 60000
#define CHALLENGE_RATE_LIMIT_MS 3000
// Wi-Fi state
enum WifiState : uint8_t {
WIFI_IDLE = 0,
WIFI_CONNECTING,
WIFI_CONNECTED,
WIFI_FAILED,
WIFI_AP_FALLBACK
};
volatile WifiState wifiState = WIFI_IDLE;
volatile uint8_t wifiRetries = 0;
volatile uint16_t lastStaReason = 0;
volatile uint32_t wifiDeadlineMs = 0;
// IR RX
RingbufHandle_t irRb = NULL;
String lastIrJson;
// IR A/B state
uint32_t *irA = nullptr, *irB = nullptr, *irC = nullptr, *scratch = nullptr;
size_t irAc = 0, irBc = 0, irCc = 0;
bool haveIrA = false, haveIrB = false;
uint32_t tIrA = 0, tIrB = 0, irWin = 0, irLast = 0;
// ✅ PERSISTENT IR STORAGE (for saving commands)
// ✅ PERSISTENT IR STORAGE (for saving commands)
uint32_t lastIrFreqHz = 38000;
uint8_t lastIrDuty = 33;
// Frame A storage
uint16_t lastIrCountA = 0;
uint32_t lastIrDataA[MAX_IR_RAW_STORE];
bool hasLastIrDataA = false;
// Frame B storage
uint16_t lastIrCountB = 0;
uint32_t lastIrDataB[MAX_IR_RAW_STORE];
bool hasLastIrDataB = false;
// Combined frame storage
uint16_t lastIrCountC = 0;
uint32_t lastIrDataC[MAX_IR_RAW_STORE];
bool hasLastIrDataC = false;
// Legacy support (points to combined by default)
uint16_t lastIrCount = 0;
uint32_t lastIrData[MAX_IR_RAW_STORE];
bool hasLastIrData = false;
// RF 433
RCSwitch rfRx = RCSwitch();
RCSwitch rfTx = RCSwitch();
String lastRfJson;
uint32_t lastRfCode = 0;
uint8_t lastRfBits = 0;
uint8_t lastRfProtocol = 0;
uint16_t lastRfPulseLen = 0;
uint32_t rfRxCount = 0;
// RX-mute during TX
volatile bool irRxPaused = false;
volatile uint32_t irRxMuteUntil = 0;
// Factory button
static bool g_btnPrev = false;
static uint32_t g_btnDownSince = 0;
// OTA State
static bool otaInProgress = false;
static uint32_t otaRebootAtMs = 0;
static uint32_t otaLastBytes = 0;
static bool otaLastOk = false;
static String otaLastErr = "";
struct OtaCfg {
String manifestUrl;
String authType;
String bearer;
String basicUser;
String basicPass;
bool autoCheck = false;
bool autoInstall = false;
uint32_t intervalMin = 360;
bool allowInsecureTLS = true;
};
OtaCfg otaCfg;
static uint32_t nextOtaCheckAtMs = 0;
static bool otaUpdateAvailable = false;
static String lastManifestVersion = "";
// Forward declarations
static void addCORS();
// ========== STORAGE HELPER FUNCTIONS ==========
String sanitizeName(const String& input) {
String name = input;
name.trim();
name.toLowerCase();
// Replace spaces with underscores
name.replace(" ", "_");
// Remove invalid characters
String clean = "";
for (size_t i = 0; i < name.length() && clean.length() < MAX_NAME_LENGTH - 1; i++) {
char c = name[i];
if ((c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '_' || c == '-') {
clean += c;
}
}
return clean.length() > 0 ? clean : "unnamed";
}
// ========== RF NAME INDEX MANAGEMENT ==========
void addRfNameToIndex(const String& name) {
prefs.begin("rf_cmd", false);
String index = prefs.getString("index", "");
// Check if name already exists
if (index.indexOf(name + ",") >= 0 || index.indexOf("," + name) >= 0 || index == name) {
prefs.end();
return;
}
// Add name to index
if (index.length() > 0) {
index += ",";
}
index += name;
// Truncate if too long
if (index.length() > MAX_INDEX_SIZE) {
Serial.println("[RF] Warning: Index truncated");
index = index.substring(0, MAX_INDEX_SIZE);
}
prefs.putString("index", index);
prefs.end();
}
void removeRfNameFromIndex(const String& name) {
prefs.begin("rf_cmd", false);
String index = prefs.getString("index", "");
// Remove name from index
index.replace(name + ",", "");
index.replace("," + name, "");
if (index == name) index = "";
prefs.putString("index", index);
prefs.end();
}
String getRfNameIndex() {
prefs.begin("rf_cmd", true);
String index = prefs.getString("index", "");
prefs.end();
return index;
}
// ========== IR NAME INDEX MANAGEMENT ==========
void addIrNameToIndex(const String& name) {
prefs.begin("ir_cmd", false);
String index = prefs.getString("index", "");
// Check if name already exists
if (index.indexOf(name + ",") >= 0 || index.indexOf("," + name) >= 0 || index == name) {
prefs.end();
return;
}
// Add name to index
if (index.length() > 0) {
index += ",";
}
index += name;
// Truncate if too long
if (index.length() > MAX_INDEX_SIZE) {
Serial.println("[IR] Warning: Index truncated");
index = index.substring(0, MAX_INDEX_SIZE);
}
prefs.putString("index", index);
prefs.end();
}
void removeIrNameFromIndex(const String& name) {
prefs.begin("ir_cmd", false);
String index = prefs.getString("index", "");
// Remove name from index
index.replace(name + ",", "");
index.replace("," + name, "");
if (index == name) index = "";
prefs.putString("index", index);
prefs.end();
}
String getIrNameIndex() {
prefs.begin("ir_cmd", true);
String index = prefs.getString("index", "");
prefs.end();
return index;
}
// ========== RF COMMAND STORAGE ==========
bool saveRfCommand(const String& name, uint32_t code, uint8_t bits, uint8_t protocol, uint16_t pulseLen) {
String cleanName = sanitizeName(name);
prefs.begin("rf_cmd", false);
// Check if we've reached max commands
int count = prefs.getInt("count", 0);
bool isUpdate = prefs.isKey(cleanName.c_str());
if (count >= MAX_RF_COMMANDS && !isUpdate) {
prefs.end();
Serial.println("[RF] Storage full!");
return false;
}
// Save command data
RfCommand cmd;
strncpy(cmd.name, cleanName.c_str(), MAX_NAME_LENGTH - 1);
cmd.name[MAX_NAME_LENGTH - 1] = '\0';
cmd.code = code;
cmd.bits = bits;
cmd.protocol = protocol;
cmd.pulseLen = pulseLen;
size_t written = prefs.putBytes(cleanName.c_str(), &cmd, sizeof(RfCommand));
if (written > 0 && !isUpdate) {
prefs.putInt("count", count + 1);
// Store name in numbered key for listing
String keyName = "n" + String(count);
prefs.putString(keyName.c_str(), cleanName);
}
prefs.end();
Serial.printf("[RF] Saved '%s': code=%u bits=%u proto=%u\n",
cleanName.c_str(), code, bits, protocol);
return written > 0;
}
bool loadRfCommand(const String& name, RfCommand& cmd) {
String cleanName = sanitizeName(name);
prefs.begin("rf_cmd", true);
size_t len = prefs.getBytesLength(cleanName.c_str());
if (len != sizeof(RfCommand)) {
prefs.end();
return false;
}
prefs.getBytes(cleanName.c_str(), &cmd, sizeof(RfCommand));
prefs.end();
return true;
}
bool deleteRfCommand(const String& name) {
String cleanName = sanitizeName(name);
prefs.begin("rf_cmd", false);
bool existed = prefs.isKey(cleanName.c_str());
if (existed) {
prefs.remove(cleanName.c_str());
int count = prefs.getInt("count", 0);
if (count > 0) {
prefs.putInt("count", count - 1);
}
}
prefs.end();
// Remove from name index
if (existed) {
removeRfNameFromIndex(cleanName);
}
Serial.printf("[RF] Deleted '%s': %s\n", cleanName.c_str(), existed ? "OK" : "NOT_FOUND");
return existed;
}
String listRfCommands() {
String index = getRfNameIndex();
DynamicJsonDocument doc(4096);
JsonArray arr = doc.createNestedArray("commands");
prefs.begin("rf_cmd", true);
int count = prefs.getInt("count", 0);
prefs.end();
doc["count"] = count;
// Parse comma-separated index
if (index.length() > 0) {
int startIdx = 0;
int commaIdx = 0;
while ((commaIdx = index.indexOf(',', startIdx)) >= 0) {
String cmdName = index.substring(startIdx, commaIdx);
cmdName.trim();
if (cmdName.length() > 0) {
RfCommand cmd;
if (loadRfCommand(cmdName, cmd)) {
JsonObject obj = arr.createNestedObject();
obj["name"] = String(cmd.name);
obj["code"] = cmd.code;
obj["bits"] = cmd.bits;
obj["protocol"] = cmd.protocol;
obj["pulseLen"] = cmd.pulseLen;
}
}
startIdx = commaIdx + 1;
}
// Handle last name (or only name if no commas)
String cmdName = index.substring(startIdx);
cmdName.trim();
if (cmdName.length() > 0) {
RfCommand cmd;
if (loadRfCommand(cmdName, cmd)) {
JsonObject obj = arr.createNestedObject();
obj["name"] = String(cmd.name);
obj["code"] = cmd.code;
obj["bits"] = cmd.bits;
obj["protocol"] = cmd.protocol;
obj["pulseLen"] = cmd.pulseLen;
}
}
}
String output;
serializeJson(doc, output);
return output;
}
// ========== IR COMMAND STORAGE ==========
bool saveIrCommand(const String& name, uint32_t freqHz, uint8_t duty, const uint32_t* raw, uint16_t count) {
String cleanName = sanitizeName(name);
if (count > MAX_IR_RAW_STORE) {
Serial.printf("[IR] Too many timings: %u (max %u)\n", count, MAX_IR_RAW_STORE);
return false;
}
prefs.begin("ir_cmd", false);
// Check if we've reached max commands
int cmdCount = prefs.getInt("count", 0);
bool isUpdate = prefs.isKey(cleanName.c_str());
if (cmdCount >= MAX_IR_COMMANDS && !isUpdate) {
prefs.end();
Serial.println("[IR] Storage full!");
return false;
}
IrCommand cmd;
// Copy and sanitize the name
strncpy(cmd.name, cleanName.c_str(), MAX_NAME_LENGTH - 1);
cmd.name[MAX_NAME_LENGTH - 1] = '\0';
// Store carrier and duty directly
cmd.freqHz = freqHz;
cmd.duty = duty;
// Truncate count if necessary
uint16_t safeCount = count;
if (safeCount > MAX_IR_RAW_STORE) safeCount = MAX_IR_RAW_STORE;
cmd.count = safeCount;
// Compress the raw pulse durations into 16‑bit values. Each duration
// measured in microseconds is divided by IR_STORE_DIV and rounded. Large
// values are saturated at 0xFFFF. See IR_STORE_DIV definition for
// details.
for (uint16_t i = 0; i < safeCount; i++) {
uint32_t v = raw[i];
// Perform rounding to minimise error; add half of divisor before
// integer division. Example: (589 + 5) / 10 = 59 → 590 µs after
// decompression.
uint32_t scaled = (v + (IR_STORE_DIV / 2)) / IR_STORE_DIV;
if (scaled > 0xFFFF) scaled = 0xFFFF;
cmd.raw[i] = (uint16_t)scaled;
}
// Zero any unused entries to avoid reading garbage when iterating
for (uint16_t i = safeCount; i < MAX_IR_RAW_STORE; i++) cmd.raw[i] = 0;
// Persist only the used portion of the struct to NVS. The
// Preferences/NVS library stores values as variable‑length blobs and
// space is scarce. Storing the entire raw buffer (all
// MAX_IR_RAW_STORE entries) would waste space when the captured
// sequence is shorter. Compute the size of the struct header (all
// fields before the raw array) then add only `safeCount` entries of
// the 16‑bit raw array. This dramatically reduces the size of
// each stored command and avoids NVS write failures due to large
// values.
const size_t headerSize = sizeof(IrCommand) - (MAX_IR_RAW_STORE * sizeof(uint16_t));
size_t dataSize = headerSize + (size_t)safeCount * sizeof(uint16_t);
size_t written = prefs.putBytes(cleanName.c_str(), &cmd, dataSize);
if (written > 0 && !isUpdate) {
prefs.putInt("count", cmdCount + 1);
// Store name in numbered key for listing
String keyName = "n" + String(cmdCount);
prefs.putString(keyName.c_str(), cleanName);
}
prefs.end();
Serial.printf("[IR] Saved '%s': freq=%uHz duty=%u%% count=%u\n",
cleanName.c_str(), freqHz, duty, count);
return written > 0;
}
bool loadIrCommand(const String& name, IrCommand& cmd) {
String cleanName = sanitizeName(name);
prefs.begin("ir_cmd", true);
size_t len = prefs.getBytesLength(cleanName.c_str());
// The stored data length must at least cover the struct header.
const size_t headerSize = sizeof(IrCommand) - (MAX_IR_RAW_STORE * sizeof(uint16_t));
if (len < headerSize) {
prefs.end();
return false;
}
// Initialise the structure so that any unused raw entries are zeroed.
memset(&cmd, 0, sizeof(IrCommand));
// Read only the stored number of bytes. Extra bytes in the struct
// remain zeroed, which is safe because cmd.count indicates how
// many raw entries are valid.
prefs.getBytes(cleanName.c_str(), &cmd, len);
prefs.end();
return true;
}
bool deleteIrCommand(const String& name) {
String cleanName = sanitizeName(name);
prefs.begin("ir_cmd", false);
bool existed = prefs.isKey(cleanName.c_str());
if (existed) {
prefs.remove(cleanName.c_str());
int count = prefs.getInt("count", 0);
if (count > 0) {
prefs.putInt("count", count - 1);
}
// Remove from numbered keys (rebuild list)
int newIdx = 0;
for (int i = 0; i < count; i++) {
String keyName = "n" + String(i);
String storedName = prefs.getString(keyName.c_str(), "");
if (storedName != cleanName && storedName.length() > 0) {
if (newIdx != i) {
String newKeyName = "n" + String(newIdx);
prefs.putString(newKeyName.c_str(), storedName);
}
newIdx++;
}
}
// Clear any leftover keys
for (int i = newIdx; i < count; i++) {
String keyName = "n" + String(i);
prefs.remove(keyName.c_str());
}
}
prefs.end();
Serial.printf("[IR] Deleted '%s': %s\n", cleanName.c_str(), existed ? "OK" : "NOT_FOUND");
return existed;
}
String listIrCommands() {
DynamicJsonDocument doc(12288);
JsonArray arr = doc.createNestedArray("commands");
prefs.begin("ir_cmd", true);
int count = prefs.getInt("count", 0);
doc["count"] = count;
doc["max"] = MAX_IR_COMMANDS;
doc["available"] = MAX_IR_COMMANDS - count;
// Iterate through numbered keys
for (int i = 0; i < count; i++) {
String keyName = "n" + String(i);
String cmdName = prefs.getString(keyName.c_str(), "");
if (cmdName.length() > 0) {
IrCommand cmd;
size_t len = prefs.getBytesLength(cmdName.c_str());
// Load the stored command if it is at least large enough to
// contain the header. The size of the header is the total
// struct size minus the maximum raw array length. Commands are
// stored as variable‑length blobs, so len may be less than
// sizeof(IrCommand) if only part of the raw array was saved.
const size_t headerSize = sizeof(IrCommand) - (MAX_IR_RAW_STORE * sizeof(uint16_t));
if (len >= headerSize) {
memset(&cmd, 0, sizeof(IrCommand));
size_t toRead = (len > sizeof(IrCommand)) ? sizeof(IrCommand) : len;
prefs.getBytes(cmdName.c_str(), &cmd, toRead);
JsonObject obj = arr.createNestedObject();
obj["name"] = String(cmd.name);
obj["freq_hz"] = cmd.freqHz;
obj["duty"] = cmd.duty;
obj["count"] = cmd.count;
// Add preview of first 10 timings. Stored values are
// compressed (divided by IR_STORE_DIV), so multiply back to
// approximate the original microsecond durations.
JsonArray preview = obj.createNestedArray("preview");
for (size_t j = 0; j < min(cmd.count, (uint16_t)10); j++) {
uint32_t us = (uint32_t)cmd.raw[j] * IR_STORE_DIV;
preview.add(us);
}
}
}
}
prefs.end();
String output;
serializeJson(doc, output);
return output;
}
// ========== CHALLENGE-RESPONSE HELPER FUNCTIONS ==========
String generateChallenge() {
uint64_t mac = ESP.getEfuseMac();
randomSeed((uint32_t)(millis() ^ (mac & 0xFFFFFFFF)));
String challenge = "";
for (int i = 0; i < CHALLENGE_DIGITS; i++) {
challenge += String(random(0, 10));
}
return challenge;
}
String getMacShort() {
String mac = WiFi.macAddress();
mac.replace(":", "");
return mac.substring(mac.length() - 6);
}
String calculateExpectedResponse(const String& challenge, const String& pin, const String& mac) {
String combined = challenge + pin + mac;
uint8_t hash[32];
mbedtls_sha256_context ctx;
mbedtls_sha256_init(&ctx);
mbedtls_sha256_starts(&ctx, 0);
mbedtls_sha256_update(&ctx, (const unsigned char*)combined.c_str(), combined.length());
mbedtls_sha256_finish(&ctx, hash);
mbedtls_sha256_free(&ctx);
uint32_t value = (hash[0] << 24) | (hash[1] << 16) | (hash[2] << 8) | hash[3];
uint32_t response = value % 1000000;
char buffer[7];
snprintf(buffer, sizeof(buffer), "%06u", response);
return String(buffer);
}
void loadPinConfig() {
prefs.begin("auth", true);
userPIN = prefs.getString("pin", "");
prefs.end();
if (userPIN.length() >= 4 && userPIN.length() <= 8) {
pinConfigured = true;
Serial.printf("[AUTH] PIN loaded (length: %d)\n", userPIN.length());
} else {
pinConfigured = false;
Serial.println("[AUTH] No PIN configured");
}
}
void savePinConfig(const String& pin) {
prefs.begin("auth", false);
prefs.putString("pin", pin);
prefs.end();
userPIN = pin;
pinConfigured = true;
Serial.printf("[AUTH] PIN saved (length: %d)\n", pin.length());
}
bool verifyChallengeResponse(const String& challenge, const String& response) {
if (!pinConfigured) {
Serial.println("[AUTH] ERROR: PIN not configured!");
return false;
}
uint32_t now = millis();
if ((now - lastChallengeCheck) < CHALLENGE_RATE_LIMIT_MS) {
Serial.println("[AUTH] Rate limit exceeded");
return false;
}
lastChallengeCheck = now;
if (challenge != currentChallenge) {
Serial.println("[AUTH] Challenge mismatch");
return false;
}
if (now > challengeExpiry) {
Serial.println("[AUTH] Challenge expired");
return false;
}
String mac = getMacShort();
String expected = calculateExpectedResponse(challenge, userPIN, mac);
bool valid = (response == expected);
Serial.printf("[AUTH] Valid: %s\n", valid ? "YES" : "NO");
if (valid) {
currentChallenge = "";
challengeExpiry = 0;
}
return valid;
}
void printTokenInfo() {
Serial.println("\n╔════════════════════════════════════════════════════════╗");
Serial.println("║ DEVICE CHALLENGE-RESPONSE AUTHENTICATION ║");
Serial.println("╠════════════════════════════════════════════════════════╣");
if (gAuthTokenSet && gAuthToken.length() > 0) {
Serial.printf("║ Token: %-47s║\n", gAuthToken.c_str());
Serial.println("║ Status: ✓ STORED ║");
} else {
Serial.println("║ Token: NOT CREATED YET ║");
}
Serial.println("╠════════════════════════════════════════════════════════╣");
if (pinConfigured) {
Serial.println("║ PIN: ✓ CONFIGURED ║");
} else {
Serial.println("║ PIN: ✗ NOT CONFIGURED ║");
}
Serial.println("╠════════════════════════════════════════════════════════╣");
Serial.printf("║ MAC: %-49s║\n", WiFi.macAddress().c_str());
Serial.printf("║ Firmware: v%-44s║\n", FIRMWARE_VERSION);
Serial.println("╚════════════════════════════════════════════════════════╝\n");
}
static String generateToken(size_t len = 32) {
static const char ALPH[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
String t;
t.reserve(len);
uint64_t mac = ESP.getEfuseMac();
randomSeed((uint32_t)(millis() ^ (mac & 0xFFFFFFFF)));
for (size_t i = 0; i < len; i++) t += ALPH[random(0, (int)sizeof(ALPH) - 1)];
return t;
}
static void authCreateNewToken(const char* reason) {
gAuthToken = generateToken(40);
gAuthTokenSet = true;
prefs.begin("wifi", false);
prefs.putString("token", gAuthToken);
prefs.end();
Serial.printf("[AUTH] Token created (%s): %s\n", reason, gAuthToken.c_str());
}
static String readTokenFromRequest() {
if (server.hasHeader("X-Auth-Token")) return server.header("X-Auth-Token");
if (server.hasHeader("Authorization")) {
String a = server.header("Authorization");
a.trim();
if (a.startsWith("Bearer ")) return a.substring(7);
return a;
}
return "";
}
static inline bool isAPOn() { return apEnabled; }
static bool requireAuth() {
if (!gAuthTokenSet) {
addCORS();
server.send(503, "application/json", "{\"error\":\"token_unavailable\"}");
return false;
}
String tok = readTokenFromRequest();
if (tok == gAuthToken) return true;
addCORS();
server.send(401, "application/json", "{\"error\":\"unauthorized\"}");
return false;
}
// Utils
static inline bool isAlnumHyphen(char c) {
return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '-';
}
static bool validHostname(const String& s) {
if (s.length() < 1 || s.length() > 63) return false;
if (s[0] == '-' || s[s.length() - 1] == '-') return false;
for (size_t i = 0; i < s.length(); i++)
if (!isAlnumHyphen(s[i])) return false;
return true;
}
static const char* wifiReasonToString(uint8_t r) {
switch (r) {
case WIFI_REASON_NO_AP_FOUND: return "NO_AP_FOUND";
case WIFI_REASON_AUTH_FAIL: return "AUTH_FAIL";
case WIFI_REASON_ASSOC_FAIL: return "ASSOC_FAIL";
case WIFI_REASON_BEACON_TIMEOUT: return "BEACON_TIMEOUT";
case WIFI_REASON_4WAY_HANDSHAKE_TIMEOUT: return "4WAY_TIMEOUT";
default: return "UNKNOWN";
}
}
static String trimWS(const String& s) {
String t = s;
t.trim();
return t;
}
// Identity
void loadIdentity() {
prefs.begin("wifi", true);
String h = prefs.getString("host", DEFAULT_HOSTNAME);
String i = prefs.getString("inst", DEFAULT_INSTANCE);
gAuthToken = prefs.getString("token", "");
prefs.end();
h.toLowerCase();
gHostname = validHostname(h) ? h : DEFAULT_HOSTNAME;
gInstance = i.length() ? i : DEFAULT_INSTANCE;
if (gAuthToken.length() > 0) {
gAuthTokenSet = true;
Serial.printf("[AUTH] Token loaded: %s\n", gAuthToken.c_str());
} else {
gAuthTokenSet = false;
Serial.println("[AUTH] No token in flash");
}
}
void saveIdentity(const String& host, const String& inst) {
prefs.begin("wifi", false);
prefs.putString("host", host);
prefs.putString("inst", inst);
prefs.end();
gHostname = host;
gInstance = inst;
}
// STA creds
void loadStaCreds() {