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.

1020 lines
31 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
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
  1. /*
  2. WEBSERVER MODULE
  3. Copyright (C) 2016-2017 by Xose Pérez <xose dot perez at gmail dot com>
  4. */
  5. #include <ESPAsyncTCP.h>
  6. #include <ESPAsyncWebServer.h>
  7. #include <ESP8266mDNS.h>
  8. #include <FS.h>
  9. #include <Hash.h>
  10. #include <AsyncJson.h>
  11. #include <ArduinoJson.h>
  12. #include <Ticker.h>
  13. #include <vector>
  14. #if EMBEDDED_WEB
  15. #include "static/index.html.gz.h"
  16. #endif
  17. AsyncWebServer * _server;
  18. AsyncWebSocket ws("/ws");
  19. Ticker deferred;
  20. typedef struct {
  21. IPAddress ip;
  22. unsigned long timestamp = 0;
  23. } ws_ticket_t;
  24. ws_ticket_t _ticket[WS_BUFFER_SIZE];
  25. typedef struct {
  26. char * url;
  27. char * key;
  28. apiGetCallbackFunction getFn = NULL;
  29. apiPutCallbackFunction putFn = NULL;
  30. } web_api_t;
  31. std::vector<web_api_t> _apis;
  32. char _last_modified[50];
  33. // -----------------------------------------------------------------------------
  34. // WEBSOCKETS
  35. // -----------------------------------------------------------------------------
  36. bool wsConnected() {
  37. return (ws.count() > 0);
  38. }
  39. bool wsSend(const char * payload) {
  40. if (ws.count() > 0) {
  41. ws.textAll(payload);
  42. }
  43. }
  44. bool wsSend(uint32_t client_id, const char * payload) {
  45. ws.text(client_id, payload);
  46. }
  47. void wsMQTTCallback(unsigned int type, const char * topic, const char * payload) {
  48. if (type == MQTT_CONNECT_EVENT) {
  49. wsSend("{\"mqttStatus\": true}");
  50. }
  51. if (type == MQTT_DISCONNECT_EVENT) {
  52. wsSend("{\"mqttStatus\": false}");
  53. }
  54. }
  55. void _wsParse(uint32_t client_id, uint8_t * payload, size_t length) {
  56. // Parse JSON input
  57. DynamicJsonBuffer jsonBuffer;
  58. JsonObject& root = jsonBuffer.parseObject((char *) payload);
  59. if (!root.success()) {
  60. DEBUG_MSG_P(PSTR("[WEBSOCKET] Error parsing data\n"));
  61. ws.text(client_id, "{\"message\": \"Error parsing data!\"}");
  62. return;
  63. }
  64. // Check actions
  65. if (root.containsKey("action")) {
  66. String action = root["action"];
  67. DEBUG_MSG_P(PSTR("[WEBSOCKET] Requested action: %s\n"), action.c_str());
  68. if (action.equals("reset")) {
  69. customReset(CUSTOM_RESET_WEB);
  70. ESP.restart();
  71. }
  72. #ifdef ITEAD_SONOFF_RFBRIDGE
  73. if (action.equals("rfblearn") && root.containsKey("data")) {
  74. JsonObject& data = root["data"];
  75. rfbLearn(data["id"], data["status"]);
  76. }
  77. if (action.equals("rfbforget") && root.containsKey("data")) {
  78. JsonObject& data = root["data"];
  79. rfbForget(data["id"], data["status"]);
  80. }
  81. if (action.equals("rfbsend") && root.containsKey("data")) {
  82. JsonObject& data = root["data"];
  83. rfbStore(data["id"], data["status"], data["data"].as<const char*>());
  84. }
  85. #endif
  86. if (action.equals("restore") && root.containsKey("data")) {
  87. JsonObject& data = root["data"];
  88. if (!data.containsKey("app") || (data["app"] != APP_NAME)) {
  89. ws.text(client_id, "{\"message\": \"The file does not look like a valid configuration backup.\"}");
  90. return;
  91. }
  92. for (unsigned int i = EEPROM_DATA_END; i < SPI_FLASH_SEC_SIZE; i++) {
  93. EEPROM.write(i, 0xFF);
  94. }
  95. for (auto element : data) {
  96. if (strcmp(element.key, "app") == 0) continue;
  97. if (strcmp(element.key, "version") == 0) continue;
  98. setSetting(element.key, element.value.as<char*>());
  99. }
  100. saveSettings();
  101. ws.text(client_id, "{\"message\": \"Changes saved. You should reboot your board now.\"}");
  102. }
  103. if (action.equals("reconnect")) {
  104. // Let the HTTP request return and disconnect after 100ms
  105. deferred.once_ms(100, wifiDisconnect);
  106. }
  107. if (action.equals("relay") && root.containsKey("data")) {
  108. JsonObject& data = root["data"];
  109. if (data.containsKey("status")) {
  110. bool status = (strcmp(data["status"], "1") == 0);
  111. unsigned int relayID = 0;
  112. if (data.containsKey("id")) {
  113. String value = data["id"];
  114. relayID = value.toInt();
  115. }
  116. relayStatus(relayID, status);
  117. }
  118. }
  119. #if LIGHT_PROVIDER != LIGHT_PROVIDER_NONE
  120. if (lightHasColor()) {
  121. if (action.equals("color") && root.containsKey("data")) {
  122. lightColor(root["data"]);
  123. lightUpdate(true, true);
  124. }
  125. if (action.equals("brightness") && root.containsKey("data")) {
  126. lightBrightness(root["data"]);
  127. lightUpdate(true, true);
  128. }
  129. }
  130. if (action.equals("channel") && root.containsKey("data")) {
  131. JsonObject& data = root["data"];
  132. if (data.containsKey("id") && data.containsKey("value")) {
  133. lightChannel(data["id"], data["value"]);
  134. lightUpdate(true, true);
  135. }
  136. }
  137. #endif
  138. };
  139. // Check config
  140. if (root.containsKey("config") && root["config"].is<JsonArray&>()) {
  141. JsonArray& config = root["config"];
  142. DEBUG_MSG_P(PSTR("[WEBSOCKET] Parsing configuration data\n"));
  143. unsigned char webMode = WEB_MODE_NORMAL;
  144. bool save = false;
  145. bool changed = false;
  146. bool changedMQTT = false;
  147. bool changedNTP = false;
  148. bool apiEnabled = false;
  149. bool dstEnabled = false;
  150. bool mqttUseJson = false;
  151. bool useColor = false;
  152. bool useWhite = false;
  153. bool useGamma = false;
  154. #if ENABLE_FAUXMO
  155. bool fauxmoEnabled = false;
  156. #endif
  157. unsigned int network = 0;
  158. unsigned int dczRelayIdx = 0;
  159. String adminPass;
  160. for (unsigned int i=0; i<config.size(); i++) {
  161. String key = config[i]["name"];
  162. String value = config[i]["value"];
  163. // Skip firmware filename
  164. if (key.equals("filename")) continue;
  165. #if ENABLE_HLW8012
  166. if (key == "powExpectedPower") {
  167. hlw8012SetExpectedActivePower(value.toInt());
  168. changed = true;
  169. }
  170. if (key == "powExpectedVoltage") {
  171. hlw8012SetExpectedVoltage(value.toInt());
  172. changed = true;
  173. }
  174. if (key == "powExpectedCurrent") {
  175. hlw8012SetExpectedCurrent(value.toFloat());
  176. changed = true;
  177. }
  178. if (key == "powExpectedReset") {
  179. hlw8012Reset();
  180. changed = true;
  181. }
  182. #endif
  183. if (key.startsWith("pow")) continue;
  184. #if ENABLE_DOMOTICZ
  185. if (key == "dczRelayIdx") {
  186. if (dczRelayIdx >= relayCount()) continue;
  187. key = key + String(dczRelayIdx);
  188. ++dczRelayIdx;
  189. }
  190. #else
  191. if (key.startsWith("dcz")) continue;
  192. #endif
  193. // Web portions
  194. if (key == "webPort") {
  195. if ((value.toInt() == 0) || (value.toInt() == 80)) {
  196. save = changed = true;
  197. delSetting(key);
  198. continue;
  199. }
  200. }
  201. if (key == "webMode") {
  202. webMode = value.toInt();
  203. continue;
  204. }
  205. // Check password
  206. if (key == "adminPass1") {
  207. adminPass = value;
  208. continue;
  209. }
  210. if (key == "adminPass2") {
  211. if (!value.equals(adminPass)) {
  212. ws.text(client_id, "{\"message\": \"Passwords do not match!\"}");
  213. return;
  214. }
  215. if (value.length() == 0) continue;
  216. ws.text(client_id, "{\"action\": \"reload\"}");
  217. key = String("adminPass");
  218. }
  219. // Checkboxes
  220. if (key == "apiEnabled") { apiEnabled = true; continue; }
  221. if (key == "ntpDST") { dstEnabled = true; continue; }
  222. if (key == "mqttUseJson") { mqttUseJson = true; continue; }
  223. if (key == "useColor") { useColor = true; continue; }
  224. if (key == "useWhite") { useWhite = true; continue; }
  225. if (key == "useGamma") { useGamma = true; continue; }
  226. #if ENABLE_FAUXMO
  227. if (key == "fauxmoEnabled") { fauxmoEnabled = true; continue; }
  228. #endif
  229. if (key == "ssid") {
  230. key = key + String(network);
  231. }
  232. if (key == "pass") {
  233. key = key + String(network);
  234. }
  235. if (key == "ip") {
  236. key = key + String(network);
  237. }
  238. if (key == "gw") {
  239. key = key + String(network);
  240. }
  241. if (key == "mask") {
  242. key = key + String(network);
  243. }
  244. if (key == "dns") {
  245. key = key + String(network);
  246. ++network;
  247. }
  248. if (value != getSetting(key)) {
  249. //DEBUG_MSG_P(PSTR("[WEBSOCKET] Storing %s = %s\n", key.c_str(), value.c_str()));
  250. setSetting(key, value);
  251. save = changed = true;
  252. if (key.startsWith("mqtt")) changedMQTT = true;
  253. if (key.startsWith("ntp")) changedNTP = true;
  254. }
  255. }
  256. if (webMode == WEB_MODE_NORMAL) {
  257. // Checkboxes
  258. setBoolSetting("apiEnabled", apiEnabled, ENABLE_API);
  259. setBoolSetting("ntpDST", dstEnabled, NTP_DAY_LIGHT);
  260. setBoolSetting("mqttUseJson", mqttUseJson, MQTT_USE_JSON);
  261. setBoolSetting("useColor", useColor, LIGHT_USE_COLOR);
  262. setBoolSetting("useWhite", useWhite, LIGHT_USE_WHITE);
  263. setBoolSetting("useGamma", useGamma, LIGHT_USE_GAMMA);
  264. #if ENABLE_FAUXMO
  265. setBoolSetting("fauxmoEnabled", fauxmoEnabled, FAUXMO_ENABLED);
  266. #endif
  267. // Clean wifi networks
  268. int i = 0;
  269. while (i < network) {
  270. if (getSetting("ssid" + String(i)).length() == 0) {
  271. delSetting("ssid" + String(i));
  272. break;
  273. }
  274. if (getSetting("pass" + String(i)).length() == 0) delSetting("pass" + String(i));
  275. if (getSetting("ip" + String(i)).length() == 0) delSetting("ip" + String(i));
  276. if (getSetting("gw" + String(i)).length() == 0) delSetting("gw" + String(i));
  277. if (getSetting("mask" + String(i)).length() == 0) delSetting("mask" + String(i));
  278. if (getSetting("dns" + String(i)).length() == 0) delSetting("dns" + String(i));
  279. ++i;
  280. }
  281. while (i < WIFI_MAX_NETWORKS) {
  282. if (getSetting("ssid" + String(i)).length() > 0) {
  283. save = changed = true;
  284. }
  285. delSetting("ssid" + String(i));
  286. delSetting("pass" + String(i));
  287. delSetting("ip" + String(i));
  288. delSetting("gw" + String(i));
  289. delSetting("mask" + String(i));
  290. delSetting("dns" + String(i));
  291. ++i;
  292. }
  293. }
  294. // Save settings
  295. if (save) {
  296. saveSettings();
  297. wifiConfigure();
  298. otaConfigure();
  299. #if ENABLE_FAUXMO
  300. fauxmoConfigure();
  301. #endif
  302. #if ENABLE_INFLUXDB
  303. influxDBConfigure();
  304. #endif
  305. mqttConfigure();
  306. #if ENABLE_RF
  307. rfBuildCodes();
  308. #endif
  309. #if ENABLE_EMON
  310. setCurrentRatio(getSetting("emonRatio").toFloat());
  311. #endif
  312. // Check if we should reconfigure MQTT connection
  313. if (changedMQTT) {
  314. mqttDisconnect();
  315. }
  316. // Check if we should reconfigure NTP connection
  317. if (changedNTP) {
  318. ntpConnect();
  319. }
  320. }
  321. if (changed) {
  322. ws.text(client_id, "{\"message\": \"Changes saved\"}");
  323. } else {
  324. ws.text(client_id, "{\"message\": \"No changes detected\"}");
  325. }
  326. }
  327. }
  328. void _wsStart(uint32_t client_id) {
  329. char chipid[6];
  330. sprintf(chipid, "%06X", ESP.getChipId());
  331. DynamicJsonBuffer jsonBuffer;
  332. JsonObject& root = jsonBuffer.createObject();
  333. bool changePassword = false;
  334. #if FORCE_CHANGE_PASS == 1
  335. String adminPass = getSetting("adminPass", ADMIN_PASS);
  336. if (adminPass.equals(ADMIN_PASS)) changePassword = true;
  337. #endif
  338. if (changePassword) {
  339. root["webMode"] = WEB_MODE_PASSWORD;
  340. } else {
  341. root["webMode"] = WEB_MODE_NORMAL;
  342. root["app"] = APP_NAME;
  343. root["version"] = APP_VERSION;
  344. root["buildDate"] = __DATE__;
  345. root["buildTime"] = __TIME__;
  346. root["manufacturer"] = String(MANUFACTURER);
  347. root["chipid"] = chipid;
  348. root["mac"] = WiFi.macAddress();
  349. root["device"] = String(DEVICE);
  350. root["hostname"] = getSetting("hostname");
  351. root["network"] = getNetwork();
  352. root["deviceip"] = getIP();
  353. root["ntpStatus"] = ntpConnected();
  354. root["ntpServer1"] = getSetting("ntpServer1", NTP_SERVER);
  355. root["ntpServer2"] = getSetting("ntpServer2");
  356. root["ntpServer3"] = getSetting("ntpServer3");
  357. root["ntpOffset"] = getSetting("ntpOffset", NTP_TIME_OFFSET).toInt();
  358. root["ntpDST"] = getSetting("ntpDST", NTP_DAY_LIGHT).toInt() == 1;
  359. root["mqttStatus"] = mqttConnected();
  360. root["mqttServer"] = getSetting("mqttServer", MQTT_SERVER);
  361. root["mqttPort"] = getSetting("mqttPort", MQTT_PORT);
  362. root["mqttUser"] = getSetting("mqttUser");
  363. root["mqttPassword"] = getSetting("mqttPassword");
  364. root["mqttTopic"] = getSetting("mqttTopic", MQTT_TOPIC);
  365. root["mqttUseJson"] = getSetting("mqttUseJson", MQTT_USE_JSON).toInt() == 1;
  366. JsonArray& relay = root.createNestedArray("relayStatus");
  367. for (unsigned char relayID=0; relayID<relayCount(); relayID++) {
  368. relay.add(relayStatus(relayID));
  369. }
  370. #if LIGHT_PROVIDER != LIGHT_PROVIDER_NONE
  371. root["colorVisible"] = 1;
  372. root["useColor"] = getSetting("useColor", LIGHT_USE_COLOR).toInt() == 1;
  373. root["useWhite"] = getSetting("useWhite", LIGHT_USE_WHITE).toInt() == 1;
  374. root["useGamma"] = getSetting("useGamma", LIGHT_USE_GAMMA).toInt() == 1;
  375. if (lightHasColor()) {
  376. root["color"] = lightColor();
  377. root["brightness"] = lightBrightness();
  378. }
  379. JsonArray& channels = root.createNestedArray("channels");
  380. for (unsigned char id=0; id < lightChannels(); id++) {
  381. channels.add(lightChannel(id));
  382. }
  383. #endif
  384. root["relayMode"] = getSetting("relayMode", RELAY_MODE);
  385. root["relayPulseMode"] = getSetting("relayPulseMode", RELAY_PULSE_MODE);
  386. root["relayPulseTime"] = getSetting("relayPulseTime", RELAY_PULSE_TIME).toFloat();
  387. if (relayCount() > 1) {
  388. root["multirelayVisible"] = 1;
  389. root["relaySync"] = getSetting("relaySync", RELAY_SYNC);
  390. }
  391. root["btnDelay"] = getSetting("btnDelay", BUTTON_DBLCLICK_DELAY).toInt();
  392. root["webPort"] = getSetting("webPort", WEBSERVER_PORT).toInt();
  393. root["apiEnabled"] = getSetting("apiEnabled", ENABLE_API).toInt() == 1;
  394. root["apiKey"] = getSetting("apiKey");
  395. root["tmpUnits"] = getSetting("tmpUnits", TMP_UNITS).toInt();
  396. #if ENABLE_DOMOTICZ
  397. root["dczVisible"] = 1;
  398. root["dczTopicIn"] = getSetting("dczTopicIn", DOMOTICZ_IN_TOPIC);
  399. root["dczTopicOut"] = getSetting("dczTopicOut", DOMOTICZ_OUT_TOPIC);
  400. JsonArray& dczRelayIdx = root.createNestedArray("dczRelayIdx");
  401. for (byte i=0; i<relayCount(); i++) {
  402. dczRelayIdx.add(relayToIdx(i));
  403. }
  404. #if ENABLE_DHT
  405. root["dczTmpIdx"] = getSetting("dczTmpIdx").toInt();
  406. root["dczHumIdx"] = getSetting("dczHumIdx").toInt();
  407. #endif
  408. #if ENABLE_DS18B20
  409. root["dczTmpIdx"] = getSetting("dczTmpIdx").toInt();
  410. #endif
  411. #if ENABLE_EMON
  412. root["dczPowIdx"] = getSetting("dczPowIdx").toInt();
  413. root["dczEnergyIdx"] = getSetting("dczEnergyIdx").toInt();
  414. root["dczCurrentIdx"] = getSetting("dczCurrentIdx").toInt();
  415. #endif
  416. #if ENABLE_ANALOG
  417. root["dczAnaIdx"] = getSetting("dczAnaIdx").toInt();
  418. #endif
  419. #if ENABLE_HLW8012
  420. root["dczPowIdx"] = getSetting("dczPowIdx").toInt();
  421. root["dczEnergyIdx"] = getSetting("dczEnergyIdx").toInt();
  422. root["dczVoltIdx"] = getSetting("dczVoltIdx").toInt();
  423. root["dczCurrentIdx"] = getSetting("dczCurrentIdx").toInt();
  424. #endif
  425. #endif
  426. #if ENABLE_INFLUXDB
  427. root["idbVisible"] = 1;
  428. root["idbHost"] = getSetting("idbHost");
  429. root["idbPort"] = getSetting("idbPort", INFLUXDB_PORT).toInt();
  430. root["idbDatabase"] = getSetting("idbDatabase");
  431. root["idbUsername"] = getSetting("idbUsername");
  432. root["idbPassword"] = getSetting("idbPassword");
  433. #endif
  434. #if ENABLE_FAUXMO
  435. root["fauxmoVisible"] = 1;
  436. root["fauxmoEnabled"] = getSetting("fauxmoEnabled", FAUXMO_ENABLED).toInt() == 1;
  437. #endif
  438. #if ENABLE_DS18B20
  439. root["dsVisible"] = 1;
  440. root["dsTmp"] = getDSTemperatureStr();
  441. #endif
  442. #if ENABLE_DHT
  443. root["dhtVisible"] = 1;
  444. root["dhtTmp"] = getDHTTemperature();
  445. root["dhtHum"] = getDHTHumidity();
  446. #endif
  447. #if ENABLE_RF
  448. root["rfVisible"] = 1;
  449. root["rfChannel"] = getSetting("rfChannel", RF_CHANNEL);
  450. root["rfDevice"] = getSetting("rfDevice", RF_DEVICE);
  451. #endif
  452. #if ENABLE_EMON
  453. root["emonVisible"] = 1;
  454. root["emonApparentPower"] = getApparentPower();
  455. root["emonCurrent"] = getCurrent();
  456. root["emonVoltage"] = getVoltage();
  457. root["emonRatio"] = getSetting("emonRatio", EMON_CURRENT_RATIO);
  458. #endif
  459. #if ENABLE_ANALOG
  460. root["analogVisible"] = 1;
  461. root["analogValue"] = getAnalog();
  462. #endif
  463. #if ENABLE_HLW8012
  464. root["powVisible"] = 1;
  465. root["powActivePower"] = getActivePower();
  466. root["powApparentPower"] = getApparentPower();
  467. root["powReactivePower"] = getReactivePower();
  468. root["powVoltage"] = getVoltage();
  469. root["powCurrent"] = String(getCurrent(), 3);
  470. root["powPowerFactor"] = String(getPowerFactor(), 2);
  471. #endif
  472. #ifdef ITEAD_SONOFF_RFBRIDGE
  473. root["rfbVisible"] = 1;
  474. root["rfbCount"] = relayCount();
  475. JsonArray& rfb = root.createNestedArray("rfb");
  476. for (byte id=0; id<relayCount(); id++) {
  477. for (byte status=0; status<2; status++) {
  478. JsonObject& node = rfb.createNestedObject();
  479. node["id"] = id;
  480. node["status"] = status;
  481. node["data"] = rfbRetrieve(id, status == 1);
  482. }
  483. }
  484. #endif
  485. root["maxNetworks"] = WIFI_MAX_NETWORKS;
  486. JsonArray& wifi = root.createNestedArray("wifi");
  487. for (byte i=0; i<WIFI_MAX_NETWORKS; i++) {
  488. if (getSetting("ssid" + String(i)).length() == 0) break;
  489. JsonObject& network = wifi.createNestedObject();
  490. network["ssid"] = getSetting("ssid" + String(i));
  491. network["pass"] = getSetting("pass" + String(i));
  492. network["ip"] = getSetting("ip" + String(i));
  493. network["gw"] = getSetting("gw" + String(i));
  494. network["mask"] = getSetting("mask" + String(i));
  495. network["dns"] = getSetting("dns" + String(i));
  496. }
  497. }
  498. String output;
  499. root.printTo(output);
  500. ws.text(client_id, (char *) output.c_str());
  501. }
  502. bool _wsAuth(AsyncWebSocketClient * client) {
  503. IPAddress ip = client->remoteIP();
  504. unsigned long now = millis();
  505. unsigned short index = 0;
  506. for (index = 0; index < WS_BUFFER_SIZE; index++) {
  507. if ((_ticket[index].ip == ip) && (now - _ticket[index].timestamp < WS_TIMEOUT)) break;
  508. }
  509. if (index == WS_BUFFER_SIZE) {
  510. DEBUG_MSG_P(PSTR("[WEBSOCKET] Validation check failed\n"));
  511. ws.text(client->id(), "{\"message\": \"Session expired, please reload page...\"}");
  512. return false;
  513. }
  514. return true;
  515. }
  516. void _wsEvent(AsyncWebSocket * server, AsyncWebSocketClient * client, AwsEventType type, void * arg, uint8_t *data, size_t len){
  517. static uint8_t * message;
  518. // Authorize
  519. #ifndef NOWSAUTH
  520. if (!_wsAuth(client)) return;
  521. #endif
  522. if (type == WS_EVT_CONNECT) {
  523. IPAddress ip = client->remoteIP();
  524. 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());
  525. _wsStart(client->id());
  526. } else if(type == WS_EVT_DISCONNECT) {
  527. DEBUG_MSG_P(PSTR("[WEBSOCKET] #%u disconnected\n"), client->id());
  528. } else if(type == WS_EVT_ERROR) {
  529. DEBUG_MSG_P(PSTR("[WEBSOCKET] #%u error(%u): %s\n"), client->id(), *((uint16_t*)arg), (char*)data);
  530. } else if(type == WS_EVT_PONG) {
  531. DEBUG_MSG_P(PSTR("[WEBSOCKET] #%u pong(%u): %s\n"), client->id(), len, len ? (char*) data : "");
  532. } else if(type == WS_EVT_DATA) {
  533. AwsFrameInfo * info = (AwsFrameInfo*)arg;
  534. // First packet
  535. if (info->index == 0) {
  536. message = (uint8_t*) malloc(info->len);
  537. }
  538. // Store data
  539. memcpy(message + info->index, data, len);
  540. // Last packet
  541. if (info->index + len == info->len) {
  542. _wsParse(client->id(), message, info->len);
  543. free(message);
  544. }
  545. }
  546. }
  547. // -----------------------------------------------------------------------------
  548. // WEBSERVER
  549. // -----------------------------------------------------------------------------
  550. void webLogRequest(AsyncWebServerRequest *request) {
  551. DEBUG_MSG_P(PSTR("[WEBSERVER] Request: %s %s\n"), request->methodToString(), request->url().c_str());
  552. }
  553. bool _authenticate(AsyncWebServerRequest *request) {
  554. String password = getSetting("adminPass", ADMIN_PASS);
  555. char httpPassword[password.length() + 1];
  556. password.toCharArray(httpPassword, password.length() + 1);
  557. return request->authenticate(HTTP_USERNAME, httpPassword);
  558. }
  559. bool _authAPI(AsyncWebServerRequest *request) {
  560. if (getSetting("apiEnabled", ENABLE_API).toInt() == 0) {
  561. DEBUG_MSG_P(PSTR("[WEBSERVER] HTTP API is not enabled\n"));
  562. request->send(403);
  563. return false;
  564. }
  565. if (!request->hasParam("apikey", (request->method() == HTTP_PUT))) {
  566. DEBUG_MSG_P(PSTR("[WEBSERVER] Missing apikey parameter\n"));
  567. request->send(403);
  568. return false;
  569. }
  570. AsyncWebParameter* p = request->getParam("apikey", (request->method() == HTTP_PUT));
  571. if (!p->value().equals(getSetting("apiKey"))) {
  572. DEBUG_MSG_P(PSTR("[WEBSERVER] Wrong apikey parameter\n"));
  573. request->send(403);
  574. return false;
  575. }
  576. return true;
  577. }
  578. bool _asJson(AsyncWebServerRequest *request) {
  579. bool asJson = false;
  580. if (request->hasHeader("Accept")) {
  581. AsyncWebHeader* h = request->getHeader("Accept");
  582. asJson = h->value().equals("application/json");
  583. }
  584. return asJson;
  585. }
  586. ArRequestHandlerFunction _bindAPI(unsigned int apiID) {
  587. return [apiID](AsyncWebServerRequest *request) {
  588. webLogRequest(request);
  589. if (!_authAPI(request)) return;
  590. web_api_t api = _apis[apiID];
  591. // Check if its a PUT
  592. if (api.putFn != NULL) {
  593. if (request->hasParam("value", request->method() == HTTP_PUT)) {
  594. AsyncWebParameter* p = request->getParam("value", request->method() == HTTP_PUT);
  595. (api.putFn)((p->value()).c_str());
  596. }
  597. }
  598. // Get response from callback
  599. char value[API_BUFFER_SIZE];
  600. (api.getFn)(value, API_BUFFER_SIZE);
  601. char *p = ltrim(value);
  602. // The response will be a 404 NOT FOUND if the resource is not available
  603. if (*value == NULL) {
  604. DEBUG_MSG_P(PSTR("[API] Sending 404 response\n"));
  605. request->send(404);
  606. return;
  607. }
  608. DEBUG_MSG_P(PSTR("[API] Sending response '%s'\n"), p);
  609. // Format response according to the Accept header
  610. if (_asJson(request)) {
  611. char buffer[64];
  612. sprintf_P(buffer, PSTR("{ \"%s\": %s }"), api.key, p);
  613. request->send(200, "application/json", buffer);
  614. } else {
  615. request->send(200, "text/plain", p);
  616. }
  617. };
  618. }
  619. void apiRegister(const char * url, const char * key, apiGetCallbackFunction getFn, apiPutCallbackFunction putFn) {
  620. // Store it
  621. web_api_t api;
  622. char buffer[40];
  623. snprintf(buffer, 39, "/api/%s", url);
  624. api.url = strdup(buffer);
  625. api.key = strdup(key);
  626. api.getFn = getFn;
  627. api.putFn = putFn;
  628. _apis.push_back(api);
  629. // Bind call
  630. unsigned int methods = HTTP_GET;
  631. if (putFn != NULL) methods += HTTP_PUT;
  632. _server->on(buffer, methods, _bindAPI(_apis.size() - 1));
  633. }
  634. void _onAPIs(AsyncWebServerRequest *request) {
  635. webLogRequest(request);
  636. if (!_authAPI(request)) return;
  637. bool asJson = _asJson(request);
  638. String output;
  639. if (asJson) {
  640. DynamicJsonBuffer jsonBuffer;
  641. JsonObject& root = jsonBuffer.createObject();
  642. for (unsigned int i=0; i < _apis.size(); i++) {
  643. root[_apis[i].key] = _apis[i].url;
  644. }
  645. root.printTo(output);
  646. request->send(200, "application/json", output);
  647. } else {
  648. for (unsigned int i=0; i < _apis.size(); i++) {
  649. output += _apis[i].key + String(" -> ") + _apis[i].url + String("\n");
  650. }
  651. request->send(200, "text/plain", output);
  652. }
  653. }
  654. void _onRPC(AsyncWebServerRequest *request) {
  655. webLogRequest(request);
  656. if (!_authAPI(request)) return;
  657. //bool asJson = _asJson(request);
  658. int response = 404;
  659. if (request->hasParam("action")) {
  660. AsyncWebParameter* p = request->getParam("action");
  661. String action = p->value();
  662. DEBUG_MSG_P(PSTR("[RPC] Action: %s\n"), action.c_str());
  663. if (action.equals("reset")) {
  664. response = 200;
  665. deferred.once_ms(100, []() {
  666. customReset(CUSTOM_RESET_RPC);
  667. ESP.restart();
  668. });
  669. }
  670. }
  671. request->send(response);
  672. }
  673. void _onAuth(AsyncWebServerRequest *request) {
  674. webLogRequest(request);
  675. if (!_authenticate(request)) return request->requestAuthentication();
  676. IPAddress ip = request->client()->remoteIP();
  677. unsigned long now = millis();
  678. unsigned short index;
  679. for (index = 0; index < WS_BUFFER_SIZE; index++) {
  680. if (_ticket[index].ip == ip) break;
  681. if (_ticket[index].timestamp == 0) break;
  682. if (now - _ticket[index].timestamp > WS_TIMEOUT) break;
  683. }
  684. if (index == WS_BUFFER_SIZE) {
  685. request->send(429);
  686. } else {
  687. _ticket[index].ip = ip;
  688. _ticket[index].timestamp = now;
  689. request->send(204);
  690. }
  691. }
  692. void _onGetConfig(AsyncWebServerRequest *request) {
  693. webLogRequest(request);
  694. if (!_authenticate(request)) return request->requestAuthentication();
  695. AsyncJsonResponse * response = new AsyncJsonResponse();
  696. JsonObject& root = response->getRoot();
  697. root["app"] = APP_NAME;
  698. root["version"] = APP_VERSION;
  699. unsigned int size = settingsKeyCount();
  700. for (unsigned int i=0; i<size; i++) {
  701. String key = settingsKeyName(i);
  702. String value = getSetting(key);
  703. root[key] = value;
  704. }
  705. char buffer[100];
  706. sprintf(buffer, "attachment; filename=\"%s-backup.json\"", (char *) getSetting("hostname").c_str());
  707. response->addHeader("Content-Disposition", buffer);
  708. response->setLength();
  709. request->send(response);
  710. }
  711. #if EMBEDDED_WEB
  712. void _onHome(AsyncWebServerRequest *request) {
  713. webLogRequest(request);
  714. if (request->header("If-Modified-Since").equals(_last_modified)) {
  715. request->send(304);
  716. } else {
  717. AsyncWebServerResponse *response = request->beginResponse_P(200, "text/html", index_html_gz, index_html_gz_len);
  718. response->addHeader("Content-Encoding", "gzip");
  719. response->addHeader("Last-Modified", _last_modified);
  720. request->send(response);
  721. }
  722. }
  723. #endif
  724. void _onUpgrade(AsyncWebServerRequest *request) {
  725. AsyncWebServerResponse *response = request->beginResponse(200, "text/plain", Update.hasError() ? "FAIL" : "OK");
  726. response->addHeader("Connection", "close");
  727. if (!Update.hasError()) {
  728. deferred.once_ms(100, []() {
  729. customReset(CUSTOM_RESET_UPGRADE);
  730. ESP.restart();
  731. });
  732. }
  733. request->send(response);
  734. }
  735. void _onUpgradeData(AsyncWebServerRequest *request, String filename, size_t index, uint8_t *data, size_t len, bool final) {
  736. if (!index) {
  737. DEBUG_MSG_P(PSTR("[UPGRADE] Start: %s\n"), filename.c_str());
  738. Update.runAsync(true);
  739. if (!Update.begin((ESP.getFreeSketchSpace() - 0x1000) & 0xFFFFF000)) {
  740. #ifdef DEBUG_PORT
  741. Update.printError(DEBUG_PORT);
  742. #endif
  743. }
  744. }
  745. if (!Update.hasError()) {
  746. if (Update.write(data, len) != len) {
  747. #ifdef DEBUG_PORT
  748. Update.printError(DEBUG_PORT);
  749. #endif
  750. }
  751. }
  752. if (final) {
  753. if (Update.end(true)){
  754. DEBUG_MSG_P(PSTR("[UPGRADE] Success: %u bytes\n"), index + len);
  755. } else {
  756. #ifdef DEBUG_PORT
  757. Update.printError(DEBUG_PORT);
  758. #endif
  759. }
  760. } else {
  761. DEBUG_MSG_P(PSTR("[UPGRADE] Progress: %u bytes\r"), index + len);
  762. }
  763. }
  764. void webSetup() {
  765. // Create server
  766. _server = new AsyncWebServer(getSetting("webPort", WEBSERVER_PORT).toInt());
  767. // Setup websocket
  768. ws.onEvent(_wsEvent);
  769. mqttRegister(wsMQTTCallback);
  770. // Cache the Last-Modifier header value
  771. sprintf(_last_modified, "%s %s GMT", __DATE__, __TIME__);
  772. // Setup webserver
  773. _server->addHandler(&ws);
  774. // Rewrites
  775. _server->rewrite("/", "/index.html");
  776. // Serve home (basic authentication protection)
  777. #if EMBEDDED_WEB
  778. _server->on("/index.html", HTTP_GET, _onHome);
  779. #endif
  780. _server->on("/config", HTTP_GET, _onGetConfig);
  781. _server->on("/auth", HTTP_GET, _onAuth);
  782. _server->on("/apis", HTTP_GET, _onAPIs);
  783. _server->on("/rpc", HTTP_GET, _onRPC);
  784. _server->on("/upgrade", HTTP_POST, _onUpgrade, _onUpgradeData);
  785. // Serve static files
  786. #if ENABLE_SPIFFS
  787. _server->serveStatic("/", SPIFFS, "/")
  788. .setLastModified(_last_modified)
  789. .setFilter([](AsyncWebServerRequest *request) -> bool {
  790. webLogRequest(request);
  791. return true;
  792. });
  793. #endif
  794. // 404
  795. _server->onNotFound([](AsyncWebServerRequest *request){
  796. request->send(404);
  797. });
  798. // Run server
  799. _server->begin();
  800. DEBUG_MSG_P(PSTR("[WEBSERVER] Webserver running on port %d\n"), getSetting("webPort", WEBSERVER_PORT).toInt());
  801. }