ai_light.ino 24 KB

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