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.

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