Repository navigation
Expand file tree
/
Copy pathnetwork_task.cpp
More file actions
1538 lines (1402 loc) · 65.5 KB
/
Copy pathnetwork_task.cpp
File metadata and controls
1538 lines (1402 loc) · 65.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
// ==========================================================================
// QBIT -- Network task
// ==========================================================================
#include "network_task.h"
#include "app_state.h"
#include "settings.h"
#include "time_manager.h"
#include "mqtt_ha.h"
#include "poke_handler.h"
#include "gif_player.h"
#include <WiFi.h>
#include <WiFiClientSecure.h>
#include <HTTPClient.h>
#include <Update.h>
#include <LittleFS.h>
#include <Preferences.h>
#include <NetWizard.h>
#include <ESPmDNS.h>
#include <ArduinoJson.h>
#include <ArduinoWebsockets.h>
#include <PubSubClient.h>
#if defined(ESP32)
#include <esp_system.h>
#include <esp_timer.h>
#include <esp_wifi.h>
#include <freertos/FreeRTOS.h>
#include <freertos/task.h>
#include <freertos/portmacro.h>
#endif
// ==========================================================================
// Configuration
// ==========================================================================
#ifndef WS_HOST
#define WS_HOST "localhost"
#endif
#ifndef WS_PORT
#define WS_PORT 3001
#endif
#define WS_PATH "/device"
#ifndef WS_API_KEY
#define WS_API_KEY ""
#endif
#define WS_RECONNECT_MS 5000
#define WIFI_RECONNECT_TIMEOUT_MS 15000
#define PORTAL_RETRY_INTERVAL_MS 30000 // while AP is up, retry saved WiFi in background every 30s
// NetWizard stopPortal() forces WiFi.mode(STA)+reconnect; WL_CONNECTED can drop briefly. Skip
// (or defer) the display "WiFi Offline" queue event right after stopPortal; still deliver if
// the link stays down after this window.
// Covers NetWizard /exit handler (NETWIZARD_EXIT_TIMEOUT 5s) + STA reconnect after stopPortal().
#define WIFI_SUPPRESS_DISCONNECT_UI_MS 10000
// Bitmap poke: 1bpp row-major, size = (height_pages) * width, height_pages <= 8
#define POKE_BMP_MAX_WIDTH 512
#define POKE_BMP_MAX_PAGES 8
// Validate decoded bitmap size matches claimed width (no integer overflow / OOB).
static bool isValidBitmapSize(uint16_t width, size_t decodedLen) {
if (width == 0 || width > POKE_BMP_MAX_WIDTH) return false;
if (decodedLen == 0) return false;
if (decodedLen % width != 0) return false;
size_t pages = decodedLen / width;
return pages <= POKE_BMP_MAX_PAGES;
}
// ==========================================================================
// External objects (created in main.cpp)
// ==========================================================================
extern AsyncWebServer server;
extern NetWizard NW;
// ==========================================================================
// Internal state
// ==========================================================================
using namespace websockets;
static WebsocketsClient _wsClient;
static bool _wsConnected = false;
// esp_timer_get_time() (us) at last WS ConnectionOpened; 0 if disconnected. Avoids millis() ~49.7d wrap.
static int64_t _wsCloudConnectedAtUs = 0;
static unsigned long _wsLastReconnect = 0;
// _wsConnected + _wsCloudConnectedAtUs are read from AsyncWeb handlers and written from WS / WiFi
// paths; take a short critical section so int64 + bool are not observed torn on 32-bit MCUs.
#if defined(ESP32)
static portMUX_TYPE _wsCloudMux = portMUX_INITIALIZER_UNLOCKED;
static void wsCloudSet(bool connected, int64_t connectedAtUs) {
portENTER_CRITICAL(&_wsCloudMux);
_wsConnected = connected;
_wsCloudConnectedAtUs = connectedAtUs;
portEXIT_CRITICAL(&_wsCloudMux);
}
static bool wsIsCloudConnected(void) {
portENTER_CRITICAL(&_wsCloudMux);
bool c = _wsConnected;
portEXIT_CRITICAL(&_wsCloudMux);
return c;
}
static void wsCloudSnapshot(bool *outConn, int64_t *outUs) {
portENTER_CRITICAL(&_wsCloudMux);
*outConn = _wsConnected;
*outUs = _wsCloudConnectedAtUs;
portEXIT_CRITICAL(&_wsCloudMux);
}
#else
static void wsCloudSet(bool connected, int64_t connectedAtUs) {
_wsConnected = connected;
_wsCloudConnectedAtUs = connectedAtUs;
}
static bool wsIsCloudConnected(void) {
return _wsConnected;
}
static void wsCloudSnapshot(bool *outConn, int64_t *outUs) {
*outConn = _wsConnected;
*outUs = _wsCloudConnectedAtUs;
}
#endif
static WiFiClient _mqttWifi;
static PubSubClient _mqttClient; // setClient() called at runtime to avoid static init order issues (fixes #1)
static unsigned long _mqttLastReconnect = 0;
static char _mqttHostStable[MQTT_HOST_MAX_LEN + 1] = {0};
#define MQTT_RECONNECT_MS 5000
static bool _wifiConnected = false;
static unsigned long _wifiLostMs = 0;
// True after STA has connected at least once this boot. Used with NW.isConfigured() so we
// do not treat first-time captive setup (no saved creds, never STA) as "reconnect → stopPortal
// before SUCCESS", while still allowing cold boot with saved creds but no router to open AP.
static bool _hadStaConnection = false;
static bool _portalRestartedForReconnect = false;
static unsigned long _portalRetryAfterMs = 0; // when to stop portal and retry saved WiFi
// After provisioning SUCCESS, delay stopPortal so the phone can poll /netwizard/status and
// POST /netwizard/exit before HTTP/AP goes away (NetWizard uses NETWIZARD_EXIT_TIMEOUT).
static unsigned long _portalProvisionStopAfterMs = 0;
static unsigned long _versionCheckAfterMs = 0; // run version check after this time
static unsigned long _tzCheckAfterMs = 0; // run timezone detection after this time
static unsigned long _wifiSuppressDisconnectUiUntilMs = 0;
static bool _wifiDisconnectUiPending = false;
static bool _nwPrevPortalSuccess = false;
// NetWizard closes the Soft AP after idle portal timeout (~5 min default). Re-open while still
// unconfigured so the OLED is not stuck on "AP in 0s" with no AP (PORTAL_ACTIVE cleared).
static unsigned long _reopenSetupPortalAfterMs = 0;
// While portal is up, avoid calling NW.connect() faster than the STA stack can finish an attempt
// (otherwise ESP logs: "sta is connecting, return error").
static unsigned long _portalBgConnectEarliestMs = 0;
// ==========================================================================
// WebSocket helpers
// ==========================================================================
static bool wsConnect() {
if (_wsClient.available()) {
_wsClient.close();
vTaskDelay(pdMS_TO_TICKS(100));
}
bool ok;
if (WS_PORT == 443) {
ok = _wsClient.connectSecure(WS_HOST, WS_PORT, WS_PATH);
} else {
ok = _wsClient.connect(WS_HOST, WS_PORT, WS_PATH);
}
if (!ok) {
Serial.println("[WS] Connection failed");
}
return ok;
}
static void wsSendDeviceInfo() {
if (!wsIsCloudConnected()) return;
StaticJsonDocument<384> doc;
doc["type"] = "device.register";
doc["id"] = getDeviceId();
doc["name"] = getDeviceName();
doc["ip"] = WiFi.localIP().toString();
doc["version"] = kQbitVersion;
String msg;
serializeJson(doc, msg);
_wsClient.send(msg);
}
void networkSendDeviceInfo() {
wsSendDeviceInfo();
}
void networkSendClaimConfirm() {
if (!wsIsCloudConnected()) return;
StaticJsonDocument<64> doc;
doc["type"] = "claim_confirm";
String msg;
serializeJson(doc, msg);
_wsClient.send(msg);
Serial.println("Claim confirmed");
}
void networkSendClaimReject() {
if (!wsIsCloudConnected()) return;
StaticJsonDocument<64> doc;
doc["type"] = "claim_reject";
String msg;
serializeJson(doc, msg);
_wsClient.send(msg);
Serial.println("Claim rejected (timeout)");
}
void networkSendFriendConfirm() {
if (!wsIsCloudConnected()) return;
StaticJsonDocument<64> doc;
doc["type"] = "friend_confirm";
String msg;
serializeJson(doc, msg);
_wsClient.send(msg);
Serial.println("Friend confirmed");
}
void networkSendFriendReject() {
if (!wsIsCloudConnected()) return;
StaticJsonDocument<64> doc;
doc["type"] = "friend_reject";
String msg;
serializeJson(doc, msg);
_wsClient.send(msg);
Serial.println("Friend request rejected (timeout)");
}
// ==========================================================================
// WebSocket event + message handlers
// ==========================================================================
static void wsEvent(WebsocketsClient &client, WebsocketsEvent event, WSInterfaceString data) {
(void)client;
(void)data;
switch (event) {
case WebsocketsEvent::ConnectionOpened:
wsCloudSet(true, esp_timer_get_time());
xEventGroupSetBits(connectivityBits, WS_CONNECTED_BIT);
Serial.println("[WS] Connected to backend");
wsSendDeviceInfo();
mqttPublishServerConnectionState(true);
{
NetworkEvent evt = {};
evt.kind = NetworkEvent::WS_STATUS;
evt.connected = true;
xQueueSend(networkEventQueue, &evt, 0);
}
break;
case WebsocketsEvent::ConnectionClosed:
wsCloudSet(false, 0);
xEventGroupClearBits(connectivityBits, WS_CONNECTED_BIT);
Serial.println("[WS] Disconnected");
mqttPublishServerConnectionState(false);
// stopPortal() after captive provisioning tears down the link briefly; the socket closes
// here then reconnects seconds later. Suppress OLED "Server Offline" in the same window
// used for WiFi disconnect UI (set when stopPortal runs / portal success is latched).
{
const unsigned long until = _wifiSuppressDisconnectUiUntilMs;
if (until == 0 || millis() >= until) {
NetworkEvent evt = {};
evt.kind = NetworkEvent::WS_STATUS;
evt.connected = false;
xQueueSend(networkEventQueue, &evt, 0);
}
}
break;
case WebsocketsEvent::GotPing:
case WebsocketsEvent::GotPong:
break;
}
}
static void wsMessage(WebsocketsClient &client, WebsocketsMessage message) {
(void)client;
if (!message.isText()) return;
String data = message.data();
StaticJsonDocument<2048> doc;
if (deserializeJson(doc, data)) return;
const char *msgType = doc["type"];
if (!msgType) return;
if (strcmp(msgType, "poke") == 0) {
const char *sender = doc["sender"] | "Someone";
const char *text = doc["text"] | "Poke!";
if (doc["senderBitmap"].is<const char*>() && doc["textBitmap"].is<const char*>()) {
const char *senderBmp = doc["senderBitmap"];
uint16_t senderW = doc["senderBitmapWidth"] | 0;
const char *textBmp = doc["textBitmap"];
uint16_t textW = doc["textBitmapWidth"] | 0;
if (senderW > 0 && textW > 0 &&
senderW <= POKE_BMP_MAX_WIDTH && textW <= POKE_BMP_MAX_WIDTH) {
size_t sLen = 0, tLen = 0;
uint8_t *sBmp = decodeBase64Alloc(senderBmp, &sLen);
uint8_t *tBmp = decodeBase64Alloc(textBmp, &tLen);
bool valid = sBmp && tBmp &&
isValidBitmapSize(senderW, sLen) &&
isValidBitmapSize(textW, tLen);
if (valid) {
NetworkEvent evt = {};
evt.kind = NetworkEvent::POKE_BITMAP;
strncpy(evt.sender, sender, sizeof(evt.sender) - 1);
strncpy(evt.text, text, sizeof(evt.text) - 1);
evt.senderBmp = sBmp;
evt.senderBmpWidth = senderW;
evt.senderBmpLen = sLen;
evt.textBmp = tBmp;
evt.textBmpWidth = textW;
evt.textBmpLen = tLen;
if (xQueueSend(networkEventQueue, &evt, pdMS_TO_TICKS(100)) != pdTRUE) {
free(sBmp);
free(tBmp);
}
} else {
if (sBmp) free(sBmp);
if (tBmp) free(tBmp);
NetworkEvent evt = {};
evt.kind = NetworkEvent::POKE;
strncpy(evt.sender, sender, sizeof(evt.sender) - 1);
strncpy(evt.text, text, sizeof(evt.text) - 1);
xQueueSend(networkEventQueue, &evt, pdMS_TO_TICKS(100));
}
} else {
NetworkEvent evt = {};
evt.kind = NetworkEvent::POKE;
strncpy(evt.sender, sender, sizeof(evt.sender) - 1);
strncpy(evt.text, text, sizeof(evt.text) - 1);
xQueueSend(networkEventQueue, &evt, pdMS_TO_TICKS(100));
}
} else {
NetworkEvent evt = {};
evt.kind = NetworkEvent::POKE;
strncpy(evt.sender, sender, sizeof(evt.sender) - 1);
strncpy(evt.text, text, sizeof(evt.text) - 1);
xQueueSend(networkEventQueue, &evt, pdMS_TO_TICKS(100));
}
mqttPublishPokeEvent(sender, text);
}
if (strcmp(msgType, "broadcast") == 0) {
const char *sender = doc["sender"] | "QBIT-NETWORK";
const char *text = doc["text"] | "";
const char *title = doc["title"] | "NOTIFY";
if (doc["senderBitmap"].is<const char*>() && doc["textBitmap"].is<const char*>()) {
const char *senderBmp = doc["senderBitmap"];
uint16_t senderW = doc["senderBitmapWidth"] | 0;
const char *textBmp = doc["textBitmap"];
uint16_t textW = doc["textBitmapWidth"] | 0;
if (senderW > 0 && textW > 0 &&
senderW <= POKE_BMP_MAX_WIDTH && textW <= POKE_BMP_MAX_WIDTH) {
size_t sLen = 0, tLen = 0;
uint8_t *sBmp = decodeBase64Alloc(senderBmp, &sLen);
uint8_t *tBmp = decodeBase64Alloc(textBmp, &tLen);
bool valid = sBmp && tBmp &&
isValidBitmapSize(senderW, sLen) &&
isValidBitmapSize(textW, tLen);
if (valid) {
NetworkEvent evt = {};
evt.kind = NetworkEvent::POKE_BITMAP;
strncpy(evt.sender, sender, sizeof(evt.sender) - 1);
evt.sender[sizeof(evt.sender) - 1] = '\0';
strncpy(evt.text, text, sizeof(evt.text) - 1);
evt.text[sizeof(evt.text) - 1] = '\0';
strncpy(evt.title, title, sizeof(evt.title) - 1);
evt.title[sizeof(evt.title) - 1] = '\0';
evt.senderBmp = sBmp;
evt.senderBmpWidth = senderW;
evt.senderBmpLen = sLen;
evt.textBmp = tBmp;
evt.textBmpWidth = textW;
evt.textBmpLen = tLen;
if (xQueueSend(networkEventQueue, &evt, pdMS_TO_TICKS(100)) != pdTRUE) {
free(sBmp);
free(tBmp);
}
} else {
if (sBmp) free(sBmp);
if (tBmp) free(tBmp);
NetworkEvent evt = {};
evt.kind = NetworkEvent::POKE;
strncpy(evt.sender, sender, sizeof(evt.sender) - 1);
evt.sender[sizeof(evt.sender) - 1] = '\0';
strncpy(evt.text, text, sizeof(evt.text) - 1);
evt.text[sizeof(evt.text) - 1] = '\0';
strncpy(evt.title, title, sizeof(evt.title) - 1);
evt.title[sizeof(evt.title) - 1] = '\0';
xQueueSend(networkEventQueue, &evt, pdMS_TO_TICKS(100));
}
} else {
NetworkEvent evt = {};
evt.kind = NetworkEvent::POKE;
strncpy(evt.sender, sender, sizeof(evt.sender) - 1);
evt.sender[sizeof(evt.sender) - 1] = '\0';
strncpy(evt.text, text, sizeof(evt.text) - 1);
evt.text[sizeof(evt.text) - 1] = '\0';
strncpy(evt.title, title, sizeof(evt.title) - 1);
evt.title[sizeof(evt.title) - 1] = '\0';
xQueueSend(networkEventQueue, &evt, pdMS_TO_TICKS(100));
}
} else {
NetworkEvent evt = {};
evt.kind = NetworkEvent::POKE;
strncpy(evt.sender, sender, sizeof(evt.sender) - 1);
evt.sender[sizeof(evt.sender) - 1] = '\0';
strncpy(evt.text, text, sizeof(evt.text) - 1);
evt.text[sizeof(evt.text) - 1] = '\0';
strncpy(evt.title, title, sizeof(evt.title) - 1);
evt.title[sizeof(evt.title) - 1] = '\0';
xQueueSend(networkEventQueue, &evt, pdMS_TO_TICKS(100));
}
}
if (strcmp(msgType, "claim_request") == 0) {
const char *userName = doc["userName"] | "Unknown";
NetworkEvent evt = {};
evt.kind = NetworkEvent::CLAIM_REQUEST;
strncpy(evt.sender, userName, sizeof(evt.sender) - 1);
xQueueSend(networkEventQueue, &evt, pdMS_TO_TICKS(100));
}
if (strcmp(msgType, "friend_request") == 0) {
const char *userName = doc["userName"] | "Unknown";
NetworkEvent evt = {};
evt.kind = NetworkEvent::FRIEND_REQUEST;
strncpy(evt.sender, userName, sizeof(evt.sender) - 1);
xQueueSend(networkEventQueue, &evt, pdMS_TO_TICKS(100));
}
}
// ==========================================================================
// Firmware version check (HTTPS GET latest.json), deferred ~15s after WiFi
// ==========================================================================
#ifndef VERSION_CHECK_URL
#define VERSION_CHECK_URL "https://jagdishtripathy.github.io/QBIT/latest.json"
#endif
#ifndef CLOUD_OTA_FIRMWARE_URL
#define CLOUD_OTA_FIRMWARE_URL "https://jagdishtripathy.github.io/QBIT/firmware.bin"
#endif
#ifndef CLOUD_OTA_LITTLEFS_URL
#define CLOUD_OTA_LITTLEFS_URL "https://jagdishtripathy.github.io/QBIT/littlefs.bin"
#endif
#define VERSION_CHECK_TIMEOUT_MS 45000 // HTTPClient uses ms (compare with millis())
#define VERSION_RECHECK_INTERVAL_MS (6UL * 60UL * 60UL * 1000UL) // periodic check while WiFi up
static char _lastCheckedRemoteVer[UPDATE_AVAILABLE_VERSION_LEN] = "";
// Parse "major.minor.patch" (ignoring optional leading 'v'/'V').
static bool parseSemVer(const char *ver, int &maj, int &min, int &pat) {
if (!ver || ver[0] == '\0') return false;
if (ver[0] == 'v' || ver[0] == 'V') ver++;
if (ver[0] < '0' || ver[0] > '9') return false;
maj = 0; min = 0; pat = 0;
return sscanf(ver, "%d.%d.%d", &maj, &min, &pat) >= 1;
}
// Returns true when remoteVer is strictly newer than localVer,
// or when localVer is "dev-build" so local test builds can always OTA to a release.
static bool isRemoteVersionNewer(const char *localVer, const char *remoteVer) {
if (!localVer || !remoteVer || remoteVer[0] == '\0') return false;
if (strcmp(localVer, "dev-build") == 0) return true;
int lMaj = 0, lMin = 0, lPat = 0;
int rMaj = 0, rMin = 0, rPat = 0;
if (parseSemVer(localVer, lMaj, lMin, lPat) && parseSemVer(remoteVer, rMaj, rMin, rPat)) {
if (rMaj != lMaj) return rMaj > lMaj;
if (rMin != lMin) return rMin > lMin;
return rPat > lPat;
}
const char *remoteNorm = (remoteVer[0] == 'v' || remoteVer[0] == 'V') ? (remoteVer + 1) : remoteVer;
const char *localNorm = (localVer[0] == 'v' || localVer[0] == 'V') ? (localVer + 1) : localVer;
return strcmp(remoteNorm, localNorm) != 0;
}
static void checkFirmwareVersion() {
Serial.println("[Version] Checking...");
WiFiClientSecure client;
client.setInsecure();
client.setTimeout(15000);
HTTPClient http;
if (!http.begin(client, VERSION_CHECK_URL)) {
Serial.println("[Version] HTTP begin failed");
return;
}
http.setTimeout(VERSION_CHECK_TIMEOUT_MS);
int code = http.GET();
if (code != 200) {
Serial.printf("[Version] GET failed: %d\n", code);
http.end();
return;
}
String payload = http.getString();
http.end();
StaticJsonDocument<384> doc;
if (deserializeJson(doc, payload)) {
Serial.println("[Version] JSON parse failed");
return;
}
const char *remoteVer = doc["version"];
if (!remoteVer || remoteVer[0] == '\0') {
Serial.println("[Version] No version in JSON");
return;
}
strncpy(_lastCheckedRemoteVer, remoteVer, UPDATE_AVAILABLE_VERSION_LEN - 1);
_lastCheckedRemoteVer[UPDATE_AVAILABLE_VERSION_LEN - 1] = '\0';
if (isRemoteVersionNewer(kQbitVersion, remoteVer)) {
updateAvailable = true;
strncpy(updateAvailableVersion, remoteVer, UPDATE_AVAILABLE_VERSION_LEN - 1);
updateAvailableVersion[UPDATE_AVAILABLE_VERSION_LEN - 1] = '\0';
Serial.printf("[Version] Update available: %s (current: %s)\n", remoteVer, kQbitVersion);
} else {
updateAvailable = false;
updateAvailableVersion[0] = '\0';
Serial.printf("[Version] Up to date: %s (remote: %s)\n", kQbitVersion, remoteVer);
}
}
// ==========================================================================
// Wireless Cloud Auto-OTA (HTTPS stream Firmware + LittleFS from GitHub Pages)
// ==========================================================================
static bool streamCloudOtaPartition(const char *url, int command, int pctStart, int pctSpan, const char *dlMsg) {
if (command == U_SPIFFS) {
strncpy(otaStatusMsg, "Preparing LittleFS...", sizeof(otaStatusMsg) - 1);
gifPlayerStop();
vTaskDelay(pdMS_TO_TICKS(50));
LittleFS.end();
vTaskDelay(pdMS_TO_TICKS(150));
} else {
strncpy(otaStatusMsg, "Connecting to cloud...", sizeof(otaStatusMsg) - 1);
}
WiFiClientSecure client;
client.setInsecure();
client.setTimeout(30000); // Stream::setTimeout takes milliseconds (30s)
client.setHandshakeTimeout(30); // setHandshakeTimeout takes seconds (30s)
HTTPClient http;
int code = -1;
for (int attempt = 1; attempt <= 3; attempt++) {
if (otaCancelRequested) return false;
client.stop();
if (attempt > 1) {
snprintf(otaStatusMsg, sizeof(otaStatusMsg), "Retry %d/3...", attempt);
vTaskDelay(pdMS_TO_TICKS(800));
}
http.setFollowRedirects(HTTPC_STRICT_FOLLOW_REDIRECTS);
http.setConnectTimeout(20000);
http.setTimeout(30000);
http.setReuse(false);
if (!http.begin(client, url)) {
strncpy(otaStatusMsg, "Connect failed", sizeof(otaStatusMsg) - 1);
continue;
}
code = http.GET();
if (code == HTTP_CODE_OK) {
break;
}
Serial.printf("[OTA] GET %s attempt %d failed: %d (freeHeap=%u)\n",
url, attempt, code, (unsigned)ESP.getFreeHeap());
http.end();
client.stop();
}
if (code != HTTP_CODE_OK) {
snprintf(otaStatusMsg, sizeof(otaStatusMsg), "HTTP error %d", code);
return false;
}
int totalLen = http.getSize();
size_t updateSize = (totalLen > 0) ? (size_t)totalLen : UPDATE_SIZE_UNKNOWN;
if (command != U_SPIFFS) {
strncpy(otaStatusMsg, "Preparing flash...", sizeof(otaStatusMsg) - 1);
}
if (!Update.begin(updateSize, command)) {
snprintf(otaStatusMsg, sizeof(otaStatusMsg), "Begin fail: %d", Update.getError());
http.end();
client.stop();
return false;
}
WiFiClient *stream = http.getStreamPtr();
const size_t OTA_BUF_SIZE = 4096;
uint8_t *buf = (uint8_t *)malloc(OTA_BUF_SIZE);
if (!buf) {
strncpy(otaStatusMsg, "Out of memory", sizeof(otaStatusMsg) - 1);
Update.abort();
http.end();
client.stop();
return false;
}
// Raise task priority during flash streaming so I2C redraws do not starve TCP reads
vTaskPrioritySet(NULL, 2);
size_t written = 0;
unsigned long lastDataMs = millis();
bool writeErr = false;
bool cancelled = false;
strncpy(otaStatusMsg, dlMsg, sizeof(otaStatusMsg) - 1);
while ((http.connected() || stream->available() > 0) && (totalLen <= 0 || (int)written < totalLen)) {
if (otaCancelRequested) {
cancelled = true;
break;
}
size_t avail = stream->available();
if (avail > 0) {
size_t toRead = (avail > OTA_BUF_SIZE) ? OTA_BUF_SIZE : avail;
int r = stream->readBytes(buf, toRead);
if (r > 0) {
if (Update.write(buf, (size_t)r) != (size_t)r) {
Serial.printf("[OTA] Flash write failed at %u bytes, err=%d\n", (unsigned)written, Update.getError());
writeErr = true;
break;
}
written += (size_t)r;
lastDataMs = millis();
if (totalLen > 0) {
int pct = pctStart + (int)((written * (unsigned long long)pctSpan) / (size_t)totalLen);
if (pct > 99) pct = 99;
otaProgressPercent = pct;
}
}
} else {
if (millis() - lastDataMs > 30000) {
Serial.printf("[OTA] Stream timeout (>30s) at %u bytes\n", (unsigned)written);
writeErr = true;
break;
}
vTaskDelay(pdMS_TO_TICKS(10));
}
}
free(buf);
http.end();
client.stop();
vTaskPrioritySet(NULL, 1);
if (cancelled) {
Update.abort();
otaCancelRequested = false;
strncpy(otaStatusMsg, "Update cancelled", sizeof(otaStatusMsg) - 1);
Serial.println("[OTA] Cloud OTA cancelled by user");
return false;
}
if (totalLen > 0 && written < (size_t)totalLen) {
Serial.printf("[OTA] Incomplete: wrote %u of %d bytes\n", (unsigned)written, totalLen);
writeErr = true;
}
if (!writeErr && Update.end(true) && Update.isFinished()) {
return true;
}
Update.abort();
snprintf(otaStatusMsg, sizeof(otaStatusMsg), "Fail: err=%d", Update.getError());
Serial.printf("[OTA] Partition OTA failed (cmd=%d, err=%u, written=%u/%d)\n",
command, (unsigned)Update.getError(), (unsigned)written, totalLen);
return false;
}
static void performCloudOta() {
otaCancelRequested = false;
if (WiFi.status() != WL_CONNECTED) {
strncpy(otaStatusMsg, "No Wi-Fi connection", sizeof(otaStatusMsg) - 1);
vTaskDelay(pdMS_TO_TICKS(2500));
otaInProgress = false;
return;
}
otaInProgress = true;
otaProgressPercent = 0;
// Free WebSocket, MQTT, and GIF file buffers FIRST so mbedTLS has maximum contiguous heap
if (_wsClient.available()) _wsClient.close();
if (_mqttClient.connected()) _mqttClient.disconnect();
gifPlayerStop();
vTaskDelay(pdMS_TO_TICKS(300));
// Only query latest.json if we don't already know an update is waiting
if (!updateAvailable || _lastCheckedRemoteVer[0] == '\0') {
strncpy(otaStatusMsg, "Checking version...", sizeof(otaStatusMsg) - 1);
checkFirmwareVersion();
vTaskDelay(pdMS_TO_TICKS(500)); // Let first TLS socket & heap reclaim cleanly
}
if (otaCancelRequested) {
strncpy(otaStatusMsg, "Update cancelled", sizeof(otaStatusMsg) - 1);
vTaskDelay(pdMS_TO_TICKS(2000));
otaInProgress = false;
return;
}
String syncedFsVer = "";
{
Preferences otaPrefs;
if (otaPrefs.begin("qbit_ota", true)) {
syncedFsVer = otaPrefs.getString("fs_ver", "");
otaPrefs.end();
}
}
bool needFsSync = (_lastCheckedRemoteVer[0] != '\0' && syncedFsVer != String(_lastCheckedRemoteVer));
if (!updateAvailable && !needFsSync) {
snprintf(otaStatusMsg, sizeof(otaStatusMsg), "Up to date! (%s)", kQbitVersion);
Serial.printf("[OTA] Already on latest firmware & LittleFS (%s), skipping flash\n", kQbitVersion);
vTaskDelay(pdMS_TO_TICKS(2500));
otaInProgress = false;
return;
}
Serial.printf("[OTA] Starting Cloud OTA (FW + LittleFS), freeHeap=%u\n", (unsigned)ESP.getFreeHeap());
bool ok = true;
if (updateAvailable) {
ok = streamCloudOtaPartition(CLOUD_OTA_FIRMWARE_URL, U_FLASH, 0, 70, "Downloading FW...");
if (ok && !otaCancelRequested) {
vTaskDelay(pdMS_TO_TICKS(500)); // Allow FW TLS socket to close cleanly before LittleFS TLS
}
}
if (ok && !otaCancelRequested) {
int fsStart = updateAvailable ? 70 : 0;
int fsSpan = updateAvailable ? 30 : 100;
ok = streamCloudOtaPartition(CLOUD_OTA_LITTLEFS_URL, U_SPIFFS, fsStart, fsSpan, "Updating LittleFS...");
}
if (ok) {
if (_lastCheckedRemoteVer[0] != '\0') {
Preferences otaPrefs;
if (otaPrefs.begin("qbit_ota", false)) {
otaPrefs.putString("fs_ver", _lastCheckedRemoteVer);
otaPrefs.end();
}
}
otaProgressPercent = 100;
strncpy(otaStatusMsg, "Success! Rebooting", sizeof(otaStatusMsg) - 1);
Serial.println("[OTA] Cloud OTA (FW + LittleFS) complete, rebooting...");
vTaskDelay(pdMS_TO_TICKS(1500));
esp_restart();
} else {
vTaskDelay(pdMS_TO_TICKS(3000));
otaInProgress = false;
}
}
// ==========================================================================
// MQTT helpers
// ==========================================================================
#define POKE_MQTT_TEXT_MAX 25 // max chars for poke message (no bitmap path)
static char _haStoredPokeText[POKE_MQTT_TEXT_MAX + 1] = {0}; // typed in HA; used when Poke button is pressed
// Sanitize and truncate to maxLen: printable ASCII only, null-terminated.
static void sanitizePokeText(char *dst, size_t dstSize, const char *src, size_t maxLen) {
if (!dst || dstSize == 0) return;
size_t di = 0;
const size_t cap = (maxLen + 1 < dstSize) ? maxLen + 1 : dstSize;
while (di < cap - 1 && src && *src) {
unsigned char c = (unsigned char)*src++;
if (c >= 0x20 && c <= 0x7E) dst[di++] = (char)c;
}
dst[di] = '\0';
}
static void mqttCallback(char *topic, byte *payload, unsigned int length) {
String topicStr = String(topic);
String prefix = getMqttPrefix();
String id = getDeviceId();
// Build raw string from payload
String rawPayload = "";
for (unsigned int i = 0; i < length; i++) rawPayload += (char)payload[i];
// Poke command (JSON payload). If user typed in HA text entity, use that; else use payload text (default "Poke!").
if (topicStr == prefix + "/" + id + "/command") {
StaticJsonDocument<1024> doc;
if (deserializeJson(doc, payload, length)) return;
const char *cmd = doc["command"];
if (!cmd) return;
if (strcmp(cmd, "poke") == 0) {
const char *sender = doc["sender"] | "Home Assistant";
const char *text = doc["text"] | "Poke!";
NetworkEvent evt = {};
evt.kind = NetworkEvent::POKE;
sanitizePokeText(evt.sender, sizeof(evt.sender), sender, POKE_MQTT_TEXT_MAX);
if (evt.sender[0] == '\0') strcpy(evt.sender, "Home Assistant");
if (_haStoredPokeText[0] != '\0') {
strncpy(evt.text, _haStoredPokeText, sizeof(evt.text) - 1);
evt.text[sizeof(evt.text) - 1] = '\0';
} else {
sanitizePokeText(evt.text, sizeof(evt.text), text, POKE_MQTT_TEXT_MAX);
if (evt.text[0] == '\0') strcpy(evt.text, "Poke!");
}
xQueueSend(networkEventQueue, &evt, pdMS_TO_TICKS(100));
mqttPublishPokeEvent(evt.sender, evt.text);
Serial.printf("[MQTT] Poke from %s: %s\n", evt.sender, evt.text);
} else if (strcmp(cmd, "music") == 0) {
bool playing = doc["playing"] | true;
const char *stateStr = doc["state"] | "";
if (strcasecmp(stateStr, "paused") == 0 || strcasecmp(stateStr, "stopped") == 0 || strcasecmp(stateStr, "off") == 0) {
playing = false;
}
const char *title = doc["title"] | (doc["song"] | "Unknown Track");
const char *artist = doc["artist"] | "Unknown Artist";
uint16_t progressSec = (uint16_t)(doc["progress"] | 0);
uint16_t durationSec = (uint16_t)(doc["duration"] | 180);
uint8_t style = (uint8_t)(doc["style"] | 0);
updateMusicState(playing, title, artist, progressSec, durationSec, style);
Serial.printf("[MQTT] Music cmd: playing=%d title=%s artist=%s\n", playing, title, artist);
} else if (strcmp(cmd, "music_stop") == 0) {
updateMusicState(false, "", "", 0, 180, 0);
}
return;
}
// HA text entity: store only (no poke). When user presses Poke button we use this or "Poke!".
if (topicStr == prefix + "/" + id + "/poke_text/set") {
const char *textSrc = rawPayload.c_str();
if (length > 0 && payload[0] == '{') {
StaticJsonDocument<256> doc;
if (!deserializeJson(doc, payload, length)) {
const char *v = doc["value"].as<const char*>();
if (!v || !v[0]) v = doc["text"].as<const char*>();
if (!v || !v[0]) v = doc["message"].as<const char*>();
if (!v || !v[0]) v = doc["state"].as<const char*>();
if (v && v[0]) textSrc = v;
}
}
sanitizePokeText(_haStoredPokeText, sizeof(_haStoredPokeText), textSrc, POKE_MQTT_TEXT_MAX);
return;
}
// Mute set (plain text: ON/OFF)
if (topicStr == prefix + "/" + id + "/mute/set") {
NetworkEvent evt = {};
evt.kind = NetworkEvent::MQTT_COMMAND;
strncpy(evt.sender, "mute", sizeof(evt.sender) - 1);
strncpy(evt.text, rawPayload.c_str(), sizeof(evt.text) - 1);
xQueueSend(networkEventQueue, &evt, pdMS_TO_TICKS(100));
return;
}
// Dedicated music topic: accepts JSON or plain text ("Title - Artist", or "stop")
if (topicStr == prefix + "/" + id + "/music") {
String trimmed = rawPayload;
trimmed.trim();
if (trimmed.length() == 0 || trimmed.equalsIgnoreCase("stop") ||
trimmed.equalsIgnoreCase("off") || trimmed.equalsIgnoreCase("pause")) {
updateMusicState(false, "", "", 0, 180, 0);
return;
}
if (trimmed[0] == '{') {
StaticJsonDocument<512> doc;
if (!deserializeJson(doc, payload, length)) {
bool playing = doc["playing"] | true;
const char *stateStr = doc["state"] | "";
if (strcasecmp(stateStr, "paused") == 0 || strcasecmp(stateStr, "stopped") == 0 || strcasecmp(stateStr, "off") == 0) {
playing = false;
}
const char *title = doc["title"] | (doc["song"] | "Unknown Track");
const char *artist = doc["artist"] | "Unknown Artist";
uint16_t progressSec = (uint16_t)(doc["progress"] | 0);
uint16_t durationSec = (uint16_t)(doc["duration"] | 180);
uint8_t style = (uint8_t)(doc["style"] | 0);
updateMusicState(playing, title, artist, progressSec, durationSec, style);
}
return;
}
int sep = trimmed.indexOf(" - ");
if (sep > 0) {
String t = trimmed.substring(0, sep);
String a = trimmed.substring(sep + 3);
updateMusicState(true, t.c_str(), a.c_str(), 0, 180, 0);
} else {
updateMusicState(true, trimmed.c_str(), "Now Playing", 0, 180, 0);
}
return;
}
// Animation next (no payload needed)
if (topicStr == prefix + "/" + id + "/animation/next") {
NetworkEvent evt = {};
evt.kind = NetworkEvent::MQTT_COMMAND;
strncpy(evt.sender, "animation_next", sizeof(evt.sender) - 1);
xQueueSend(networkEventQueue, &evt, pdMS_TO_TICKS(100));
return;
}
}
static void mqttReconnect() {
// Only attempt MQTT connect when WiFi is actually connected.
// This avoids PubSubClient errors like rc = -2 when there is no network.
String mqttHost = getMqttHost();
mqttHost.trim();
if (!getMqttEnabled() || mqttHost.length() == 0) return;
if (!_wifiConnected || WiFi.status() != WL_CONNECTED) return;
if (_mqttClient.connected()) return;
unsigned long now = millis();
if (now - _mqttLastReconnect < MQTT_RECONNECT_MS) return;
_mqttLastReconnect = now;
const uint16_t mqttPort = getMqttPort();
String mqttUser = getMqttUser();
String mqttPass = getMqttPass();
String prefix = getMqttPrefix();
String id = getDeviceId();
// Keep host in static storage; PubSubClient::setServer(const char*) stores
// the pointer and may outlive temporary Strings. Length already capped by settings.
if (mqttHost.length() >= sizeof(_mqttHostStable))
Serial.printf("[MQTT] Host truncated to %u chars\n", (unsigned)(sizeof(_mqttHostStable) - 1));
strncpy(_mqttHostStable, mqttHost.c_str(), sizeof(_mqttHostStable) - 1);
_mqttHostStable[sizeof(_mqttHostStable) - 1] = '\0';
_mqttClient.setClient(_mqttWifi);
IPAddress brokerIp;
if (brokerIp.fromString(_mqttHostStable)) {
_mqttClient.setServer(brokerIp, mqttPort);
} else {
_mqttClient.setServer(_mqttHostStable, mqttPort);
}
_mqttClient.setBufferSize(1024);
_mqttClient.setCallback(mqttCallback);
Serial.printf("[MQTT] Connecting to %s:%u\n", _mqttHostStable, mqttPort);
String clientId = "qbit-" + id;
String statusTopic = prefix + "/" + id + "/status";
bool ok;
if (mqttUser.length() > 0) {
ok = _mqttClient.connect(clientId.c_str(),
mqttUser.c_str(), mqttPass.c_str(),
statusTopic.c_str(), 0, true, "offline");
} else {
ok = _mqttClient.connect(clientId.c_str(),
statusTopic.c_str(), 0, true, "offline");
}
if (ok) {
Serial.printf("[MQTT] Connected to %s:%u\n", _mqttHostStable, mqttPort);
xEventGroupSetBits(connectivityBits, MQTT_CONNECTED_BIT);
// Publish online + info
_mqttClient.publish(statusTopic.c_str(), "online", true);
String infoTopic = prefix + "/" + id + "/info";
StaticJsonDocument<256> info;
info["id"] = id;
info["name"] = getDeviceName();
info["ip"] = WiFi.localIP().toString();
String infoStr;
serializeJson(info, infoStr);
_mqttClient.publish(infoTopic.c_str(), infoStr.c_str(), true);
// Subscribe to command topics
_mqttClient.subscribe((prefix + "/" + id + "/command").c_str());
_mqttClient.subscribe((prefix + "/" + id + "/poke_text/set").c_str());
_mqttClient.subscribe((prefix + "/" + id + "/mute/set").c_str());
_mqttClient.subscribe((prefix + "/" + id + "/animation/next").c_str());
_mqttClient.subscribe((prefix + "/" + id + "/music").c_str());
// Publish HA discovery
mqttPublishHADiscovery(&_mqttClient);
mqttPublishServerConnectionState(wsIsCloudConnected());
} else {
Serial.printf("[MQTT] Connection failed (rc=%d)\n", _mqttClient.state());
}
}
// ==========================================================================
// Network task main loop
// ==========================================================================
void networkTask(void *param) {
(void)param;
// Wait a bit for WiFi to initialize
vTaskDelay(pdMS_TO_TICKS(500));