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.

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