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.

1200 lines
36 KiB

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