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