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.

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