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.

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