ai_light.ino 22 KB

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