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.

1142 lines
35 KiB

8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
7 years ago
7 years ago
7 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["build"] = buildTime();
  316. root["manufacturer"] = String(MANUFACTURER);
  317. root["chipid"] = chipid;
  318. root["mac"] = WiFi.macAddress();
  319. root["device"] = String(DEVICE);
  320. root["hostname"] = getSetting("hostname");
  321. root["network"] = getNetwork();
  322. root["deviceip"] = getIP();
  323. root["time"] = ntpDateTime();
  324. root["uptime"] = getUptime();
  325. root["heap"] = ESP.getFreeHeap();
  326. root["sketch_size"] = ESP.getSketchSize();
  327. root["free_size"] = ESP.getFreeSketchSpace();
  328. #if NTP_SUPPORT
  329. root["ntpVisible"] = 1;
  330. root["ntpStatus"] = ntpConnected();
  331. root["ntpServer1"] = getSetting("ntpServer1", NTP_SERVER);
  332. root["ntpServer2"] = getSetting("ntpServer2");
  333. root["ntpServer3"] = getSetting("ntpServer3");
  334. root["ntpOffset"] = getSetting("ntpOffset", NTP_TIME_OFFSET).toInt();
  335. root["ntpDST"] = getSetting("ntpDST", NTP_DAY_LIGHT).toInt() == 1;
  336. #endif
  337. root["mqttStatus"] = mqttConnected();
  338. root["mqttServer"] = getSetting("mqttServer", MQTT_SERVER);
  339. root["mqttPort"] = getSetting("mqttPort", MQTT_PORT);
  340. root["mqttUser"] = getSetting("mqttUser");
  341. root["mqttPassword"] = getSetting("mqttPassword");
  342. #if ASYNC_TCP_SSL_ENABLED
  343. root["mqttsslVisible"] = 1;
  344. root["mqttUseSSL"] = getSetting("mqttUseSSL", 0).toInt() == 1;
  345. root["mqttFP"] = getSetting("mqttFP");
  346. #endif
  347. root["mqttTopic"] = getSetting("mqttTopic", MQTT_TOPIC);
  348. root["mqttUseJson"] = getSetting("mqttUseJson", MQTT_USE_JSON).toInt() == 1;
  349. JsonArray& relay = root.createNestedArray("relayStatus");
  350. for (unsigned char relayID=0; relayID<relayCount(); relayID++) {
  351. relay.add(relayStatus(relayID));
  352. }
  353. #if LIGHT_PROVIDER != LIGHT_PROVIDER_NONE
  354. root["colorVisible"] = 1;
  355. root["useColor"] = getSetting("useColor", LIGHT_USE_COLOR).toInt() == 1;
  356. root["useWhite"] = getSetting("useWhite", LIGHT_USE_WHITE).toInt() == 1;
  357. root["useGamma"] = getSetting("useGamma", LIGHT_USE_GAMMA).toInt() == 1;
  358. if (lightHasColor()) {
  359. root["color"] = lightColor();
  360. root["brightness"] = lightBrightness();
  361. }
  362. JsonArray& channels = root.createNestedArray("channels");
  363. for (unsigned char id=0; id < lightChannels(); id++) {
  364. channels.add(lightChannel(id));
  365. }
  366. #endif
  367. root["relayMode"] = getSetting("relayMode", RELAY_MODE);
  368. root["relayPulseMode"] = getSetting("relayPulseMode", RELAY_PULSE_MODE);
  369. root["relayPulseTime"] = getSetting("relayPulseTime", RELAY_PULSE_TIME).toFloat();
  370. if (relayCount() > 1) {
  371. root["multirelayVisible"] = 1;
  372. root["relaySync"] = getSetting("relaySync", RELAY_SYNC);
  373. }
  374. root["btnDelay"] = getSetting("btnDelay", BUTTON_DBLCLICK_DELAY).toInt();
  375. root["webPort"] = getSetting("webPort", WEB_PORT).toInt();
  376. root["apiEnabled"] = getSetting("apiEnabled", API_ENABLED).toInt() == 1;
  377. root["apiKey"] = getSetting("apiKey");
  378. root["tmpUnits"] = getSetting("tmpUnits", TMP_UNITS).toInt();
  379. #if DOMOTICZ_SUPPORT
  380. root["dczVisible"] = 1;
  381. root["dczEnabled"] = getSetting("dczEnabled", DOMOTICZ_ENABLED).toInt() == 1;
  382. root["dczTopicIn"] = getSetting("dczTopicIn", DOMOTICZ_IN_TOPIC);
  383. root["dczTopicOut"] = getSetting("dczTopicOut", DOMOTICZ_OUT_TOPIC);
  384. JsonArray& dczRelayIdx = root.createNestedArray("dczRelayIdx");
  385. for (byte i=0; i<relayCount(); i++) {
  386. dczRelayIdx.add(domoticzIdx(i));
  387. }
  388. #if DHT_SUPPORT
  389. root["dczTmpIdx"] = getSetting("dczTmpIdx").toInt();
  390. root["dczHumIdx"] = getSetting("dczHumIdx").toInt();
  391. #endif
  392. #if DS18B20_SUPPORT
  393. root["dczTmpIdx"] = getSetting("dczTmpIdx").toInt();
  394. #endif
  395. #if EMON_SUPPORT
  396. root["dczPowIdx"] = getSetting("dczPowIdx").toInt();
  397. root["dczEnergyIdx"] = getSetting("dczEnergyIdx").toInt();
  398. root["dczCurrentIdx"] = getSetting("dczCurrentIdx").toInt();
  399. #endif
  400. #if ANALOG_SUPPORT
  401. root["dczAnaIdx"] = getSetting("dczAnaIdx").toInt();
  402. #endif
  403. #if HLW8012_SUPPORT
  404. root["dczPowIdx"] = getSetting("dczPowIdx").toInt();
  405. root["dczEnergyIdx"] = getSetting("dczEnergyIdx").toInt();
  406. root["dczVoltIdx"] = getSetting("dczVoltIdx").toInt();
  407. root["dczCurrentIdx"] = getSetting("dczCurrentIdx").toInt();
  408. #endif
  409. #endif
  410. #if INFLUXDB_SUPPORT
  411. root["idbVisible"] = 1;
  412. root["idbHost"] = getSetting("idbHost");
  413. root["idbPort"] = getSetting("idbPort", INFLUXDB_PORT).toInt();
  414. root["idbDatabase"] = getSetting("idbDatabase");
  415. root["idbUsername"] = getSetting("idbUsername");
  416. root["idbPassword"] = getSetting("idbPassword");
  417. #endif
  418. #if ALEXA_SUPPORT
  419. root["alexaVisible"] = 1;
  420. root["alexaEnabled"] = getSetting("alexaEnabled", ALEXA_ENABLED).toInt() == 1;
  421. #endif
  422. #if DS18B20_SUPPORT
  423. root["dsVisible"] = 1;
  424. root["dsTmp"] = getDSTemperatureStr();
  425. #endif
  426. #if DHT_SUPPORT
  427. root["dhtVisible"] = 1;
  428. root["dhtTmp"] = getDHTTemperature();
  429. root["dhtHum"] = getDHTHumidity();
  430. #endif
  431. #if RF_SUPPORT
  432. root["rfVisible"] = 1;
  433. root["rfChannel"] = getSetting("rfChannel", RF_CHANNEL);
  434. root["rfDevice"] = getSetting("rfDevice", RF_DEVICE);
  435. #endif
  436. #if EMON_SUPPORT
  437. root["emonVisible"] = 1;
  438. root["emonApparentPower"] = getApparentPower();
  439. root["emonCurrent"] = getCurrent();
  440. root["emonVoltage"] = getVoltage();
  441. root["emonRatio"] = getSetting("emonRatio", EMON_CURRENT_RATIO);
  442. #endif
  443. #if ANALOG_SUPPORT
  444. root["analogVisible"] = 1;
  445. root["analogValue"] = getAnalog();
  446. #endif
  447. #if HLW8012_SUPPORT
  448. root["powVisible"] = 1;
  449. root["powActivePower"] = getActivePower();
  450. root["powApparentPower"] = getApparentPower();
  451. root["powReactivePower"] = getReactivePower();
  452. root["powVoltage"] = getVoltage();
  453. root["powCurrent"] = String(getCurrent(), 3);
  454. root["powPowerFactor"] = String(getPowerFactor(), 2);
  455. #endif
  456. #ifdef ITEAD_SONOFF_RFBRIDGE
  457. root["rfbVisible"] = 1;
  458. root["rfbCount"] = relayCount();
  459. JsonArray& rfb = root.createNestedArray("rfb");
  460. for (byte id=0; id<relayCount(); id++) {
  461. for (byte status=0; status<2; status++) {
  462. JsonObject& node = rfb.createNestedObject();
  463. node["id"] = id;
  464. node["status"] = status;
  465. node["data"] = rfbRetrieve(id, status == 1);
  466. }
  467. }
  468. #endif
  469. root["maxNetworks"] = WIFI_MAX_NETWORKS;
  470. JsonArray& wifi = root.createNestedArray("wifi");
  471. for (byte i=0; i<WIFI_MAX_NETWORKS; i++) {
  472. if (getSetting("ssid" + String(i)).length() == 0) break;
  473. JsonObject& network = wifi.createNestedObject();
  474. network["ssid"] = getSetting("ssid" + String(i));
  475. network["pass"] = getSetting("pass" + String(i));
  476. network["ip"] = getSetting("ip" + String(i));
  477. network["gw"] = getSetting("gw" + String(i));
  478. network["mask"] = getSetting("mask" + String(i));
  479. network["dns"] = getSetting("dns" + String(i));
  480. }
  481. }
  482. String output;
  483. root.printTo(output);
  484. wsSend(client_id, (char *) output.c_str());
  485. }
  486. bool _wsAuth(AsyncWebSocketClient * client) {
  487. IPAddress ip = client->remoteIP();
  488. unsigned long now = millis();
  489. unsigned short index = 0;
  490. for (index = 0; index < WS_BUFFER_SIZE; index++) {
  491. if ((_ticket[index].ip == ip) && (now - _ticket[index].timestamp < WS_TIMEOUT)) break;
  492. }
  493. if (index == WS_BUFFER_SIZE) {
  494. DEBUG_MSG_P(PSTR("[WEBSOCKET] Validation check failed\n"));
  495. wsSend_P(client->id(), PSTR("{\"message\": \"Session expired, please reload page...\"}"));
  496. return false;
  497. }
  498. return true;
  499. }
  500. void _wsEvent(AsyncWebSocket * server, AsyncWebSocketClient * client, AwsEventType type, void * arg, uint8_t *data, size_t len){
  501. static uint8_t * message;
  502. // Authorize
  503. #ifndef NOWSAUTH
  504. if (!_wsAuth(client)) return;
  505. #endif
  506. if (type == WS_EVT_CONNECT) {
  507. IPAddress ip = client->remoteIP();
  508. 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());
  509. _wsStart(client->id());
  510. } else if(type == WS_EVT_DISCONNECT) {
  511. DEBUG_MSG_P(PSTR("[WEBSOCKET] #%u disconnected\n"), client->id());
  512. } else if(type == WS_EVT_ERROR) {
  513. DEBUG_MSG_P(PSTR("[WEBSOCKET] #%u error(%u): %s\n"), client->id(), *((uint16_t*)arg), (char*)data);
  514. } else if(type == WS_EVT_PONG) {
  515. DEBUG_MSG_P(PSTR("[WEBSOCKET] #%u pong(%u): %s\n"), client->id(), len, len ? (char*) data : "");
  516. } else if(type == WS_EVT_DATA) {
  517. AwsFrameInfo * info = (AwsFrameInfo*)arg;
  518. // First packet
  519. if (info->index == 0) {
  520. message = (uint8_t*) malloc(info->len);
  521. }
  522. // Store data
  523. memcpy(message + info->index, data, len);
  524. // Last packet
  525. if (info->index + len == info->len) {
  526. _wsParse(client->id(), message, info->len);
  527. free(message);
  528. }
  529. }
  530. }
  531. // -----------------------------------------------------------------------------
  532. bool wsConnected() {
  533. return (_ws.count() > 0);
  534. }
  535. void wsSend(const char * payload) {
  536. if (_ws.count() > 0) {
  537. _ws.textAll(payload);
  538. }
  539. }
  540. void wsSend_P(PGM_P payload) {
  541. if (_ws.count() > 0) {
  542. char buffer[strlen_P(payload)];
  543. strcpy_P(buffer, payload);
  544. _ws.textAll(buffer);
  545. }
  546. }
  547. void wsSend(uint32_t client_id, const char * payload) {
  548. _ws.text(client_id, payload);
  549. }
  550. void wsSend_P(uint32_t client_id, PGM_P payload) {
  551. char buffer[strlen_P(payload)];
  552. strcpy_P(buffer, payload);
  553. _ws.text(client_id, buffer);
  554. }
  555. void wsSetup() {
  556. _ws.onEvent(_wsEvent);
  557. mqttRegister(_wsMQTTCallback);
  558. _server->addHandler(&_ws);
  559. _server->on("/auth", HTTP_GET, _onAuth);
  560. }
  561. // -----------------------------------------------------------------------------
  562. // API
  563. // -----------------------------------------------------------------------------
  564. bool _authAPI(AsyncWebServerRequest *request) {
  565. if (getSetting("apiEnabled", API_ENABLED).toInt() == 0) {
  566. DEBUG_MSG_P(PSTR("[WEBSERVER] HTTP API is not enabled\n"));
  567. request->send(403);
  568. return false;
  569. }
  570. if (!request->hasParam("apikey", (request->method() == HTTP_PUT))) {
  571. DEBUG_MSG_P(PSTR("[WEBSERVER] Missing apikey parameter\n"));
  572. request->send(403);
  573. return false;
  574. }
  575. AsyncWebParameter* p = request->getParam("apikey", (request->method() == HTTP_PUT));
  576. if (!p->value().equals(getSetting("apiKey"))) {
  577. DEBUG_MSG_P(PSTR("[WEBSERVER] Wrong apikey parameter\n"));
  578. request->send(403);
  579. return false;
  580. }
  581. return true;
  582. }
  583. bool _asJson(AsyncWebServerRequest *request) {
  584. bool asJson = false;
  585. if (request->hasHeader("Accept")) {
  586. AsyncWebHeader* h = request->getHeader("Accept");
  587. asJson = h->value().equals("application/json");
  588. }
  589. return asJson;
  590. }
  591. ArRequestHandlerFunction _bindAPI(unsigned int apiID) {
  592. return [apiID](AsyncWebServerRequest *request) {
  593. _webLog(request);
  594. if (!_authAPI(request)) return;
  595. web_api_t api = _apis[apiID];
  596. // Check if its a PUT
  597. if (api.putFn != NULL) {
  598. if (request->hasParam("value", request->method() == HTTP_PUT)) {
  599. AsyncWebParameter* p = request->getParam("value", request->method() == HTTP_PUT);
  600. (api.putFn)((p->value()).c_str());
  601. }
  602. }
  603. // Get response from callback
  604. char value[API_BUFFER_SIZE];
  605. (api.getFn)(value, API_BUFFER_SIZE);
  606. char *p = ltrim(value);
  607. // The response will be a 404 NOT FOUND if the resource is not available
  608. if (!value) {
  609. DEBUG_MSG_P(PSTR("[API] Sending 404 response\n"));
  610. request->send(404);
  611. return;
  612. }
  613. DEBUG_MSG_P(PSTR("[API] Sending response '%s'\n"), p);
  614. // Format response according to the Accept header
  615. if (_asJson(request)) {
  616. char buffer[64];
  617. snprintf_P(buffer, sizeof(buffer), PSTR("{ \"%s\": %s }"), api.key, p);
  618. request->send(200, "application/json", buffer);
  619. } else {
  620. request->send(200, "text/plain", p);
  621. }
  622. };
  623. }
  624. void _onAPIs(AsyncWebServerRequest *request) {
  625. _webLog(request);
  626. if (!_authAPI(request)) return;
  627. bool asJson = _asJson(request);
  628. String output;
  629. if (asJson) {
  630. DynamicJsonBuffer jsonBuffer;
  631. JsonObject& root = jsonBuffer.createObject();
  632. for (unsigned int i=0; i < _apis.size(); i++) {
  633. root[_apis[i].key] = _apis[i].url;
  634. }
  635. root.printTo(output);
  636. request->send(200, "application/json", output);
  637. } else {
  638. for (unsigned int i=0; i < _apis.size(); i++) {
  639. output += _apis[i].key + String(" -> ") + _apis[i].url + String("\n");
  640. }
  641. request->send(200, "text/plain", output);
  642. }
  643. }
  644. void _onRPC(AsyncWebServerRequest *request) {
  645. _webLog(request);
  646. if (!_authAPI(request)) return;
  647. //bool asJson = _asJson(request);
  648. int response = 404;
  649. if (request->hasParam("action")) {
  650. AsyncWebParameter* p = request->getParam("action");
  651. String action = p->value();
  652. DEBUG_MSG_P(PSTR("[RPC] Action: %s\n"), action.c_str());
  653. if (action.equals("reset")) {
  654. response = 200;
  655. _web_defer.once_ms(100, []() {
  656. customReset(CUSTOM_RESET_RPC);
  657. ESP.restart();
  658. });
  659. }
  660. }
  661. request->send(response);
  662. }
  663. // -----------------------------------------------------------------------------
  664. void apiRegister(const char * url, const char * key, apiGetCallbackFunction getFn, apiPutCallbackFunction putFn) {
  665. // Store it
  666. web_api_t api;
  667. char buffer[40];
  668. snprintf_P(buffer, sizeof(buffer), PSTR("/api/%s"), url);
  669. api.url = strdup(buffer);
  670. api.key = strdup(key);
  671. api.getFn = getFn;
  672. api.putFn = putFn;
  673. _apis.push_back(api);
  674. // Bind call
  675. unsigned int methods = HTTP_GET;
  676. if (putFn != NULL) methods += HTTP_PUT;
  677. _server->on(buffer, methods, _bindAPI(_apis.size() - 1));
  678. }
  679. void apiSetup() {
  680. _server->on("/apis", HTTP_GET, _onAPIs);
  681. _server->on("/rpc", HTTP_GET, _onRPC);
  682. }
  683. // -----------------------------------------------------------------------------
  684. // WEBSERVER
  685. // -----------------------------------------------------------------------------
  686. void _webLog(AsyncWebServerRequest *request) {
  687. DEBUG_MSG_P(PSTR("[WEBSERVER] Request: %s %s\n"), request->methodToString(), request->url().c_str());
  688. }
  689. bool _authenticate(AsyncWebServerRequest *request) {
  690. String password = getSetting("adminPass", ADMIN_PASS);
  691. char httpPassword[password.length() + 1];
  692. password.toCharArray(httpPassword, password.length() + 1);
  693. return request->authenticate(WEB_USERNAME, httpPassword);
  694. }
  695. void _onAuth(AsyncWebServerRequest *request) {
  696. _webLog(request);
  697. if (!_authenticate(request)) return request->requestAuthentication();
  698. IPAddress ip = request->client()->remoteIP();
  699. unsigned long now = millis();
  700. unsigned short index;
  701. for (index = 0; index < WS_BUFFER_SIZE; index++) {
  702. if (_ticket[index].ip == ip) break;
  703. if (_ticket[index].timestamp == 0) break;
  704. if (now - _ticket[index].timestamp > WS_TIMEOUT) break;
  705. }
  706. if (index == WS_BUFFER_SIZE) {
  707. request->send(429);
  708. } else {
  709. _ticket[index].ip = ip;
  710. _ticket[index].timestamp = now;
  711. request->send(204);
  712. }
  713. }
  714. void _onGetConfig(AsyncWebServerRequest *request) {
  715. _webLog(request);
  716. if (!_authenticate(request)) return request->requestAuthentication();
  717. AsyncJsonResponse * response = new AsyncJsonResponse();
  718. JsonObject& root = response->getRoot();
  719. root["app"] = APP_NAME;
  720. root["version"] = APP_VERSION;
  721. unsigned int size = settingsKeyCount();
  722. for (unsigned int i=0; i<size; i++) {
  723. String key = settingsKeyName(i);
  724. String value = getSetting(key);
  725. root[key] = value;
  726. }
  727. char buffer[100];
  728. snprintf_P(buffer, sizeof(buffer), PSTR("attachment; filename=\"%s-backup.json\""), (char *) getSetting("hostname").c_str());
  729. response->addHeader("Content-Disposition", buffer);
  730. response->setLength();
  731. request->send(response);
  732. }
  733. #if WEB_EMBEDDED
  734. void _onHome(AsyncWebServerRequest *request) {
  735. _webLog(request);
  736. if (request->header("If-Modified-Since").equals(_last_modified)) {
  737. request->send(304);
  738. } else {
  739. #if ASYNC_TCP_SSL_ENABLED
  740. // Chunked response, we calculate the chunks based on free heap (in multiples of 32)
  741. // This is necessary when a TLS connection is open since it sucks too much memory
  742. DEBUG_MSG_P(PSTR("[MAIN] Free heap: %d bytes\n"), ESP.getFreeHeap());
  743. size_t max = (ESP.getFreeHeap() / 3) & 0xFFE0;
  744. AsyncWebServerResponse *response = request->beginChunkedResponse("text/html", [max](uint8_t *buffer, size_t maxLen, size_t index) -> size_t {
  745. // Get the chunk based on the index and maxLen
  746. size_t len = index_html_gz_len - index;
  747. if (len > maxLen) len = maxLen;
  748. if (len > max) len = max;
  749. if (len > 0) memcpy_P(buffer, index_html_gz + index, len);
  750. DEBUG_MSG_P(PSTR("[WEB] Sending %d%%%% (max chunk size: %4d)\r"), int(100 * index / index_html_gz_len), max);
  751. if (len == 0) DEBUG_MSG_P(PSTR("\n"));
  752. // Return the actual length of the chunk (0 for end of file)
  753. return len;
  754. });
  755. #else
  756. AsyncWebServerResponse *response = request->beginResponse_P(200, "text/html", index_html_gz, index_html_gz_len);
  757. #endif
  758. response->addHeader("Content-Encoding", "gzip");
  759. response->addHeader("Last-Modified", _last_modified);
  760. request->send(response);
  761. }
  762. }
  763. #endif
  764. #if ASYNC_TCP_SSL_ENABLED & WEB_SSL_ENABLED
  765. int _onCertificate(void * arg, const char *filename, uint8_t **buf) {
  766. #if WEB_EMBEDDED
  767. if (strcmp(filename, "server.cer") == 0) {
  768. uint8_t * nbuf = (uint8_t*) malloc(server_cer_len);
  769. memcpy_P(nbuf, server_cer, server_cer_len);
  770. *buf = nbuf;
  771. DEBUG_MSG_P(PSTR("[WEB] SSL File: %s - OK\n"), filename);
  772. return server_cer_len;
  773. }
  774. if (strcmp(filename, "server.key") == 0) {
  775. uint8_t * nbuf = (uint8_t*) malloc(server_key_len);
  776. memcpy_P(nbuf, server_key, server_key_len);
  777. *buf = nbuf;
  778. DEBUG_MSG_P(PSTR("[WEB] SSL File: %s - OK\n"), filename);
  779. return server_key_len;
  780. }
  781. DEBUG_MSG_P(PSTR("[WEB] SSL File: %s - ERROR\n"), filename);
  782. *buf = 0;
  783. return 0;
  784. #else
  785. File file = SPIFFS.open(filename, "r");
  786. if (file) {
  787. size_t size = file.size();
  788. uint8_t * nbuf = (uint8_t*) malloc(size);
  789. if (nbuf) {
  790. size = file.read(nbuf, size);
  791. file.close();
  792. *buf = nbuf;
  793. DEBUG_MSG_P(PSTR("[WEB] SSL File: %s - OK\n"), filename);
  794. return size;
  795. }
  796. file.close();
  797. }
  798. DEBUG_MSG_P(PSTR("[WEB] SSL File: %s - ERROR\n"), filename);
  799. *buf = 0;
  800. return 0;
  801. #endif
  802. }
  803. #endif
  804. void _onUpgrade(AsyncWebServerRequest *request) {
  805. AsyncWebServerResponse *response = request->beginResponse(200, "text/plain", Update.hasError() ? "FAIL" : "OK");
  806. response->addHeader("Connection", "close");
  807. if (!Update.hasError()) {
  808. _web_defer.once_ms(100, []() {
  809. customReset(CUSTOM_RESET_UPGRADE);
  810. ESP.restart();
  811. });
  812. }
  813. request->send(response);
  814. }
  815. void _onUpgradeData(AsyncWebServerRequest *request, String filename, size_t index, uint8_t *data, size_t len, bool final) {
  816. if (!index) {
  817. DEBUG_MSG_P(PSTR("[UPGRADE] Start: %s\n"), filename.c_str());
  818. Update.runAsync(true);
  819. if (!Update.begin((ESP.getFreeSketchSpace() - 0x1000) & 0xFFFFF000)) {
  820. #ifdef DEBUG_PORT
  821. Update.printError(DEBUG_PORT);
  822. #endif
  823. }
  824. }
  825. if (!Update.hasError()) {
  826. if (Update.write(data, len) != len) {
  827. #ifdef DEBUG_PORT
  828. Update.printError(DEBUG_PORT);
  829. #endif
  830. }
  831. }
  832. if (final) {
  833. if (Update.end(true)){
  834. DEBUG_MSG_P(PSTR("[UPGRADE] Success: %u bytes\n"), index + len);
  835. } else {
  836. #ifdef DEBUG_PORT
  837. Update.printError(DEBUG_PORT);
  838. #endif
  839. }
  840. } else {
  841. DEBUG_MSG_P(PSTR("[UPGRADE] Progress: %u bytes\r"), index + len);
  842. }
  843. }
  844. // -----------------------------------------------------------------------------
  845. void webSetup() {
  846. // Cache the Last-Modifier header value
  847. snprintf_P(_last_modified, sizeof(_last_modified), PSTR("%s %s GMT"), __DATE__, __TIME__);
  848. // Create server
  849. #if ASYNC_TCP_SSL_ENABLED & WEB_SSL_ENABLED
  850. unsigned int port = 443;
  851. #else
  852. unsigned int port = getSetting("webPort", WEB_PORT).toInt();
  853. #endif
  854. _server = new AsyncWebServer(port);
  855. // Setup websocket
  856. wsSetup();
  857. // API setup
  858. apiSetup();
  859. // Rewrites
  860. _server->rewrite("/", "/index.html");
  861. // Serve home (basic authentication protection)
  862. #if WEB_EMBEDDED
  863. _server->on("/index.html", HTTP_GET, _onHome);
  864. #endif
  865. _server->on("/config", HTTP_GET, _onGetConfig);
  866. _server->on("/upgrade", HTTP_POST, _onUpgrade, _onUpgradeData);
  867. // Serve static files
  868. #if SPIFFS_SUPPORT
  869. _server->serveStatic("/", SPIFFS, "/")
  870. .setLastModified(_last_modified)
  871. .setFilter([](AsyncWebServerRequest *request) -> bool {
  872. _webLog(request);
  873. return true;
  874. });
  875. #endif
  876. // 404
  877. _server->onNotFound([](AsyncWebServerRequest *request){
  878. request->send(404);
  879. });
  880. // Run server
  881. #if ASYNC_TCP_SSL_ENABLED & WEB_SSL_ENABLED
  882. _server->onSslFileRequest(_onCertificate, NULL);
  883. _server->beginSecure("server.cer", "server.key", NULL);
  884. #else
  885. _server->begin();
  886. #endif
  887. DEBUG_MSG_P(PSTR("[WEBSERVER] Webserver running on port %d\n"), port);
  888. }
  889. #endif // WEB_SUPPORT