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.

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