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.

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