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.

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