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.

1188 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
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. // The response will be a 404 NOT FOUND if the resource is not available
  641. if (!value) {
  642. DEBUG_MSG_P(PSTR("[API] Sending 404 response\n"));
  643. request->send(404);
  644. return;
  645. }
  646. DEBUG_MSG_P(PSTR("[API] Sending response '%s'\n"), value);
  647. // Format response according to the Accept header
  648. if (_asJson(request)) {
  649. char buffer[64];
  650. snprintf_P(buffer, sizeof(buffer), PSTR("{ \"%s\": %s }"), api.key, value);
  651. request->send(200, "application/json", buffer);
  652. } else {
  653. request->send(200, "text/plain", value);
  654. }
  655. };
  656. }
  657. void _onAPIs(AsyncWebServerRequest *request) {
  658. _webLog(request);
  659. if (!_authAPI(request)) return;
  660. bool asJson = _asJson(request);
  661. String output;
  662. if (asJson) {
  663. DynamicJsonBuffer jsonBuffer;
  664. JsonObject& root = jsonBuffer.createObject();
  665. for (unsigned int i=0; i < _apis.size(); i++) {
  666. root[_apis[i].key] = _apis[i].url;
  667. }
  668. root.printTo(output);
  669. request->send(200, "application/json", output);
  670. } else {
  671. for (unsigned int i=0; i < _apis.size(); i++) {
  672. output += _apis[i].key + String(" -> ") + _apis[i].url + String("\n");
  673. }
  674. request->send(200, "text/plain", output);
  675. }
  676. }
  677. void _onRPC(AsyncWebServerRequest *request) {
  678. _webLog(request);
  679. if (!_authAPI(request)) return;
  680. //bool asJson = _asJson(request);
  681. int response = 404;
  682. if (request->hasParam("action")) {
  683. AsyncWebParameter* p = request->getParam("action");
  684. String action = p->value();
  685. DEBUG_MSG_P(PSTR("[RPC] Action: %s\n"), action.c_str());
  686. if (action.equals("reset")) {
  687. response = 200;
  688. _web_defer.once_ms(100, []() {
  689. customReset(CUSTOM_RESET_RPC);
  690. ESP.restart();
  691. });
  692. }
  693. }
  694. request->send(response);
  695. }
  696. // -----------------------------------------------------------------------------
  697. void apiRegister(const char * url, const char * key, apiGetCallbackFunction getFn, apiPutCallbackFunction putFn) {
  698. // Store it
  699. web_api_t api;
  700. char buffer[40];
  701. snprintf_P(buffer, sizeof(buffer), PSTR("/api/%s"), url);
  702. api.url = strdup(buffer);
  703. api.key = strdup(key);
  704. api.getFn = getFn;
  705. api.putFn = putFn;
  706. _apis.push_back(api);
  707. // Bind call
  708. unsigned int methods = HTTP_GET;
  709. if (putFn != NULL) methods += HTTP_PUT;
  710. _server->on(buffer, methods, _bindAPI(_apis.size() - 1));
  711. }
  712. void apiSetup() {
  713. _server->on("/apis", HTTP_GET, _onAPIs);
  714. _server->on("/rpc", HTTP_GET, _onRPC);
  715. }
  716. // -----------------------------------------------------------------------------
  717. // WEBSERVER
  718. // -----------------------------------------------------------------------------
  719. void _webLog(AsyncWebServerRequest *request) {
  720. DEBUG_MSG_P(PSTR("[WEBSERVER] Request: %s %s\n"), request->methodToString(), request->url().c_str());
  721. }
  722. bool _authenticate(AsyncWebServerRequest *request) {
  723. String password = getSetting("adminPass", ADMIN_PASS);
  724. char httpPassword[password.length() + 1];
  725. password.toCharArray(httpPassword, password.length() + 1);
  726. return request->authenticate(WEB_USERNAME, httpPassword);
  727. }
  728. void _onAuth(AsyncWebServerRequest *request) {
  729. _webLog(request);
  730. if (!_authenticate(request)) return request->requestAuthentication();
  731. IPAddress ip = request->client()->remoteIP();
  732. unsigned long now = millis();
  733. unsigned short index;
  734. for (index = 0; index < WS_BUFFER_SIZE; index++) {
  735. if (_ticket[index].ip == ip) break;
  736. if (_ticket[index].timestamp == 0) break;
  737. if (now - _ticket[index].timestamp > WS_TIMEOUT) break;
  738. }
  739. if (index == WS_BUFFER_SIZE) {
  740. request->send(429);
  741. } else {
  742. _ticket[index].ip = ip;
  743. _ticket[index].timestamp = now;
  744. request->send(204);
  745. }
  746. }
  747. void _onGetConfig(AsyncWebServerRequest *request) {
  748. _webLog(request);
  749. if (!_authenticate(request)) return request->requestAuthentication();
  750. AsyncJsonResponse * response = new AsyncJsonResponse();
  751. JsonObject& root = response->getRoot();
  752. root["app"] = APP_NAME;
  753. root["version"] = APP_VERSION;
  754. unsigned int size = settingsKeyCount();
  755. for (unsigned int i=0; i<size; i++) {
  756. String key = settingsKeyName(i);
  757. String value = getSetting(key);
  758. root[key] = value;
  759. }
  760. char buffer[100];
  761. snprintf_P(buffer, sizeof(buffer), PSTR("attachment; filename=\"%s-backup.json\""), (char *) getSetting("hostname").c_str());
  762. response->addHeader("Content-Disposition", buffer);
  763. response->setLength();
  764. request->send(response);
  765. }
  766. #if WEB_EMBEDDED
  767. void _onHome(AsyncWebServerRequest *request) {
  768. _webLog(request);
  769. if (request->header("If-Modified-Since").equals(_last_modified)) {
  770. request->send(304);
  771. } else {
  772. #if ASYNC_TCP_SSL_ENABLED
  773. // Chunked response, we calculate the chunks based on free heap (in multiples of 32)
  774. // This is necessary when a TLS connection is open since it sucks too much memory
  775. DEBUG_MSG_P(PSTR("[MAIN] Free heap: %d bytes\n"), ESP.getFreeHeap());
  776. size_t max = (ESP.getFreeHeap() / 3) & 0xFFE0;
  777. AsyncWebServerResponse *response = request->beginChunkedResponse("text/html", [max](uint8_t *buffer, size_t maxLen, size_t index) -> size_t {
  778. // Get the chunk based on the index and maxLen
  779. size_t len = index_html_gz_len - index;
  780. if (len > maxLen) len = maxLen;
  781. if (len > max) len = max;
  782. if (len > 0) memcpy_P(buffer, index_html_gz + index, len);
  783. DEBUG_MSG_P(PSTR("[WEB] Sending %d%%%% (max chunk size: %4d)\r"), int(100 * index / index_html_gz_len), max);
  784. if (len == 0) DEBUG_MSG_P(PSTR("\n"));
  785. // Return the actual length of the chunk (0 for end of file)
  786. return len;
  787. });
  788. #else
  789. AsyncWebServerResponse *response = request->beginResponse_P(200, "text/html", index_html_gz, index_html_gz_len);
  790. #endif
  791. response->addHeader("Content-Encoding", "gzip");
  792. response->addHeader("Last-Modified", _last_modified);
  793. request->send(response);
  794. }
  795. }
  796. #endif
  797. #if ASYNC_TCP_SSL_ENABLED & WEB_SSL_ENABLED
  798. int _onCertificate(void * arg, const char *filename, uint8_t **buf) {
  799. #if WEB_EMBEDDED
  800. if (strcmp(filename, "server.cer") == 0) {
  801. uint8_t * nbuf = (uint8_t*) malloc(server_cer_len);
  802. memcpy_P(nbuf, server_cer, server_cer_len);
  803. *buf = nbuf;
  804. DEBUG_MSG_P(PSTR("[WEB] SSL File: %s - OK\n"), filename);
  805. return server_cer_len;
  806. }
  807. if (strcmp(filename, "server.key") == 0) {
  808. uint8_t * nbuf = (uint8_t*) malloc(server_key_len);
  809. memcpy_P(nbuf, server_key, server_key_len);
  810. *buf = nbuf;
  811. DEBUG_MSG_P(PSTR("[WEB] SSL File: %s - OK\n"), filename);
  812. return server_key_len;
  813. }
  814. DEBUG_MSG_P(PSTR("[WEB] SSL File: %s - ERROR\n"), filename);
  815. *buf = 0;
  816. return 0;
  817. #else
  818. File file = SPIFFS.open(filename, "r");
  819. if (file) {
  820. size_t size = file.size();
  821. uint8_t * nbuf = (uint8_t*) malloc(size);
  822. if (nbuf) {
  823. size = file.read(nbuf, size);
  824. file.close();
  825. *buf = nbuf;
  826. DEBUG_MSG_P(PSTR("[WEB] SSL File: %s - OK\n"), filename);
  827. return size;
  828. }
  829. file.close();
  830. }
  831. DEBUG_MSG_P(PSTR("[WEB] SSL File: %s - ERROR\n"), filename);
  832. *buf = 0;
  833. return 0;
  834. #endif
  835. }
  836. #endif
  837. void _onUpgrade(AsyncWebServerRequest *request) {
  838. char buffer[10];
  839. if (!Update.hasError()) {
  840. sprintf_P(buffer, PSTR("OK"));
  841. } else {
  842. sprintf_P(buffer, PSTR("ERROR %d"), Update.getError());
  843. }
  844. AsyncWebServerResponse *response = request->beginResponse(200, "text/plain", buffer);
  845. response->addHeader("Connection", "close");
  846. if (!Update.hasError()) {
  847. _web_defer.once_ms(100, []() {
  848. customReset(CUSTOM_RESET_UPGRADE);
  849. ESP.restart();
  850. });
  851. }
  852. request->send(response);
  853. }
  854. void _onUpgradeData(AsyncWebServerRequest *request, String filename, size_t index, uint8_t *data, size_t len, bool final) {
  855. if (!index) {
  856. DEBUG_MSG_P(PSTR("[UPGRADE] Start: %s\n"), filename.c_str());
  857. Update.runAsync(true);
  858. if (!Update.begin((ESP.getFreeSketchSpace() - 0x1000) & 0xFFFFF000)) {
  859. #ifdef DEBUG_PORT
  860. Update.printError(DEBUG_PORT);
  861. #endif
  862. }
  863. }
  864. if (!Update.hasError()) {
  865. if (Update.write(data, len) != len) {
  866. #ifdef DEBUG_PORT
  867. Update.printError(DEBUG_PORT);
  868. #endif
  869. }
  870. }
  871. if (final) {
  872. if (Update.end(true)){
  873. DEBUG_MSG_P(PSTR("[UPGRADE] Success: %u bytes\n"), index + len);
  874. } else {
  875. #ifdef DEBUG_PORT
  876. Update.printError(DEBUG_PORT);
  877. #endif
  878. }
  879. } else {
  880. DEBUG_MSG_P(PSTR("[UPGRADE] Progress: %u bytes\r"), index + len);
  881. }
  882. }
  883. // -----------------------------------------------------------------------------
  884. void webSetup() {
  885. // Cache the Last-Modifier header value
  886. snprintf_P(_last_modified, sizeof(_last_modified), PSTR("%s %s GMT"), __DATE__, __TIME__);
  887. // Create server
  888. #if ASYNC_TCP_SSL_ENABLED & WEB_SSL_ENABLED
  889. unsigned int port = 443;
  890. #else
  891. unsigned int port = getSetting("webPort", WEB_PORT).toInt();
  892. #endif
  893. _server = new AsyncWebServer(port);
  894. // Setup websocket
  895. wsSetup();
  896. // API setup
  897. apiSetup();
  898. // Rewrites
  899. _server->rewrite("/", "/index.html");
  900. // Serve home (basic authentication protection)
  901. #if WEB_EMBEDDED
  902. _server->on("/index.html", HTTP_GET, _onHome);
  903. #endif
  904. _server->on("/config", HTTP_GET, _onGetConfig);
  905. _server->on("/upgrade", HTTP_POST, _onUpgrade, _onUpgradeData);
  906. // Serve static files
  907. #if SPIFFS_SUPPORT
  908. _server->serveStatic("/", SPIFFS, "/")
  909. .setLastModified(_last_modified)
  910. .setFilter([](AsyncWebServerRequest *request) -> bool {
  911. _webLog(request);
  912. return true;
  913. });
  914. #endif
  915. // 404
  916. _server->onNotFound([](AsyncWebServerRequest *request){
  917. request->send(404);
  918. });
  919. // Run server
  920. #if ASYNC_TCP_SSL_ENABLED & WEB_SSL_ENABLED
  921. _server->onSslFileRequest(_onCertificate, NULL);
  922. _server->beginSecure("server.cer", "server.key", NULL);
  923. #else
  924. _server->begin();
  925. #endif
  926. DEBUG_MSG_P(PSTR("[WEBSERVER] Webserver running on port %d\n"), port);
  927. }
  928. #endif // WEB_SUPPORT