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.

1034 lines
31 KiB

8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
7 years ago
7 years ago
7 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
  1. /*
  2. WEBSERVER MODULE
  3. Copyright (C) 2016-2017 by Xose Pérez <xose dot perez at gmail dot com>
  4. */
  5. #if WEB_SUPPORT
  6. #include <ESPAsyncTCP.h>
  7. #include <ESPAsyncWebServer.h>
  8. #include <FS.h>
  9. #include <AsyncJson.h>
  10. #include <ArduinoJson.h>
  11. #include <Ticker.h>
  12. #include <vector>
  13. #if WEB_EMBEDDED
  14. #include "static/index.html.gz.h"
  15. #endif
  16. // -----------------------------------------------------------------------------
  17. AsyncWebServer * _server;
  18. char _last_modified[50];
  19. Ticker _web_defer;
  20. // -----------------------------------------------------------------------------
  21. AsyncWebSocket _ws("/ws");
  22. typedef struct {
  23. IPAddress ip;
  24. unsigned long timestamp = 0;
  25. } ws_ticket_t;
  26. ws_ticket_t _ticket[WS_BUFFER_SIZE];
  27. // -----------------------------------------------------------------------------
  28. typedef struct {
  29. char * url;
  30. char * key;
  31. apiGetCallbackFunction getFn = NULL;
  32. apiPutCallbackFunction putFn = NULL;
  33. } web_api_t;
  34. std::vector<web_api_t> _apis;
  35. // -----------------------------------------------------------------------------
  36. // WEBSOCKETS
  37. // -----------------------------------------------------------------------------
  38. void _wsMQTTCallback(unsigned int type, const char * topic, const char * payload) {
  39. if (type == MQTT_CONNECT_EVENT) {
  40. wsSend_P(PSTR("{\"mqttStatus\": true}"));
  41. }
  42. if (type == MQTT_DISCONNECT_EVENT) {
  43. wsSend_P(PSTR("{\"mqttStatus\": false}"));
  44. }
  45. }
  46. void _wsParse(uint32_t client_id, uint8_t * payload, size_t length) {
  47. // Parse JSON input
  48. DynamicJsonBuffer jsonBuffer;
  49. JsonObject& root = jsonBuffer.parseObject((char *) payload);
  50. if (!root.success()) {
  51. DEBUG_MSG_P(PSTR("[WEBSOCKET] Error parsing data\n"));
  52. wsSend_P(client_id, PSTR("{\"message\": \"Error parsing data!\"}"));
  53. return;
  54. }
  55. // Check actions
  56. if (root.containsKey("action")) {
  57. String action = root["action"];
  58. DEBUG_MSG_P(PSTR("[WEBSOCKET] Requested action: %s\n"), action.c_str());
  59. if (action.equals("reset")) {
  60. customReset(CUSTOM_RESET_WEB);
  61. ESP.restart();
  62. }
  63. #ifdef ITEAD_SONOFF_RFBRIDGE
  64. if (action.equals("rfblearn") && root.containsKey("data")) {
  65. JsonObject& data = root["data"];
  66. rfbLearn(data["id"], data["status"]);
  67. }
  68. if (action.equals("rfbforget") && root.containsKey("data")) {
  69. JsonObject& data = root["data"];
  70. rfbForget(data["id"], data["status"]);
  71. }
  72. if (action.equals("rfbsend") && root.containsKey("data")) {
  73. JsonObject& data = root["data"];
  74. rfbStore(data["id"], data["status"], data["data"].as<const char*>());
  75. }
  76. #endif
  77. if (action.equals("restore") && root.containsKey("data")) {
  78. JsonObject& data = root["data"];
  79. if (!data.containsKey("app") || (data["app"] != APP_NAME)) {
  80. wsSend_P(client_id, PSTR("{\"message\": \"The file does not look like a valid configuration backup.\"}"));
  81. return;
  82. }
  83. for (unsigned int i = EEPROM_DATA_END; i < SPI_FLASH_SEC_SIZE; i++) {
  84. EEPROM.write(i, 0xFF);
  85. }
  86. for (auto element : data) {
  87. if (strcmp(element.key, "app") == 0) continue;
  88. if (strcmp(element.key, "version") == 0) continue;
  89. setSetting(element.key, element.value.as<char*>());
  90. }
  91. saveSettings();
  92. wsSend_P(client_id, PSTR("{\"message\": \"Changes saved. You should reboot your board now.\"}"));
  93. }
  94. if (action.equals("reconnect")) {
  95. // Let the HTTP request return and disconnect after 100ms
  96. _web_defer.once_ms(100, wifiDisconnect);
  97. }
  98. if (action.equals("relay") && root.containsKey("data")) {
  99. JsonObject& data = root["data"];
  100. if (data.containsKey("status")) {
  101. bool status = (strcmp(data["status"], "1") == 0);
  102. unsigned int relayID = 0;
  103. if (data.containsKey("id")) {
  104. String value = data["id"];
  105. relayID = value.toInt();
  106. }
  107. relayStatus(relayID, status);
  108. }
  109. }
  110. #if LIGHT_PROVIDER != LIGHT_PROVIDER_NONE
  111. if (lightHasColor()) {
  112. if (action.equals("color") && root.containsKey("data")) {
  113. lightColor(root["data"]);
  114. lightUpdate(true, true);
  115. }
  116. if (action.equals("brightness") && root.containsKey("data")) {
  117. lightBrightness(root["data"]);
  118. lightUpdate(true, true);
  119. }
  120. }
  121. if (action.equals("channel") && root.containsKey("data")) {
  122. JsonObject& data = root["data"];
  123. if (data.containsKey("id") && data.containsKey("value")) {
  124. lightChannel(data["id"], data["value"]);
  125. lightUpdate(true, true);
  126. }
  127. }
  128. #endif
  129. };
  130. // Check config
  131. if (root.containsKey("config") && root["config"].is<JsonArray&>()) {
  132. JsonArray& config = root["config"];
  133. DEBUG_MSG_P(PSTR("[WEBSOCKET] Parsing configuration data\n"));
  134. unsigned char webMode = WEB_MODE_NORMAL;
  135. bool save = false;
  136. bool changed = false;
  137. bool changedMQTT = false;
  138. bool changedNTP = false;
  139. unsigned int network = 0;
  140. unsigned int dczRelayIdx = 0;
  141. String adminPass;
  142. for (unsigned int i=0; i<config.size(); i++) {
  143. String key = config[i]["name"];
  144. String value = config[i]["value"];
  145. // Skip firmware filename
  146. if (key.equals("filename")) continue;
  147. #if HLW8012_SUPPORT
  148. if (key == "powExpectedPower") {
  149. hlw8012SetExpectedActivePower(value.toInt());
  150. changed = true;
  151. }
  152. if (key == "powExpectedVoltage") {
  153. hlw8012SetExpectedVoltage(value.toInt());
  154. changed = true;
  155. }
  156. if (key == "powExpectedCurrent") {
  157. hlw8012SetExpectedCurrent(value.toFloat());
  158. changed = true;
  159. }
  160. if (key == "powExpectedReset") {
  161. hlw8012Reset();
  162. changed = true;
  163. }
  164. #endif
  165. if (key.startsWith("pow")) continue;
  166. #if DOMOTICZ_SUPPORT
  167. if (key == "dczRelayIdx") {
  168. if (dczRelayIdx >= relayCount()) continue;
  169. key = key + String(dczRelayIdx);
  170. ++dczRelayIdx;
  171. }
  172. #else
  173. if (key.startsWith("dcz")) continue;
  174. #endif
  175. // Web portions
  176. if (key == "webPort") {
  177. if ((value.toInt() == 0) || (value.toInt() == 80)) {
  178. save = changed = true;
  179. delSetting(key);
  180. continue;
  181. }
  182. }
  183. if (key == "webMode") {
  184. webMode = value.toInt();
  185. continue;
  186. }
  187. // Check password
  188. if (key == "adminPass1") {
  189. adminPass = value;
  190. continue;
  191. }
  192. if (key == "adminPass2") {
  193. if (!value.equals(adminPass)) {
  194. wsSend_P(client_id, PSTR("{\"message\": \"Passwords do not match!\"}"));
  195. return;
  196. }
  197. if (value.length() == 0) continue;
  198. wsSend_P(client_id, PSTR("{\"action\": \"reload\"}"));
  199. key = String("adminPass");
  200. }
  201. if (key == "ssid") {
  202. key = key + String(network);
  203. }
  204. if (key == "pass") {
  205. key = key + String(network);
  206. }
  207. if (key == "ip") {
  208. key = key + String(network);
  209. }
  210. if (key == "gw") {
  211. key = key + String(network);
  212. }
  213. if (key == "mask") {
  214. key = key + String(network);
  215. }
  216. if (key == "dns") {
  217. key = key + String(network);
  218. ++network;
  219. }
  220. if (value != getSetting(key)) {
  221. //DEBUG_MSG_P(PSTR("[WEBSOCKET] Storing %s = %s\n", key.c_str(), value.c_str()));
  222. setSetting(key, value);
  223. save = changed = true;
  224. if (key.startsWith("mqtt")) changedMQTT = true;
  225. if (key.startsWith("ntp")) changedNTP = true;
  226. }
  227. }
  228. if (webMode == WEB_MODE_NORMAL) {
  229. // Clean wifi networks
  230. int i = 0;
  231. while (i < network) {
  232. if (getSetting("ssid" + String(i)).length() == 0) {
  233. delSetting("ssid" + String(i));
  234. break;
  235. }
  236. if (getSetting("pass" + String(i)).length() == 0) delSetting("pass" + String(i));
  237. if (getSetting("ip" + String(i)).length() == 0) delSetting("ip" + String(i));
  238. if (getSetting("gw" + String(i)).length() == 0) delSetting("gw" + String(i));
  239. if (getSetting("mask" + String(i)).length() == 0) delSetting("mask" + String(i));
  240. if (getSetting("dns" + String(i)).length() == 0) delSetting("dns" + String(i));
  241. ++i;
  242. }
  243. while (i < WIFI_MAX_NETWORKS) {
  244. if (getSetting("ssid" + String(i)).length() > 0) {
  245. save = changed = true;
  246. }
  247. delSetting("ssid" + String(i));
  248. delSetting("pass" + String(i));
  249. delSetting("ip" + String(i));
  250. delSetting("gw" + String(i));
  251. delSetting("mask" + String(i));
  252. delSetting("dns" + String(i));
  253. ++i;
  254. }
  255. }
  256. // Save settings
  257. if (save) {
  258. saveSettings();
  259. wifiConfigure();
  260. otaConfigure();
  261. #if ALEXA_SUPPORT
  262. alexaConfigure();
  263. #endif
  264. #if INFLUXDB_SUPPORT
  265. influxDBConfigure();
  266. #endif
  267. #if DOMOTICZ_SUPPORT
  268. domoticzConfigure();
  269. #endif
  270. mqttConfigure();
  271. #if RF_SUPPORT
  272. rfBuildCodes();
  273. #endif
  274. #if EMON_SUPPORT
  275. setCurrentRatio(getSetting("emonRatio").toFloat());
  276. #endif
  277. // Check if we should reconfigure MQTT connection
  278. if (changedMQTT) {
  279. mqttDisconnect();
  280. }
  281. // Check if we should reconfigure NTP connection
  282. if (changedNTP) {
  283. ntpConnect();
  284. }
  285. }
  286. if (changed) {
  287. wsSend_P(client_id, PSTR("{\"message\": \"Changes saved\"}"));
  288. } else {
  289. wsSend_P(client_id, PSTR("{\"message\": \"No changes detected\"}"));
  290. }
  291. }
  292. }
  293. void _wsStart(uint32_t client_id) {
  294. char chipid[6];
  295. snprintf_P(chipid, sizeof(chipid), PSTR("%06X"), ESP.getChipId());
  296. DynamicJsonBuffer jsonBuffer;
  297. JsonObject& root = jsonBuffer.createObject();
  298. bool changePassword = false;
  299. #if WEB_FORCE_PASS_CHANGE
  300. String adminPass = getSetting("adminPass", ADMIN_PASS);
  301. if (adminPass.equals(ADMIN_PASS)) changePassword = true;
  302. #endif
  303. if (changePassword) {
  304. root["webMode"] = WEB_MODE_PASSWORD;
  305. } else {
  306. root["webMode"] = WEB_MODE_NORMAL;
  307. root["app"] = APP_NAME;
  308. root["version"] = APP_VERSION;
  309. root["buildDate"] = __DATE__;
  310. root["buildTime"] = __TIME__;
  311. root["manufacturer"] = String(MANUFACTURER);
  312. root["chipid"] = chipid;
  313. root["mac"] = WiFi.macAddress();
  314. root["device"] = String(DEVICE);
  315. root["hostname"] = getSetting("hostname");
  316. root["network"] = getNetwork();
  317. root["deviceip"] = getIP();
  318. root["ntpStatus"] = ntpConnected();
  319. root["ntpServer1"] = getSetting("ntpServer1", NTP_SERVER);
  320. root["ntpServer2"] = getSetting("ntpServer2");
  321. root["ntpServer3"] = getSetting("ntpServer3");
  322. root["ntpOffset"] = getSetting("ntpOffset", NTP_TIME_OFFSET).toInt();
  323. root["ntpDST"] = getSetting("ntpDST", NTP_DAY_LIGHT).toInt() == 1;
  324. root["mqttStatus"] = mqttConnected();
  325. root["mqttServer"] = getSetting("mqttServer", MQTT_SERVER);
  326. root["mqttPort"] = getSetting("mqttPort", MQTT_PORT);
  327. root["mqttUser"] = getSetting("mqttUser");
  328. root["mqttPassword"] = getSetting("mqttPassword");
  329. root["mqttTopic"] = getSetting("mqttTopic", MQTT_TOPIC);
  330. root["mqttUseJson"] = getSetting("mqttUseJson", MQTT_USE_JSON).toInt() == 1;
  331. JsonArray& relay = root.createNestedArray("relayStatus");
  332. for (unsigned char relayID=0; relayID<relayCount(); relayID++) {
  333. relay.add(relayStatus(relayID));
  334. }
  335. #if LIGHT_PROVIDER != LIGHT_PROVIDER_NONE
  336. root["colorVisible"] = 1;
  337. root["useColor"] = getSetting("useColor", LIGHT_USE_COLOR).toInt() == 1;
  338. root["useWhite"] = getSetting("useWhite", LIGHT_USE_WHITE).toInt() == 1;
  339. root["useGamma"] = getSetting("useGamma", LIGHT_USE_GAMMA).toInt() == 1;
  340. if (lightHasColor()) {
  341. root["color"] = lightColor();
  342. root["brightness"] = lightBrightness();
  343. }
  344. JsonArray& channels = root.createNestedArray("channels");
  345. for (unsigned char id=0; id < lightChannels(); id++) {
  346. channels.add(lightChannel(id));
  347. }
  348. #endif
  349. root["relayMode"] = getSetting("relayMode", RELAY_MODE);
  350. root["relayPulseMode"] = getSetting("relayPulseMode", RELAY_PULSE_MODE);
  351. root["relayPulseTime"] = getSetting("relayPulseTime", RELAY_PULSE_TIME).toFloat();
  352. if (relayCount() > 1) {
  353. root["multirelayVisible"] = 1;
  354. root["relaySync"] = getSetting("relaySync", RELAY_SYNC);
  355. }
  356. root["btnDelay"] = getSetting("btnDelay", BUTTON_DBLCLICK_DELAY).toInt();
  357. root["webPort"] = getSetting("webPort", WEB_PORT).toInt();
  358. root["apiEnabled"] = getSetting("apiEnabled", API_ENABLED).toInt() == 1;
  359. root["apiKey"] = getSetting("apiKey");
  360. root["tmpUnits"] = getSetting("tmpUnits", TMP_UNITS).toInt();
  361. #if DOMOTICZ_SUPPORT
  362. root["dczVisible"] = 1;
  363. root["dczEnabled"] = getSetting("dczEnabled", DOMOTICZ_ENABLED).toInt() == 1;
  364. root["dczTopicIn"] = getSetting("dczTopicIn", DOMOTICZ_IN_TOPIC);
  365. root["dczTopicOut"] = getSetting("dczTopicOut", DOMOTICZ_OUT_TOPIC);
  366. JsonArray& dczRelayIdx = root.createNestedArray("dczRelayIdx");
  367. for (byte i=0; i<relayCount(); i++) {
  368. dczRelayIdx.add(domoticzIdx(i));
  369. }
  370. #if DHT_SUPPORT
  371. root["dczTmpIdx"] = getSetting("dczTmpIdx").toInt();
  372. root["dczHumIdx"] = getSetting("dczHumIdx").toInt();
  373. #endif
  374. #if DS18B20_SUPPORT
  375. root["dczTmpIdx"] = getSetting("dczTmpIdx").toInt();
  376. #endif
  377. #if EMON_SUPPORT
  378. root["dczPowIdx"] = getSetting("dczPowIdx").toInt();
  379. root["dczEnergyIdx"] = getSetting("dczEnergyIdx").toInt();
  380. root["dczCurrentIdx"] = getSetting("dczCurrentIdx").toInt();
  381. #endif
  382. #if ANALOG_SUPPORT
  383. root["dczAnaIdx"] = getSetting("dczAnaIdx").toInt();
  384. #endif
  385. #if HLW8012_SUPPORT
  386. root["dczPowIdx"] = getSetting("dczPowIdx").toInt();
  387. root["dczEnergyIdx"] = getSetting("dczEnergyIdx").toInt();
  388. root["dczVoltIdx"] = getSetting("dczVoltIdx").toInt();
  389. root["dczCurrentIdx"] = getSetting("dczCurrentIdx").toInt();
  390. #endif
  391. #endif
  392. #if INFLUXDB_SUPPORT
  393. root["idbVisible"] = 1;
  394. root["idbHost"] = getSetting("idbHost");
  395. root["idbPort"] = getSetting("idbPort", INFLUXDB_PORT).toInt();
  396. root["idbDatabase"] = getSetting("idbDatabase");
  397. root["idbUsername"] = getSetting("idbUsername");
  398. root["idbPassword"] = getSetting("idbPassword");
  399. #endif
  400. #if ALEXA_SUPPORT
  401. root["alexaVisible"] = 1;
  402. root["alexaEnabled"] = getSetting("alexaEnabled", ALEXA_ENABLED).toInt() == 1;
  403. #endif
  404. #if DS18B20_SUPPORT
  405. root["dsVisible"] = 1;
  406. root["dsTmp"] = getDSTemperatureStr();
  407. #endif
  408. #if DHT_SUPPORT
  409. root["dhtVisible"] = 1;
  410. root["dhtTmp"] = getDHTTemperature();
  411. root["dhtHum"] = getDHTHumidity();
  412. #endif
  413. #if RF_SUPPORT
  414. root["rfVisible"] = 1;
  415. root["rfChannel"] = getSetting("rfChannel", RF_CHANNEL);
  416. root["rfDevice"] = getSetting("rfDevice", RF_DEVICE);
  417. #endif
  418. #if EMON_SUPPORT
  419. root["emonVisible"] = 1;
  420. root["emonApparentPower"] = getApparentPower();
  421. root["emonCurrent"] = getCurrent();
  422. root["emonVoltage"] = getVoltage();
  423. root["emonRatio"] = getSetting("emonRatio", EMON_CURRENT_RATIO);
  424. #endif
  425. #if ANALOG_SUPPORT
  426. root["analogVisible"] = 1;
  427. root["analogValue"] = getAnalog();
  428. #endif
  429. #if HLW8012_SUPPORT
  430. root["powVisible"] = 1;
  431. root["powActivePower"] = getActivePower();
  432. root["powApparentPower"] = getApparentPower();
  433. root["powReactivePower"] = getReactivePower();
  434. root["powVoltage"] = getVoltage();
  435. root["powCurrent"] = String(getCurrent(), 3);
  436. root["powPowerFactor"] = String(getPowerFactor(), 2);
  437. #endif
  438. #ifdef ITEAD_SONOFF_RFBRIDGE
  439. root["rfbVisible"] = 1;
  440. root["rfbCount"] = relayCount();
  441. JsonArray& rfb = root.createNestedArray("rfb");
  442. for (byte id=0; id<relayCount(); id++) {
  443. for (byte status=0; status<2; status++) {
  444. JsonObject& node = rfb.createNestedObject();
  445. node["id"] = id;
  446. node["status"] = status;
  447. node["data"] = rfbRetrieve(id, status == 1);
  448. }
  449. }
  450. #endif
  451. root["maxNetworks"] = WIFI_MAX_NETWORKS;
  452. JsonArray& wifi = root.createNestedArray("wifi");
  453. for (byte i=0; i<WIFI_MAX_NETWORKS; i++) {
  454. if (getSetting("ssid" + String(i)).length() == 0) break;
  455. JsonObject& network = wifi.createNestedObject();
  456. network["ssid"] = getSetting("ssid" + String(i));
  457. network["pass"] = getSetting("pass" + String(i));
  458. network["ip"] = getSetting("ip" + String(i));
  459. network["gw"] = getSetting("gw" + String(i));
  460. network["mask"] = getSetting("mask" + String(i));
  461. network["dns"] = getSetting("dns" + String(i));
  462. }
  463. }
  464. String output;
  465. root.printTo(output);
  466. wsSend(client_id, (char *) output.c_str());
  467. }
  468. bool _wsAuth(AsyncWebSocketClient * client) {
  469. IPAddress ip = client->remoteIP();
  470. unsigned long now = millis();
  471. unsigned short index = 0;
  472. for (index = 0; index < WS_BUFFER_SIZE; index++) {
  473. if ((_ticket[index].ip == ip) && (now - _ticket[index].timestamp < WS_TIMEOUT)) break;
  474. }
  475. if (index == WS_BUFFER_SIZE) {
  476. DEBUG_MSG_P(PSTR("[WEBSOCKET] Validation check failed\n"));
  477. wsSend_P(client->id(), PSTR("{\"message\": \"Session expired, please reload page...\"}"));
  478. return false;
  479. }
  480. return true;
  481. }
  482. void _wsEvent(AsyncWebSocket * server, AsyncWebSocketClient * client, AwsEventType type, void * arg, uint8_t *data, size_t len){
  483. static uint8_t * message;
  484. // Authorize
  485. #ifndef NOWSAUTH
  486. if (!_wsAuth(client)) return;
  487. #endif
  488. if (type == WS_EVT_CONNECT) {
  489. IPAddress ip = client->remoteIP();
  490. 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());
  491. _wsStart(client->id());
  492. } else if(type == WS_EVT_DISCONNECT) {
  493. DEBUG_MSG_P(PSTR("[WEBSOCKET] #%u disconnected\n"), client->id());
  494. } else if(type == WS_EVT_ERROR) {
  495. DEBUG_MSG_P(PSTR("[WEBSOCKET] #%u error(%u): %s\n"), client->id(), *((uint16_t*)arg), (char*)data);
  496. } else if(type == WS_EVT_PONG) {
  497. DEBUG_MSG_P(PSTR("[WEBSOCKET] #%u pong(%u): %s\n"), client->id(), len, len ? (char*) data : "");
  498. } else if(type == WS_EVT_DATA) {
  499. AwsFrameInfo * info = (AwsFrameInfo*)arg;
  500. // First packet
  501. if (info->index == 0) {
  502. message = (uint8_t*) malloc(info->len);
  503. }
  504. // Store data
  505. memcpy(message + info->index, data, len);
  506. // Last packet
  507. if (info->index + len == info->len) {
  508. _wsParse(client->id(), message, info->len);
  509. free(message);
  510. }
  511. }
  512. }
  513. // -----------------------------------------------------------------------------
  514. bool wsConnected() {
  515. return (_ws.count() > 0);
  516. }
  517. void wsSend(const char * payload) {
  518. if (_ws.count() > 0) {
  519. _ws.textAll(payload);
  520. }
  521. }
  522. void wsSend_P(PGM_P payload) {
  523. if (_ws.count() > 0) {
  524. char buffer[strlen_P(payload)];
  525. strcpy_P(buffer, payload);
  526. _ws.textAll(buffer);
  527. }
  528. }
  529. void wsSend(uint32_t client_id, const char * payload) {
  530. _ws.text(client_id, payload);
  531. }
  532. void wsSend_P(uint32_t client_id, PGM_P payload) {
  533. char buffer[strlen_P(payload)];
  534. strcpy_P(buffer, payload);
  535. _ws.text(client_id, buffer);
  536. }
  537. void wsSetup() {
  538. _ws.onEvent(_wsEvent);
  539. mqttRegister(_wsMQTTCallback);
  540. _server->addHandler(&_ws);
  541. _server->on("/auth", HTTP_GET, _onAuth);
  542. }
  543. // -----------------------------------------------------------------------------
  544. // API
  545. // -----------------------------------------------------------------------------
  546. bool _authAPI(AsyncWebServerRequest *request) {
  547. if (getSetting("apiEnabled", API_ENABLED).toInt() == 0) {
  548. DEBUG_MSG_P(PSTR("[WEBSERVER] HTTP API is not enabled\n"));
  549. request->send(403);
  550. return false;
  551. }
  552. if (!request->hasParam("apikey", (request->method() == HTTP_PUT))) {
  553. DEBUG_MSG_P(PSTR("[WEBSERVER] Missing apikey parameter\n"));
  554. request->send(403);
  555. return false;
  556. }
  557. AsyncWebParameter* p = request->getParam("apikey", (request->method() == HTTP_PUT));
  558. if (!p->value().equals(getSetting("apiKey"))) {
  559. DEBUG_MSG_P(PSTR("[WEBSERVER] Wrong apikey parameter\n"));
  560. request->send(403);
  561. return false;
  562. }
  563. return true;
  564. }
  565. bool _asJson(AsyncWebServerRequest *request) {
  566. bool asJson = false;
  567. if (request->hasHeader("Accept")) {
  568. AsyncWebHeader* h = request->getHeader("Accept");
  569. asJson = h->value().equals("application/json");
  570. }
  571. return asJson;
  572. }
  573. ArRequestHandlerFunction _bindAPI(unsigned int apiID) {
  574. return [apiID](AsyncWebServerRequest *request) {
  575. _webLog(request);
  576. if (!_authAPI(request)) return;
  577. web_api_t api = _apis[apiID];
  578. // Check if its a PUT
  579. if (api.putFn != NULL) {
  580. if (request->hasParam("value", request->method() == HTTP_PUT)) {
  581. AsyncWebParameter* p = request->getParam("value", request->method() == HTTP_PUT);
  582. (api.putFn)((p->value()).c_str());
  583. }
  584. }
  585. // Get response from callback
  586. char value[API_BUFFER_SIZE];
  587. (api.getFn)(value, API_BUFFER_SIZE);
  588. char *p = ltrim(value);
  589. // The response will be a 404 NOT FOUND if the resource is not available
  590. if (!value) {
  591. DEBUG_MSG_P(PSTR("[API] Sending 404 response\n"));
  592. request->send(404);
  593. return;
  594. }
  595. DEBUG_MSG_P(PSTR("[API] Sending response '%s'\n"), p);
  596. // Format response according to the Accept header
  597. if (_asJson(request)) {
  598. char buffer[64];
  599. snprintf_P(buffer, sizeof(buffer), PSTR("{ \"%s\": %s }"), api.key, p);
  600. request->send(200, "application/json", buffer);
  601. } else {
  602. request->send(200, "text/plain", p);
  603. }
  604. };
  605. }
  606. void _onAPIs(AsyncWebServerRequest *request) {
  607. _webLog(request);
  608. if (!_authAPI(request)) return;
  609. bool asJson = _asJson(request);
  610. String output;
  611. if (asJson) {
  612. DynamicJsonBuffer jsonBuffer;
  613. JsonObject& root = jsonBuffer.createObject();
  614. for (unsigned int i=0; i < _apis.size(); i++) {
  615. root[_apis[i].key] = _apis[i].url;
  616. }
  617. root.printTo(output);
  618. request->send(200, "application/json", output);
  619. } else {
  620. for (unsigned int i=0; i < _apis.size(); i++) {
  621. output += _apis[i].key + String(" -> ") + _apis[i].url + String("\n");
  622. }
  623. request->send(200, "text/plain", output);
  624. }
  625. }
  626. void _onRPC(AsyncWebServerRequest *request) {
  627. _webLog(request);
  628. if (!_authAPI(request)) return;
  629. //bool asJson = _asJson(request);
  630. int response = 404;
  631. if (request->hasParam("action")) {
  632. AsyncWebParameter* p = request->getParam("action");
  633. String action = p->value();
  634. DEBUG_MSG_P(PSTR("[RPC] Action: %s\n"), action.c_str());
  635. if (action.equals("reset")) {
  636. response = 200;
  637. _web_defer.once_ms(100, []() {
  638. customReset(CUSTOM_RESET_RPC);
  639. ESP.restart();
  640. });
  641. }
  642. }
  643. request->send(response);
  644. }
  645. // -----------------------------------------------------------------------------
  646. void apiRegister(const char * url, const char * key, apiGetCallbackFunction getFn, apiPutCallbackFunction putFn) {
  647. // Store it
  648. web_api_t api;
  649. char buffer[40];
  650. snprintf_P(buffer, sizeof(buffer), PSTR("/api/%s"), url);
  651. api.url = strdup(buffer);
  652. api.key = strdup(key);
  653. api.getFn = getFn;
  654. api.putFn = putFn;
  655. _apis.push_back(api);
  656. // Bind call
  657. unsigned int methods = HTTP_GET;
  658. if (putFn != NULL) methods += HTTP_PUT;
  659. _server->on(buffer, methods, _bindAPI(_apis.size() - 1));
  660. }
  661. void apiSetup() {
  662. _server->on("/apis", HTTP_GET, _onAPIs);
  663. _server->on("/rpc", HTTP_GET, _onRPC);
  664. }
  665. // -----------------------------------------------------------------------------
  666. // WEBSERVER
  667. // -----------------------------------------------------------------------------
  668. void _webLog(AsyncWebServerRequest *request) {
  669. DEBUG_MSG_P(PSTR("[WEBSERVER] Request: %s %s\n"), request->methodToString(), request->url().c_str());
  670. }
  671. bool _authenticate(AsyncWebServerRequest *request) {
  672. String password = getSetting("adminPass", ADMIN_PASS);
  673. char httpPassword[password.length() + 1];
  674. password.toCharArray(httpPassword, password.length() + 1);
  675. return request->authenticate(WEB_USERNAME, httpPassword);
  676. }
  677. void _onAuth(AsyncWebServerRequest *request) {
  678. _webLog(request);
  679. if (!_authenticate(request)) return request->requestAuthentication();
  680. IPAddress ip = request->client()->remoteIP();
  681. unsigned long now = millis();
  682. unsigned short index;
  683. for (index = 0; index < WS_BUFFER_SIZE; index++) {
  684. if (_ticket[index].ip == ip) break;
  685. if (_ticket[index].timestamp == 0) break;
  686. if (now - _ticket[index].timestamp > WS_TIMEOUT) break;
  687. }
  688. if (index == WS_BUFFER_SIZE) {
  689. request->send(429);
  690. } else {
  691. _ticket[index].ip = ip;
  692. _ticket[index].timestamp = now;
  693. request->send(204);
  694. }
  695. }
  696. void _onGetConfig(AsyncWebServerRequest *request) {
  697. _webLog(request);
  698. if (!_authenticate(request)) return request->requestAuthentication();
  699. AsyncJsonResponse * response = new AsyncJsonResponse();
  700. JsonObject& root = response->getRoot();
  701. root["app"] = APP_NAME;
  702. root["version"] = APP_VERSION;
  703. unsigned int size = settingsKeyCount();
  704. for (unsigned int i=0; i<size; i++) {
  705. String key = settingsKeyName(i);
  706. String value = getSetting(key);
  707. root[key] = value;
  708. }
  709. char buffer[100];
  710. snprintf_P(buffer, sizeof(buffer), PSTR("attachment; filename=\"%s-backup.json\""), (char *) getSetting("hostname").c_str());
  711. response->addHeader("Content-Disposition", buffer);
  712. response->setLength();
  713. request->send(response);
  714. }
  715. #if WEB_EMBEDDED
  716. void _onHome(AsyncWebServerRequest *request) {
  717. _webLog(request);
  718. if (request->header("If-Modified-Since").equals(_last_modified)) {
  719. request->send(304);
  720. } else {
  721. AsyncWebServerResponse *response = request->beginResponse_P(200, "text/html", index_html_gz, index_html_gz_len);
  722. response->addHeader("Content-Encoding", "gzip");
  723. response->addHeader("Last-Modified", _last_modified);
  724. request->send(response);
  725. }
  726. }
  727. #endif
  728. void _onUpgrade(AsyncWebServerRequest *request) {
  729. AsyncWebServerResponse *response = request->beginResponse(200, "text/plain", Update.hasError() ? "FAIL" : "OK");
  730. response->addHeader("Connection", "close");
  731. if (!Update.hasError()) {
  732. _web_defer.once_ms(100, []() {
  733. customReset(CUSTOM_RESET_UPGRADE);
  734. ESP.restart();
  735. });
  736. }
  737. request->send(response);
  738. }
  739. void _onUpgradeData(AsyncWebServerRequest *request, String filename, size_t index, uint8_t *data, size_t len, bool final) {
  740. if (!index) {
  741. DEBUG_MSG_P(PSTR("[UPGRADE] Start: %s\n"), filename.c_str());
  742. Update.runAsync(true);
  743. if (!Update.begin((ESP.getFreeSketchSpace() - 0x1000) & 0xFFFFF000)) {
  744. #ifdef DEBUG_PORT
  745. Update.printError(DEBUG_PORT);
  746. #endif
  747. }
  748. }
  749. if (!Update.hasError()) {
  750. if (Update.write(data, len) != len) {
  751. #ifdef DEBUG_PORT
  752. Update.printError(DEBUG_PORT);
  753. #endif
  754. }
  755. }
  756. if (final) {
  757. if (Update.end(true)){
  758. DEBUG_MSG_P(PSTR("[UPGRADE] Success: %u bytes\n"), index + len);
  759. } else {
  760. #ifdef DEBUG_PORT
  761. Update.printError(DEBUG_PORT);
  762. #endif
  763. }
  764. } else {
  765. DEBUG_MSG_P(PSTR("[UPGRADE] Progress: %u bytes\r"), index + len);
  766. }
  767. }
  768. // -----------------------------------------------------------------------------
  769. void webSetup() {
  770. // Cache the Last-Modifier header value
  771. snprintf_P(_last_modified, sizeof(_last_modified), PSTR("%s %s GMT"), __DATE__, __TIME__);
  772. // Create server
  773. _server = new AsyncWebServer(getSetting("webPort", WEB_PORT).toInt());
  774. // Setup websocket
  775. wsSetup();
  776. // API setup
  777. apiSetup();
  778. // Rewrites
  779. _server->rewrite("/", "/index.html");
  780. // Serve home (basic authentication protection)
  781. #if WEB_EMBEDDED
  782. _server->on("/index.html", HTTP_GET, _onHome);
  783. #endif
  784. _server->on("/config", HTTP_GET, _onGetConfig);
  785. _server->on("/upgrade", HTTP_POST, _onUpgrade, _onUpgradeData);
  786. // Serve static files
  787. #if SPIFFS_SUPPORT
  788. _server->serveStatic("/", SPIFFS, "/")
  789. .setLastModified(_last_modified)
  790. .setFilter([](AsyncWebServerRequest *request) -> bool {
  791. _webLog(request);
  792. return true;
  793. });
  794. #endif
  795. // 404
  796. _server->onNotFound([](AsyncWebServerRequest *request){
  797. request->send(404);
  798. });
  799. // Run server
  800. _server->begin();
  801. DEBUG_MSG_P(PSTR("[WEBSERVER] Webserver running on port %d\n"), getSetting("webPort", WEB_PORT).toInt());
  802. }
  803. #endif // WEB_SUPPORT