ai_light.ino 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667
  1. #include <WiFi.h>
  2. #include <PubSubClient.h>
  3. #include <ArduinoJson.h>
  4. #include <BLEDevice.h>
  5. #include <BLEServer.h>
  6. #include <BLEUtils.h>
  7. #include <BLE2902.h>
  8. #include <Preferences.h>
  9. // =====================================================
  10. // ESP32-C3 SuperMini + 原玩具公共正极灯板:BLE + MQTT 双模式
  11. //
  12. // 功能:
  13. // - 开机始终启动 BLE,支持灯效控制 + WiFi/MQTT 配置
  14. // - MQTT 模式下同时连接 WiFi/MQTT
  15. // - 运行时长按 BOOT 按钮 3 秒 → 切换 BLE/MQTT 模式并重启
  16. //
  17. // BLE 配置:
  18. // Service: b8b7e001-7a6b-4f4f-9a8b-11c0ffee0001
  19. // Mode: b8b7e002-... (读写/通知 - 灯效模式)
  20. // Config: b8b7e003-... (读写 - WiFi/MQTT 配置 JSON)
  21. //
  22. // 配置 JSON 格式(写入 Config 特征):
  23. // {
  24. // "wifi_ssid": "xxx",
  25. // "wifi_pass": "xxx",
  26. // "mqtt_broker": "192.168.1.100",
  27. // "mqtt_port": 1883,
  28. // "mqtt_user": "user",
  29. // "mqtt_pass": "pass",
  30. // "mqtt_client": "AI-Light",
  31. // "mqtt_topic": "opencode/status",
  32. // "mqtt_status": "openCodeLight/status"
  33. // }
  34. //
  35. // 接线方式(V3 版本):
  36. // ESP32 3.3V -> 原灯板 + / 原电池正极
  37. // ESP32 IO2 -> 220Ω -> L1 控制点 = 黄灯
  38. // ESP32 IO3 -> 220Ω -> L2 控制点 = 绿灯
  39. // ESP32 IO4 -> 220Ω -> L3 控制点 = 红灯
  40. // =====================================================
  41. // =====================================================
  42. // BLE 配置
  43. // =====================================================
  44. const char* BLE_DEVICE_NAME = "AI-Light";
  45. #define SERVICE_UUID "b8b7e001-7a6b-4f4f-9a8b-11c0ffee0001"
  46. #define MODE_CHAR_UUID "b8b7e002-7a6b-4f4f-9a8b-11c0ffee0001"
  47. #define CONFIG_CHAR_UUID "b8b7e003-7a6b-4f4f-9a8b-11c0ffee0001"
  48. // =====================================================
  49. // 引脚定义(V3 版本)
  50. // =====================================================
  51. const int RED_PIN = 4;
  52. const int GREEN_PIN = 3;
  53. const int YELLOW_PIN = 2;
  54. const int WIFI_LED_PIN = 8;
  55. const int BTN_BOOT_PIN = 9;
  56. const int PWM_FREQ = 5000;
  57. const int PWM_RESOLUTION = 8;
  58. const int RED_MAX = 255;
  59. const int YELLOW_MAX = 220;
  60. const int GREEN_MAX = 220;
  61. const unsigned long NORMAL_MODE_TIMEOUT_MS = 5UL * 60UL * 1000UL;
  62. const unsigned long TRAFFIC_MODE_TIMEOUT_MS = 10UL * 60UL * 1000UL;
  63. const unsigned long LONG_PRESS_MS = 3000;
  64. // =====================================================
  65. // 全局状态
  66. // =====================================================
  67. String currentMode = "init";
  68. unsigned long modeStart = 0;
  69. bool useMQTT = true;
  70. WiFiClient wifiClient;
  71. PubSubClient mqttClient(wifiClient);
  72. BLEServer* pServer = nullptr;
  73. BLECharacteristic* pModeCharacteristic = nullptr;
  74. BLECharacteristic* pConfigCharacteristic = nullptr;
  75. bool bleDeviceConnected = false;
  76. bool wifiConnected = false;
  77. Preferences preferences;
  78. String cfgWifiSsid = "";
  79. String cfgWifiPass = "";
  80. String cfgMqttBroker = "";
  81. uint16_t cfgMqttPort = 1883;
  82. String cfgMqttUser = "";
  83. String cfgMqttPass = "";
  84. String cfgMqttClient = "AI-Light";
  85. String cfgMqttTopic = "opencode/status";
  86. String cfgMqttStatus = "openCodeLight/status";
  87. // =====================================================
  88. // NVS 配置读写
  89. // =====================================================
  90. void loadConfig() {
  91. cfgWifiSsid = preferences.getString("wifi_ssid", "");
  92. cfgWifiPass = preferences.getString("wifi_pass", "");
  93. cfgMqttBroker = preferences.getString("mqtt_broker", "");
  94. cfgMqttPort = preferences.getUInt("mqtt_port", 1883);
  95. cfgMqttUser = preferences.getString("mqtt_user", "");
  96. cfgMqttPass = preferences.getString("mqtt_pass", "");
  97. cfgMqttClient = preferences.getString("mqtt_client", "AI-Light");
  98. cfgMqttTopic = preferences.getString("mqtt_topic", "opencode/status");
  99. cfgMqttStatus = preferences.getString("mqtt_status", "openCodeLight/status");
  100. }
  101. bool isConfigComplete() {
  102. return cfgWifiSsid.length() > 0 && cfgMqttBroker.length() > 0;
  103. }
  104. String getConfigJson() {
  105. JsonDocument doc;
  106. doc["wifi_ssid"] = cfgWifiSsid;
  107. doc["mqtt_broker"] = cfgMqttBroker;
  108. doc["mqtt_port"] = cfgMqttPort;
  109. doc["mqtt_user"] = cfgMqttUser;
  110. doc["mqtt_client"] = cfgMqttClient;
  111. doc["mqtt_topic"] = cfgMqttTopic;
  112. doc["mqtt_status"] = cfgMqttStatus;
  113. doc["comm_mode"] = useMQTT ? 1 : 0;
  114. String out;
  115. serializeJson(doc, out);
  116. return out;
  117. }
  118. void saveConfigFromJson(const String& json) {
  119. JsonDocument doc;
  120. DeserializationError err = deserializeJson(doc, json);
  121. if (err) {
  122. Serial.print("Config JSON parse error: ");
  123. Serial.println(err.c_str());
  124. return;
  125. }
  126. if (doc.containsKey("wifi_ssid"))
  127. preferences.putString("wifi_ssid", doc["wifi_ssid"].as<String>());
  128. if (doc.containsKey("wifi_pass"))
  129. preferences.putString("wifi_pass", doc["wifi_pass"].as<String>());
  130. if (doc.containsKey("mqtt_broker"))
  131. preferences.putString("mqtt_broker", doc["mqtt_broker"].as<String>());
  132. if (doc.containsKey("mqtt_port"))
  133. preferences.putUInt("mqtt_port", doc["mqtt_port"].as<uint16_t>());
  134. if (doc.containsKey("mqtt_user"))
  135. preferences.putString("mqtt_user", doc["mqtt_user"].as<String>());
  136. if (doc.containsKey("mqtt_pass"))
  137. preferences.putString("mqtt_pass", doc["mqtt_pass"].as<String>());
  138. if (doc.containsKey("mqtt_client"))
  139. preferences.putString("mqtt_client", doc["mqtt_client"].as<String>());
  140. if (doc.containsKey("mqtt_topic"))
  141. preferences.putString("mqtt_topic", doc["mqtt_topic"].as<String>());
  142. if (doc.containsKey("mqtt_status"))
  143. preferences.putString("mqtt_status", doc["mqtt_status"].as<String>());
  144. Serial.println("Config saved. Restarting...");
  145. delay(500);
  146. ESP.restart();
  147. }
  148. // =====================================================
  149. // 基础工具函数:公共正极反相输出
  150. // =====================================================
  151. void writeLed(int pin, int value) {
  152. value = constrain(value, 0, 255);
  153. int pwmValue = 255 - value;
  154. ledcWrite(pin, pwmValue);
  155. }
  156. void allOff() {
  157. writeLed(RED_PIN, 0);
  158. writeLed(YELLOW_PIN, 0);
  159. writeLed(GREEN_PIN, 0);
  160. }
  161. void setOnly(int red, int yellow, int green) {
  162. writeLed(RED_PIN, constrain(red, 0, RED_MAX));
  163. writeLed(YELLOW_PIN, constrain(yellow, 0, YELLOW_MAX));
  164. writeLed(GREEN_PIN, constrain(green, 0, GREEN_MAX));
  165. }
  166. int triWave(unsigned long t, unsigned long period, int maxValue) {
  167. unsigned long x = t % period;
  168. if (x < period / 2) return map(x, 0, period / 2, 0, maxValue);
  169. return map(x, period / 2, period, maxValue, 0);
  170. }
  171. int fadeInOutBrightness(
  172. unsigned long t, unsigned long fadeIn, unsigned long hold,
  173. unsigned long fadeOut, unsigned long offTime, int maxValue
  174. ) {
  175. unsigned long total = fadeIn + hold + fadeOut + offTime;
  176. unsigned long x = t % total;
  177. if (x < fadeIn) return map(x, 0, fadeIn, 0, maxValue);
  178. x -= fadeIn;
  179. if (x < hold) return maxValue;
  180. x -= hold;
  181. if (x < fadeOut) return map(x, 0, fadeOut, maxValue, 0);
  182. return 0;
  183. }
  184. void fadeToStatic(int targetRed, int targetYellow, int targetGreen, int fadeMs = 80) {
  185. allOff();
  186. int steps = 12;
  187. int delayPerStep = max(1, fadeMs / steps);
  188. for (int i = 0; i <= steps; i++) {
  189. float p = (float)i / steps;
  190. setOnly(targetRed * p, targetYellow * p, targetGreen * p);
  191. delay(delayPerStep);
  192. }
  193. }
  194. // =====================================================
  195. // 模式处理
  196. // =====================================================
  197. bool isValidMode(String mode) {
  198. return (
  199. mode == "red" || mode == "yellow" || mode == "green" ||
  200. mode == "busy" || mode == "error" || mode == "thinking" ||
  201. mode == "ai" || mode == "success" || mode == "traffic" ||
  202. mode == "alarm" || mode == "init" || mode == "off" || mode == "idle"
  203. );
  204. }
  205. void publishStatus() {
  206. if (useMQTT && mqttClient.connected()) {
  207. mqttClient.publish(cfgMqttStatus.c_str(), currentMode.c_str(), true);
  208. }
  209. }
  210. void notifyMode() {
  211. if (pModeCharacteristic) {
  212. pModeCharacteristic->setValue(currentMode.c_str());
  213. if (bleDeviceConnected) pModeCharacteristic->notify();
  214. }
  215. }
  216. void setMode(String mode) {
  217. mode.trim();
  218. mode.toLowerCase();
  219. if (!isValidMode(mode)) {
  220. Serial.print("Unknown mode: ");
  221. Serial.println(mode);
  222. return;
  223. }
  224. if (mode == "idle") mode = "traffic";
  225. if (mode == currentMode) return;
  226. currentMode = mode;
  227. modeStart = millis();
  228. Serial.print("Mode: ");
  229. Serial.println(currentMode);
  230. if (mode == "red") fadeToStatic(RED_MAX, 0, 0, 80);
  231. else if (mode == "yellow") fadeToStatic(0, YELLOW_MAX, 0, 80);
  232. else if (mode == "green") fadeToStatic(0, 0, GREEN_MAX, 80);
  233. else if (mode == "success") setOnly(0, 0, GREEN_MAX);
  234. else if (mode == "off") allOff();
  235. publishStatus();
  236. notifyMode();
  237. }
  238. void autoTimeoutCheck() {
  239. unsigned long elapsed = millis() - modeStart;
  240. if (currentMode == "off") return;
  241. if (currentMode == "traffic") {
  242. if (elapsed >= TRAFFIC_MODE_TIMEOUT_MS) setMode("off");
  243. return;
  244. }
  245. if (elapsed >= NORMAL_MODE_TIMEOUT_MS) setMode("traffic");
  246. }
  247. // =====================================================
  248. // 灯效模式
  249. // =====================================================
  250. void updateBusy() {
  251. unsigned long t = millis() - modeStart;
  252. int y = fadeInOutBrightness(t, 80, 500, 120, 500, YELLOW_MAX);
  253. setOnly(0, y, 0);
  254. }
  255. void updateError() {
  256. unsigned long t = millis() - modeStart;
  257. int r = fadeInOutBrightness(t, 40, 180, 80, 180, RED_MAX);
  258. setOnly(r, 0, 0);
  259. }
  260. void updateThinking() {
  261. unsigned long t = millis() - modeStart;
  262. const unsigned long period = 1050;
  263. unsigned long x = t % period;
  264. int g = 0, y = 0, r = 0;
  265. if (x < 350) {
  266. g = map(x, 0, 350, GREEN_MAX, 70);
  267. y = map(x, 0, 350, 20, YELLOW_MAX);
  268. } else if (x < 700) {
  269. unsigned long p = x - 350;
  270. g = map(p, 0, 350, 70, 0);
  271. y = map(p, 0, 350, YELLOW_MAX, 70);
  272. r = map(p, 0, 350, 20, RED_MAX);
  273. } else {
  274. unsigned long p = x - 700;
  275. g = map(p, 0, 350, 20, GREEN_MAX);
  276. y = map(p, 0, 350, 70, 0);
  277. r = map(p, 0, 350, RED_MAX, 70);
  278. }
  279. setOnly(r, y, g);
  280. }
  281. void updateAi() {
  282. unsigned long t = millis() - modeStart;
  283. const unsigned long period = 1800;
  284. unsigned long x = t % period;
  285. int g = triWave((x + 0) % period, period, 150);
  286. int y = triWave((x + period / 3) % period, period, 140);
  287. int r = triWave((x + 2 * period / 3) % period, period, 170);
  288. setOnly(r, y, g);
  289. }
  290. void updateSuccess() { setOnly(0, 0, GREEN_MAX); }
  291. void updateAlarm() {
  292. unsigned long t = millis() - modeStart;
  293. const unsigned long phaseMs = 260;
  294. int phase = (t / phaseMs) % 2;
  295. unsigned long inside = t % phaseMs;
  296. int brightness;
  297. if (inside < 60) brightness = map(inside, 0, 60, 0, 255);
  298. else if (inside < 180) brightness = 255;
  299. else brightness = map(inside, 180, phaseMs, 255, 0);
  300. if (phase == 0) setOnly(brightness, 0, 0);
  301. else setOnly(0, min(brightness, YELLOW_MAX), 0);
  302. }
  303. void updateTraffic() {
  304. unsigned long t = (millis() - modeStart) % 15000;
  305. if (t < 5000) {
  306. setOnly(0, 0, GREEN_MAX);
  307. } else if (t < 6500) {
  308. unsigned long phase = (t - 5000) % 500;
  309. int g = 0;
  310. if (phase < 60) g = map(phase, 0, 60, 0, GREEN_MAX);
  311. else if (phase < 230) g = GREEN_MAX;
  312. else if (phase < 320) g = map(phase, 230, 320, GREEN_MAX, 0);
  313. setOnly(0, 0, g);
  314. } else if (t < 8500) {
  315. setOnly(0, YELLOW_MAX, 0);
  316. } else if (t < 13500) {
  317. setOnly(RED_MAX, 0, 0);
  318. } else {
  319. unsigned long phase = (t - 13500) % 500;
  320. int r = 0;
  321. if (phase < 60) r = map(phase, 0, 60, 0, RED_MAX);
  322. else if (phase < 230) r = RED_MAX;
  323. else if (phase < 320) r = map(phase, 230, 320, RED_MAX, 0);
  324. setOnly(r, 0, 0);
  325. }
  326. }
  327. void updateInit() {
  328. unsigned long t = millis() - modeStart;
  329. const unsigned long period = 2500;
  330. unsigned long x = t % period;
  331. int brightness;
  332. if (x < 800) brightness = map(x, 0, 800, 0, 200);
  333. else if (x < 1200) brightness = 200;
  334. else if (x < 2000) brightness = map(x, 1200, 2000, 200, 0);
  335. else brightness = 0;
  336. setOnly(brightness, brightness, brightness);
  337. }
  338. void breathingGreen(int times) {
  339. const unsigned long period = 2500;
  340. for (int i = 0; i < times; i++) {
  341. unsigned long start = millis();
  342. while (millis() - start < period) {
  343. unsigned long t = millis() - start;
  344. int brightness;
  345. if (t < 800) brightness = map(t, 0, 800, 0, GREEN_MAX);
  346. else if (t < 1200) brightness = GREEN_MAX;
  347. else if (t < 2000) brightness = map(t, 1200, 2000, GREEN_MAX, 0);
  348. else brightness = 0;
  349. setOnly(0, 0, brightness);
  350. delay(5);
  351. }
  352. }
  353. allOff();
  354. }
  355. // =====================================================
  356. // BOOT 按钮处理
  357. // =====================================================
  358. unsigned long bootPressStart = 0;
  359. bool bootWasPressed = false;
  360. bool switchTriggered = false;
  361. void checkBootButton() {
  362. bool pressed = (digitalRead(BTN_BOOT_PIN) == LOW);
  363. if (pressed && !bootWasPressed) {
  364. bootPressStart = millis();
  365. bootWasPressed = true;
  366. }
  367. if (pressed && bootWasPressed && !switchTriggered) {
  368. if (millis() - bootPressStart >= LONG_PRESS_MS) {
  369. switchTriggered = true;
  370. Serial.println("BOOT long press -> switching mode...");
  371. allOff();
  372. for (int i = 0; i < 3; i++) {
  373. setOnly(100, 100, 100); delay(100);
  374. allOff(); delay(100);
  375. }
  376. useMQTT = !useMQTT;
  377. preferences.putUInt("comm_mode", useMQTT ? 1 : 0);
  378. delay(200);
  379. ESP.restart();
  380. }
  381. }
  382. if (!pressed) {
  383. bootWasPressed = false;
  384. switchTriggered = false;
  385. }
  386. }
  387. // =====================================================
  388. // 状态 LED
  389. // =====================================================
  390. unsigned long lastStatusLedToggle = 0;
  391. bool statusLedState = false;
  392. void updateStatusLed() {
  393. bool connected = (useMQTT && wifiConnected) ? (WiFi.status() == WL_CONNECTED) : bleDeviceConnected;
  394. if (connected) {
  395. digitalWrite(WIFI_LED_PIN, LOW);
  396. return;
  397. }
  398. if (millis() - lastStatusLedToggle >= 500) {
  399. statusLedState = !statusLedState;
  400. digitalWrite(WIFI_LED_PIN, statusLedState ? LOW : HIGH);
  401. lastStatusLedToggle = millis();
  402. }
  403. }
  404. // =====================================================
  405. // BLE
  406. // =====================================================
  407. class ServerCallbacks : public BLEServerCallbacks {
  408. void onConnect(BLEServer* s) { bleDeviceConnected = true; Serial.println("BLE connected."); }
  409. void onDisconnect(BLEServer* s) { bleDeviceConnected = false; Serial.println("BLE disconnected."); delay(100); BLEDevice::startAdvertising(); }
  410. };
  411. class ModeCharCallbacks : public BLECharacteristicCallbacks {
  412. void onWrite(BLECharacteristic* c) { setMode(c->getValue()); }
  413. void onRead(BLECharacteristic* c) { c->setValue(currentMode.c_str()); }
  414. };
  415. class ConfigCharCallbacks : public BLECharacteristicCallbacks {
  416. void onWrite(BLECharacteristic* c) { saveConfigFromJson(c->getValue()); }
  417. void onRead(BLECharacteristic* c) { c->setValue(getConfigJson().c_str()); }
  418. };
  419. void setupBLE() {
  420. Serial.println("Starting BLE...");
  421. BLEDevice::init(BLE_DEVICE_NAME);
  422. pServer = BLEDevice::createServer();
  423. pServer->setCallbacks(new ServerCallbacks());
  424. BLEService* pService = pServer->createService(BLEUUID(SERVICE_UUID), 20);
  425. pModeCharacteristic = pService->createCharacteristic(MODE_CHAR_UUID,
  426. BLECharacteristic::PROPERTY_READ | BLECharacteristic::PROPERTY_WRITE | BLECharacteristic::PROPERTY_NOTIFY);
  427. pModeCharacteristic->setCallbacks(new ModeCharCallbacks());
  428. pModeCharacteristic->setValue(currentMode.c_str());
  429. pModeCharacteristic->addDescriptor(new BLE2902());
  430. pConfigCharacteristic = pService->createCharacteristic(CONFIG_CHAR_UUID,
  431. BLECharacteristic::PROPERTY_READ | BLECharacteristic::PROPERTY_WRITE);
  432. pConfigCharacteristic->setCallbacks(new ConfigCharCallbacks());
  433. pService->start();
  434. BLEAdvertising* pAdvertising = BLEDevice::getAdvertising();
  435. pAdvertising->addServiceUUID(SERVICE_UUID);
  436. pAdvertising->setScanResponse(true);
  437. pAdvertising->setMinPreferred(0x0c);
  438. pAdvertising->setMaxPreferred(0x18);
  439. BLEDevice::startAdvertising();
  440. Serial.println("BLE advertising.");
  441. }
  442. // =====================================================
  443. // MQTT
  444. // =====================================================
  445. void mqttCallback(char* topic, byte* payload, unsigned int length) {
  446. String message = "";
  447. for (unsigned int i = 0; i < length; i++) message += (char)payload[i];
  448. Serial.print("MQTT: "); Serial.print(topic); Serial.print(" -> "); Serial.println(message);
  449. JsonDocument doc;
  450. if (deserializeJson(doc, message)) { setMode(message); return; }
  451. const char* code = doc["code"];
  452. if (code) {
  453. String c = String(code);
  454. if (c == "idle") setMode("idle");
  455. else if (c == "busy" || c == "running") setMode("busy");
  456. else if (c == "retry" || c == "permission") setMode("alarm");
  457. else if (c == "pending") setMode("yellow");
  458. else if (c == "reasoning") setMode("thinking");
  459. else if (c == "using_tool") setMode("ai");
  460. else if (c == "error") setMode("error");
  461. else setMode(c);
  462. }
  463. }
  464. bool connectWiFi() {
  465. Serial.print("Connecting WiFi");
  466. WiFi.mode(WIFI_STA);
  467. WiFi.begin(cfgWifiSsid.c_str(), cfgWifiPass.c_str());
  468. for (int retry = 1; retry <= 5; retry++) {
  469. Serial.printf("\nWiFi %d/5", retry);
  470. int attempts = 0;
  471. while (WiFi.status() != WL_CONNECTED && attempts < 60) {
  472. delay(5); setOnly(100, 100, 100); updateStatusLed(); Serial.print("."); attempts++;
  473. }
  474. if (WiFi.status() == WL_CONNECTED) {
  475. Serial.printf("\nWiFi OK. IP: %s\n", WiFi.localIP().toString().c_str());
  476. digitalWrite(WIFI_LED_PIN, LOW);
  477. return true;
  478. }
  479. Serial.println("\nFailed, retrying..."); delay(2000);
  480. }
  481. Serial.println("\nWiFi failed. Turning off WiFi.");
  482. WiFi.disconnect(true);
  483. WiFi.mode(WIFI_OFF);
  484. return false;
  485. }
  486. bool connectMQTT() {
  487. mqttClient.setServer(cfgMqttBroker.c_str(), cfgMqttPort);
  488. mqttClient.setCallback(mqttCallback);
  489. Serial.print("MQTT connecting");
  490. int attempts = 0;
  491. while (!mqttClient.connected()) {
  492. if (mqttClient.connect(cfgMqttClient.c_str(), cfgMqttUser.c_str(), cfgMqttPass.c_str())) {
  493. Serial.println("\nMQTT OK.");
  494. mqttClient.subscribe(cfgMqttTopic.c_str());
  495. allOff(); breathingGreen(3); publishStatus();
  496. return true;
  497. }
  498. Serial.print("."); delay(500);
  499. if (++attempts > 60) { Serial.println("\nMQTT failed!"); return false; }
  500. }
  501. return false;
  502. }
  503. void checkMQTTConnection() {
  504. if (useMQTT && !mqttClient.connected()) { Serial.println("MQTT reconnecting..."); connectMQTT(); }
  505. }
  506. // =====================================================
  507. // 初始化
  508. // =====================================================
  509. void setup() {
  510. Serial.begin(115200);
  511. delay(500);
  512. ledcAttach(RED_PIN, PWM_FREQ, PWM_RESOLUTION);
  513. ledcAttach(YELLOW_PIN, PWM_FREQ, PWM_RESOLUTION);
  514. ledcAttach(GREEN_PIN, PWM_FREQ, PWM_RESOLUTION);
  515. pinMode(WIFI_LED_PIN, OUTPUT);
  516. pinMode(BTN_BOOT_PIN, INPUT_PULLUP);
  517. digitalWrite(WIFI_LED_PIN, HIGH);
  518. allOff();
  519. preferences.begin("ai-light", false);
  520. useMQTT = (preferences.getUInt("comm_mode", 1) != 0);
  521. loadConfig();
  522. Serial.println();
  523. Serial.println("=== AI-Light ===");
  524. Serial.printf("Mode: %s\n", useMQTT ? "MQTT" : "BLE-only");
  525. Serial.printf("WiFi: %s\n", cfgWifiSsid.length() > 0 ? cfgWifiSsid.c_str() : "(not set)");
  526. Serial.printf("MQTT: %s\n", cfgMqttBroker.length() > 0 ? cfgMqttBroker.c_str() : "(not set)");
  527. currentMode = "init";
  528. modeStart = millis();
  529. if (useMQTT && isConfigComplete()) {
  530. wifiConnected = connectWiFi();
  531. if (wifiConnected) {
  532. connectMQTT();
  533. setMode("traffic");
  534. Serial.println("WiFi/MQTT mode. Long press BOOT (3s) to switch.");
  535. return;
  536. }
  537. Serial.println("WiFi failed. Entering BLE config mode.");
  538. }
  539. setupBLE();
  540. delay(100);
  541. setMode("traffic");
  542. Serial.println("BLE config mode. Long press BOOT (3s) to switch.");
  543. }
  544. // =====================================================
  545. // 主循环
  546. // =====================================================
  547. void loop() {
  548. updateStatusLed();
  549. checkBootButton();
  550. if (useMQTT && wifiConnected) {
  551. if (WiFi.status() != WL_CONNECTED) {
  552. Serial.println("WiFi lost, reconnecting...");
  553. wifiConnected = connectWiFi();
  554. if (!wifiConnected) {
  555. Serial.println("WiFi failed. BLE config mode active.");
  556. }
  557. }
  558. if (wifiConnected) {
  559. checkMQTTConnection();
  560. mqttClient.loop();
  561. }
  562. }
  563. autoTimeoutCheck();
  564. if (currentMode == "busy") updateBusy();
  565. else if (currentMode == "error") updateError();
  566. else if (currentMode == "thinking") updateThinking();
  567. else if (currentMode == "ai") updateAi();
  568. else if (currentMode == "success") updateSuccess();
  569. else if (currentMode == "traffic") updateTraffic();
  570. else if (currentMode == "alarm") updateAlarm();
  571. else if (currentMode == "init") updateInit();
  572. else if (currentMode == "off") allOff();
  573. delay(5);
  574. }