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.

755 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 <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. root["tmpCorrection"] = getSetting("tmpCorrection", TMP_CORRECTION).toFloat();
  417. #if HOMEASSISTANT_SUPPORT
  418. root["haVisible"] = 1;
  419. root["haPrefix"] = getSetting("haPrefix", HOMEASSISTANT_PREFIX);
  420. #endif // HOMEASSISTANT_SUPPORT
  421. #if DOMOTICZ_SUPPORT
  422. root["dczVisible"] = 1;
  423. root["dczEnabled"] = getSetting("dczEnabled", DOMOTICZ_ENABLED).toInt() == 1;
  424. root["dczSkip"] = getSetting("dczSkip", DOMOTICZ_SKIP_TIME);
  425. root["dczTopicIn"] = getSetting("dczTopicIn", DOMOTICZ_IN_TOPIC);
  426. root["dczTopicOut"] = getSetting("dczTopicOut", DOMOTICZ_OUT_TOPIC);
  427. JsonArray& dczRelayIdx = root.createNestedArray("dczRelayIdx");
  428. for (byte i=0; i<relayCount(); i++) {
  429. dczRelayIdx.add(domoticzIdx(i));
  430. }
  431. #if DHT_SUPPORT
  432. root["dczTmpIdx"] = getSetting("dczTmpIdx").toInt();
  433. root["dczHumIdx"] = getSetting("dczHumIdx").toInt();
  434. #endif
  435. #if DS18B20_SUPPORT
  436. root["dczTmpIdx"] = getSetting("dczTmpIdx").toInt();
  437. #endif
  438. #if ANALOG_SUPPORT
  439. root["dczAnaIdx"] = getSetting("dczAnaIdx").toInt();
  440. #endif
  441. #if POWER_PROVIDER != POWER_PROVIDER_NONE
  442. root["dczPowIdx"] = getSetting("dczPowIdx").toInt();
  443. root["dczEnergyIdx"] = getSetting("dczEnergyIdx").toInt();
  444. root["dczCurrentIdx"] = getSetting("dczCurrentIdx").toInt();
  445. #if POWER_HAS_ACTIVE
  446. root["dczVoltIdx"] = getSetting("dczVoltIdx").toInt();
  447. #endif
  448. #endif
  449. #endif
  450. #if DS18B20_SUPPORT
  451. root["dsVisible"] = 1;
  452. root["dsTmp"] = getDSTemperatureStr();
  453. #endif
  454. #if DHT_SUPPORT
  455. root["dhtVisible"] = 1;
  456. root["dhtTmp"] = getDHTTemperature();
  457. root["dhtHum"] = getDHTHumidity();
  458. #endif
  459. #if RF_SUPPORT
  460. root["rfVisible"] = 1;
  461. root["rfChannel"] = getSetting("rfChannel", RF_CHANNEL);
  462. root["rfDevice"] = getSetting("rfDevice", RF_DEVICE);
  463. #endif
  464. #if POWER_PROVIDER != POWER_PROVIDER_NONE
  465. root["pwrVisible"] = 1;
  466. root["pwrCurrent"] = getCurrent();
  467. root["pwrVoltage"] = getVoltage();
  468. root["pwrApparent"] = getApparentPower();
  469. root["pwrEnergy"] = getPowerEnergy();
  470. root["pwrReadEvery"] = powerReadInterval();
  471. root["pwrReportEvery"] = powerReportInterval();
  472. #if POWER_HAS_ACTIVE
  473. root["pwrActive"] = getActivePower();
  474. root["pwrReactive"] = getReactivePower();
  475. root["pwrFactor"] = int(100 * getPowerFactor());
  476. #endif
  477. #if (POWER_PROVIDER == POWER_PROVIDER_EMON_ANALOG) || (POWER_PROVIDER == POWER_PROVIDER_EMON_ADC121)
  478. root["emonVisible"] = 1;
  479. #endif
  480. #if POWER_PROVIDER == POWER_PROVIDER_HLW8012
  481. root["hlwVisible"] = 1;
  482. #endif
  483. #if POWER_PROVIDER == POWER_PROVIDER_V9261F
  484. root["v9261fVisible"] = 1;
  485. #endif
  486. #if POWER_PROVIDER == POWER_PROVIDER_ECH1560
  487. root["ech1560fVisible"] = 1;
  488. #endif
  489. #endif
  490. #if NOFUSS_SUPPORT
  491. root["nofussVisible"] = 1;
  492. root["nofussEnabled"] = getSetting("nofussEnabled", NOFUSS_ENABLED).toInt() == 1;
  493. root["nofussServer"] = getSetting("nofussServer", NOFUSS_SERVER);
  494. #endif
  495. #ifdef ITEAD_SONOFF_RFBRIDGE
  496. root["rfbVisible"] = 1;
  497. root["rfbCount"] = relayCount();
  498. JsonArray& rfb = root.createNestedArray("rfb");
  499. for (byte id=0; id<relayCount(); id++) {
  500. for (byte status=0; status<2; status++) {
  501. JsonObject& node = rfb.createNestedObject();
  502. node["id"] = id;
  503. node["status"] = status;
  504. node["data"] = rfbRetrieve(id, status == 1);
  505. }
  506. }
  507. #endif
  508. #if TELNET_SUPPORT
  509. root["telnetVisible"] = 1;
  510. root["telnetSTA"] = getSetting("telnetSTA", TELNET_STA).toInt() == 1;
  511. #endif
  512. root["maxNetworks"] = WIFI_MAX_NETWORKS;
  513. JsonArray& wifi = root.createNestedArray("wifi");
  514. for (byte i=0; i<WIFI_MAX_NETWORKS; i++) {
  515. if (getSetting("ssid" + String(i)).length() == 0) break;
  516. JsonObject& network = wifi.createNestedObject();
  517. network["ssid"] = getSetting("ssid" + String(i));
  518. network["pass"] = getSetting("pass" + String(i));
  519. network["ip"] = getSetting("ip" + String(i));
  520. network["gw"] = getSetting("gw" + String(i));
  521. network["mask"] = getSetting("mask" + String(i));
  522. network["dns"] = getSetting("dns" + String(i));
  523. }
  524. // Module setters
  525. for (unsigned char i = 0; i < _ws_sender_callbacks.size(); i++) {
  526. (_ws_sender_callbacks[i])(root);
  527. }
  528. }
  529. String output;
  530. root.printTo(output);
  531. wsSend(client_id, (char *) output.c_str());
  532. }
  533. void _wsEvent(AsyncWebSocket * server, AsyncWebSocketClient * client, AwsEventType type, void * arg, uint8_t *data, size_t len){
  534. if (type == WS_EVT_CONNECT) {
  535. IPAddress ip = client->remoteIP();
  536. 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());
  537. _wsStart(client->id());
  538. client->_tempObject = new WebSocketIncommingBuffer(&_wsParse, true);
  539. wifiReconnectCheck();
  540. } else if(type == WS_EVT_DISCONNECT) {
  541. DEBUG_MSG_P(PSTR("[WEBSOCKET] #%u disconnected\n"), client->id());
  542. if (client->_tempObject) {
  543. delete (WebSocketIncommingBuffer *) client->_tempObject;
  544. }
  545. wifiReconnectCheck();
  546. } else if(type == WS_EVT_ERROR) {
  547. DEBUG_MSG_P(PSTR("[WEBSOCKET] #%u error(%u): %s\n"), client->id(), *((uint16_t*)arg), (char*)data);
  548. } else if(type == WS_EVT_PONG) {
  549. DEBUG_MSG_P(PSTR("[WEBSOCKET] #%u pong(%u): %s\n"), client->id(), len, len ? (char*) data : "");
  550. } else if(type == WS_EVT_DATA) {
  551. //DEBUG_MSG_P(PSTR("[WEBSOCKET] #%u data(%u): %s\n"), client->id(), len, len ? (char*) data : "");
  552. WebSocketIncommingBuffer *buffer = (WebSocketIncommingBuffer *)client->_tempObject;
  553. AwsFrameInfo * info = (AwsFrameInfo*)arg;
  554. buffer->data_event(client, info, data, len);
  555. }
  556. }
  557. // -----------------------------------------------------------------------------
  558. // Piblic API
  559. // -----------------------------------------------------------------------------
  560. bool wsConnected() {
  561. return (_ws.count() > 0);
  562. }
  563. void wsRegister(ws_callback_f sender, ws_callback_f receiver) {
  564. _ws_sender_callbacks.push_back(sender);
  565. if (receiver) _ws_receiver_callbacks.push_back(receiver);
  566. }
  567. void wsSend(ws_callback_f sender) {
  568. if (_ws.count() > 0) {
  569. DynamicJsonBuffer jsonBuffer;
  570. JsonObject& root = jsonBuffer.createObject();
  571. sender(root);
  572. String output;
  573. root.printTo(output);
  574. wsSend((char *) output.c_str());
  575. }
  576. }
  577. void wsSend(const char * payload) {
  578. if (_ws.count() > 0) {
  579. _ws.textAll(payload);
  580. }
  581. }
  582. void wsSend_P(PGM_P payload) {
  583. if (_ws.count() > 0) {
  584. char buffer[strlen_P(payload)];
  585. strcpy_P(buffer, payload);
  586. _ws.textAll(buffer);
  587. }
  588. }
  589. void wsSend(uint32_t client_id, const char * payload) {
  590. _ws.text(client_id, payload);
  591. }
  592. void wsSend_P(uint32_t client_id, PGM_P payload) {
  593. char buffer[strlen_P(payload)];
  594. strcpy_P(buffer, payload);
  595. _ws.text(client_id, buffer);
  596. }
  597. void wsConfigure() {
  598. _ws.setAuthentication(WEB_USERNAME, (const char *) getSetting("adminPass", ADMIN_PASS).c_str());
  599. }
  600. void wsSetup() {
  601. _ws.onEvent(_wsEvent);
  602. wsConfigure();
  603. webServer()->addHandler(&_ws);
  604. mqttRegister(_wsMQTTCallback);
  605. }
  606. #endif // WEB_SUPPORT