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.

1143 lines
35 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["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["wifiGain"] = getSetting("wifiGain", WIFI_GAIN).toFloat();
  470. root["maxNetworks"] = WIFI_MAX_NETWORKS;
  471. JsonArray& wifi = root.createNestedArray("wifi");
  472. for (byte i=0; i<WIFI_MAX_NETWORKS; i++) {
  473. if (getSetting("ssid" + String(i)).length() == 0) break;
  474. JsonObject& network = wifi.createNestedObject();
  475. network["ssid"] = getSetting("ssid" + String(i));
  476. network["pass"] = getSetting("pass" + String(i));
  477. network["ip"] = getSetting("ip" + String(i));
  478. network["gw"] = getSetting("gw" + String(i));
  479. network["mask"] = getSetting("mask" + String(i));
  480. network["dns"] = getSetting("dns" + String(i));
  481. }
  482. }
  483. String output;
  484. root.printTo(output);
  485. wsSend(client_id, (char *) output.c_str());
  486. }
  487. bool _wsAuth(AsyncWebSocketClient * client) {
  488. IPAddress ip = client->remoteIP();
  489. unsigned long now = millis();
  490. unsigned short index = 0;
  491. for (index = 0; index < WS_BUFFER_SIZE; index++) {
  492. if ((_ticket[index].ip == ip) && (now - _ticket[index].timestamp < WS_TIMEOUT)) break;
  493. }
  494. if (index == WS_BUFFER_SIZE) {
  495. DEBUG_MSG_P(PSTR("[WEBSOCKET] Validation check failed\n"));
  496. wsSend_P(client->id(), PSTR("{\"message\": \"Session expired, please reload page...\"}"));
  497. return false;
  498. }
  499. return true;
  500. }
  501. void _wsEvent(AsyncWebSocket * server, AsyncWebSocketClient * client, AwsEventType type, void * arg, uint8_t *data, size_t len){
  502. static uint8_t * message;
  503. // Authorize
  504. #ifndef NOWSAUTH
  505. if (!_wsAuth(client)) return;
  506. #endif
  507. if (type == WS_EVT_CONNECT) {
  508. IPAddress ip = client->remoteIP();
  509. 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());
  510. _wsStart(client->id());
  511. } else if(type == WS_EVT_DISCONNECT) {
  512. DEBUG_MSG_P(PSTR("[WEBSOCKET] #%u disconnected\n"), client->id());
  513. } else if(type == WS_EVT_ERROR) {
  514. DEBUG_MSG_P(PSTR("[WEBSOCKET] #%u error(%u): %s\n"), client->id(), *((uint16_t*)arg), (char*)data);
  515. } else if(type == WS_EVT_PONG) {
  516. DEBUG_MSG_P(PSTR("[WEBSOCKET] #%u pong(%u): %s\n"), client->id(), len, len ? (char*) data : "");
  517. } else if(type == WS_EVT_DATA) {
  518. AwsFrameInfo * info = (AwsFrameInfo*)arg;
  519. // First packet
  520. if (info->index == 0) {
  521. message = (uint8_t*) malloc(info->len);
  522. }
  523. // Store data
  524. memcpy(message + info->index, data, len);
  525. // Last packet
  526. if (info->index + len == info->len) {
  527. _wsParse(client->id(), message, info->len);
  528. free(message);
  529. }
  530. }
  531. }
  532. // -----------------------------------------------------------------------------
  533. bool wsConnected() {
  534. return (_ws.count() > 0);
  535. }
  536. void wsSend(const char * payload) {
  537. if (_ws.count() > 0) {
  538. _ws.textAll(payload);
  539. }
  540. }
  541. void wsSend_P(PGM_P payload) {
  542. if (_ws.count() > 0) {
  543. char buffer[strlen_P(payload)];
  544. strcpy_P(buffer, payload);
  545. _ws.textAll(buffer);
  546. }
  547. }
  548. void wsSend(uint32_t client_id, const char * payload) {
  549. _ws.text(client_id, payload);
  550. }
  551. void wsSend_P(uint32_t client_id, PGM_P payload) {
  552. char buffer[strlen_P(payload)];
  553. strcpy_P(buffer, payload);
  554. _ws.text(client_id, buffer);
  555. }
  556. void wsSetup() {
  557. _ws.onEvent(_wsEvent);
  558. mqttRegister(_wsMQTTCallback);
  559. _server->addHandler(&_ws);
  560. _server->on("/auth", HTTP_GET, _onAuth);
  561. }
  562. // -----------------------------------------------------------------------------
  563. // API
  564. // -----------------------------------------------------------------------------
  565. bool _authAPI(AsyncWebServerRequest *request) {
  566. if (getSetting("apiEnabled", API_ENABLED).toInt() == 0) {
  567. DEBUG_MSG_P(PSTR("[WEBSERVER] HTTP API is not enabled\n"));
  568. request->send(403);
  569. return false;
  570. }
  571. if (!request->hasParam("apikey", (request->method() == HTTP_PUT))) {
  572. DEBUG_MSG_P(PSTR("[WEBSERVER] Missing apikey parameter\n"));
  573. request->send(403);
  574. return false;
  575. }
  576. AsyncWebParameter* p = request->getParam("apikey", (request->method() == HTTP_PUT));
  577. if (!p->value().equals(getSetting("apiKey"))) {
  578. DEBUG_MSG_P(PSTR("[WEBSERVER] Wrong apikey parameter\n"));
  579. request->send(403);
  580. return false;
  581. }
  582. return true;
  583. }
  584. bool _asJson(AsyncWebServerRequest *request) {
  585. bool asJson = false;
  586. if (request->hasHeader("Accept")) {
  587. AsyncWebHeader* h = request->getHeader("Accept");
  588. asJson = h->value().equals("application/json");
  589. }
  590. return asJson;
  591. }
  592. ArRequestHandlerFunction _bindAPI(unsigned int apiID) {
  593. return [apiID](AsyncWebServerRequest *request) {
  594. _webLog(request);
  595. if (!_authAPI(request)) return;
  596. web_api_t api = _apis[apiID];
  597. // Check if its a PUT
  598. if (api.putFn != NULL) {
  599. if (request->hasParam("value", request->method() == HTTP_PUT)) {
  600. AsyncWebParameter* p = request->getParam("value", request->method() == HTTP_PUT);
  601. (api.putFn)((p->value()).c_str());
  602. }
  603. }
  604. // Get response from callback
  605. char value[API_BUFFER_SIZE];
  606. (api.getFn)(value, API_BUFFER_SIZE);
  607. char *p = ltrim(value);
  608. // The response will be a 404 NOT FOUND if the resource is not available
  609. if (!value) {
  610. DEBUG_MSG_P(PSTR("[API] Sending 404 response\n"));
  611. request->send(404);
  612. return;
  613. }
  614. DEBUG_MSG_P(PSTR("[API] Sending response '%s'\n"), p);
  615. // Format response according to the Accept header
  616. if (_asJson(request)) {
  617. char buffer[64];
  618. snprintf_P(buffer, sizeof(buffer), PSTR("{ \"%s\": %s }"), api.key, p);
  619. request->send(200, "application/json", buffer);
  620. } else {
  621. request->send(200, "text/plain", p);
  622. }
  623. };
  624. }
  625. void _onAPIs(AsyncWebServerRequest *request) {
  626. _webLog(request);
  627. if (!_authAPI(request)) return;
  628. bool asJson = _asJson(request);
  629. String output;
  630. if (asJson) {
  631. DynamicJsonBuffer jsonBuffer;
  632. JsonObject& root = jsonBuffer.createObject();
  633. for (unsigned int i=0; i < _apis.size(); i++) {
  634. root[_apis[i].key] = _apis[i].url;
  635. }
  636. root.printTo(output);
  637. request->send(200, "application/json", output);
  638. } else {
  639. for (unsigned int i=0; i < _apis.size(); i++) {
  640. output += _apis[i].key + String(" -> ") + _apis[i].url + String("\n");
  641. }
  642. request->send(200, "text/plain", output);
  643. }
  644. }
  645. void _onRPC(AsyncWebServerRequest *request) {
  646. _webLog(request);
  647. if (!_authAPI(request)) return;
  648. //bool asJson = _asJson(request);
  649. int response = 404;
  650. if (request->hasParam("action")) {
  651. AsyncWebParameter* p = request->getParam("action");
  652. String action = p->value();
  653. DEBUG_MSG_P(PSTR("[RPC] Action: %s\n"), action.c_str());
  654. if (action.equals("reset")) {
  655. response = 200;
  656. _web_defer.once_ms(100, []() {
  657. customReset(CUSTOM_RESET_RPC);
  658. ESP.restart();
  659. });
  660. }
  661. }
  662. request->send(response);
  663. }
  664. // -----------------------------------------------------------------------------
  665. void apiRegister(const char * url, const char * key, apiGetCallbackFunction getFn, apiPutCallbackFunction putFn) {
  666. // Store it
  667. web_api_t api;
  668. char buffer[40];
  669. snprintf_P(buffer, sizeof(buffer), PSTR("/api/%s"), url);
  670. api.url = strdup(buffer);
  671. api.key = strdup(key);
  672. api.getFn = getFn;
  673. api.putFn = putFn;
  674. _apis.push_back(api);
  675. // Bind call
  676. unsigned int methods = HTTP_GET;
  677. if (putFn != NULL) methods += HTTP_PUT;
  678. _server->on(buffer, methods, _bindAPI(_apis.size() - 1));
  679. }
  680. void apiSetup() {
  681. _server->on("/apis", HTTP_GET, _onAPIs);
  682. _server->on("/rpc", HTTP_GET, _onRPC);
  683. }
  684. // -----------------------------------------------------------------------------
  685. // WEBSERVER
  686. // -----------------------------------------------------------------------------
  687. void _webLog(AsyncWebServerRequest *request) {
  688. DEBUG_MSG_P(PSTR("[WEBSERVER] Request: %s %s\n"), request->methodToString(), request->url().c_str());
  689. }
  690. bool _authenticate(AsyncWebServerRequest *request) {
  691. String password = getSetting("adminPass", ADMIN_PASS);
  692. char httpPassword[password.length() + 1];
  693. password.toCharArray(httpPassword, password.length() + 1);
  694. return request->authenticate(WEB_USERNAME, httpPassword);
  695. }
  696. void _onAuth(AsyncWebServerRequest *request) {
  697. _webLog(request);
  698. if (!_authenticate(request)) return request->requestAuthentication();
  699. IPAddress ip = request->client()->remoteIP();
  700. unsigned long now = millis();
  701. unsigned short index;
  702. for (index = 0; index < WS_BUFFER_SIZE; index++) {
  703. if (_ticket[index].ip == ip) break;
  704. if (_ticket[index].timestamp == 0) break;
  705. if (now - _ticket[index].timestamp > WS_TIMEOUT) break;
  706. }
  707. if (index == WS_BUFFER_SIZE) {
  708. request->send(429);
  709. } else {
  710. _ticket[index].ip = ip;
  711. _ticket[index].timestamp = now;
  712. request->send(204);
  713. }
  714. }
  715. void _onGetConfig(AsyncWebServerRequest *request) {
  716. _webLog(request);
  717. if (!_authenticate(request)) return request->requestAuthentication();
  718. AsyncJsonResponse * response = new AsyncJsonResponse();
  719. JsonObject& root = response->getRoot();
  720. root["app"] = APP_NAME;
  721. root["version"] = APP_VERSION;
  722. unsigned int size = settingsKeyCount();
  723. for (unsigned int i=0; i<size; i++) {
  724. String key = settingsKeyName(i);
  725. String value = getSetting(key);
  726. root[key] = value;
  727. }
  728. char buffer[100];
  729. snprintf_P(buffer, sizeof(buffer), PSTR("attachment; filename=\"%s-backup.json\""), (char *) getSetting("hostname").c_str());
  730. response->addHeader("Content-Disposition", buffer);
  731. response->setLength();
  732. request->send(response);
  733. }
  734. #if WEB_EMBEDDED
  735. void _onHome(AsyncWebServerRequest *request) {
  736. _webLog(request);
  737. if (request->header("If-Modified-Since").equals(_last_modified)) {
  738. request->send(304);
  739. } else {
  740. #if ASYNC_TCP_SSL_ENABLED
  741. // Chunked response, we calculate the chunks based on free heap (in multiples of 32)
  742. // This is necessary when a TLS connection is open since it sucks too much memory
  743. DEBUG_MSG_P(PSTR("[MAIN] Free heap: %d bytes\n"), ESP.getFreeHeap());
  744. size_t max = (ESP.getFreeHeap() / 3) & 0xFFE0;
  745. AsyncWebServerResponse *response = request->beginChunkedResponse("text/html", [max](uint8_t *buffer, size_t maxLen, size_t index) -> size_t {
  746. // Get the chunk based on the index and maxLen
  747. size_t len = index_html_gz_len - index;
  748. if (len > maxLen) len = maxLen;
  749. if (len > max) len = max;
  750. if (len > 0) memcpy_P(buffer, index_html_gz + index, len);
  751. DEBUG_MSG_P(PSTR("[WEB] Sending %d%%%% (max chunk size: %4d)\r"), int(100 * index / index_html_gz_len), max);
  752. if (len == 0) DEBUG_MSG_P(PSTR("\n"));
  753. // Return the actual length of the chunk (0 for end of file)
  754. return len;
  755. });
  756. #else
  757. AsyncWebServerResponse *response = request->beginResponse_P(200, "text/html", index_html_gz, index_html_gz_len);
  758. #endif
  759. response->addHeader("Content-Encoding", "gzip");
  760. response->addHeader("Last-Modified", _last_modified);
  761. request->send(response);
  762. }
  763. }
  764. #endif
  765. #if ASYNC_TCP_SSL_ENABLED & WEB_SSL_ENABLED
  766. int _onCertificate(void * arg, const char *filename, uint8_t **buf) {
  767. #if WEB_EMBEDDED
  768. if (strcmp(filename, "server.cer") == 0) {
  769. uint8_t * nbuf = (uint8_t*) malloc(server_cer_len);
  770. memcpy_P(nbuf, server_cer, server_cer_len);
  771. *buf = nbuf;
  772. DEBUG_MSG_P(PSTR("[WEB] SSL File: %s - OK\n"), filename);
  773. return server_cer_len;
  774. }
  775. if (strcmp(filename, "server.key") == 0) {
  776. uint8_t * nbuf = (uint8_t*) malloc(server_key_len);
  777. memcpy_P(nbuf, server_key, server_key_len);
  778. *buf = nbuf;
  779. DEBUG_MSG_P(PSTR("[WEB] SSL File: %s - OK\n"), filename);
  780. return server_key_len;
  781. }
  782. DEBUG_MSG_P(PSTR("[WEB] SSL File: %s - ERROR\n"), filename);
  783. *buf = 0;
  784. return 0;
  785. #else
  786. File file = SPIFFS.open(filename, "r");
  787. if (file) {
  788. size_t size = file.size();
  789. uint8_t * nbuf = (uint8_t*) malloc(size);
  790. if (nbuf) {
  791. size = file.read(nbuf, size);
  792. file.close();
  793. *buf = nbuf;
  794. DEBUG_MSG_P(PSTR("[WEB] SSL File: %s - OK\n"), filename);
  795. return size;
  796. }
  797. file.close();
  798. }
  799. DEBUG_MSG_P(PSTR("[WEB] SSL File: %s - ERROR\n"), filename);
  800. *buf = 0;
  801. return 0;
  802. #endif
  803. }
  804. #endif
  805. void _onUpgrade(AsyncWebServerRequest *request) {
  806. AsyncWebServerResponse *response = request->beginResponse(200, "text/plain", Update.hasError() ? "FAIL" : "OK");
  807. response->addHeader("Connection", "close");
  808. if (!Update.hasError()) {
  809. _web_defer.once_ms(100, []() {
  810. customReset(CUSTOM_RESET_UPGRADE);
  811. ESP.restart();
  812. });
  813. }
  814. request->send(response);
  815. }
  816. void _onUpgradeData(AsyncWebServerRequest *request, String filename, size_t index, uint8_t *data, size_t len, bool final) {
  817. if (!index) {
  818. DEBUG_MSG_P(PSTR("[UPGRADE] Start: %s\n"), filename.c_str());
  819. Update.runAsync(true);
  820. if (!Update.begin((ESP.getFreeSketchSpace() - 0x1000) & 0xFFFFF000)) {
  821. #ifdef DEBUG_PORT
  822. Update.printError(DEBUG_PORT);
  823. #endif
  824. }
  825. }
  826. if (!Update.hasError()) {
  827. if (Update.write(data, len) != len) {
  828. #ifdef DEBUG_PORT
  829. Update.printError(DEBUG_PORT);
  830. #endif
  831. }
  832. }
  833. if (final) {
  834. if (Update.end(true)){
  835. DEBUG_MSG_P(PSTR("[UPGRADE] Success: %u bytes\n"), index + len);
  836. } else {
  837. #ifdef DEBUG_PORT
  838. Update.printError(DEBUG_PORT);
  839. #endif
  840. }
  841. } else {
  842. DEBUG_MSG_P(PSTR("[UPGRADE] Progress: %u bytes\r"), index + len);
  843. }
  844. }
  845. // -----------------------------------------------------------------------------
  846. void webSetup() {
  847. // Cache the Last-Modifier header value
  848. snprintf_P(_last_modified, sizeof(_last_modified), PSTR("%s %s GMT"), __DATE__, __TIME__);
  849. // Create server
  850. #if ASYNC_TCP_SSL_ENABLED & WEB_SSL_ENABLED
  851. unsigned int port = 443;
  852. #else
  853. unsigned int port = getSetting("webPort", WEB_PORT).toInt();
  854. #endif
  855. _server = new AsyncWebServer(port);
  856. // Setup websocket
  857. wsSetup();
  858. // API setup
  859. apiSetup();
  860. // Rewrites
  861. _server->rewrite("/", "/index.html");
  862. // Serve home (basic authentication protection)
  863. #if WEB_EMBEDDED
  864. _server->on("/index.html", HTTP_GET, _onHome);
  865. #endif
  866. _server->on("/config", HTTP_GET, _onGetConfig);
  867. _server->on("/upgrade", HTTP_POST, _onUpgrade, _onUpgradeData);
  868. // Serve static files
  869. #if SPIFFS_SUPPORT
  870. _server->serveStatic("/", SPIFFS, "/")
  871. .setLastModified(_last_modified)
  872. .setFilter([](AsyncWebServerRequest *request) -> bool {
  873. _webLog(request);
  874. return true;
  875. });
  876. #endif
  877. // 404
  878. _server->onNotFound([](AsyncWebServerRequest *request){
  879. request->send(404);
  880. });
  881. // Run server
  882. #if ASYNC_TCP_SSL_ENABLED & WEB_SSL_ENABLED
  883. _server->onSslFileRequest(_onCertificate, NULL);
  884. _server->beginSecure("server.cer", "server.key", NULL);
  885. #else
  886. _server->begin();
  887. #endif
  888. DEBUG_MSG_P(PSTR("[WEBSERVER] Webserver running on port %d\n"), port);
  889. }
  890. #endif // WEB_SUPPORT