Fork of the espurna firmware for `mhsw` switches
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1237 lines
38 KiB

8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
7 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
  1. /*
  2. WEBSERVER MODULE
  3. Copyright (C) 2016-2017 by Xose Pérez <xose dot perez at gmail dot com>
  4. */
  5. #if WEB_SUPPORT
  6. #include <ESPAsyncTCP.h>
  7. #include <ESPAsyncWebServer.h>
  8. #include <Hash.h>
  9. #include <FS.h>
  10. #include <AsyncJson.h>
  11. #include <ArduinoJson.h>
  12. #include <Ticker.h>
  13. #include <vector>
  14. #include "web.h"
  15. #if WEB_EMBEDDED
  16. #include "static/index.html.gz.h"
  17. #endif // WEB_EMBEDDED
  18. #if ASYNC_TCP_SSL_ENABLED & WEB_SSL_ENABLED
  19. #include "static/server.cer.h"
  20. #include "static/server.key.h"
  21. #endif // ASYNC_TCP_SSL_ENABLED & WEB_SSL_ENABLED
  22. // -----------------------------------------------------------------------------
  23. AsyncWebServer * _server;
  24. char _last_modified[50];
  25. Ticker _web_defer;
  26. // -----------------------------------------------------------------------------
  27. AsyncWebSocket _ws("/ws");
  28. typedef struct {
  29. IPAddress ip;
  30. unsigned long timestamp = 0;
  31. } ws_ticket_t;
  32. ws_ticket_t _ticket[WS_BUFFER_SIZE];
  33. // -----------------------------------------------------------------------------
  34. typedef struct {
  35. char * url;
  36. char * key;
  37. apiGetCallbackFunction getFn = NULL;
  38. apiPutCallbackFunction putFn = NULL;
  39. } web_api_t;
  40. std::vector<web_api_t> _apis;
  41. // -----------------------------------------------------------------------------
  42. // WEBSOCKETS
  43. // -----------------------------------------------------------------------------
  44. void _wsMQTTCallback(unsigned int type, const char * topic, const char * payload) {
  45. if (type == MQTT_CONNECT_EVENT) {
  46. wsSend_P(PSTR("{\"mqttStatus\": true}"));
  47. }
  48. if (type == MQTT_DISCONNECT_EVENT) {
  49. wsSend_P(PSTR("{\"mqttStatus\": false}"));
  50. }
  51. }
  52. void _wsParse(AsyncWebSocketClient *client, uint8_t * payload, size_t length) {
  53. // Get client ID
  54. uint32_t client_id = client->id();
  55. // Parse JSON input
  56. DynamicJsonBuffer jsonBuffer;
  57. JsonObject& root = jsonBuffer.parseObject((char *) payload);
  58. if (!root.success()) {
  59. DEBUG_MSG_P(PSTR("[WEBSOCKET] Error parsing data\n"));
  60. wsSend_P(client_id, PSTR("{\"message\": 3}"));
  61. return;
  62. }
  63. // Check actions
  64. if (root.containsKey("action")) {
  65. String action = root["action"];
  66. DEBUG_MSG_P(PSTR("[WEBSOCKET] Requested action: %s\n"), action.c_str());
  67. if (action.equals("reset")) {
  68. customReset(CUSTOM_RESET_WEB);
  69. ESP.restart();
  70. }
  71. #ifdef ITEAD_SONOFF_RFBRIDGE
  72. if (action.equals("rfblearn") && root.containsKey("data")) {
  73. JsonObject& data = root["data"];
  74. rfbLearn(data["id"], data["status"]);
  75. }
  76. if (action.equals("rfbforget") && root.containsKey("data")) {
  77. JsonObject& data = root["data"];
  78. rfbForget(data["id"], data["status"]);
  79. }
  80. if (action.equals("rfbsend") && root.containsKey("data")) {
  81. JsonObject& data = root["data"];
  82. rfbStore(data["id"], data["status"], data["data"].as<const char*>());
  83. }
  84. #endif
  85. if (action.equals("restore") && root.containsKey("data")) {
  86. JsonObject& data = root["data"];
  87. if (!data.containsKey("app") || (data["app"] != APP_NAME)) {
  88. wsSend_P(client_id, PSTR("{\"message\": 4}"));
  89. return;
  90. }
  91. for (unsigned int i = EEPROM_DATA_END; i < SPI_FLASH_SEC_SIZE; i++) {
  92. EEPROM.write(i, 0xFF);
  93. }
  94. for (auto element : data) {
  95. if (strcmp(element.key, "app") == 0) continue;
  96. if (strcmp(element.key, "version") == 0) continue;
  97. setSetting(element.key, element.value.as<char*>());
  98. }
  99. saveSettings();
  100. wsSend_P(client_id, PSTR("{\"message\": 5}"));
  101. }
  102. if (action.equals("reconnect")) {
  103. // Let the HTTP request return and disconnect after 100ms
  104. _web_defer.once_ms(100, wifiDisconnect);
  105. }
  106. if (action.equals("relay") && root.containsKey("data")) {
  107. JsonObject& data = root["data"];
  108. if (data.containsKey("status")) {
  109. unsigned char value = relayParsePayload(data["status"]);
  110. if (value == 3) {
  111. relayWS();
  112. } else if (value < 3) {
  113. unsigned int relayID = 0;
  114. if (data.containsKey("id")) {
  115. String value = data["id"];
  116. relayID = value.toInt();
  117. }
  118. // Action to perform
  119. if (value == 0) {
  120. relayStatus(relayID, false);
  121. } else if (value == 1) {
  122. relayStatus(relayID, true);
  123. } else if (value == 2) {
  124. relayToggle(relayID);
  125. }
  126. }
  127. }
  128. }
  129. #if LIGHT_PROVIDER != LIGHT_PROVIDER_NONE
  130. if (lightHasColor()) {
  131. if (action.equals("rgb") && root.containsKey("data")) {
  132. lightColor((const char *) root["data"], true);
  133. lightUpdate(true, true);
  134. }
  135. if (action.equals("brightness") && root.containsKey("data")) {
  136. lightBrightness(root["data"]);
  137. lightUpdate(true, true);
  138. }
  139. if (action.equals("hsv") && root.containsKey("data")) {
  140. lightColor((const char *) root["data"], false);
  141. lightUpdate(true, true);
  142. }
  143. }
  144. if (action.equals("channel") && root.containsKey("data")) {
  145. JsonObject& data = root["data"];
  146. if (data.containsKey("id") && data.containsKey("value")) {
  147. lightChannel(data["id"], data["value"]);
  148. lightUpdate(true, true);
  149. }
  150. }
  151. #ifdef LIGHT_PROVIDER_EXPERIMENTAL_RGB_ONLY_HSV_IR
  152. if (action.equals("anim_mode") && root.containsKey("data")) {
  153. lightAnimMode(root["data"]);
  154. lightUpdate(true, true);
  155. }
  156. if (action.equals("anim_speed") && root.containsKey("data")) {
  157. lightAnimSpeed(root["data"]);
  158. lightUpdate(true, true);
  159. }
  160. #endif //LIGHT_PROVIDER_EXPERIMENTAL_RGB_ONLY_HSV_IR
  161. #endif //LIGHT_PROVIDER != LIGHT_PROVIDER_NONE
  162. };
  163. // Check config
  164. if (root.containsKey("config") && root["config"].is<JsonArray&>()) {
  165. JsonArray& config = root["config"];
  166. DEBUG_MSG_P(PSTR("[WEBSOCKET] Parsing configuration data\n"));
  167. unsigned char webMode = WEB_MODE_NORMAL;
  168. bool save = false;
  169. bool changed = false;
  170. bool changedMQTT = false;
  171. bool changedNTP = false;
  172. unsigned int network = 0;
  173. unsigned int dczRelayIdx = 0;
  174. String adminPass;
  175. for (unsigned int i=0; i<config.size(); i++) {
  176. String key = config[i]["name"];
  177. String value = config[i]["value"];
  178. // Skip firmware filename
  179. if (key.equals("filename")) continue;
  180. #if POWER_PROVIDER != POWER_PROVIDER_NONE
  181. if (key == "pwrExpectedP") {
  182. powerCalibrate(POWER_MAGNITUDE_ACTIVE, value.toFloat());
  183. changed = true;
  184. continue;
  185. }
  186. if (key == "pwrExpectedV") {
  187. powerCalibrate(POWER_MAGNITUDE_VOLTAGE, value.toFloat());
  188. changed = true;
  189. continue;
  190. }
  191. if (key == "pwrExpectedC") {
  192. powerCalibrate(POWER_MAGNITUDE_CURRENT, value.toFloat());
  193. changed = true;
  194. continue;
  195. }
  196. if (key == "pwrExpectedF") {
  197. powerCalibrate(POWER_MAGNITUDE_POWER_FACTOR, value.toFloat());
  198. changed = true;
  199. continue;
  200. }
  201. if (key == "pwrResetCalibration") {
  202. if (value.toInt() == 1) {
  203. powerResetCalibration();
  204. changed = true;
  205. }
  206. continue;
  207. }
  208. #endif
  209. #if DOMOTICZ_SUPPORT
  210. if (key == "dczRelayIdx") {
  211. if (dczRelayIdx >= relayCount()) continue;
  212. key = key + String(dczRelayIdx);
  213. ++dczRelayIdx;
  214. }
  215. #else
  216. if (key.startsWith("dcz")) continue;
  217. #endif
  218. // Web portions
  219. if (key == "webPort") {
  220. if ((value.toInt() == 0) || (value.toInt() == 80)) {
  221. save = changed = true;
  222. delSetting(key);
  223. continue;
  224. }
  225. }
  226. if (key == "webMode") {
  227. webMode = value.toInt();
  228. continue;
  229. }
  230. // Check password
  231. if (key == "adminPass1") {
  232. adminPass = value;
  233. continue;
  234. }
  235. if (key == "adminPass2") {
  236. if (!value.equals(adminPass)) {
  237. wsSend_P(client_id, PSTR("{\"message\": 7}"));
  238. return;
  239. }
  240. if (value.length() == 0) continue;
  241. wsSend_P(client_id, PSTR("{\"action\": \"reload\"}"));
  242. key = String("adminPass");
  243. }
  244. if (key == "ssid") {
  245. key = key + String(network);
  246. }
  247. if (key == "pass") {
  248. key = key + String(network);
  249. }
  250. if (key == "ip") {
  251. key = key + String(network);
  252. }
  253. if (key == "gw") {
  254. key = key + String(network);
  255. }
  256. if (key == "mask") {
  257. key = key + String(network);
  258. }
  259. if (key == "dns") {
  260. key = key + String(network);
  261. ++network;
  262. }
  263. if (value != getSetting(key)) {
  264. //DEBUG_MSG_P(PSTR("[WEBSOCKET] Storing %s = %s\n", key.c_str(), value.c_str()));
  265. setSetting(key, value);
  266. save = changed = true;
  267. if (key.startsWith("mqtt")) changedMQTT = true;
  268. #if NTP_SUPPORT
  269. if (key.startsWith("ntp")) changedNTP = true;
  270. #endif
  271. }
  272. }
  273. if (webMode == WEB_MODE_NORMAL) {
  274. // Clean wifi networks
  275. int i = 0;
  276. while (i < network) {
  277. if (!hasSetting("ssid", i)) {
  278. delSetting("ssid", i);
  279. break;
  280. }
  281. if (!hasSetting("pass", i)) delSetting("pass", i);
  282. if (!hasSetting("ip", i)) delSetting("ip", i);
  283. if (!hasSetting("gw", i)) delSetting("gw", i);
  284. if (!hasSetting("mask", i)) delSetting("mask", i);
  285. if (!hasSetting("dns", i)) delSetting("dns", i);
  286. ++i;
  287. }
  288. while (i < WIFI_MAX_NETWORKS) {
  289. if (hasSetting("ssid", i)) {
  290. save = changed = true;
  291. }
  292. delSetting("ssid", i);
  293. delSetting("pass", i);
  294. delSetting("ip", i);
  295. delSetting("gw", i);
  296. delSetting("mask", i);
  297. delSetting("dns", i);
  298. ++i;
  299. }
  300. }
  301. // Save settings
  302. if (save) {
  303. saveSettings();
  304. wifiConfigure();
  305. otaConfigure();
  306. if (changedMQTT) {
  307. mqttConfigure();
  308. mqttDisconnect();
  309. }
  310. #if ALEXA_SUPPORT
  311. alexaConfigure();
  312. #endif
  313. #if INFLUXDB_SUPPORT
  314. influxDBConfigure();
  315. #endif
  316. #if DOMOTICZ_SUPPORT
  317. domoticzConfigure();
  318. #endif
  319. #if NOFUSS_SUPPORT
  320. nofussConfigure();
  321. #endif
  322. #if RF_SUPPORT
  323. rfBuildCodes();
  324. #endif
  325. #if POWER_PROVIDER != POWER_PROVIDER_NONE
  326. powerConfigure();
  327. #endif
  328. #if LIGHT_PROVIDER != LIGHT_PROVIDER_NONE
  329. #if LIGHT_SAVE_ENABLED == 0
  330. lightSave();
  331. #endif
  332. #endif
  333. #if NTP_SUPPORT
  334. if (changedNTP) ntpConfigure();
  335. #endif
  336. #if HOMEASSISTANT_SUPPORT
  337. haConfigure();
  338. #endif
  339. }
  340. if (changed) {
  341. wsSend_P(client_id, PSTR("{\"message\": 8}"));
  342. } else {
  343. wsSend_P(client_id, PSTR("{\"message\": 9}"));
  344. }
  345. }
  346. }
  347. void _wsStart(uint32_t client_id) {
  348. char chipid[7];
  349. snprintf_P(chipid, sizeof(chipid), PSTR("%06X"), ESP.getChipId());
  350. DynamicJsonBuffer jsonBuffer;
  351. JsonObject& root = jsonBuffer.createObject();
  352. bool changePassword = false;
  353. #if WEB_FORCE_PASS_CHANGE
  354. String adminPass = getSetting("adminPass", ADMIN_PASS);
  355. if (adminPass.equals(ADMIN_PASS)) changePassword = true;
  356. #endif
  357. if (changePassword) {
  358. root["webMode"] = WEB_MODE_PASSWORD;
  359. } else {
  360. root["webMode"] = WEB_MODE_NORMAL;
  361. root["app_name"] = APP_NAME;
  362. root["app_version"] = APP_VERSION;
  363. root["app_build"] = buildTime();
  364. root["manufacturer"] = MANUFACTURER;
  365. root["chipid"] = chipid;
  366. root["mac"] = WiFi.macAddress();
  367. root["device"] = DEVICE;
  368. root["hostname"] = getSetting("hostname");
  369. root["network"] = getNetwork();
  370. root["deviceip"] = getIP();
  371. root["time"] = ntpDateTime();
  372. root["uptime"] = getUptime();
  373. root["heap"] = ESP.getFreeHeap();
  374. root["sketch_size"] = ESP.getSketchSize();
  375. root["free_size"] = ESP.getFreeSketchSpace();
  376. #if NTP_SUPPORT
  377. root["ntpVisible"] = 1;
  378. root["ntpStatus"] = ntpConnected();
  379. root["ntpServer1"] = getSetting("ntpServer1", NTP_SERVER);
  380. root["ntpServer2"] = getSetting("ntpServer2");
  381. root["ntpServer3"] = getSetting("ntpServer3");
  382. root["ntpOffset"] = getSetting("ntpOffset", NTP_TIME_OFFSET).toInt();
  383. root["ntpDST"] = getSetting("ntpDST", NTP_DAY_LIGHT).toInt() == 1;
  384. #endif
  385. root["mqttStatus"] = mqttConnected();
  386. root["mqttEnabled"] = mqttEnabled();
  387. root["mqttServer"] = getSetting("mqttServer", MQTT_SERVER);
  388. root["mqttPort"] = getSetting("mqttPort", MQTT_PORT);
  389. root["mqttUser"] = getSetting("mqttUser");
  390. root["mqttPassword"] = getSetting("mqttPassword");
  391. #if ASYNC_TCP_SSL_ENABLED
  392. root["mqttsslVisible"] = 1;
  393. root["mqttUseSSL"] = getSetting("mqttUseSSL", 0).toInt() == 1;
  394. root["mqttFP"] = getSetting("mqttFP");
  395. #endif
  396. root["mqttTopic"] = getSetting("mqttTopic", MQTT_TOPIC);
  397. root["mqttUseJson"] = getSetting("mqttUseJson", MQTT_USE_JSON).toInt() == 1;
  398. JsonArray& relay = root.createNestedArray("relayStatus");
  399. for (unsigned char relayID=0; relayID<relayCount(); relayID++) {
  400. relay.add(relayStatus(relayID));
  401. }
  402. #if LIGHT_PROVIDER != LIGHT_PROVIDER_NONE
  403. root["colorVisible"] = 1;
  404. root["useColor"] = getSetting("useColor", LIGHT_USE_COLOR).toInt() == 1;
  405. root["useWhite"] = getSetting("useWhite", LIGHT_USE_WHITE).toInt() == 1;
  406. root["useGamma"] = getSetting("useGamma", LIGHT_USE_GAMMA).toInt() == 1;
  407. root["useCSS"] = getSetting("useCSS", LIGHT_USE_CSS).toInt() == 1;
  408. bool useRGB = getSetting("useRGB", LIGHT_USE_RGB).toInt() == 1;
  409. root["useRGB"] = useRGB;
  410. if (lightHasColor()) {
  411. if (useRGB) {
  412. root["rgb"] = lightColor(true);
  413. root["brightness"] = lightBrightness();
  414. } else {
  415. root["hsv"] = lightColor(false);
  416. }
  417. #ifdef LIGHT_PROVIDER_EXPERIMENTAL_RGB_ONLY_HSV_IR
  418. root["anim_mode"] = lightAnimMode();
  419. root["anim_speed"] = lightAnimSpeed();
  420. #endif // LIGHT_PROVIDER_EXPERIMENTAL_RGB_ONLY_HSV_IR
  421. }
  422. JsonArray& channels = root.createNestedArray("channels");
  423. for (unsigned char id=0; id < lightChannels(); id++) {
  424. channels.add(lightChannel(id));
  425. }
  426. #endif
  427. root["relayMode"] = getSetting("relayMode", RELAY_MODE);
  428. root["relayPulseMode"] = getSetting("relayPulseMode", RELAY_PULSE_MODE);
  429. root["relayPulseTime"] = getSetting("relayPulseTime", RELAY_PULSE_TIME).toFloat();
  430. if (relayCount() > 1) {
  431. root["multirelayVisible"] = 1;
  432. root["relaySync"] = getSetting("relaySync", RELAY_SYNC);
  433. }
  434. root["btnDelay"] = getSetting("btnDelay", BUTTON_DBLCLICK_DELAY).toInt();
  435. root["webPort"] = getSetting("webPort", WEB_PORT).toInt();
  436. root["apiEnabled"] = getSetting("apiEnabled", API_ENABLED).toInt() == 1;
  437. root["apiKey"] = getSetting("apiKey");
  438. root["apiRealTime"] = getSetting("apiRealTime", API_REAL_TIME_VALUES).toInt() == 1;
  439. root["tmpUnits"] = getSetting("tmpUnits", TMP_UNITS).toInt();
  440. #if HOMEASSISTANT_SUPPORT
  441. root["haVisible"] = 1;
  442. root["haPrefix"] = getSetting("haPrefix", HOMEASSISTANT_PREFIX);
  443. #endif // HOMEASSISTANT_SUPPORT
  444. #if DOMOTICZ_SUPPORT
  445. root["dczVisible"] = 1;
  446. root["dczEnabled"] = getSetting("dczEnabled", DOMOTICZ_ENABLED).toInt() == 1;
  447. root["dczTopicIn"] = getSetting("dczTopicIn", DOMOTICZ_IN_TOPIC);
  448. root["dczTopicOut"] = getSetting("dczTopicOut", DOMOTICZ_OUT_TOPIC);
  449. JsonArray& dczRelayIdx = root.createNestedArray("dczRelayIdx");
  450. for (byte i=0; i<relayCount(); i++) {
  451. dczRelayIdx.add(domoticzIdx(i));
  452. }
  453. #if DHT_SUPPORT
  454. root["dczTmpIdx"] = getSetting("dczTmpIdx").toInt();
  455. root["dczHumIdx"] = getSetting("dczHumIdx").toInt();
  456. #endif
  457. #if DS18B20_SUPPORT
  458. root["dczTmpIdx"] = getSetting("dczTmpIdx").toInt();
  459. #endif
  460. #if ANALOG_SUPPORT
  461. root["dczAnaIdx"] = getSetting("dczAnaIdx").toInt();
  462. #endif
  463. #if POWER_PROVIDER != POWER_PROVIDER_NONE
  464. root["dczPowIdx"] = getSetting("dczPowIdx").toInt();
  465. root["dczEnergyIdx"] = getSetting("dczEnergyIdx").toInt();
  466. root["dczCurrentIdx"] = getSetting("dczCurrentIdx").toInt();
  467. #if POWER_HAS_ACTIVE
  468. root["dczVoltIdx"] = getSetting("dczVoltIdx").toInt();
  469. #endif
  470. #endif
  471. #endif
  472. #if INFLUXDB_SUPPORT
  473. root["idbVisible"] = 1;
  474. root["idbHost"] = getSetting("idbHost");
  475. root["idbPort"] = getSetting("idbPort", INFLUXDB_PORT).toInt();
  476. root["idbDatabase"] = getSetting("idbDatabase");
  477. root["idbUsername"] = getSetting("idbUsername");
  478. root["idbPassword"] = getSetting("idbPassword");
  479. #endif
  480. #if ALEXA_SUPPORT
  481. root["alexaVisible"] = 1;
  482. root["alexaEnabled"] = getSetting("alexaEnabled", ALEXA_ENABLED).toInt() == 1;
  483. #endif
  484. #if DS18B20_SUPPORT
  485. root["dsVisible"] = 1;
  486. root["dsTmp"] = getDSTemperatureStr();
  487. #endif
  488. #if DHT_SUPPORT
  489. root["dhtVisible"] = 1;
  490. root["dhtTmp"] = getDHTTemperature();
  491. root["dhtHum"] = getDHTHumidity();
  492. #endif
  493. #if RF_SUPPORT
  494. root["rfVisible"] = 1;
  495. root["rfChannel"] = getSetting("rfChannel", RF_CHANNEL);
  496. root["rfDevice"] = getSetting("rfDevice", RF_DEVICE);
  497. #endif
  498. #if ANALOG_SUPPORT
  499. root["analogVisible"] = 1;
  500. root["analogValue"] = getAnalog();
  501. #endif
  502. #if COUNTER_SUPPORT
  503. root["counterVisible"] = 1;
  504. root["counterValue"] = getCounter();
  505. #endif
  506. #if POWER_PROVIDER != POWER_PROVIDER_NONE
  507. root["pwrVisible"] = 1;
  508. root["pwrCurrent"] = getCurrent();
  509. root["pwrVoltage"] = getVoltage();
  510. root["pwrApparent"] = getApparentPower();
  511. root["pwrEnergy"] = getPowerEnergy();
  512. root["pwrReadEvery"] = powerReadInterval();
  513. root["pwrReportEvery"] = powerReportInterval();
  514. #if POWER_HAS_ACTIVE
  515. root["pwrActive"] = getActivePower();
  516. root["pwrReactive"] = getReactivePower();
  517. root["pwrFactor"] = int(100 * getPowerFactor());
  518. #endif
  519. #if (POWER_PROVIDER == POWER_PROVIDER_EMON_ANALOG) || (POWER_PROVIDER == POWER_PROVIDER_EMON_ADC121)
  520. root["emonVisible"] = 1;
  521. #endif
  522. #if POWER_PROVIDER == POWER_PROVIDER_HLW8012
  523. root["hlwVisible"] = 1;
  524. #endif
  525. #if POWER_PROVIDER == POWER_PROVIDER_V9261F
  526. root["v9261fVisible"] = 1;
  527. #endif
  528. #if POWER_PROVIDER == POWER_PROVIDER_ECH1560
  529. root["ech1560fVisible"] = 1;
  530. #endif
  531. #endif
  532. #if NOFUSS_SUPPORT
  533. root["nofussVisible"] = 1;
  534. root["nofussEnabled"] = getSetting("nofussEnabled", NOFUSS_ENABLED).toInt() == 1;
  535. root["nofussServer"] = getSetting("nofussServer", NOFUSS_SERVER);
  536. #endif
  537. #ifdef ITEAD_SONOFF_RFBRIDGE
  538. root["rfbVisible"] = 1;
  539. root["rfbCount"] = relayCount();
  540. JsonArray& rfb = root.createNestedArray("rfb");
  541. for (byte id=0; id<relayCount(); id++) {
  542. for (byte status=0; status<2; status++) {
  543. JsonObject& node = rfb.createNestedObject();
  544. node["id"] = id;
  545. node["status"] = status;
  546. node["data"] = rfbRetrieve(id, status == 1);
  547. }
  548. }
  549. #endif
  550. #if TELNET_SUPPORT
  551. root["telnetVisible"] = 1;
  552. root["telnetSTA"] = getSetting("telnetSTA", TELNET_STA).toInt() == 1;
  553. #endif
  554. root["maxNetworks"] = WIFI_MAX_NETWORKS;
  555. JsonArray& wifi = root.createNestedArray("wifi");
  556. for (byte i=0; i<WIFI_MAX_NETWORKS; i++) {
  557. if (getSetting("ssid" + String(i)).length() == 0) break;
  558. JsonObject& network = wifi.createNestedObject();
  559. network["ssid"] = getSetting("ssid" + String(i));
  560. network["pass"] = getSetting("pass" + String(i));
  561. network["ip"] = getSetting("ip" + String(i));
  562. network["gw"] = getSetting("gw" + String(i));
  563. network["mask"] = getSetting("mask" + String(i));
  564. network["dns"] = getSetting("dns" + String(i));
  565. }
  566. }
  567. String output;
  568. root.printTo(output);
  569. wsSend(client_id, (char *) output.c_str());
  570. }
  571. bool _wsAuth(AsyncWebSocketClient * client) {
  572. IPAddress ip = client->remoteIP();
  573. unsigned long now = millis();
  574. unsigned short index = 0;
  575. for (index = 0; index < WS_BUFFER_SIZE; index++) {
  576. if ((_ticket[index].ip == ip) && (now - _ticket[index].timestamp < WS_TIMEOUT)) break;
  577. }
  578. if (index == WS_BUFFER_SIZE) {
  579. DEBUG_MSG_P(PSTR("[WEBSOCKET] Validation check failed\n"));
  580. wsSend_P(client->id(), PSTR("{\"message\": 10}"));
  581. return false;
  582. }
  583. return true;
  584. }
  585. void _wsEvent(AsyncWebSocket * server, AsyncWebSocketClient * client, AwsEventType type, void * arg, uint8_t *data, size_t len){
  586. if (type == WS_EVT_CONNECT) {
  587. // Authorize
  588. #ifndef NOWSAUTH
  589. if (!_wsAuth(client)) return;
  590. #endif
  591. IPAddress ip = client->remoteIP();
  592. DEBUG_MSG_P(PSTR("[WEBSOCKET] #%u connected, ip: %d.%d.%d.%d, url: %s\n"), client->id(), ip[0], ip[1], ip[2], ip[3], server->url());
  593. _wsStart(client->id());
  594. client->_tempObject = new WebSocketIncommingBuffer(&_wsParse, true);
  595. wifiReconnectCheck();
  596. } else if(type == WS_EVT_DISCONNECT) {
  597. DEBUG_MSG_P(PSTR("[WEBSOCKET] #%u disconnected\n"), client->id());
  598. if (client->_tempObject) {
  599. delete (WebSocketIncommingBuffer *) client->_tempObject;
  600. }
  601. wifiReconnectCheck();
  602. } else if(type == WS_EVT_ERROR) {
  603. DEBUG_MSG_P(PSTR("[WEBSOCKET] #%u error(%u): %s\n"), client->id(), *((uint16_t*)arg), (char*)data);
  604. } else if(type == WS_EVT_PONG) {
  605. DEBUG_MSG_P(PSTR("[WEBSOCKET] #%u pong(%u): %s\n"), client->id(), len, len ? (char*) data : "");
  606. } else if(type == WS_EVT_DATA) {
  607. WebSocketIncommingBuffer *buffer = (WebSocketIncommingBuffer *)client->_tempObject;
  608. AwsFrameInfo * info = (AwsFrameInfo*)arg;
  609. buffer->data_event(client, info, data, len);
  610. }
  611. }
  612. // -----------------------------------------------------------------------------
  613. bool wsConnected() {
  614. return (_ws.count() > 0);
  615. }
  616. void wsSend(const char * payload) {
  617. if (_ws.count() > 0) {
  618. _ws.textAll(payload);
  619. }
  620. }
  621. void wsSend_P(PGM_P payload) {
  622. if (_ws.count() > 0) {
  623. char buffer[strlen_P(payload)];
  624. strcpy_P(buffer, payload);
  625. _ws.textAll(buffer);
  626. }
  627. }
  628. void wsSend(uint32_t client_id, const char * payload) {
  629. _ws.text(client_id, payload);
  630. }
  631. void wsSend_P(uint32_t client_id, PGM_P payload) {
  632. char buffer[strlen_P(payload)];
  633. strcpy_P(buffer, payload);
  634. _ws.text(client_id, buffer);
  635. }
  636. void wsSetup() {
  637. _ws.onEvent(_wsEvent);
  638. mqttRegister(_wsMQTTCallback);
  639. _server->addHandler(&_ws);
  640. _server->on("/auth", HTTP_GET, _onAuth);
  641. }
  642. // -----------------------------------------------------------------------------
  643. // API
  644. // -----------------------------------------------------------------------------
  645. bool _authAPI(AsyncWebServerRequest *request) {
  646. if (getSetting("apiEnabled", API_ENABLED).toInt() == 0) {
  647. DEBUG_MSG_P(PSTR("[WEBSERVER] HTTP API is not enabled\n"));
  648. request->send(403);
  649. return false;
  650. }
  651. if (!request->hasParam("apikey", (request->method() == HTTP_PUT))) {
  652. DEBUG_MSG_P(PSTR("[WEBSERVER] Missing apikey parameter\n"));
  653. request->send(403);
  654. return false;
  655. }
  656. AsyncWebParameter* p = request->getParam("apikey", (request->method() == HTTP_PUT));
  657. if (!p->value().equals(getSetting("apiKey"))) {
  658. DEBUG_MSG_P(PSTR("[WEBSERVER] Wrong apikey parameter\n"));
  659. request->send(403);
  660. return false;
  661. }
  662. return true;
  663. }
  664. bool _asJson(AsyncWebServerRequest *request) {
  665. bool asJson = false;
  666. if (request->hasHeader("Accept")) {
  667. AsyncWebHeader* h = request->getHeader("Accept");
  668. asJson = h->value().equals("application/json");
  669. }
  670. return asJson;
  671. }
  672. ArRequestHandlerFunction _bindAPI(unsigned int apiID) {
  673. return [apiID](AsyncWebServerRequest *request) {
  674. _webLog(request);
  675. if (!_authAPI(request)) return;
  676. web_api_t api = _apis[apiID];
  677. // Check if its a PUT
  678. if (api.putFn != NULL) {
  679. if (request->hasParam("value", request->method() == HTTP_PUT)) {
  680. AsyncWebParameter* p = request->getParam("value", request->method() == HTTP_PUT);
  681. (api.putFn)((p->value()).c_str());
  682. }
  683. }
  684. // Get response from callback
  685. char value[API_BUFFER_SIZE];
  686. (api.getFn)(value, API_BUFFER_SIZE);
  687. // The response will be a 404 NOT FOUND if the resource is not available
  688. if (!value) {
  689. DEBUG_MSG_P(PSTR("[API] Sending 404 response\n"));
  690. request->send(404);
  691. return;
  692. }
  693. DEBUG_MSG_P(PSTR("[API] Sending response '%s'\n"), value);
  694. // Format response according to the Accept header
  695. if (_asJson(request)) {
  696. char buffer[64];
  697. snprintf_P(buffer, sizeof(buffer), PSTR("{ \"%s\": %s }"), api.key, value);
  698. request->send(200, "application/json", buffer);
  699. } else {
  700. request->send(200, "text/plain", value);
  701. }
  702. };
  703. }
  704. void _onAPIs(AsyncWebServerRequest *request) {
  705. _webLog(request);
  706. if (!_authAPI(request)) return;
  707. bool asJson = _asJson(request);
  708. String output;
  709. if (asJson) {
  710. DynamicJsonBuffer jsonBuffer;
  711. JsonObject& root = jsonBuffer.createObject();
  712. for (unsigned int i=0; i < _apis.size(); i++) {
  713. root[_apis[i].key] = _apis[i].url;
  714. }
  715. root.printTo(output);
  716. request->send(200, "application/json", output);
  717. } else {
  718. for (unsigned int i=0; i < _apis.size(); i++) {
  719. output += _apis[i].key + String(" -> ") + _apis[i].url + String("\n");
  720. }
  721. request->send(200, "text/plain", output);
  722. }
  723. }
  724. void _onRPC(AsyncWebServerRequest *request) {
  725. _webLog(request);
  726. if (!_authAPI(request)) return;
  727. //bool asJson = _asJson(request);
  728. int response = 404;
  729. if (request->hasParam("action")) {
  730. AsyncWebParameter* p = request->getParam("action");
  731. String action = p->value();
  732. DEBUG_MSG_P(PSTR("[RPC] Action: %s\n"), action.c_str());
  733. if (action.equals("reset")) {
  734. response = 200;
  735. _web_defer.once_ms(100, []() {
  736. customReset(CUSTOM_RESET_RPC);
  737. ESP.restart();
  738. });
  739. }
  740. }
  741. request->send(response);
  742. }
  743. // -----------------------------------------------------------------------------
  744. void apiRegister(const char * url, const char * key, apiGetCallbackFunction getFn, apiPutCallbackFunction putFn) {
  745. // Store it
  746. web_api_t api;
  747. char buffer[40];
  748. snprintf_P(buffer, sizeof(buffer), PSTR("/api/%s"), url);
  749. api.url = strdup(buffer);
  750. api.key = strdup(key);
  751. api.getFn = getFn;
  752. api.putFn = putFn;
  753. _apis.push_back(api);
  754. // Bind call
  755. unsigned int methods = HTTP_GET;
  756. if (putFn != NULL) methods += HTTP_PUT;
  757. _server->on(buffer, methods, _bindAPI(_apis.size() - 1));
  758. }
  759. void apiSetup() {
  760. _server->on("/apis", HTTP_GET, _onAPIs);
  761. _server->on("/rpc", HTTP_GET, _onRPC);
  762. }
  763. // -----------------------------------------------------------------------------
  764. // WEBSERVER
  765. // -----------------------------------------------------------------------------
  766. void _webLog(AsyncWebServerRequest *request) {
  767. DEBUG_MSG_P(PSTR("[WEBSERVER] Request: %s %s\n"), request->methodToString(), request->url().c_str());
  768. }
  769. bool _authenticate(AsyncWebServerRequest *request) {
  770. String password = getSetting("adminPass", ADMIN_PASS);
  771. char httpPassword[password.length() + 1];
  772. password.toCharArray(httpPassword, password.length() + 1);
  773. return request->authenticate(WEB_USERNAME, httpPassword);
  774. }
  775. void _onAuth(AsyncWebServerRequest *request) {
  776. _webLog(request);
  777. if (!_authenticate(request)) return request->requestAuthentication();
  778. IPAddress ip = request->client()->remoteIP();
  779. unsigned long now = millis();
  780. unsigned short index;
  781. for (index = 0; index < WS_BUFFER_SIZE; index++) {
  782. if (_ticket[index].ip == ip) break;
  783. if (_ticket[index].timestamp == 0) break;
  784. if (now - _ticket[index].timestamp > WS_TIMEOUT) break;
  785. }
  786. if (index == WS_BUFFER_SIZE) {
  787. request->send(429);
  788. } else {
  789. _ticket[index].ip = ip;
  790. _ticket[index].timestamp = now;
  791. request->send(204);
  792. }
  793. }
  794. void _onGetConfig(AsyncWebServerRequest *request) {
  795. _webLog(request);
  796. if (!_authenticate(request)) return request->requestAuthentication();
  797. AsyncJsonResponse * response = new AsyncJsonResponse();
  798. JsonObject& root = response->getRoot();
  799. root["app"] = APP_NAME;
  800. root["version"] = APP_VERSION;
  801. unsigned int size = settingsKeyCount();
  802. for (unsigned int i=0; i<size; i++) {
  803. String key = settingsKeyName(i);
  804. String value = getSetting(key);
  805. root[key] = value;
  806. }
  807. char buffer[100];
  808. snprintf_P(buffer, sizeof(buffer), PSTR("attachment; filename=\"%s-backup.json\""), (char *) getSetting("hostname").c_str());
  809. response->addHeader("Content-Disposition", buffer);
  810. response->setLength();
  811. request->send(response);
  812. }
  813. #if WEB_EMBEDDED
  814. void _onHome(AsyncWebServerRequest *request) {
  815. _webLog(request);
  816. if (request->header("If-Modified-Since").equals(_last_modified)) {
  817. request->send(304);
  818. } else {
  819. #if ASYNC_TCP_SSL_ENABLED
  820. // Chunked response, we calculate the chunks based on free heap (in multiples of 32)
  821. // This is necessary when a TLS connection is open since it sucks too much memory
  822. DEBUG_MSG_P(PSTR("[MAIN] Free heap: %d bytes\n"), ESP.getFreeHeap());
  823. size_t max = (ESP.getFreeHeap() / 3) & 0xFFE0;
  824. AsyncWebServerResponse *response = request->beginChunkedResponse("text/html", [max](uint8_t *buffer, size_t maxLen, size_t index) -> size_t {
  825. // Get the chunk based on the index and maxLen
  826. size_t len = index_html_gz_len - index;
  827. if (len > maxLen) len = maxLen;
  828. if (len > max) len = max;
  829. if (len > 0) memcpy_P(buffer, index_html_gz + index, len);
  830. DEBUG_MSG_P(PSTR("[WEB] Sending %d%%%% (max chunk size: %4d)\r"), int(100 * index / index_html_gz_len), max);
  831. if (len == 0) DEBUG_MSG_P(PSTR("\n"));
  832. // Return the actual length of the chunk (0 for end of file)
  833. return len;
  834. });
  835. #else
  836. AsyncWebServerResponse *response = request->beginResponse_P(200, "text/html", index_html_gz, index_html_gz_len);
  837. #endif
  838. response->addHeader("Content-Encoding", "gzip");
  839. response->addHeader("Last-Modified", _last_modified);
  840. request->send(response);
  841. }
  842. }
  843. #endif
  844. #if ASYNC_TCP_SSL_ENABLED & WEB_SSL_ENABLED
  845. int _onCertificate(void * arg, const char *filename, uint8_t **buf) {
  846. #if WEB_EMBEDDED
  847. if (strcmp(filename, "server.cer") == 0) {
  848. uint8_t * nbuf = (uint8_t*) malloc(server_cer_len);
  849. memcpy_P(nbuf, server_cer, server_cer_len);
  850. *buf = nbuf;
  851. DEBUG_MSG_P(PSTR("[WEB] SSL File: %s - OK\n"), filename);
  852. return server_cer_len;
  853. }
  854. if (strcmp(filename, "server.key") == 0) {
  855. uint8_t * nbuf = (uint8_t*) malloc(server_key_len);
  856. memcpy_P(nbuf, server_key, server_key_len);
  857. *buf = nbuf;
  858. DEBUG_MSG_P(PSTR("[WEB] SSL File: %s - OK\n"), filename);
  859. return server_key_len;
  860. }
  861. DEBUG_MSG_P(PSTR("[WEB] SSL File: %s - ERROR\n"), filename);
  862. *buf = 0;
  863. return 0;
  864. #else
  865. File file = SPIFFS.open(filename, "r");
  866. if (file) {
  867. size_t size = file.size();
  868. uint8_t * nbuf = (uint8_t*) malloc(size);
  869. if (nbuf) {
  870. size = file.read(nbuf, size);
  871. file.close();
  872. *buf = nbuf;
  873. DEBUG_MSG_P(PSTR("[WEB] SSL File: %s - OK\n"), filename);
  874. return size;
  875. }
  876. file.close();
  877. }
  878. DEBUG_MSG_P(PSTR("[WEB] SSL File: %s - ERROR\n"), filename);
  879. *buf = 0;
  880. return 0;
  881. #endif
  882. }
  883. #endif
  884. void _onUpgrade(AsyncWebServerRequest *request) {
  885. char buffer[10];
  886. if (!Update.hasError()) {
  887. sprintf_P(buffer, PSTR("OK"));
  888. } else {
  889. sprintf_P(buffer, PSTR("ERROR %d"), Update.getError());
  890. }
  891. AsyncWebServerResponse *response = request->beginResponse(200, "text/plain", buffer);
  892. response->addHeader("Connection", "close");
  893. if (!Update.hasError()) {
  894. _web_defer.once_ms(100, []() {
  895. customReset(CUSTOM_RESET_UPGRADE);
  896. ESP.restart();
  897. });
  898. }
  899. request->send(response);
  900. }
  901. void _onUpgradeData(AsyncWebServerRequest *request, String filename, size_t index, uint8_t *data, size_t len, bool final) {
  902. if (!index) {
  903. DEBUG_MSG_P(PSTR("[UPGRADE] Start: %s\n"), filename.c_str());
  904. Update.runAsync(true);
  905. if (!Update.begin((ESP.getFreeSketchSpace() - 0x1000) & 0xFFFFF000)) {
  906. #ifdef DEBUG_PORT
  907. Update.printError(DEBUG_PORT);
  908. #endif
  909. }
  910. }
  911. if (!Update.hasError()) {
  912. if (Update.write(data, len) != len) {
  913. #ifdef DEBUG_PORT
  914. Update.printError(DEBUG_PORT);
  915. #endif
  916. }
  917. }
  918. if (final) {
  919. if (Update.end(true)){
  920. DEBUG_MSG_P(PSTR("[UPGRADE] Success: %u bytes\n"), index + len);
  921. } else {
  922. #ifdef DEBUG_PORT
  923. Update.printError(DEBUG_PORT);
  924. #endif
  925. }
  926. } else {
  927. DEBUG_MSG_P(PSTR("[UPGRADE] Progress: %u bytes\r"), index + len);
  928. }
  929. }
  930. // -----------------------------------------------------------------------------
  931. void webSetup() {
  932. // Cache the Last-Modifier header value
  933. snprintf_P(_last_modified, sizeof(_last_modified), PSTR("%s %s GMT"), __DATE__, __TIME__);
  934. // Create server
  935. #if ASYNC_TCP_SSL_ENABLED & WEB_SSL_ENABLED
  936. unsigned int port = 443;
  937. #else
  938. unsigned int port = getSetting("webPort", WEB_PORT).toInt();
  939. #endif
  940. _server = new AsyncWebServer(port);
  941. // Setup websocket
  942. wsSetup();
  943. // API setup
  944. apiSetup();
  945. // Rewrites
  946. _server->rewrite("/", "/index.html");
  947. // Serve home (basic authentication protection)
  948. #if WEB_EMBEDDED
  949. _server->on("/index.html", HTTP_GET, _onHome);
  950. #endif
  951. _server->on("/config", HTTP_GET, _onGetConfig);
  952. _server->on("/upgrade", HTTP_POST, _onUpgrade, _onUpgradeData);
  953. // Serve static files
  954. #if SPIFFS_SUPPORT
  955. _server->serveStatic("/", SPIFFS, "/")
  956. .setLastModified(_last_modified)
  957. .setFilter([](AsyncWebServerRequest *request) -> bool {
  958. _webLog(request);
  959. return true;
  960. });
  961. #endif
  962. // 404
  963. _server->onNotFound([](AsyncWebServerRequest *request){
  964. request->send(404);
  965. });
  966. // Run server
  967. #if ASYNC_TCP_SSL_ENABLED & WEB_SSL_ENABLED
  968. _server->onSslFileRequest(_onCertificate, NULL);
  969. _server->beginSecure("server.cer", "server.key", NULL);
  970. #else
  971. _server->begin();
  972. #endif
  973. DEBUG_MSG_P(PSTR("[WEBSERVER] Webserver running on port %d\n"), port);
  974. }
  975. #endif // WEB_SUPPORT