-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAriaFanBLE.ino
More file actions
762 lines (636 loc) · 24.9 KB
/
Copy pathAriaFanBLE.ino
File metadata and controls
762 lines (636 loc) · 24.9 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
//==============================================================================
// ARIA FAN BLE CONTROLLER
// Version: 1.0.0
// License: MIT
// Description: ESP32-based BLE bridge to control Elite Aria cycling fan
// from Home Assistant via MQTT
//==============================================================================
#define VERSION "1.0.0"
//==============================================================================
// INCLUDES AND PIN DEFINITIONS
//==============================================================================
#include <FastLED.h>
#include <WiFi.h>
#include <BLEDevice.h>
#include <BLEUtils.h>
#include <BLEScan.h>
#include <BLEAdvertisedDevice.h>
#include <PubSubClient.h>
#include <WebServer.h>
#include "secrets.h"
#define LED_PIN 27
#define NUM_LEDS 1
CRGB leds[NUM_LEDS];
//==============================================================================
// BLE GLOBALS AND UUIDS
//==============================================================================
// Aria BLE Service and Characteristics
static BLEUUID serviceUUID("347B0001-7635-408B-8918-8FF3949CE592");
static BLEUUID char0040UUID("347B0040-7635-408B-8918-8FF3949CE592"); // Write + Notify
static BLEUUID charStatusUUID("347B0042-7635-408B-8918-8FF3949CE592"); // Notify characteristic
// BLE Client globals
static BLEAdvertisedDevice* myDevice;
static BLEClient* pClient = nullptr;
static BLERemoteCharacteristic* pRemoteChar0040 = nullptr;
static BLERemoteCharacteristic* pRemoteCharStatus = nullptr;
static boolean doConnect = false;
static boolean connected = false;
static boolean doScan = false;
static unsigned long lastScanTime = 0;
static boolean justReconnected = false;
static boolean isFirstConnection = true;
static int targetFanSpeed = 25;
static uint8_t targetMode = 0x00;
static boolean needsStateRestore = false;
static unsigned long stateRestoreTime = 0;
//==============================================================================
// MQTT AND WEB SERVER GLOBALS
//==============================================================================
// MQTT globals
WiFiClient espClient;
PubSubClient mqttClient(espClient);
unsigned long lastMqttReconnectAttempt = 0;
// Web server for viewing logs
WebServer server(80);
// Circular log buffer
#define LOG_SIZE 30
String logBuffer[LOG_SIZE];
int logIndex = 0;
//==============================================================================
// FAN STATE VARIABLES
//==============================================================================
// Fan control
int currentFanSpeed = 25; // 0-100 percentage
uint8_t currentMode = 0x00; // 0x00=Manual, 0x01=Speed, 0x02=Power, 0x03=HR, 0x04=Temp
//==============================================================================
// LOGGING SYSTEM
//==============================================================================
// Logging function - logs to both circular buffer and MQTT
void mqttLog(const char* message) {
// Create timestamped entry
char timestamped[256];
// Try to get actual time if available, otherwise use uptime
time_t now;
struct tm timeinfo;
if (time(&now) && localtime_r(&now, &timeinfo) && timeinfo.tm_year > (2020 - 1900)) {
// We have valid time from NTP
char timeStr[32];
strftime(timeStr, sizeof(timeStr), "%Y-%m-%d %H:%M:%S", &timeinfo);
snprintf(timestamped, sizeof(timestamped), "[%s] %s", timeStr, message);
} else {
// Fall back to uptime in human-readable format
unsigned long uptime = millis() / 1000;
unsigned long days = uptime / 86400;
unsigned long hours = (uptime % 86400) / 3600;
unsigned long minutes = (uptime % 3600) / 60;
unsigned long seconds = uptime % 60;
char uptimeStr[32];
if (days > 0) {
snprintf(uptimeStr, sizeof(uptimeStr), "%lud %luh", days, hours);
} else if (hours > 0) {
snprintf(uptimeStr, sizeof(uptimeStr), "%luh %lum", hours, minutes);
} else if (minutes > 0) {
snprintf(uptimeStr, sizeof(uptimeStr), "%lum %lus", minutes, seconds);
} else {
snprintf(uptimeStr, sizeof(uptimeStr), "%lus", seconds);
}
snprintf(timestamped, sizeof(timestamped), "[+%s] %s", uptimeStr, message);
}
// Add to circular buffer
logBuffer[logIndex] = timestamped;
logIndex = (logIndex + 1) % LOG_SIZE;
// Also log to Serial
Serial.println(timestamped);
// Publish to MQTT if connected
if (mqttClient.connected()) {
mqttClient.publish("aria/log/info", timestamped);
}
}
//==============================================================================
// MQTT HANDLERS
//==============================================================================
// MQTT callback for incoming messages
void mqttCallback(char* topic, byte* payload, unsigned int length) {
Serial.print("[MQTT] Message arrived on topic: ");
Serial.println(topic);
// Convert payload to string
String message = "";
for (int i = 0; i < length; i++) {
message += (char)payload[i];
}
Serial.print("[MQTT] Payload: ");
Serial.println(message);
// Handle aria/on/set topic (ON/OFF)
if (String(topic) == "aria/on/set") {
char logMsg[100];
if (message == "ON") {
snprintf(logMsg, sizeof(logMsg), "MQTT command: Turn on (set to 25%%)");
mqttLog(logMsg);
targetFanSpeed = 25;
setFanSpeed(25);
} else if (message == "OFF") {
snprintf(logMsg, sizeof(logMsg), "MQTT command: Turn off (set to 0%%)");
mqttLog(logMsg);
targetFanSpeed = 0;
setFanSpeed(0);
}
}
// Handle aria/speed/set topic (percentage)
else if (String(topic) == "aria/speed/set") {
int speed = message.toInt();
char logMsg[100];
snprintf(logMsg, sizeof(logMsg), "MQTT command: Set speed to %d%%", speed);
mqttLog(logMsg);
targetFanSpeed = speed; // Update target
setFanSpeed(speed);
}
// Handle aria/mode/set topic
else if (String(topic) == "aria/mode/set") {
uint8_t mode = 0x00;
if (message == "Manual") mode = 0x00;
else if (message == "Speed") mode = 0x01;
else if (message == "Power") mode = 0x02;
else if (message == "HR") mode = 0x03;
else if (message == "Temp") mode = 0x04;
char logMsg[100];
snprintf(logMsg, sizeof(logMsg), "MQTT command: Set mode to %s (0x%02X)", message.c_str(), mode);
mqttLog(logMsg);
targetMode = mode; // Update target
setAriaMode(mode);
}
}
//==============================================================================
// BLE NOTIFICATION CALLBACKS
//==============================================================================
// Helper functions for status updates
const char* getModeName(uint8_t mode) {
static const char* modeNames[] = {"Manual", "Speed", "Power", "HR", "Temp"};
return (mode <= 0x04) ? modeNames[mode] : "Unknown";
}
void publishModeStatus(uint8_t mode) {
if (mqttClient.connected() && mode <= 0x04) {
mqttClient.publish("aria/mode/state", getModeName(mode));
}
}
void publishSpeedStatus(int speed) {
if (mqttClient.connected()) {
char speedStr[4];
snprintf(speedStr, sizeof(speedStr), "%d", speed);
mqttClient.publish("aria/speed/state", speedStr, true); // Retained
// Publish ON/OFF state based on speed (retained)
if (speed == 0) {
mqttClient.publish("aria/on/state", "OFF", true); // Retained
} else {
mqttClient.publish("aria/on/state", "ON", true); // Retained
}
}
}
// Notification callback for status updates
static void notifyCallback(
BLERemoteCharacteristic* pBLERemoteCharacteristic,
uint8_t* pData,
size_t length,
bool isNotify) {
Serial.print("[BLE] Status notification: ");
for (int i = 0; i < length; i++) {
Serial.printf("%02X ", pData[i]);
}
Serial.println();
// Parse status: [mode, speed, 0x00, 0x02]
if (length == 4) {
uint8_t newMode = pData[0]; // Mode is in byte 0
uint8_t newSpeed = pData[1]; // Speed is in byte 1
// If we just reconnected, update state and schedule restoration
if (justReconnected) {
char logMsg[100];
snprintf(logMsg, sizeof(logMsg), "Fan current state after reconnection: mode %s (0x%02X), speed %d%%",
getModeName(newMode), newMode, newSpeed);
mqttLog(logMsg);
// Update to fan's current state
currentMode = newMode;
currentFanSpeed = newSpeed;
// Publish current state to MQTT
publishModeStatus(newMode);
publishSpeedStatus(newSpeed);
// Check if this is first connection after boot or a BLE reconnect
if (isFirstConnection) {
// First connection after ESP32 boot - accept fan's current state
snprintf(logMsg, sizeof(logMsg), "First connection after boot - accepting fan state (not restoring)");
mqttLog(logMsg);
// Update target to match fan's actual state
targetMode = newMode;
targetFanSpeed = newSpeed;
isFirstConnection = false;
} else {
// BLE reconnect during operation - restore target state if different
if (targetMode != newMode || targetFanSpeed != newSpeed) {
snprintf(logMsg, sizeof(logMsg), "Scheduling state restore: mode 0x%02X, speed %d%%", targetMode, targetFanSpeed);
mqttLog(logMsg);
needsStateRestore = true;
stateRestoreTime = millis() + 500; // Restore after 500ms
}
}
justReconnected = false;
return;
}
// Normal notification handling (not after reconnection)
// Check if mode changed
if (newMode != currentMode && newMode <= 0x04) {
currentMode = newMode;
char logMsg[100];
snprintf(logMsg, sizeof(logMsg), "BLE notification: Mode changed to %s (0x%02X)", getModeName(newMode), newMode);
mqttLog(logMsg);
publishModeStatus(newMode);
}
// Check if speed changed
if (newSpeed != currentFanSpeed) {
currentFanSpeed = newSpeed;
char logMsg[100];
snprintf(logMsg, sizeof(logMsg), "BLE notification: Speed changed to %d%%", currentFanSpeed);
mqttLog(logMsg);
publishSpeedStatus(currentFanSpeed);
}
}
}
//==============================================================================
// BLE CONNECTION MANAGEMENT
//==============================================================================
class MyClientCallback : public BLEClientCallbacks {
void onConnect(BLEClient* pclient) {
Serial.println("[BLE] Connected to Aria");
leds[0] = CRGB::Green;
FastLED.show();
}
void onDisconnect(BLEClient* pclient) {
connected = false;
mqttLog("BLE disconnected - will attempt reconnection");
leds[0] = CRGB::Red;
FastLED.show();
doScan = true; // Trigger rescan
}
};
bool connectToServer() {
Serial.print("[BLE] Forming a connection to ");
Serial.println(myDevice->getAddress().toString().c_str());
// Clean up old client if exists
if (pClient != nullptr) {
delete pClient;
pClient = nullptr;
}
pClient = BLEDevice::createClient();
Serial.println("[BLE] Created client");
pClient->setClientCallbacks(new MyClientCallback());
// Connect to the Aria BLE Server
if (!pClient->connect(myDevice)) {
Serial.println("[BLE] Failed to connect to server");
delete pClient;
pClient = nullptr;
return false;
}
Serial.println("[BLE] Connected to server");
// Obtain a reference to the service
BLERemoteService* pRemoteService = pClient->getService(serviceUUID);
if (pRemoteService == nullptr) {
Serial.print("[BLE] Failed to find service UUID: ");
Serial.println(serviceUUID.toString().c_str());
pClient->disconnect();
return false;
}
Serial.println("[BLE] Found Aria service");
// Get characteristic 347B0040 (Write + Notify)
pRemoteChar0040 = pRemoteService->getCharacteristic(char0040UUID);
if (pRemoteChar0040 != nullptr) {
Serial.println("[BLE] Found 347B0040 (Write + Notify)");
}
// Get status characteristic 347B0042 (Notify)
pRemoteCharStatus = pRemoteService->getCharacteristic(charStatusUUID);
if (pRemoteCharStatus == nullptr) {
Serial.println("[BLE] Failed to find status characteristic");
pClient->disconnect();
return false;
}
Serial.println("[BLE] Found 347B0042 (Status/Notify)");
// Register for status notifications
if(pRemoteCharStatus->canNotify()) {
pRemoteCharStatus->registerForNotify(notifyCallback);
Serial.println("[BLE] Registered for status notifications");
}
connected = true;
// Store our target state and wait for fan to report its current state
targetFanSpeed = currentFanSpeed;
targetMode = currentMode;
justReconnected = true;
char logMsg[100];
snprintf(logMsg, sizeof(logMsg), "BLE reconnected - target state: mode 0x%02X, speed %d%%", targetMode, targetFanSpeed);
mqttLog(logMsg);
// The notification callback will handle syncing to target state
return true;
}
// Scan for BLE servers and find the Aria
class MyAdvertisedDeviceCallbacks: public BLEAdvertisedDeviceCallbacks {
void onResult(BLEAdvertisedDevice advertisedDevice) {
// Only log devices with names or our service
if (advertisedDevice.haveName() ||
(advertisedDevice.haveServiceUUID() && advertisedDevice.isAdvertisingService(serviceUUID))) {
Serial.print("[BLE] Device found: ");
Serial.println(advertisedDevice.toString().c_str());
}
// Check if this is the Aria by looking for the service UUID
if (advertisedDevice.haveServiceUUID() && advertisedDevice.isAdvertisingService(serviceUUID)) {
BLEDevice::getScan()->stop();
myDevice = new BLEAdvertisedDevice(advertisedDevice);
doConnect = true;
doScan = false;
Serial.println("[BLE] Found Aria fan!");
}
}
};
//==============================================================================
// FAN CONTROL FUNCTIONS
//==============================================================================
void setAriaMode(uint8_t mode) {
if (!connected || pRemoteChar0040 == nullptr) {
Serial.println("[BLE] Not connected, cannot set mode");
return;
}
// Mode change command: [0x05, mode]
// 0x00=Manual, 0x01=Speed, 0x02=Power, 0x03=HR, 0x04=Temp
uint8_t cmd[2] = {0x05, mode};
Serial.printf("[BLE] Setting mode to: 0x%02X (%s)\n", mode, getModeName(mode));
Serial.printf("[BLE] Writing [0x05, 0x%02X] to 347B0040\n", mode);
pRemoteChar0040->writeValue(cmd, 2, true);
currentMode = mode;
// Publish mode status to MQTT
publishModeStatus(mode);
if (mqttClient.connected() && mode <= 0x04) {
Serial.printf("[MQTT] Published mode status: %s\n", getModeName(mode));
}
// Give the fan time to process mode change
delay(500);
}
void setFanSpeed(int percentage) {
if (!connected) {
Serial.println("[BLE] Not connected, cannot set fan speed");
return;
}
// Clamp percentage to 0-100
if (percentage < 0) percentage = 0;
if (percentage > 100) percentage = 100;
Serial.printf("[BLE] Setting fan speed to %d%%\n", percentage);
// Speed control command: [0x03, 0x01, speed_percentage]
// Write to 347B0040
if (pRemoteChar0040 != nullptr) {
uint8_t cmd[3] = {0x03, 0x01, (uint8_t)percentage};
Serial.printf("[BLE] Writing [0x03, 0x01, 0x%02X] to 347B0040\n", percentage);
pRemoteChar0040->writeValue(cmd, 3, true);
Serial.println("[BLE] Command sent!");
currentFanSpeed = percentage;
// Publish status back to MQTT
publishSpeedStatus(percentage);
if (mqttClient.connected()) {
Serial.printf("[MQTT] Published status: %d%%\n", percentage);
}
} else {
Serial.println("[BLE] ERROR: 347B0040 characteristic not available");
}
}
boolean reconnectMqtt() {
Serial.print("[MQTT] Attempting connection to ");
Serial.print(MQTT_SERVER);
Serial.print(":");
Serial.println(MQTT_PORT);
if (mqttClient.connect("AriaFanBLE", MQTT_USER, MQTT_PASSWORD)) {
Serial.println("[MQTT] Connected to MQTT broker");
// Subscribe to control topics
mqttClient.subscribe("aria/on/set");
mqttClient.subscribe("aria/speed/set");
mqttClient.subscribe("aria/mode/set");
Serial.println("[MQTT] Subscribed to aria/on/set, aria/speed/set, and aria/mode/set");
return true;
}
Serial.print("[MQTT] Connection failed, rc=");
Serial.println(mqttClient.state());
return false;
}
//==============================================================================
// SETUP
//==============================================================================
void setup() {
Serial.begin(115200);
FastLED.addLeds<WS2812, LED_PIN, GRB>(leds, NUM_LEDS);
FastLED.setBrightness(20);
Serial.println("\n\nATOM Lite - Aria Fan BLE Client");
Serial.printf("Version: %s\n", VERSION);
Serial.printf("[Heap] At startup: %d bytes free\n", ESP.getFreeHeap());
// Red LED during startup
leds[0] = CRGB::Red;
FastLED.show();
// Connect to WiFi (for future MQTT)
Serial.print("[WiFi] Connecting to WiFi");
WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("\n[WiFi] Connected!");
Serial.print("[WiFi] IP Address: ");
Serial.println(WiFi.localIP());
Serial.printf("[Heap] After WiFi: %d bytes free\n", ESP.getFreeHeap());
// Give network stack time to fully initialize (DNS, etc)
Serial.println("[WiFi] Waiting for network stack to settle...");
delay(2000);
// Configure time via NTP
Serial.println("[Time] Syncing time with NTP...");
configTime(0, 0, "pool.ntp.org", "time.nist.gov"); // GMT+0, no DST
setenv("TZ", "UTC", 1); // Set timezone to UTC (adjust as needed)
tzset();
// Wait a bit for time sync (non-blocking, will use uptime if not synced yet)
delay(1000);
time_t now = time(nullptr);
if (now > 1000000000) { // Sanity check for valid timestamp
Serial.print("[Time] Current time: ");
Serial.println(ctime(&now));
} else {
Serial.println("[Time] NTP not synced yet, will use uptime for now");
}
// Initialize web server for log viewing
server.on("/", []() {
server.send(200, "text/plain", "Aria Fan Controller - visit /logs for logs, /status for diagnostics");
});
server.on("/status", []() {
// Count actual logs in buffer
int actualLogCount = 0;
for (int i = 0; i < LOG_SIZE; i++) {
if (logBuffer[i].length() > 0) {
actualLogCount++;
}
}
String json = "{";
json += "\"version\":\"" + String(VERSION) + "\",";
json += "\"heap_free\":" + String(ESP.getFreeHeap()) + ",";
json += "\"heap_size\":" + String(ESP.getHeapSize()) + ",";
json += "\"heap_min_free\":" + String(ESP.getMinFreeHeap()) + ",";
json += "\"psram_free\":" + String(ESP.getFreePsram()) + ",";
json += "\"psram_size\":" + String(ESP.getPsramSize()) + ",";
json += "\"cpu_freq_mhz\":" + String(ESP.getCpuFreqMHz()) + ",";
json += "\"uptime_sec\":" + String(millis() / 1000) + ",";
json += "\"wifi_connected\":" + String(WiFi.status() == WL_CONNECTED ? "true" : "false") + ",";
json += "\"mqtt_connected\":" + String(mqttClient.connected() ? "true" : "false") + ",";
json += "\"ble_connected\":" + String(connected ? "true" : "false") + ",";
json += "\"log_count\":" + String(actualLogCount) + ",";
json += "\"log_capacity\":" + String(LOG_SIZE);
json += "}";
server.send(200, "application/json", json);
});
server.on("/logs", []() {
// Log heap usage before serving
uint32_t heapBefore = ESP.getFreeHeap();
// Safety check: reject if insufficient heap to build page safely
// 12KB threshold = 8KB page buffer + 4KB headroom for TCP/processing
if (heapBefore < 12000) {
server.send(503, "text/plain", "Service Unavailable - Low memory");
Serial.printf("[Web] /logs rejected - low heap: %d bytes\n", heapBefore);
return;
}
// Build entire HTML page in memory (faster than chunked transfer)
String html = "";
html.reserve(8192); // Pre-allocate: ~500 bytes header + ~6KB logs (30 × 200 bytes) + footer
// HTML header
html += "<!DOCTYPE html><html><head>";
html += "<title>Aria Fan Logs</title>";
html += "<style>body{font-family:monospace;margin:20px;background:#1e1e1e;color:#d4d4d4;}";
html += "pre{background:#252526;padding:10px;border-radius:5px;}</style>";
html += "</head><body>";
html += "<h1>Aria Fan Logs (Last " + String(LOG_SIZE) + " entries)</h1>";
// Format uptime nicely
unsigned long uptime = millis() / 1000;
unsigned long days = uptime / 86400;
unsigned long hours = (uptime % 86400) / 3600;
unsigned long minutes = (uptime % 3600) / 60;
unsigned long seconds = uptime % 60;
String uptimeStr;
if (days > 0) {
uptimeStr = String(days) + "d " + String(hours) + "h " + String(minutes) + "m";
} else if (hours > 0) {
uptimeStr = String(hours) + "h " + String(minutes) + "m " + String(seconds) + "s";
} else if (minutes > 0) {
uptimeStr = String(minutes) + "m " + String(seconds) + "s";
} else {
uptimeStr = String(seconds) + "s";
}
// Add heap info to page
html += "<p>Uptime: " + uptimeStr + " | Free Heap: " + String(heapBefore) + " bytes";
html += " | Min Free: " + String(ESP.getMinFreeHeap()) + " bytes</p>";
html += "<pre>";
// Add all logs to the page
for (int i = 0; i < LOG_SIZE; i++) {
int idx = (logIndex + i) % LOG_SIZE;
if (logBuffer[idx].length() > 0) {
html += logBuffer[idx] + "\n";
}
}
html += "</pre></body></html>";
// Send the complete page in one go
server.send(200, "text/html", html);
});
server.begin();
Serial.println("[Web] Web server started");
Serial.print("[Web] Visit http://");
Serial.print(WiFi.localIP());
Serial.println("/logs");
Serial.printf("[Heap] After WebServer: %d bytes free\n", ESP.getFreeHeap());
// Initialize MQTT
Serial.println("[MQTT] Connecting to MQTT broker...");
mqttClient.setServer(MQTT_SERVER, MQTT_PORT);
mqttClient.setCallback(mqttCallback);
if (reconnectMqtt()) {
Serial.println("[MQTT] MQTT ready!");
} else {
Serial.println("[MQTT] MQTT connection failed, will retry in loop");
}
Serial.printf("[Heap] After MQTT: %d bytes free\n", ESP.getFreeHeap());
// Initialize BLE
Serial.println("[BLE] Initializing BLE client...");
BLEDevice::init("");
Serial.printf("[Heap] After BLE init: %d bytes free\n", ESP.getFreeHeap());
// Retrieve a Scanner and set the callback we want to use to be informed when we
// have detected a new device. Specify that we want active scanning and start the
// scan to run for 5 seconds.
BLEScan* pBLEScan = BLEDevice::getScan();
pBLEScan->setAdvertisedDeviceCallbacks(new MyAdvertisedDeviceCallbacks());
pBLEScan->setInterval(1349);
pBLEScan->setWindow(449);
pBLEScan->setActiveScan(true);
Serial.println("[BLE] Starting scan for Aria fan...");
leds[0] = CRGB::Yellow;
FastLED.show();
doScan = true;
Serial.printf("[Heap] Setup complete - free: %d bytes, min free ever: %d bytes\n",
ESP.getFreeHeap(), ESP.getMinFreeHeap());
}
//==============================================================================
// MAIN LOOP
//==============================================================================
void loop() {
// Handle web server requests
server.handleClient();
// Handle MQTT connection
if (!mqttClient.connected()) {
unsigned long now = millis();
if (now - lastMqttReconnectAttempt > 5000) {
lastMqttReconnectAttempt = now;
Serial.println("[MQTT] Attempting to reconnect...");
if (reconnectMqtt()) {
lastMqttReconnectAttempt = 0;
}
}
} else {
mqttClient.loop();
}
// If the flag "doConnect" is true then we have scanned for and found the desired
// BLE Server with which we wish to connect. Now we connect to it. Once we are
// connected we set the connected flag to be true.
if (doConnect == true) {
if (connectToServer()) {
Serial.println("[BLE] Connected to Aria fan");
leds[0] = CRGB::Green;
FastLED.show();
} else {
Serial.println("[BLE] Failed to connect, will retry");
leds[0] = CRGB::Red;
FastLED.show();
doScan = true;
}
doConnect = false;
}
// If not connected and not currently trying to connect, scan periodically
if (!connected && !doConnect) {
unsigned long now = millis();
if (doScan || (now - lastScanTime > 10000)) { // Retry scan every 10 seconds
Serial.println("[BLE] Starting new scan...");
leds[0] = CRGB::Yellow;
FastLED.show();
BLEDevice::getScan()->start(5, false); // Scan for 5 seconds
doScan = false;
lastScanTime = now;
}
}
// Handle state restoration (deferred from BLE callback)
// Wait for both BLE and MQTT to be connected before restoring
if (needsStateRestore && connected && mqttClient.connected() && millis() >= stateRestoreTime) {
needsStateRestore = false;
char logMsg[100];
snprintf(logMsg, sizeof(logMsg), "Restoring target state: mode 0x%02X, speed %d%%", targetMode, targetFanSpeed);
mqttLog(logMsg);
// Restore mode if different
if (targetMode != currentMode) {
setAriaMode(targetMode);
delay(100); // Brief delay between mode and speed commands
}
// Restore speed if different
if (targetFanSpeed != currentFanSpeed) {
setFanSpeed(targetFanSpeed);
}
}
delay(10);
}