ai_light.ino 22 KB

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