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.

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