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.

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