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.

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