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.

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