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.

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