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.

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