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.

1162 lines
36 KiB

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