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.

690 lines
20 KiB

8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
  1. /*
  2. WEBSERVER MODULE
  3. Copyright (C) 2016-2017 by Xose Pérez <xose dot perez at gmail dot com>
  4. */
  5. #include <ESPAsyncTCP.h>
  6. #include <ESPAsyncWebServer.h>
  7. #include <ESP8266mDNS.h>
  8. #include <FS.h>
  9. #include <Hash.h>
  10. #include <AsyncJson.h>
  11. #include <ArduinoJson.h>
  12. #include <Ticker.h>
  13. #include <vector>
  14. AsyncWebServer server(80);
  15. AsyncWebSocket ws("/ws");
  16. Ticker deferred;
  17. typedef struct {
  18. IPAddress ip;
  19. unsigned long timestamp = 0;
  20. } ws_ticket_t;
  21. ws_ticket_t _ticket[WS_BUFFER_SIZE];
  22. typedef struct {
  23. char * url;
  24. char * key;
  25. apiGetCallbackFunction getFn = NULL;
  26. apiPutCallbackFunction putFn = NULL;
  27. } web_api_t;
  28. std::vector<web_api_t> _apis;
  29. // -----------------------------------------------------------------------------
  30. // WEBSOCKETS
  31. // -----------------------------------------------------------------------------
  32. bool wsSend(const char * payload) {
  33. DEBUG_MSG("[WEBSOCKET] Broadcasting '%s'\n", payload);
  34. ws.textAll(payload);
  35. }
  36. bool wsSend(uint32_t client_id, const char * payload) {
  37. DEBUG_MSG("[WEBSOCKET] Sending '%s' to #%ld\n", payload, client_id);
  38. ws.text(client_id, payload);
  39. }
  40. void wsMQTTCallback(unsigned int type, const char * topic, const char * payload) {
  41. if (type == MQTT_CONNECT_EVENT) {
  42. wsSend("{\"mqttStatus\": true}");
  43. }
  44. if (type == MQTT_DISCONNECT_EVENT) {
  45. wsSend("{\"mqttStatus\": false}");
  46. }
  47. }
  48. void _wsParse(uint32_t client_id, uint8_t * payload, size_t length) {
  49. // Parse JSON input
  50. DynamicJsonBuffer jsonBuffer;
  51. JsonObject& root = jsonBuffer.parseObject((char *) payload);
  52. if (!root.success()) {
  53. DEBUG_MSG("[WEBSOCKET] Error parsing data\n");
  54. ws.text(client_id, "{\"message\": \"Error parsing data!\"}");
  55. return;
  56. }
  57. // Check actions
  58. if (root.containsKey("action")) {
  59. String action = root["action"];
  60. unsigned int relayID = 0;
  61. if (root.containsKey("relayID")) {
  62. String value = root["relayID"];
  63. relayID = value.toInt();
  64. }
  65. DEBUG_MSG("[WEBSOCKET] Requested action: %s\n", action.c_str());
  66. if (action.equals("reset")) ESP.reset();
  67. if (action.equals("reconnect")) {
  68. // Let the HTTP request return and disconnect after 100ms
  69. deferred.once_ms(100, wifiDisconnect);
  70. }
  71. if (action.equals("on")) relayStatus(relayID, true);
  72. if (action.equals("off")) relayStatus(relayID, false);
  73. };
  74. // Check config
  75. if (root.containsKey("config") && root["config"].is<JsonArray&>()) {
  76. JsonArray& config = root["config"];
  77. DEBUG_MSG("[WEBSOCKET] Parsing configuration data\n");
  78. bool save = false;
  79. bool changed = false;
  80. bool changedMQTT = false;
  81. bool apiEnabled = false;
  82. #if ENABLE_FAUXMO
  83. bool fauxmoEnabled = false;
  84. #endif
  85. unsigned int network = 0;
  86. unsigned int dczRelayIdx = 0;
  87. String adminPass;
  88. for (unsigned int i=0; i<config.size(); i++) {
  89. String key = config[i]["name"];
  90. String value = config[i]["value"];
  91. #if ENABLE_POW
  92. if (key == "powExpectedPower") {
  93. powSetExpectedActivePower(value.toInt());
  94. changed = true;
  95. }
  96. if (key == "powExpectedVoltage") {
  97. powSetExpectedVoltage(value.toInt());
  98. changed = true;
  99. }
  100. if (key == "powExpectedCurrent") {
  101. powSetExpectedCurrent(value.toInt());
  102. changed = true;
  103. }
  104. if (key == "powExpectedReset") {
  105. powReset();
  106. changed = true;
  107. }
  108. #endif
  109. if (key.startsWith("pow")) continue;
  110. #if ENABLE_DOMOTICZ
  111. if (key == "dczRelayIdx") {
  112. if (dczRelayIdx >= relayCount()) continue;
  113. key = key + String(dczRelayIdx);
  114. ++dczRelayIdx;
  115. }
  116. #else
  117. if (key.startsWith("dcz")) continue;
  118. #endif
  119. // Check password
  120. if (key == "adminPass1") {
  121. adminPass = value;
  122. continue;
  123. }
  124. if (key == "adminPass2") {
  125. if (!value.equals(adminPass)) {
  126. ws.text(client_id, "{\"message\": \"Passwords do not match!\"}");
  127. return;
  128. }
  129. if (value.length() == 0) continue;
  130. ws.text(client_id, "{\"action\": \"reload\"}");
  131. key = String("adminPass");
  132. }
  133. // Checkboxes
  134. if (key == "apiEnabled") {
  135. apiEnabled = true;
  136. continue;
  137. }
  138. #if ENABLE_FAUXMO
  139. if (key == "fauxmoEnabled") {
  140. fauxmoEnabled = true;
  141. continue;
  142. }
  143. #endif
  144. if (key == "ssid") {
  145. key = key + String(network);
  146. }
  147. if (key == "pass") {
  148. key = key + String(network);
  149. }
  150. if (key == "ip") {
  151. key = key + String(network);
  152. }
  153. if (key == "gw") {
  154. key = key + String(network);
  155. }
  156. if (key == "mask") {
  157. key = key + String(network);
  158. }
  159. if (key == "dns") {
  160. key = key + String(network);
  161. ++network;
  162. }
  163. if (value != getSetting(key)) {
  164. //DEBUG_MSG("[WEBSOCKET] Storing %s = %s\n", key.c_str(), value.c_str());
  165. setSetting(key, value);
  166. save = changed = true;
  167. if (key.startsWith("mqtt")) changedMQTT = true;
  168. }
  169. }
  170. // Checkboxes
  171. if (apiEnabled != (getSetting("apiEnabled").toInt() == 1)) {
  172. setSetting("apiEnabled", apiEnabled);
  173. save = changed = true;
  174. }
  175. #if ENABLE_FAUXMO
  176. if (fauxmoEnabled != (getSetting("fauxmoEnabled").toInt() == 1)) {
  177. setSetting("fauxmoEnabled", fauxmoEnabled);
  178. save = changed = true;
  179. }
  180. #endif
  181. // Clean wifi networks
  182. for (int i = 0; i < network; i++) {
  183. if (getSetting("pass" + String(i)).length() == 0) delSetting("pass" + String(i));
  184. if (getSetting("ip" + String(i)).length() == 0) delSetting("ip" + String(i));
  185. if (getSetting("gw" + String(i)).length() == 0) delSetting("gw" + String(i));
  186. if (getSetting("mask" + String(i)).length() == 0) delSetting("mask" + String(i));
  187. if (getSetting("dns" + String(i)).length() == 0) delSetting("dns" + String(i));
  188. }
  189. for (int i = network; i<WIFI_MAX_NETWORKS; i++) {
  190. if (getSetting("ssid" + String(i)).length() > 0) {
  191. save = changed = true;
  192. }
  193. delSetting("ssid" + String(i));
  194. delSetting("pass" + String(i));
  195. delSetting("ip" + String(i));
  196. delSetting("gw" + String(i));
  197. delSetting("mask" + String(i));
  198. delSetting("dns" + String(i));
  199. }
  200. // Save settings
  201. if (save) {
  202. saveSettings();
  203. wifiConfigure();
  204. otaConfigure();
  205. #if ENABLE_FAUXMO
  206. fauxmoConfigure();
  207. #endif
  208. buildTopics();
  209. #if ENABLE_RF
  210. rfBuildCodes();
  211. #endif
  212. #if ENABLE_EMON
  213. setCurrentRatio(getSetting("emonRatio").toFloat());
  214. #endif
  215. // Check if we should reconfigure MQTT connection
  216. if (changedMQTT) {
  217. mqttDisconnect();
  218. }
  219. }
  220. if (changed) {
  221. ws.text(client_id, "{\"message\": \"Changes saved\"}");
  222. } else {
  223. ws.text(client_id, "{\"message\": \"No changes detected\"}");
  224. }
  225. }
  226. }
  227. void _wsStart(uint32_t client_id) {
  228. char chipid[6];
  229. sprintf(chipid, "%06X", ESP.getChipId());
  230. DynamicJsonBuffer jsonBuffer;
  231. JsonObject& root = jsonBuffer.createObject();
  232. root["app"] = APP_NAME;
  233. root["version"] = APP_VERSION;
  234. root["buildDate"] = __DATE__;
  235. root["buildTime"] = __TIME__;
  236. root["manufacturer"] = String(MANUFACTURER);
  237. root["chipid"] = chipid;
  238. root["mac"] = WiFi.macAddress();
  239. root["device"] = String(DEVICE);
  240. root["hostname"] = getSetting("hostname", HOSTNAME);
  241. root["network"] = getNetwork();
  242. root["deviceip"] = getIP();
  243. root["mqttStatus"] = mqttConnected();
  244. root["mqttServer"] = getSetting("mqttServer", MQTT_SERVER);
  245. root["mqttPort"] = getSetting("mqttPort", MQTT_PORT);
  246. root["mqttUser"] = getSetting("mqttUser");
  247. root["mqttPassword"] = getSetting("mqttPassword");
  248. root["mqttTopic"] = getSetting("mqttTopic", MQTT_TOPIC);
  249. JsonArray& relay = root.createNestedArray("relayStatus");
  250. for (unsigned char relayID=0; relayID<relayCount(); relayID++) {
  251. relay.add(relayStatus(relayID));
  252. }
  253. root["relayMode"] = getSetting("relayMode", RELAY_MODE);
  254. if (relayCount() > 1) {
  255. root["multirelayVisible"] = 1;
  256. root["relaySync"] = getSetting("relaySync", RELAY_SYNC);
  257. }
  258. root["apiEnabled"] = getSetting("apiEnabled").toInt() == 1;
  259. root["apiKey"] = getSetting("apiKey");
  260. #if ENABLE_DOMOTICZ
  261. root["dczVisible"] = 1;
  262. root["dczTopicIn"] = getSetting("dczTopicIn", DOMOTICZ_IN_TOPIC);
  263. root["dczTopicOut"] = getSetting("dczTopicOut", DOMOTICZ_OUT_TOPIC);
  264. JsonArray& dczRelayIdx = root.createNestedArray("dczRelayIdx");
  265. for (byte i=0; i<relayCount(); i++) {
  266. dczRelayIdx.add(relayToIdx(i));
  267. }
  268. #if ENABLE_DHT
  269. root["dczTmpIdx"] = getSetting("dczTmpIdx").toInt();
  270. root["dczHumIdx"] = getSetting("dczHumIdx").toInt();
  271. #endif
  272. #if ENABLE_DS18B20
  273. root["dczTmpIdx"] = getSetting("dczTmpIdx").toInt();
  274. #endif
  275. #if ENABLE_EMON
  276. root["dczPowIdx"] = getSetting("dczPowIdx").toInt();
  277. #endif
  278. #if ENABLE_POW
  279. root["dczPowIdx"] = getSetting("dczPowIdx").toInt();
  280. #endif
  281. #endif
  282. #if ENABLE_FAUXMO
  283. root["fauxmoVisible"] = 1;
  284. root["fauxmoEnabled"] = getSetting("fauxmoEnabled", FAUXMO_ENABLED).toInt() == 1;
  285. #endif
  286. #if ENABLE_DS18B20
  287. root["dsVisible"] = 1;
  288. root["dsTmp"] = getDSTemperature();
  289. #endif
  290. #if ENABLE_DHT
  291. root["dhtVisible"] = 1;
  292. root["dhtTmp"] = getDHTTemperature();
  293. root["dhtHum"] = getDHTHumidity();
  294. #endif
  295. #if ENABLE_RF
  296. root["rfVisible"] = 1;
  297. root["rfChannel"] = getSetting("rfChannel", RF_CHANNEL);
  298. root["rfDevice"] = getSetting("rfDevice", RF_DEVICE);
  299. #endif
  300. #if ENABLE_EMON
  301. root["emonVisible"] = 1;
  302. root["emonPower"] = getPower();
  303. root["emonMains"] = getSetting("emonMains", EMON_MAINS_VOLTAGE);
  304. root["emonRatio"] = getSetting("emonRatio", EMON_CURRENT_RATIO);
  305. #endif
  306. #if ENABLE_POW
  307. root["powVisible"] = 1;
  308. root["powActivePower"] = getActivePower();
  309. root["powApparentPower"] = getApparentPower();
  310. root["powReactivePower"] = getReactivePower();
  311. root["powVoltage"] = getVoltage();
  312. root["powCurrent"] = getCurrent();
  313. root["powPowerFactor"] = getPowerFactor();
  314. #endif
  315. root["maxNetworks"] = WIFI_MAX_NETWORKS;
  316. JsonArray& wifi = root.createNestedArray("wifi");
  317. for (byte i=0; i<WIFI_MAX_NETWORKS; i++) {
  318. if (getSetting("ssid" + String(i)).length() == 0) break;
  319. JsonObject& network = wifi.createNestedObject();
  320. network["ssid"] = getSetting("ssid" + String(i));
  321. network["pass"] = getSetting("pass" + String(i));
  322. network["ip"] = getSetting("ip" + String(i));
  323. network["gw"] = getSetting("gw" + String(i));
  324. network["mask"] = getSetting("mask" + String(i));
  325. network["dns"] = getSetting("dns" + String(i));
  326. }
  327. String output;
  328. root.printTo(output);
  329. ws.text(client_id, (char *) output.c_str());
  330. }
  331. bool _wsAuth(AsyncWebSocketClient * client) {
  332. IPAddress ip = client->remoteIP();
  333. unsigned long now = millis();
  334. unsigned short index = 0;
  335. for (index = 0; index < WS_BUFFER_SIZE; index++) {
  336. if ((_ticket[index].ip == ip) && (now - _ticket[index].timestamp < WS_TIMEOUT)) break;
  337. }
  338. if (index == WS_BUFFER_SIZE) {
  339. DEBUG_MSG("[WEBSOCKET] Validation check failed\n");
  340. ws.text(client->id(), "{\"message\": \"Session expired, please reload page...\"}");
  341. return false;
  342. }
  343. return true;
  344. }
  345. void _wsEvent(AsyncWebSocket * server, AsyncWebSocketClient * client, AwsEventType type, void * arg, uint8_t *data, size_t len){
  346. static uint8_t * message;
  347. // Authorize
  348. #ifndef NOWSAUTH
  349. if (!_wsAuth(client)) return;
  350. #endif
  351. if (type == WS_EVT_CONNECT) {
  352. IPAddress ip = client->remoteIP();
  353. DEBUG_MSG("[WEBSOCKET] #%u connected, ip: %d.%d.%d.%d, url: %s\n", client->id(), ip[0], ip[1], ip[2], ip[3], server->url());
  354. _wsStart(client->id());
  355. } else if(type == WS_EVT_DISCONNECT) {
  356. DEBUG_MSG("[WEBSOCKET] #%u disconnected\n", client->id());
  357. } else if(type == WS_EVT_ERROR) {
  358. DEBUG_MSG("[WEBSOCKET] #%u error(%u): %s\n", client->id(), *((uint16_t*)arg), (char*)data);
  359. } else if(type == WS_EVT_PONG) {
  360. DEBUG_MSG("[WEBSOCKET] #%u pong(%u): %s\n", client->id(), len, len ? (char*) data : "");
  361. } else if(type == WS_EVT_DATA) {
  362. AwsFrameInfo * info = (AwsFrameInfo*)arg;
  363. // First packet
  364. if (info->index == 0) {
  365. //Serial.printf("Before malloc: %d\n", ESP.getFreeHeap());
  366. message = (uint8_t*) malloc(info->len);
  367. //Serial.printf("After malloc: %d\n", ESP.getFreeHeap());
  368. }
  369. // Store data
  370. memcpy(message + info->index, data, len);
  371. // Last packet
  372. if (info->index + len == info->len) {
  373. _wsParse(client->id(), message, info->len);
  374. //Serial.printf("Before free: %d\n", ESP.getFreeHeap());
  375. free(message);
  376. //Serial.printf("After free: %d\n", ESP.getFreeHeap());
  377. }
  378. }
  379. }
  380. // -----------------------------------------------------------------------------
  381. // WEBSERVER
  382. // -----------------------------------------------------------------------------
  383. void webLogRequest(AsyncWebServerRequest *request) {
  384. DEBUG_MSG("[WEBSERVER] Request: %s %s\n", request->methodToString(), request->url().c_str());
  385. }
  386. bool _authenticate(AsyncWebServerRequest *request) {
  387. String password = getSetting("adminPass", ADMIN_PASS);
  388. char httpPassword[password.length() + 1];
  389. password.toCharArray(httpPassword, password.length() + 1);
  390. return request->authenticate(HTTP_USERNAME, httpPassword);
  391. }
  392. bool _authAPI(AsyncWebServerRequest *request) {
  393. if (getSetting("apiEnabled").toInt() == 0) {
  394. DEBUG_MSG("[WEBSERVER] HTTP API is not enabled\n");
  395. request->send(403);
  396. return false;
  397. }
  398. if (!request->hasParam("apikey", (request->method() == HTTP_PUT))) {
  399. DEBUG_MSG("[WEBSERVER] Missing apikey parameter\n");
  400. request->send(403);
  401. return false;
  402. }
  403. AsyncWebParameter* p = request->getParam("apikey", (request->method() == HTTP_PUT));
  404. if (!p->value().equals(getSetting("apiKey"))) {
  405. DEBUG_MSG("[WEBSERVER] Wrong apikey parameter\n");
  406. request->send(403);
  407. return false;
  408. }
  409. return true;
  410. }
  411. ArRequestHandlerFunction _bindAPI(unsigned int apiID) {
  412. return [apiID](AsyncWebServerRequest *request) {
  413. webLogRequest(request);
  414. if (!_authAPI(request)) return;
  415. bool asJson = false;
  416. if (request->hasHeader("Accept")) {
  417. AsyncWebHeader* h = request->getHeader("Accept");
  418. asJson = h->value().equals("application/json");
  419. }
  420. web_api_t api = _apis[apiID];
  421. if (request->method() == HTTP_PUT) {
  422. if (request->hasParam("value", true)) {
  423. AsyncWebParameter* p = request->getParam("value", true);
  424. (api.putFn)((p->value()).c_str());
  425. }
  426. }
  427. char value[10];
  428. (api.getFn)(value, 10);
  429. // jump over leading spaces
  430. char *p = value;
  431. while ((unsigned char) *p == ' ') ++p;
  432. if (asJson) {
  433. char buffer[64];
  434. sprintf_P(buffer, PSTR("{ \"%s\": %s }"), api.key, p);
  435. request->send(200, "application/json", buffer);
  436. } else {
  437. request->send(200, "text/plain", p);
  438. }
  439. };
  440. }
  441. void apiRegister(const char * url, const char * key, apiGetCallbackFunction getFn, apiPutCallbackFunction putFn) {
  442. // Store it
  443. web_api_t api;
  444. api.url = strdup(url);
  445. api.key = strdup(key);
  446. api.getFn = getFn;
  447. api.putFn = putFn;
  448. _apis.push_back(api);
  449. // Bind call
  450. unsigned int methods = HTTP_GET;
  451. if (putFn != NULL) methods += HTTP_PUT;
  452. server.on(url, methods, _bindAPI(_apis.size() - 1));
  453. }
  454. void _onAPIs(AsyncWebServerRequest *request) {
  455. webLogRequest(request);
  456. if (!_authAPI(request)) return;
  457. bool asJson = false;
  458. if (request->hasHeader("Accept")) {
  459. AsyncWebHeader* h = request->getHeader("Accept");
  460. asJson = h->value().equals("application/json");
  461. }
  462. String output;
  463. if (asJson) {
  464. DynamicJsonBuffer jsonBuffer;
  465. JsonObject& root = jsonBuffer.createObject();
  466. for (unsigned int i=0; i < _apis.size(); i++) {
  467. root[_apis[i].key] = _apis[i].url;
  468. }
  469. root.printTo(output);
  470. request->send(200, "application/json", output);
  471. } else {
  472. for (unsigned int i=0; i < _apis.size(); i++) {
  473. output += _apis[i].key + String(" -> ") + _apis[i].url + String("\n<br />");
  474. }
  475. request->send(200, "text/plain", output);
  476. }
  477. }
  478. void _onHome(AsyncWebServerRequest *request) {
  479. DEBUG_MSG("[DEBUG] Free heap: %d bytes\n", ESP.getFreeHeap());
  480. FSInfo fs_info;
  481. if (SPIFFS.info(fs_info)) {
  482. DEBUG_MSG("[DEBUG] File system total size: %d bytes\n", fs_info.totalBytes);
  483. DEBUG_MSG(" used size : %d bytes\n", fs_info.usedBytes);
  484. DEBUG_MSG(" block size: %d bytes\n", fs_info.blockSize);
  485. DEBUG_MSG(" page size : %d bytes\n", fs_info.pageSize);
  486. DEBUG_MSG(" max files : %d\n", fs_info.maxOpenFiles);
  487. DEBUG_MSG(" max length: %d\n", fs_info.maxPathLength);
  488. } else {
  489. DEBUG_MSG("[DEBUG] Error, FS not accesible!\n");
  490. }
  491. webLogRequest(request);
  492. if (!_authenticate(request)) return request->requestAuthentication();
  493. String password = getSetting("adminPass", ADMIN_PASS);
  494. if (password.equals(ADMIN_PASS)) {
  495. request->send(SPIFFS, "/password.html");
  496. } else {
  497. request->send(SPIFFS, "/index.html");
  498. }
  499. }
  500. void _onAuth(AsyncWebServerRequest *request) {
  501. webLogRequest(request);
  502. if (!_authenticate(request)) return request->requestAuthentication();
  503. IPAddress ip = request->client()->remoteIP();
  504. unsigned long now = millis();
  505. unsigned short index;
  506. for (index = 0; index < WS_BUFFER_SIZE; index++) {
  507. if (_ticket[index].ip == ip) break;
  508. if (_ticket[index].timestamp == 0) break;
  509. if (now - _ticket[index].timestamp > WS_TIMEOUT) break;
  510. }
  511. if (index == WS_BUFFER_SIZE) {
  512. request->send(423);
  513. } else {
  514. _ticket[index].ip = ip;
  515. _ticket[index].timestamp = now;
  516. request->send(204);
  517. }
  518. }
  519. AsyncWebServer * getServer() {
  520. return &server;
  521. }
  522. void webSetup() {
  523. // Setup websocket
  524. ws.onEvent(_wsEvent);
  525. mqttRegister(wsMQTTCallback);
  526. // Setup webserver
  527. server.addHandler(&ws);
  528. // Serve home (basic authentication protection)
  529. server.on("/", HTTP_GET, _onHome);
  530. server.on("/index.html", HTTP_GET, _onHome);
  531. server.on("/auth", HTTP_GET, _onAuth);
  532. server.on("/apis", HTTP_GET, _onAPIs);
  533. // Serve static files
  534. char lastModified[50];
  535. sprintf(lastModified, "%s %s GMT", __DATE__, __TIME__);
  536. server.serveStatic("/", SPIFFS, "/").setLastModified(lastModified);
  537. // 404
  538. server.onNotFound([](AsyncWebServerRequest *request){
  539. request->send(404);
  540. });
  541. // Run server
  542. server.begin();
  543. }