ai_light.ino 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757
  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. // - 连续短按 BOOT 按钮 3 下 → 恢复出厂设置并重启
  17. //
  18. // BLE 配置:
  19. // Service: b8b7e001-7a6b-4f4f-9a8b-11c0ffee0001
  20. // Mode: b8b7e002-... (读写/通知 - 灯效模式)
  21. // Config: b8b7e003-... (读写 - WiFi/MQTT 配置 JSON)
  22. //
  23. // 配置 JSON 格式(写入 Config 特征或 MQTT config topic):
  24. // {
  25. // "wifi_ssid": "xxx",
  26. // "wifi_pass": "xxx",
  27. // "mqtt_broker": "192.168.1.100",
  28. // "mqtt_port": 1883,
  29. // "mqtt_user": "user",
  30. // "mqtt_pass": "pass",
  31. // "mqtt_client": "AI-Light",
  32. // "mqtt_topic": "agent/status",
  33. // "mqtt_status": "agentLight/status",
  34. // "mqtt_topic_config": "agent/status/config",
  35. // "pin_red": 4,
  36. // "pin_green": 3,
  37. // "pin_yellow": 2
  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. const unsigned long TRIPLE_PRESS_WINDOW_MS = 1500;
  73. const int TRIPLE_PRESS_COUNT = 3;
  74. // =====================================================
  75. // 全局状态
  76. // =====================================================
  77. String currentMode = "init";
  78. unsigned long modeStart = 0;
  79. bool useMQTT = true;
  80. WiFiClient wifiClient;
  81. PubSubClient mqttClient(wifiClient);
  82. BLEServer* pServer = nullptr;
  83. BLECharacteristic* pModeCharacteristic = nullptr;
  84. BLECharacteristic* pConfigCharacteristic = nullptr;
  85. bool bleDeviceConnected = false;
  86. bool wifiConnected = false;
  87. Preferences preferences;
  88. String cfgWifiSsid = "";
  89. String cfgWifiPass = "";
  90. String cfgMqttBroker = "";
  91. uint16_t cfgMqttPort = 1883;
  92. String cfgMqttUser = "";
  93. String cfgMqttPass = "";
  94. String cfgMqttClient = "AI-Light";
  95. String cfgMqttTopic = "agent/status";
  96. String cfgMqttStatus = "agentLight/status";
  97. String cfgMqttTopicConfig = "agent/status/config";
  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", "agent/status");
  110. cfgMqttStatus = preferences.getString("mqtt_status", "agentLight/status");
  111. cfgMqttTopicConfig = preferences.getString("mqtt_topic_cfg", "agent/status/config");
  112. redPin = preferences.getUInt("pin_red", 4);
  113. greenPin = preferences.getUInt("pin_green", 3);
  114. yellowPin = preferences.getUInt("pin_yellow", 2);
  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["mqtt_topic_config"] = cfgMqttTopicConfig;
  130. doc["comm_mode"] = useMQTT ? 1 : 0;
  131. doc["pin_red"] = redPin;
  132. doc["pin_green"] = greenPin;
  133. doc["pin_yellow"] = yellowPin;
  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("mqtt_topic_config"))
  165. preferences.putString("mqtt_topic_cfg", doc["mqtt_topic_config"].as<String>());
  166. if (doc.containsKey("pin_red"))
  167. preferences.putUInt("pin_red", doc["pin_red"].as<uint8_t>());
  168. if (doc.containsKey("pin_green"))
  169. preferences.putUInt("pin_green", doc["pin_green"].as<uint8_t>());
  170. if (doc.containsKey("pin_yellow"))
  171. preferences.putUInt("pin_yellow", doc["pin_yellow"].as<uint8_t>());
  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. unsigned long lastPressEnd = 0;
  390. int pressCount = 0;
  391. void factoryReset() {
  392. Serial.println("Factory reset! Clearing all config...");
  393. allOff();
  394. for (int i = 0; i < 5; i++) {
  395. setOnly(255, 0, 0); delay(200);
  396. allOff(); delay(200);
  397. }
  398. preferences.clear();
  399. Serial.println("NVS cleared. Restarting...");
  400. delay(500);
  401. ESP.restart();
  402. }
  403. void checkBootButton() {
  404. bool pressed = (digitalRead(BUTTON_PIN) == LOW);
  405. if (pressed && !bootWasPressed) {
  406. bootPressStart = millis();
  407. bootWasPressed = true;
  408. switchTriggered = false;
  409. }
  410. if (pressed && bootWasPressed && !switchTriggered) {
  411. if (millis() - bootPressStart >= LONG_PRESS_MS) {
  412. switchTriggered = true;
  413. Serial.println("BOOT long press -> switching mode...");
  414. allOff();
  415. for (int i = 0; i < 3; i++) {
  416. setOnly(100, 100, 100); delay(100);
  417. allOff(); delay(100);
  418. }
  419. useMQTT = !useMQTT;
  420. preferences.putUInt("comm_mode", useMQTT ? 1 : 0);
  421. delay(200);
  422. ESP.restart();
  423. }
  424. }
  425. if (!pressed && bootWasPressed) {
  426. bootWasPressed = false;
  427. unsigned long pressDuration = millis() - bootPressStart;
  428. if (pressDuration < LONG_PRESS_MS) {
  429. if (millis() - lastPressEnd > TRIPLE_PRESS_WINDOW_MS) {
  430. pressCount = 0;
  431. }
  432. pressCount++;
  433. lastPressEnd = millis();
  434. Serial.printf("Short press %d/%d\n", pressCount, TRIPLE_PRESS_COUNT);
  435. if (pressCount >= TRIPLE_PRESS_COUNT) {
  436. pressCount = 0;
  437. factoryReset();
  438. }
  439. }
  440. }
  441. }
  442. // =====================================================
  443. // 状态 LED
  444. // =====================================================
  445. unsigned long lastStatusLedToggle = 0;
  446. bool statusLedState = false;
  447. void updateStatusLed() {
  448. bool connected = (useMQTT && wifiConnected) ? (WiFi.status() == WL_CONNECTED) : bleDeviceConnected;
  449. if (connected) {
  450. digitalWrite(STATUS_PIN, LOW);
  451. return;
  452. }
  453. if (millis() - lastStatusLedToggle >= 500) {
  454. statusLedState = !statusLedState;
  455. digitalWrite(STATUS_PIN, statusLedState ? LOW : HIGH);
  456. lastStatusLedToggle = millis();
  457. }
  458. }
  459. // =====================================================
  460. // BLE
  461. // =====================================================
  462. class ServerCallbacks : public BLEServerCallbacks {
  463. void onConnect(BLEServer* s) {
  464. bleDeviceConnected = true;
  465. Serial.println("BLE connected.");
  466. if (currentMode == "init") setMode("traffic");
  467. }
  468. void onDisconnect(BLEServer* s) {
  469. bleDeviceConnected = false;
  470. Serial.println("BLE disconnected.");
  471. delay(100);
  472. BLEDevice::startAdvertising();
  473. }
  474. };
  475. class ModeCharCallbacks : public BLECharacteristicCallbacks {
  476. void onWrite(BLECharacteristic* c) {
  477. String val = c->getValue();
  478. Serial.print("BLE Mode received: ");
  479. Serial.println(val);
  480. if (val == "restart") {
  481. Serial.println("Restarting...");
  482. delay(500);
  483. ESP.restart();
  484. }
  485. setMode(val);
  486. }
  487. void onRead(BLECharacteristic* c) { c->setValue(currentMode.c_str()); }
  488. };
  489. class ConfigCharCallbacks : public BLECharacteristicCallbacks {
  490. void onWrite(BLECharacteristic* c) {
  491. String val = c->getValue();
  492. Serial.print("BLE Config received: ");
  493. Serial.println(val);
  494. saveConfigFromJson(val);
  495. }
  496. void onRead(BLECharacteristic* c) { c->setValue(getConfigJson().c_str()); }
  497. };
  498. void setupBLE() {
  499. Serial.println("Starting BLE...");
  500. BLEDevice::init(BLE_DEVICE_NAME);
  501. pServer = BLEDevice::createServer();
  502. pServer->setCallbacks(new ServerCallbacks());
  503. BLEService* pService = pServer->createService(BLEUUID(SERVICE_UUID), 20);
  504. pModeCharacteristic = pService->createCharacteristic(MODE_CHAR_UUID,
  505. BLECharacteristic::PROPERTY_READ | BLECharacteristic::PROPERTY_WRITE | BLECharacteristic::PROPERTY_NOTIFY);
  506. pModeCharacteristic->setCallbacks(new ModeCharCallbacks());
  507. pModeCharacteristic->setValue(currentMode.c_str());
  508. pModeCharacteristic->addDescriptor(new BLE2902());
  509. pConfigCharacteristic = pService->createCharacteristic(CONFIG_CHAR_UUID,
  510. BLECharacteristic::PROPERTY_READ | BLECharacteristic::PROPERTY_WRITE);
  511. pConfigCharacteristic->setCallbacks(new ConfigCharCallbacks());
  512. pService->start();
  513. BLEAdvertising* pAdvertising = BLEDevice::getAdvertising();
  514. pAdvertising->addServiceUUID(SERVICE_UUID);
  515. pAdvertising->setScanResponse(true);
  516. pAdvertising->setMinPreferred(0x0c);
  517. pAdvertising->setMaxPreferred(0x18);
  518. BLEDevice::startAdvertising();
  519. Serial.println("BLE advertising.");
  520. }
  521. // =====================================================
  522. // MQTT
  523. // =====================================================
  524. void mqttCallback(char* topic, byte* payload, unsigned int length) {
  525. String message = "";
  526. for (unsigned int i = 0; i < length; i++) message += (char)payload[i];
  527. Serial.print("MQTT: "); Serial.print(topic); Serial.print(" -> "); Serial.println(message);
  528. if (String(topic) == cfgMqttTopicConfig) {
  529. saveConfigFromJson(message);
  530. return;
  531. }
  532. JsonDocument doc;
  533. if (deserializeJson(doc, message)) { setMode(message); return; }
  534. const char* code = doc["code"];
  535. if (code) {
  536. String c = String(code);
  537. if (c == "idle") setMode("idle");
  538. else if (c == "busy" || c == "running") setMode("busy");
  539. else if (c == "retry" || c == "permission") setMode("alarm");
  540. else if (c == "pending") setMode("yellow");
  541. else if (c == "reasoning") setMode("thinking");
  542. else if (c == "using_tool") setMode("ai");
  543. else if (c == "error") setMode("error");
  544. else setMode(c);
  545. }
  546. }
  547. bool connectWiFi() {
  548. Serial.print("Connecting WiFi");
  549. WiFi.mode(WIFI_STA);
  550. WiFi.begin(cfgWifiSsid.c_str(), cfgWifiPass.c_str());
  551. for (int retry = 1; retry <= 5; retry++) {
  552. Serial.printf("\nWiFi %d/5", retry);
  553. int attempts = 0;
  554. while (WiFi.status() != WL_CONNECTED && attempts < 60) {
  555. delay(5);
  556. updateInit();
  557. updateStatusLed();
  558. Serial.print(".");
  559. attempts++;
  560. }
  561. if (WiFi.status() == WL_CONNECTED) {
  562. Serial.printf("\nWiFi OK. IP: %s\n", WiFi.localIP().toString().c_str());
  563. digitalWrite(STATUS_PIN, LOW);
  564. return true;
  565. }
  566. Serial.println("\nFailed, retrying..."); delay(2000);
  567. }
  568. Serial.println("\nWiFi failed. Turning off WiFi.");
  569. WiFi.disconnect(true);
  570. WiFi.mode(WIFI_OFF);
  571. return false;
  572. }
  573. bool connectMQTT() {
  574. mqttClient.setServer(cfgMqttBroker.c_str(), cfgMqttPort);
  575. mqttClient.setCallback(mqttCallback);
  576. Serial.print("MQTT connecting");
  577. int attempts = 0;
  578. while (!mqttClient.connected()) {
  579. if (mqttClient.connect(cfgMqttClient.c_str(), cfgMqttUser.c_str(), cfgMqttPass.c_str())) {
  580. Serial.println("\nMQTT OK.");
  581. mqttClient.subscribe(cfgMqttTopic.c_str());
  582. mqttClient.subscribe(cfgMqttTopicConfig.c_str());
  583. allOff(); breathingGreen(3); publishStatus();
  584. return true;
  585. }
  586. Serial.print("."); delay(500);
  587. if (++attempts > 60) { Serial.println("\nMQTT failed!"); return false; }
  588. }
  589. return false;
  590. }
  591. void checkMQTTConnection() {
  592. if (useMQTT && !mqttClient.connected()) { Serial.println("MQTT reconnecting..."); connectMQTT(); }
  593. }
  594. // =====================================================
  595. // 初始化
  596. // =====================================================
  597. void setup() {
  598. Serial.begin(115200);
  599. delay(500);
  600. preferences.begin("ai-light", false);
  601. useMQTT = (preferences.getUInt("comm_mode", 1) != 0);
  602. loadConfig();
  603. ledcAttach(redPin, PWM_FREQ, PWM_RESOLUTION);
  604. ledcAttach(yellowPin, PWM_FREQ, PWM_RESOLUTION);
  605. ledcAttach(greenPin, PWM_FREQ, PWM_RESOLUTION);
  606. pinMode(STATUS_PIN, OUTPUT);
  607. pinMode(BUTTON_PIN, INPUT_PULLUP);
  608. digitalWrite(STATUS_PIN, HIGH);
  609. currentMode = "init";
  610. modeStart = millis();
  611. Serial.println();
  612. Serial.println("=== AI-Light ===");
  613. Serial.printf("Mode: %s\n", useMQTT ? "MQTT" : "BLE-only");
  614. Serial.printf("WiFi: %s\n", cfgWifiSsid.length() > 0 ? cfgWifiSsid.c_str() : "(not set)");
  615. Serial.printf("MQTT: %s\n", cfgMqttBroker.length() > 0 ? cfgMqttBroker.c_str() : "(not set)");
  616. Serial.printf("Pins: R=%d G=%d Y=%d\n", redPin, greenPin, yellowPin);
  617. if (useMQTT && isConfigComplete()) {
  618. wifiConnected = connectWiFi();
  619. if (wifiConnected) {
  620. connectMQTT();
  621. setMode("traffic");
  622. Serial.println("WiFi/MQTT mode. Long press BOOT (3s) to switch.");
  623. return;
  624. }
  625. Serial.println("WiFi failed. Entering BLE config mode.");
  626. }
  627. setupBLE();
  628. Serial.println("BLE advertising. Waiting for connection...");
  629. }
  630. // =====================================================
  631. // 主循环
  632. // =====================================================
  633. void loop() {
  634. updateStatusLed();
  635. checkBootButton();
  636. if (useMQTT && wifiConnected) {
  637. if (WiFi.status() != WL_CONNECTED) {
  638. Serial.println("WiFi lost, reconnecting...");
  639. wifiConnected = connectWiFi();
  640. if (!wifiConnected) {
  641. Serial.println("WiFi failed. BLE config mode active.");
  642. }
  643. }
  644. if (wifiConnected) {
  645. checkMQTTConnection();
  646. mqttClient.loop();
  647. }
  648. }
  649. autoTimeoutCheck();
  650. if (currentMode == "busy") updateBusy();
  651. else if (currentMode == "error") updateError();
  652. else if (currentMode == "thinking") updateThinking();
  653. else if (currentMode == "ai") updateAi();
  654. else if (currentMode == "success") updateSuccess();
  655. else if (currentMode == "traffic") updateTraffic();
  656. else if (currentMode == "alarm") updateAlarm();
  657. else if (currentMode == "init") updateInit();
  658. else if (currentMode == "off") allOff();
  659. delay(5);
  660. }