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.

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