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.

751 lines
25 KiB

  1. /*
  2. WEBSOCKET 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 <ArduinoJson.h>
  9. #include "ws.h"
  10. AsyncWebSocket _ws("/ws");
  11. // -----------------------------------------------------------------------------
  12. // Private methods
  13. // -----------------------------------------------------------------------------
  14. void _wsMQTTCallback(unsigned int type, const char * topic, const char * payload) {
  15. if (type == MQTT_CONNECT_EVENT) {
  16. wsSend_P(PSTR("{\"mqttStatus\": true}"));
  17. }
  18. if (type == MQTT_DISCONNECT_EVENT) {
  19. wsSend_P(PSTR("{\"mqttStatus\": false}"));
  20. }
  21. }
  22. void _wsParse(AsyncWebSocketClient *client, uint8_t * payload, size_t length) {
  23. //DEBUG_MSG_P(PSTR("[WEBSOCKET] Parsing: %s\n"), length ? (char*) payload : "");
  24. // Get client ID
  25. uint32_t client_id = client->id();
  26. // Parse JSON input
  27. DynamicJsonBuffer jsonBuffer;
  28. JsonObject& root = jsonBuffer.parseObject((char *) payload);
  29. if (!root.success()) {
  30. DEBUG_MSG_P(PSTR("[WEBSOCKET] Error parsing data\n"));
  31. wsSend_P(client_id, PSTR("{\"message\": 3}"));
  32. return;
  33. }
  34. // Check actions
  35. if (root.containsKey("action")) {
  36. String action = root["action"];
  37. DEBUG_MSG_P(PSTR("[WEBSOCKET] Requested action: %s\n"), action.c_str());
  38. if (action.equals("reset")) {
  39. customReset(CUSTOM_RESET_WEB);
  40. ESP.restart();
  41. }
  42. #ifdef ITEAD_SONOFF_RFBRIDGE
  43. if (action.equals("rfblearn") && root.containsKey("data")) {
  44. JsonObject& data = root["data"];
  45. rfbLearn(data["id"], data["status"]);
  46. }
  47. if (action.equals("rfbforget") && root.containsKey("data")) {
  48. JsonObject& data = root["data"];
  49. rfbForget(data["id"], data["status"]);
  50. }
  51. if (action.equals("rfbsend") && root.containsKey("data")) {
  52. JsonObject& data = root["data"];
  53. rfbStore(data["id"], data["status"], data["data"].as<const char*>());
  54. }
  55. #endif
  56. if (action.equals("restore") && root.containsKey("data")) {
  57. JsonObject& data = root["data"];
  58. if (!data.containsKey("app") || (data["app"] != APP_NAME)) {
  59. wsSend_P(client_id, PSTR("{\"message\": 4}"));
  60. return;
  61. }
  62. for (unsigned int i = EEPROM_DATA_END; i < SPI_FLASH_SEC_SIZE; i++) {
  63. EEPROM.write(i, 0xFF);
  64. }
  65. for (auto element : data) {
  66. if (strcmp(element.key, "app") == 0) continue;
  67. if (strcmp(element.key, "version") == 0) continue;
  68. setSetting(element.key, element.value.as<char*>());
  69. }
  70. saveSettings();
  71. wsSend_P(client_id, PSTR("{\"message\": 5}"));
  72. }
  73. if (action.equals("reconnect")) {
  74. // Let the HTTP request return and disconnect after 100ms
  75. _web_defer.once_ms(100, wifiDisconnect);
  76. }
  77. if (action.equals("relay") && root.containsKey("data")) {
  78. JsonObject& data = root["data"];
  79. if (data.containsKey("status")) {
  80. unsigned char value = relayParsePayload(data["status"]);
  81. if (value == 3) {
  82. relayWS();
  83. } else if (value < 3) {
  84. unsigned int relayID = 0;
  85. if (data.containsKey("id")) {
  86. String value = data["id"];
  87. relayID = value.toInt();
  88. }
  89. // Action to perform
  90. if (value == 0) {
  91. relayStatus(relayID, false);
  92. } else if (value == 1) {
  93. relayStatus(relayID, true);
  94. } else if (value == 2) {
  95. relayToggle(relayID);
  96. }
  97. }
  98. }
  99. }
  100. #if LIGHT_PROVIDER != LIGHT_PROVIDER_NONE
  101. if (lightHasColor()) {
  102. if (action.equals("rgb") && root.containsKey("data")) {
  103. lightColor((const char *) root["data"], true);
  104. lightUpdate(true, true);
  105. }
  106. if (action.equals("brightness") && root.containsKey("data")) {
  107. lightBrightness(root["data"]);
  108. lightUpdate(true, true);
  109. }
  110. if (action.equals("hsv") && root.containsKey("data")) {
  111. lightColor((const char *) root["data"], false);
  112. lightUpdate(true, true);
  113. }
  114. }
  115. if (action.equals("channel") && root.containsKey("data")) {
  116. JsonObject& data = root["data"];
  117. if (data.containsKey("id") && data.containsKey("value")) {
  118. lightChannel(data["id"], data["value"]);
  119. lightUpdate(true, true);
  120. }
  121. }
  122. #ifdef LIGHT_PROVIDER_EXPERIMENTAL_RGB_ONLY_HSV_IR
  123. if (action.equals("anim_mode") && root.containsKey("data")) {
  124. lightAnimMode(root["data"]);
  125. lightUpdate(true, true);
  126. }
  127. if (action.equals("anim_speed") && root.containsKey("data")) {
  128. lightAnimSpeed(root["data"]);
  129. lightUpdate(true, true);
  130. }
  131. #endif //LIGHT_PROVIDER_EXPERIMENTAL_RGB_ONLY_HSV_IR
  132. #endif //LIGHT_PROVIDER != LIGHT_PROVIDER_NONE
  133. };
  134. // Check config
  135. if (root.containsKey("config") && root["config"].is<JsonArray&>()) {
  136. JsonArray& config = root["config"];
  137. DEBUG_MSG_P(PSTR("[WEBSOCKET] Parsing configuration data\n"));
  138. unsigned char webMode = WEB_MODE_NORMAL;
  139. bool save = false;
  140. bool changed = false;
  141. bool changedMQTT = false;
  142. bool changedNTP = false;
  143. unsigned int network = 0;
  144. unsigned int dczRelayIdx = 0;
  145. String adminPass;
  146. for (unsigned int i=0; i<config.size(); i++) {
  147. String key = config[i]["name"];
  148. String value = config[i]["value"];
  149. // Skip firmware filename
  150. if (key.equals("filename")) continue;
  151. #if POWER_PROVIDER != POWER_PROVIDER_NONE
  152. if (key == "pwrExpectedP") {
  153. powerCalibrate(POWER_MAGNITUDE_ACTIVE, value.toFloat());
  154. changed = true;
  155. continue;
  156. }
  157. if (key == "pwrExpectedV") {
  158. powerCalibrate(POWER_MAGNITUDE_VOLTAGE, value.toFloat());
  159. changed = true;
  160. continue;
  161. }
  162. if (key == "pwrExpectedC") {
  163. powerCalibrate(POWER_MAGNITUDE_CURRENT, value.toFloat());
  164. changed = true;
  165. continue;
  166. }
  167. if (key == "pwrExpectedF") {
  168. powerCalibrate(POWER_MAGNITUDE_POWER_FACTOR, value.toFloat());
  169. changed = true;
  170. continue;
  171. }
  172. if (key == "pwrResetCalibration") {
  173. if (value.toInt() == 1) {
  174. powerResetCalibration();
  175. changed = true;
  176. }
  177. continue;
  178. }
  179. #endif
  180. #if DOMOTICZ_SUPPORT
  181. if (key == "dczRelayIdx") {
  182. if (dczRelayIdx >= relayCount()) continue;
  183. key = key + String(dczRelayIdx);
  184. ++dczRelayIdx;
  185. }
  186. #else
  187. if (key.startsWith("dcz")) continue;
  188. #endif
  189. // Web portions
  190. if (key == "webPort") {
  191. if ((value.toInt() == 0) || (value.toInt() == 80)) {
  192. save = changed = true;
  193. delSetting(key);
  194. continue;
  195. }
  196. }
  197. if (key == "webMode") {
  198. webMode = value.toInt();
  199. continue;
  200. }
  201. // Check password
  202. if (key == "adminPass1") {
  203. adminPass = value;
  204. continue;
  205. }
  206. if (key == "adminPass2") {
  207. if (!value.equals(adminPass)) {
  208. wsSend_P(client_id, PSTR("{\"message\": 7}"));
  209. return;
  210. }
  211. if (value.length() == 0) continue;
  212. wsSend_P(client_id, PSTR("{\"action\": \"reload\"}"));
  213. key = String("adminPass");
  214. }
  215. if (key == "ssid") {
  216. key = key + String(network);
  217. }
  218. if (key == "pass") {
  219. key = key + String(network);
  220. }
  221. if (key == "ip") {
  222. key = key + String(network);
  223. }
  224. if (key == "gw") {
  225. key = key + String(network);
  226. }
  227. if (key == "mask") {
  228. key = key + String(network);
  229. }
  230. if (key == "dns") {
  231. key = key + String(network);
  232. ++network;
  233. }
  234. if (value != getSetting(key)) {
  235. //DEBUG_MSG_P(PSTR("[WEBSOCKET] Storing %s = %s\n", key.c_str(), value.c_str()));
  236. setSetting(key, value);
  237. save = changed = true;
  238. if (key.startsWith("mqtt")) changedMQTT = true;
  239. #if NTP_SUPPORT
  240. if (key.startsWith("ntp")) changedNTP = true;
  241. #endif
  242. }
  243. }
  244. if (webMode == WEB_MODE_NORMAL) {
  245. // Clean wifi networks
  246. int i = 0;
  247. while (i < network) {
  248. if (!hasSetting("ssid", i)) {
  249. delSetting("ssid", i);
  250. break;
  251. }
  252. if (!hasSetting("pass", i)) delSetting("pass", i);
  253. if (!hasSetting("ip", i)) delSetting("ip", i);
  254. if (!hasSetting("gw", i)) delSetting("gw", i);
  255. if (!hasSetting("mask", i)) delSetting("mask", i);
  256. if (!hasSetting("dns", i)) delSetting("dns", i);
  257. ++i;
  258. }
  259. while (i < WIFI_MAX_NETWORKS) {
  260. if (hasSetting("ssid", i)) {
  261. save = changed = true;
  262. }
  263. delSetting("ssid", i);
  264. delSetting("pass", i);
  265. delSetting("ip", i);
  266. delSetting("gw", i);
  267. delSetting("mask", i);
  268. delSetting("dns", i);
  269. ++i;
  270. }
  271. }
  272. // Save settings
  273. if (save) {
  274. wsConfigure();
  275. saveSettings();
  276. wifiConfigure();
  277. otaConfigure();
  278. if (changedMQTT) {
  279. mqttConfigure();
  280. mqttDisconnect();
  281. }
  282. #if ALEXA_SUPPORT
  283. alexaConfigure();
  284. #endif
  285. #if INFLUXDB_SUPPORT
  286. idbConfigure();
  287. #endif
  288. #if DOMOTICZ_SUPPORT
  289. domoticzConfigure();
  290. #endif
  291. #if NOFUSS_SUPPORT
  292. nofussConfigure();
  293. #endif
  294. #if RF_SUPPORT
  295. rfBuildCodes();
  296. #endif
  297. #if POWER_PROVIDER != POWER_PROVIDER_NONE
  298. powerConfigure();
  299. #endif
  300. #if LIGHT_PROVIDER != LIGHT_PROVIDER_NONE
  301. #if LIGHT_SAVE_ENABLED == 0
  302. lightSave();
  303. #endif
  304. #endif
  305. #if NTP_SUPPORT
  306. if (changedNTP) ntpConfigure();
  307. #endif
  308. #if HOMEASSISTANT_SUPPORT
  309. haConfigure();
  310. #endif
  311. }
  312. if (changed) {
  313. wsSend_P(client_id, PSTR("{\"message\": 8}"));
  314. } else {
  315. wsSend_P(client_id, PSTR("{\"message\": 9}"));
  316. }
  317. }
  318. }
  319. void _wsStart(uint32_t client_id) {
  320. char chipid[7];
  321. snprintf_P(chipid, sizeof(chipid), PSTR("%06X"), ESP.getChipId());
  322. DynamicJsonBuffer jsonBuffer;
  323. JsonObject& root = jsonBuffer.createObject();
  324. bool changePassword = false;
  325. #if WEB_FORCE_PASS_CHANGE
  326. String adminPass = getSetting("adminPass", ADMIN_PASS);
  327. if (adminPass.equals(ADMIN_PASS)) changePassword = true;
  328. #endif
  329. if (changePassword) {
  330. root["webMode"] = WEB_MODE_PASSWORD;
  331. } else {
  332. root["webMode"] = WEB_MODE_NORMAL;
  333. root["app_name"] = APP_NAME;
  334. root["app_version"] = APP_VERSION;
  335. root["app_build"] = buildTime();
  336. root["manufacturer"] = MANUFACTURER;
  337. root["chipid"] = chipid;
  338. root["mac"] = WiFi.macAddress();
  339. root["device"] = DEVICE;
  340. root["hostname"] = getSetting("hostname");
  341. root["network"] = getNetwork();
  342. root["deviceip"] = getIP();
  343. root["time"] = ntpDateTime();
  344. root["uptime"] = getUptime();
  345. root["heap"] = ESP.getFreeHeap();
  346. root["sketch_size"] = ESP.getSketchSize();
  347. root["free_size"] = ESP.getFreeSketchSpace();
  348. #if NTP_SUPPORT
  349. root["ntpVisible"] = 1;
  350. root["ntpStatus"] = ntpConnected();
  351. root["ntpServer1"] = getSetting("ntpServer1", NTP_SERVER);
  352. root["ntpServer2"] = getSetting("ntpServer2");
  353. root["ntpServer3"] = getSetting("ntpServer3");
  354. root["ntpOffset"] = getSetting("ntpOffset", NTP_TIME_OFFSET).toInt();
  355. root["ntpDST"] = getSetting("ntpDST", NTP_DAY_LIGHT).toInt() == 1;
  356. #endif
  357. root["mqttStatus"] = mqttConnected();
  358. root["mqttEnabled"] = mqttEnabled();
  359. root["mqttServer"] = getSetting("mqttServer", MQTT_SERVER);
  360. root["mqttPort"] = getSetting("mqttPort", MQTT_PORT);
  361. root["mqttUser"] = getSetting("mqttUser");
  362. root["mqttPassword"] = getSetting("mqttPassword");
  363. #if ASYNC_TCP_SSL_ENABLED
  364. root["mqttsslVisible"] = 1;
  365. root["mqttUseSSL"] = getSetting("mqttUseSSL", 0).toInt() == 1;
  366. root["mqttFP"] = getSetting("mqttFP");
  367. #endif
  368. root["mqttTopic"] = getSetting("mqttTopic", MQTT_TOPIC);
  369. root["mqttUseJson"] = getSetting("mqttUseJson", MQTT_USE_JSON).toInt() == 1;
  370. JsonArray& relay = root.createNestedArray("relayStatus");
  371. for (unsigned char relayID=0; relayID<relayCount(); relayID++) {
  372. relay.add(relayStatus(relayID));
  373. }
  374. #if LIGHT_PROVIDER != LIGHT_PROVIDER_NONE
  375. root["colorVisible"] = 1;
  376. root["useColor"] = getSetting("useColor", LIGHT_USE_COLOR).toInt() == 1;
  377. root["useWhite"] = getSetting("useWhite", LIGHT_USE_WHITE).toInt() == 1;
  378. root["useGamma"] = getSetting("useGamma", LIGHT_USE_GAMMA).toInt() == 1;
  379. root["useCSS"] = getSetting("useCSS", LIGHT_USE_CSS).toInt() == 1;
  380. bool useRGB = getSetting("useRGB", LIGHT_USE_RGB).toInt() == 1;
  381. root["useRGB"] = useRGB;
  382. if (lightHasColor()) {
  383. if (useRGB) {
  384. root["rgb"] = lightColor(true);
  385. root["brightness"] = lightBrightness();
  386. } else {
  387. root["hsv"] = lightColor(false);
  388. }
  389. #ifdef LIGHT_PROVIDER_EXPERIMENTAL_RGB_ONLY_HSV_IR
  390. root["anim_mode"] = lightAnimMode();
  391. root["anim_speed"] = lightAnimSpeed();
  392. #endif // LIGHT_PROVIDER_EXPERIMENTAL_RGB_ONLY_HSV_IR
  393. }
  394. JsonArray& channels = root.createNestedArray("channels");
  395. for (unsigned char id=0; id < lightChannels(); id++) {
  396. channels.add(lightChannel(id));
  397. }
  398. #endif
  399. root["relayMode"] = getSetting("relayMode", RELAY_MODE);
  400. root["relayPulseMode"] = getSetting("relayPulseMode", RELAY_PULSE_MODE);
  401. root["relayPulseTime"] = getSetting("relayPulseTime", RELAY_PULSE_TIME).toFloat();
  402. if (relayCount() > 1) {
  403. root["multirelayVisible"] = 1;
  404. root["relaySync"] = getSetting("relaySync", RELAY_SYNC);
  405. }
  406. root["btnDelay"] = getSetting("btnDelay", BUTTON_DBLCLICK_DELAY).toInt();
  407. root["webPort"] = getSetting("webPort", WEB_PORT).toInt();
  408. root["apiEnabled"] = getSetting("apiEnabled", API_ENABLED).toInt() == 1;
  409. root["apiKey"] = getSetting("apiKey");
  410. root["apiRealTime"] = getSetting("apiRealTime", API_REAL_TIME_VALUES).toInt() == 1;
  411. root["tmpUnits"] = getSetting("tmpUnits", TMP_UNITS).toInt();
  412. #if HOMEASSISTANT_SUPPORT
  413. root["haVisible"] = 1;
  414. root["haPrefix"] = getSetting("haPrefix", HOMEASSISTANT_PREFIX);
  415. #endif // HOMEASSISTANT_SUPPORT
  416. #if DOMOTICZ_SUPPORT
  417. root["dczVisible"] = 1;
  418. root["dczEnabled"] = getSetting("dczEnabled", DOMOTICZ_ENABLED).toInt() == 1;
  419. root["dczSkip"] = getSetting("dczSkip", DOMOTICZ_SKIP_TIME);
  420. root["dczTopicIn"] = getSetting("dczTopicIn", DOMOTICZ_IN_TOPIC);
  421. root["dczTopicOut"] = getSetting("dczTopicOut", DOMOTICZ_OUT_TOPIC);
  422. JsonArray& dczRelayIdx = root.createNestedArray("dczRelayIdx");
  423. for (byte i=0; i<relayCount(); i++) {
  424. dczRelayIdx.add(domoticzIdx(i));
  425. }
  426. #if DHT_SUPPORT
  427. root["dczTmpIdx"] = getSetting("dczTmpIdx").toInt();
  428. root["dczHumIdx"] = getSetting("dczHumIdx").toInt();
  429. #endif
  430. #if DS18B20_SUPPORT
  431. root["dczTmpIdx"] = getSetting("dczTmpIdx").toInt();
  432. #endif
  433. #if ANALOG_SUPPORT
  434. root["dczAnaIdx"] = getSetting("dczAnaIdx").toInt();
  435. #endif
  436. #if POWER_PROVIDER != POWER_PROVIDER_NONE
  437. root["dczPowIdx"] = getSetting("dczPowIdx").toInt();
  438. root["dczEnergyIdx"] = getSetting("dczEnergyIdx").toInt();
  439. root["dczCurrentIdx"] = getSetting("dczCurrentIdx").toInt();
  440. #if POWER_HAS_ACTIVE
  441. root["dczVoltIdx"] = getSetting("dczVoltIdx").toInt();
  442. #endif
  443. #endif
  444. #endif
  445. #if INFLUXDB_SUPPORT
  446. root["idbVisible"] = 1;
  447. root["idbHost"] = getSetting("idbHost");
  448. root["idbPort"] = getSetting("idbPort", INFLUXDB_PORT).toInt();
  449. root["idbDatabase"] = getSetting("idbDatabase");
  450. root["idbUsername"] = getSetting("idbUsername");
  451. root["idbPassword"] = getSetting("idbPassword");
  452. #endif
  453. #if ALEXA_SUPPORT
  454. root["alexaVisible"] = 1;
  455. root["alexaEnabled"] = getSetting("alexaEnabled", ALEXA_ENABLED).toInt() == 1;
  456. #endif
  457. #if DS18B20_SUPPORT
  458. root["dsVisible"] = 1;
  459. root["dsTmp"] = getDSTemperatureStr();
  460. #endif
  461. #if DHT_SUPPORT
  462. root["dhtVisible"] = 1;
  463. root["dhtTmp"] = getDHTTemperature();
  464. root["dhtHum"] = getDHTHumidity();
  465. #endif
  466. #if RF_SUPPORT
  467. root["rfVisible"] = 1;
  468. root["rfChannel"] = getSetting("rfChannel", RF_CHANNEL);
  469. root["rfDevice"] = getSetting("rfDevice", RF_DEVICE);
  470. #endif
  471. #if ANALOG_SUPPORT
  472. root["analogVisible"] = 1;
  473. root["analogValue"] = getAnalog();
  474. #endif
  475. #if COUNTER_SUPPORT
  476. root["counterVisible"] = 1;
  477. root["counterValue"] = getCounter();
  478. #endif
  479. #if POWER_PROVIDER != POWER_PROVIDER_NONE
  480. root["pwrVisible"] = 1;
  481. root["pwrCurrent"] = getCurrent();
  482. root["pwrVoltage"] = getVoltage();
  483. root["pwrApparent"] = getApparentPower();
  484. root["pwrEnergy"] = getPowerEnergy();
  485. root["pwrReadEvery"] = powerReadInterval();
  486. root["pwrReportEvery"] = powerReportInterval();
  487. #if POWER_HAS_ACTIVE
  488. root["pwrActive"] = getActivePower();
  489. root["pwrReactive"] = getReactivePower();
  490. root["pwrFactor"] = int(100 * getPowerFactor());
  491. #endif
  492. #if (POWER_PROVIDER == POWER_PROVIDER_EMON_ANALOG) || (POWER_PROVIDER == POWER_PROVIDER_EMON_ADC121)
  493. root["emonVisible"] = 1;
  494. #endif
  495. #if POWER_PROVIDER == POWER_PROVIDER_HLW8012
  496. root["hlwVisible"] = 1;
  497. #endif
  498. #if POWER_PROVIDER == POWER_PROVIDER_V9261F
  499. root["v9261fVisible"] = 1;
  500. #endif
  501. #if POWER_PROVIDER == POWER_PROVIDER_ECH1560
  502. root["ech1560fVisible"] = 1;
  503. #endif
  504. #endif
  505. #if NOFUSS_SUPPORT
  506. root["nofussVisible"] = 1;
  507. root["nofussEnabled"] = getSetting("nofussEnabled", NOFUSS_ENABLED).toInt() == 1;
  508. root["nofussServer"] = getSetting("nofussServer", NOFUSS_SERVER);
  509. #endif
  510. #ifdef ITEAD_SONOFF_RFBRIDGE
  511. root["rfbVisible"] = 1;
  512. root["rfbCount"] = relayCount();
  513. JsonArray& rfb = root.createNestedArray("rfb");
  514. for (byte id=0; id<relayCount(); id++) {
  515. for (byte status=0; status<2; status++) {
  516. JsonObject& node = rfb.createNestedObject();
  517. node["id"] = id;
  518. node["status"] = status;
  519. node["data"] = rfbRetrieve(id, status == 1);
  520. }
  521. }
  522. #endif
  523. #if TELNET_SUPPORT
  524. root["telnetVisible"] = 1;
  525. root["telnetSTA"] = getSetting("telnetSTA", TELNET_STA).toInt() == 1;
  526. #endif
  527. root["maxNetworks"] = WIFI_MAX_NETWORKS;
  528. JsonArray& wifi = root.createNestedArray("wifi");
  529. for (byte i=0; i<WIFI_MAX_NETWORKS; i++) {
  530. if (getSetting("ssid" + String(i)).length() == 0) break;
  531. JsonObject& network = wifi.createNestedObject();
  532. network["ssid"] = getSetting("ssid" + String(i));
  533. network["pass"] = getSetting("pass" + String(i));
  534. network["ip"] = getSetting("ip" + String(i));
  535. network["gw"] = getSetting("gw" + String(i));
  536. network["mask"] = getSetting("mask" + String(i));
  537. network["dns"] = getSetting("dns" + String(i));
  538. }
  539. }
  540. String output;
  541. root.printTo(output);
  542. wsSend(client_id, (char *) output.c_str());
  543. }
  544. void _wsEvent(AsyncWebSocket * server, AsyncWebSocketClient * client, AwsEventType type, void * arg, uint8_t *data, size_t len){
  545. if (type == WS_EVT_CONNECT) {
  546. IPAddress ip = client->remoteIP();
  547. 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());
  548. _wsStart(client->id());
  549. client->_tempObject = new WebSocketIncommingBuffer(&_wsParse, true);
  550. wifiReconnectCheck();
  551. } else if(type == WS_EVT_DISCONNECT) {
  552. DEBUG_MSG_P(PSTR("[WEBSOCKET] #%u disconnected\n"), client->id());
  553. if (client->_tempObject) {
  554. delete (WebSocketIncommingBuffer *) client->_tempObject;
  555. }
  556. wifiReconnectCheck();
  557. } else if(type == WS_EVT_ERROR) {
  558. DEBUG_MSG_P(PSTR("[WEBSOCKET] #%u error(%u): %s\n"), client->id(), *((uint16_t*)arg), (char*)data);
  559. } else if(type == WS_EVT_PONG) {
  560. DEBUG_MSG_P(PSTR("[WEBSOCKET] #%u pong(%u): %s\n"), client->id(), len, len ? (char*) data : "");
  561. } else if(type == WS_EVT_DATA) {
  562. //DEBUG_MSG_P(PSTR("[WEBSOCKET] #%u data(%u): %s\n"), client->id(), len, len ? (char*) data : "");
  563. WebSocketIncommingBuffer *buffer = (WebSocketIncommingBuffer *)client->_tempObject;
  564. AwsFrameInfo * info = (AwsFrameInfo*)arg;
  565. buffer->data_event(client, info, data, len);
  566. }
  567. }
  568. // -----------------------------------------------------------------------------
  569. // Piblic API
  570. // -----------------------------------------------------------------------------
  571. bool wsConnected() {
  572. return (_ws.count() > 0);
  573. }
  574. void wsSend(const char * payload) {
  575. if (_ws.count() > 0) {
  576. _ws.textAll(payload);
  577. }
  578. }
  579. void wsSend_P(PGM_P payload) {
  580. if (_ws.count() > 0) {
  581. char buffer[strlen_P(payload)];
  582. strcpy_P(buffer, payload);
  583. _ws.textAll(buffer);
  584. }
  585. }
  586. void wsSend(uint32_t client_id, const char * payload) {
  587. _ws.text(client_id, payload);
  588. }
  589. void wsSend_P(uint32_t client_id, PGM_P payload) {
  590. char buffer[strlen_P(payload)];
  591. strcpy_P(buffer, payload);
  592. _ws.text(client_id, buffer);
  593. }
  594. void wsConfigure() {
  595. _ws.setAuthentication(WEB_USERNAME, (const char *) getSetting("adminPass", ADMIN_PASS).c_str());
  596. }
  597. void wsSetup() {
  598. _ws.onEvent(_wsEvent);
  599. wsConfigure();
  600. webServer()->addHandler(&_ws);
  601. mqttRegister(_wsMQTTCallback);
  602. }
  603. #endif // WEB_SUPPORT