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.

1018 lines
30 KiB

8 years ago
7 years ago
7 years ago
7 years ago
8 years ago
8 years ago
7 years ago
7 years ago
7 years ago
7 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
  1. var websock;
  2. var password = false;
  3. var maxNetworks;
  4. var messages = [];
  5. var webhost;
  6. var numChanged = 0;
  7. var numReboot = 0;
  8. var numReconnect = 0;
  9. var numReload = 0;
  10. var useWhite = false;
  11. // -----------------------------------------------------------------------------
  12. // Messages
  13. // -----------------------------------------------------------------------------
  14. function initMessages() {
  15. messages[ 1] = "Remote update started";
  16. messages[ 2] = "OTA update started";
  17. messages[ 3] = "Error parsing data!";
  18. messages[ 4] = "The file does not look like a valid configuration backup or is corrupted";
  19. messages[ 5] = "Changes saved. You should reboot your board now";
  20. messages[ 7] = "Passwords do not match!";
  21. messages[ 8] = "Changes saved";
  22. messages[ 9] = "No changes detected";
  23. messages[10] = "Session expired, please reload page...";
  24. }
  25. function sensorType(type) {
  26. var types = [
  27. "Temperature", "Humidity", "Pressure",
  28. "Current", "Voltage", "Active Power", "Apparent Power",
  29. "Reactive Power", "Energy", "Energy (delta)", "Power Factor",
  30. "Analog", "Digital", "Events",
  31. "PM1.0", "PM2.5", "PM10", "CO2"
  32. ];
  33. if (1 <= type && type <= types.length) return types[type-1];
  34. return null;
  35. }
  36. // -----------------------------------------------------------------------------
  37. // Utils
  38. // -----------------------------------------------------------------------------
  39. // http://www.the-art-of-web.com/javascript/validate-password/
  40. function checkPassword(str) {
  41. // at least one lowercase and one uppercase letter or number
  42. // at least five characters (letters, numbers or special characters)
  43. var re = /^(?=.*[A-Z\d])(?=.*[a-z])[\w~!@#$%^&*\(\)<>,.\?;:{}\[\]\\|]{5,}$/;
  44. return re.test(str);
  45. }
  46. function zeroPad(number, positions) {
  47. return ("0".repeat(positions) + number).slice(-positions);
  48. }
  49. function validateForm(form) {
  50. // password
  51. var adminPass1 = $("input[name='adminPass1']", form).val();
  52. if (adminPass1.length > 0 && !checkPassword(adminPass1)) {
  53. alert("The password you have entered is not valid, it must have at least 5 characters, 1 lowercase and 1 uppercase or number!");
  54. return false;
  55. }
  56. var adminPass2 = $("input[name='adminPass2']", form).val();
  57. if (adminPass1 != adminPass2) {
  58. alert("Passwords are different!");
  59. return false;
  60. }
  61. return true;
  62. }
  63. function valueSet(data, name, value) {
  64. for (var i in data) {
  65. if (data[i]['name'] == name) {
  66. data[i]['value'] = value;
  67. return;
  68. }
  69. }
  70. data.push({'name': name, 'value': value});
  71. }
  72. function randomString(length, chars) {
  73. var mask = '';
  74. if (chars.indexOf('a') > -1) mask += 'abcdefghijklmnopqrstuvwxyz';
  75. if (chars.indexOf('A') > -1) mask += 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
  76. if (chars.indexOf('#') > -1) mask += '0123456789';
  77. if (chars.indexOf('@') > -1) mask += 'ABCDEF';
  78. if (chars.indexOf('!') > -1) mask += '~`!@#$%^&*()_+-={}[]:";\'<>?,./|\\';
  79. var result = '';
  80. for (var i = length; i > 0; --i) result += mask[Math.round(Math.random() * (mask.length - 1))];
  81. return result;
  82. }
  83. function generateAPIKey() {
  84. var apikey = randomString(16, '@#');
  85. $("input[name=\"apiKey\"]").val(apikey);
  86. return false;
  87. }
  88. function getJson(str) {
  89. try {
  90. return JSON.parse(str);
  91. } catch (e) {
  92. return false;
  93. }
  94. }
  95. // -----------------------------------------------------------------------------
  96. // Actions
  97. // -----------------------------------------------------------------------------
  98. function doReload(milliseconds) {
  99. milliseconds = (typeof milliseconds == 'undefined') ? 0 : parseInt(milliseconds);
  100. setTimeout(function() {
  101. window.location.reload();
  102. }, milliseconds);
  103. }
  104. function doUpdate() {
  105. var form = $("#formSave");
  106. if (validateForm(form)) {
  107. // Get data
  108. var data = form.serializeArray();
  109. // Post-process
  110. delete(data['filename']);
  111. $("input[type='checkbox']").each(function() {
  112. var name = $(this).attr("name");
  113. if (name) {
  114. valueSet(data, name, $(this).is(':checked') ? 1 : 0);
  115. }
  116. });
  117. websock.send(JSON.stringify({'config': data}));
  118. $(".pwrExpected").val(0);
  119. $("input[name='pwrResetCalibration']")
  120. .prop("checked", false)
  121. .iphoneStyle("refresh");
  122. numChanged = 0;
  123. setTimeout(function() {
  124. if (numReboot > 0) {
  125. var response = window.confirm("You have to reboot the board for the changes to take effect, do you want to do it now?");
  126. if (response == true) doReboot(false);
  127. } else if (numReconnect > 0) {
  128. var response = window.confirm("You have to reconnect to the WiFi for the changes to take effect, do you want to do it now?");
  129. if (response == true) doReconnect(false);
  130. } else if (numReload > 0) {
  131. var response = window.confirm("You have to reload the page to see the latest changes, do you want to do it now?");
  132. if (response == true) doReload();
  133. }
  134. resetOriginals();
  135. }, 1000);
  136. }
  137. return false;
  138. }
  139. function doUpgrade() {
  140. var contents = $("input[name='upgrade']")[0].files[0];
  141. if (typeof contents == 'undefined') {
  142. alert("First you have to select a file from your computer.");
  143. return false;
  144. }
  145. var filename = $("input[name='upgrade']").val().split('\\').pop();
  146. var data = new FormData();
  147. data.append('upgrade', contents, filename);
  148. $.ajax({
  149. // Your server script to process the upload
  150. url: webhost + 'upgrade',
  151. type: 'POST',
  152. // Form data
  153. data: data,
  154. // Tell jQuery not to process data or worry about content-type
  155. // You *must* include these options!
  156. cache: false,
  157. contentType: false,
  158. processData: false,
  159. success: function(data, text) {
  160. $("#upgrade-progress").hide();
  161. if (data == 'OK') {
  162. alert("Firmware image uploaded, board rebooting. This page will be refreshed in 5 seconds.");
  163. doReload(5000);
  164. } else {
  165. alert("There was an error trying to upload the new image, please try again (" + data + ").");
  166. }
  167. },
  168. // Custom XMLHttpRequest
  169. xhr: function() {
  170. $("#upgrade-progress").show();
  171. var myXhr = $.ajaxSettings.xhr();
  172. if (myXhr.upload) {
  173. // For handling the progress of the upload
  174. myXhr.upload.addEventListener('progress', function(e) {
  175. if (e.lengthComputable) {
  176. $('progress').attr({ value: e.loaded, max: e.total });
  177. }
  178. } , false);
  179. }
  180. return myXhr;
  181. },
  182. });
  183. return false;
  184. }
  185. function doUpdatePassword() {
  186. var form = $("#formPassword");
  187. if (validateForm(form)) {
  188. var data = form.serializeArray();
  189. websock.send(JSON.stringify({'config': data}));
  190. }
  191. return false;
  192. }
  193. function doReboot(ask) {
  194. ask = (typeof ask == 'undefined') ? true : ask;
  195. if (numChanged > 0) {
  196. var response = window.confirm("Some changes have not been saved yet, do you want to save them first?");
  197. if (response == true) return doUpdate();
  198. }
  199. if (ask) {
  200. var response = window.confirm("Are you sure you want to reboot the device?");
  201. if (response == false) return false;
  202. }
  203. websock.send(JSON.stringify({'action': 'reboot'}));
  204. doReload(5000);
  205. return false;
  206. }
  207. function doReconnect(ask) {
  208. ask = (typeof ask == 'undefined') ? true : ask;
  209. if (numChanged > 0) {
  210. var response = window.confirm("Some changes have not been saved yet, do you want to save them first?");
  211. if (response == true) return doUpdate();
  212. }
  213. if (ask) {
  214. var response = window.confirm("Are you sure you want to disconnect from the current WIFI network?");
  215. if (response == false) return false;
  216. }
  217. websock.send(JSON.stringify({'action': 'reconnect'}));
  218. doReload(5000);
  219. return false;
  220. }
  221. function doBackup() {
  222. document.getElementById('downloader').src = webhost + 'config';
  223. return false;
  224. }
  225. function onFileUpload(event) {
  226. var inputFiles = this.files;
  227. if (inputFiles == undefined || inputFiles.length == 0) return false;
  228. var inputFile = inputFiles[0];
  229. this.value = "";
  230. var response = window.confirm("Previous settings will be overwritten. Are you sure you want to restore this settings?");
  231. if (response == false) return false;
  232. var reader = new FileReader();
  233. reader.onload = function(e) {
  234. var data = getJson(e.target.result);
  235. if (data) {
  236. websock.send(JSON.stringify({'action': 'restore', 'data': data}));
  237. } else {
  238. alert(messages[4]);
  239. }
  240. };
  241. reader.readAsText(inputFile);
  242. return false;
  243. }
  244. function doRestore() {
  245. if (typeof window.FileReader !== 'function') {
  246. alert("The file API isn't supported on this browser yet.");
  247. } else {
  248. $("#uploader").click();
  249. }
  250. return false;
  251. }
  252. function doToggle(element, value) {
  253. var relayID = parseInt(element.attr("data"));
  254. websock.send(JSON.stringify({'action': 'relay', 'data': { 'id': relayID, 'status': value ? 1 : 0 }}));
  255. return false;
  256. }
  257. // -----------------------------------------------------------------------------
  258. // Visualization
  259. // -----------------------------------------------------------------------------
  260. function showPanel() {
  261. $(".panel").hide();
  262. $("#" + $(this).attr("data")).show();
  263. if ($("#layout").hasClass('active')) toggleMenu();
  264. $("input[type='checkbox']").iphoneStyle("calculateDimensions").iphoneStyle("refresh");
  265. };
  266. function toggleMenu() {
  267. $("#layout").toggleClass('active');
  268. $("#menu").toggleClass('active');
  269. $("#menuLink").toggleClass('active');
  270. }
  271. // -----------------------------------------------------------------------------
  272. // Domoticz
  273. // -----------------------------------------------------------------------------
  274. function createRelayIdxs(data) {
  275. var current = $("#domoticzRelays > div").length;
  276. if (current > 0) return;
  277. var template = $("#relayIdxTemplate .pure-g")[0];
  278. for (var i=0; i<data.length; i++) {
  279. var line = $(template).clone();
  280. if (data.length > 1) $("label", line).html("Switch #" + i);
  281. $("input", line).attr("name", "dczRelayIdx" + i).attr("tabindex", 40 + i).val(data[i]);
  282. line.appendTo("#domoticzRelays");
  283. }
  284. }
  285. function createSensorIdxs(data) {
  286. var current = $("#domoticzSensors > div").length;
  287. if (current > 0) return;
  288. var template = $("#sensorIdxTemplate .pure-g")[0];
  289. for (var i=0; i<data.length; i++) {
  290. var line = $(template).clone();
  291. $("label", line).html(sensorType(data[i].type));
  292. $("div.hint", line).html(data[i].name);
  293. $("input", line).attr("name", "dczSensor" + i).attr("tabindex", 40 + i).val(data[i].idx);
  294. line.appendTo("#domoticzSensors");
  295. }
  296. }
  297. // -----------------------------------------------------------------------------
  298. // Wifi
  299. // -----------------------------------------------------------------------------
  300. function addNetwork() {
  301. var numNetworks = $("#networks > div").length;
  302. if (numNetworks >= maxNetworks) {
  303. alert("Max number of networks reached");
  304. return;
  305. }
  306. var tabindex = 200 + numNetworks * 10;
  307. var template = $("#networkTemplate").children();
  308. var line = $(template).clone();
  309. $(line).find("input").each(function() {
  310. $(this).attr("tabindex", tabindex++);
  311. });
  312. $(line).find(".button-del-network").on('click', delNetwork);
  313. $(line).find(".button-more-network").on('click', moreNetwork);
  314. line.appendTo("#networks");
  315. return line;
  316. }
  317. function delNetwork() {
  318. var parent = $(this).parents(".pure-g");
  319. $(parent).remove();
  320. }
  321. function moreNetwork() {
  322. var parent = $(this).parents(".pure-g");
  323. $("div.more", parent).toggle();
  324. }
  325. // -----------------------------------------------------------------------------
  326. // Relays
  327. // -----------------------------------------------------------------------------
  328. function initRelays(data) {
  329. var current = $("#relays > div").length;
  330. if (current > 0) return;
  331. var template = $("#relayTemplate .pure-g")[0];
  332. for (var i=0; i<data.length; i++) {
  333. var line = $(template).clone();
  334. if (data.length > 1) $(".relay_id", line).html(" " + (i+1));
  335. $("input", line).attr("data", i).prop("checked", data[i]);
  336. line.appendTo("#relays");
  337. $(":checkbox", line).iphoneStyle({
  338. onChange: doToggle,
  339. resizeContainer: true,
  340. resizeHandle: true,
  341. checkedLabel: 'ON',
  342. uncheckedLabel: 'OFF'
  343. }).iphoneStyle("refresh");
  344. }
  345. }
  346. function addRelayGroup() {
  347. var numGroups = $("#relayGroups > div").length;
  348. var tabindex = 200 + numGroups * 2;
  349. var template = $("#relayGroupTemplate").children();
  350. var line = $(template).clone();
  351. var element = $("span.relay_id", line);
  352. if (element.length) element.html(numGroups+1);
  353. $(line).find("input").each(function() {
  354. $(this).attr("tabindex", tabindex++);
  355. });
  356. line.appendTo("#relayGroups");
  357. return line;
  358. }
  359. // -----------------------------------------------------------------------------
  360. // Sensors
  361. // -----------------------------------------------------------------------------
  362. function initSensors(data) {
  363. // check if already initialized
  364. var done = $("#sensors > div").length;
  365. if (done > 0) return;
  366. // add templates
  367. var template = $("#sensorTemplate").children();
  368. for (var i=0; i<data.length; i++) {
  369. var line = $(template).clone();
  370. $("label", line).html(sensorType(data[i].type));
  371. $("div.hint", line).html(data[i].description);
  372. $("input", line).attr("data", i);
  373. line.appendTo("#sensors");
  374. }
  375. }
  376. // -----------------------------------------------------------------------------
  377. // Lights
  378. // -----------------------------------------------------------------------------
  379. function initColorRGB() {
  380. // check if already initialized
  381. var done = $("#colors > div").length;
  382. if (done > 0) return;
  383. // add template
  384. var template = $("#colorRGBTemplate").children();
  385. var line = $(template).clone();
  386. line.appendTo("#colors");
  387. // init color wheel
  388. $('input[name="color"]').wheelColorPicker({
  389. sliders: 'wrgbp'
  390. }).on('sliderup', function() {
  391. var value = $(this).wheelColorPicker('getValue', 'css');
  392. websock.send(JSON.stringify({'action': 'color', 'data' : {'rgb': value}}));
  393. });
  394. // init bright slider
  395. $('#brightness').on("change", function() {
  396. var value = $(this).val();
  397. var parent = $(this).parents(".pure-g");
  398. $("span", parent).html(value);
  399. websock.send(JSON.stringify({'action': 'color', 'data' : {'brightness': value}}));
  400. });
  401. }
  402. function initColorHSV() {
  403. // check if already initialized
  404. var done = $("#colors > div").length;
  405. if (done > 0) return;
  406. // add template
  407. var template = $("#colorHSVTemplate").children();
  408. var line = $(template).clone();
  409. line.appendTo("#colors");
  410. // init color wheel
  411. $('input[name="color"]').wheelColorPicker({
  412. sliders: 'whsvp'
  413. }).on('sliderup', function() {
  414. var color = $(this).wheelColorPicker('getColor');
  415. var value = parseInt(color.h * 360) + "," + parseInt(color.s * 100) + "," + parseInt(color.v * 100);
  416. websock.send(JSON.stringify({'action': 'color', 'data' : {'hsv': value}}));
  417. });
  418. }
  419. function initChannels(num) {
  420. // check if already initialized
  421. var done = $("#channels > div").length > 0;
  422. if (done) return;
  423. // does it have color channels?
  424. var colors = $("#colors > div").length > 0;
  425. // calculate channels to create
  426. var max = num;
  427. if (colors) {
  428. max = num % 3;
  429. if ((max > 0) & useWhite) max--;
  430. }
  431. var start = num - max;
  432. // add templates
  433. var template = $("#channelTemplate").children();
  434. for (var i=0; i<max; i++) {
  435. var channel_id = start + i;
  436. var line = $(template).clone();
  437. $("span.slider", line).attr("data", channel_id);
  438. $("input.slider", line).attr("data", channel_id).on("change", function() {
  439. var id = $(this).attr("data");
  440. var value = $(this).val();
  441. var parent = $(this).parents(".pure-g");
  442. $("span", parent).html(value);
  443. websock.send(JSON.stringify({'action': 'channel', 'data' : { 'id': id, 'value': value }}));
  444. });
  445. $("label", line).html("Channel " + (channel_id + 1));
  446. line.appendTo("#channels");
  447. }
  448. }
  449. // -----------------------------------------------------------------------------
  450. // RFBridge
  451. // -----------------------------------------------------------------------------
  452. function addRfbNode() {
  453. var numNodes = $("#rfbNodes > fieldset").length;
  454. var template = $("#rfbNodeTemplate").children();
  455. var line = $(template).clone();
  456. var status = true;
  457. $("span", line).html(numNodes+1);
  458. $(line).find("input").each(function() {
  459. $(this).attr("data-id", numNodes);
  460. $(this).attr("data-status", status ? 1 : 0);
  461. status = !status;
  462. });
  463. $(line).find(".button-rfb-learn").on('click', rfbLearn);
  464. $(line).find(".button-rfb-forget").on('click', rfbForget);
  465. $(line).find(".button-rfb-send").on('click', rfbSend);
  466. line.appendTo("#rfbNodes");
  467. return line;
  468. }
  469. function rfbLearn() {
  470. var parent = $(this).parents(".pure-g");
  471. var input = $("input", parent);
  472. websock.send(JSON.stringify({'action': 'rfblearn', 'data' : {'id' : input.attr("data-id"), 'status': input.attr("data-status")}}));
  473. }
  474. function rfbForget() {
  475. var parent = $(this).parents(".pure-g");
  476. var input = $("input", parent);
  477. websock.send(JSON.stringify({'action': 'rfbforget', 'data' : {'id' : input.attr("data-id"), 'status': input.attr("data-status")}}));
  478. }
  479. function rfbSend() {
  480. var parent = $(this).parents(".pure-g");
  481. var input = $("input", parent);
  482. websock.send(JSON.stringify({'action': 'rfbsend', 'data' : {'id' : input.attr("data-id"), 'status': input.attr("data-status"), 'data': input.val()}}));
  483. }
  484. // -----------------------------------------------------------------------------
  485. // Processing
  486. // -----------------------------------------------------------------------------
  487. function processData(data) {
  488. console.log(data);
  489. // title
  490. if ("app_name" in data) {
  491. var title = data.app_name;
  492. if ("app_version" in data) {
  493. title = title + " " + data.app_version;
  494. }
  495. $(".pure-menu-heading").html(title);
  496. if ("hostname" in data) {
  497. title = data.hostname + " - " + title;
  498. }
  499. document.title = title;
  500. }
  501. Object.keys(data).forEach(function(key) {
  502. // ---------------------------------------------------------------------
  503. // ---------------------------------------------------------------------
  504. // Web mode
  505. // ---------------------------------------------------------------------
  506. if (key == "webMode") {
  507. password = data.webMode == 1;
  508. $("#layout").toggle(data.webMode == 0);
  509. $("#password").toggle(data.webMode == 1);
  510. }
  511. // ---------------------------------------------------------------------
  512. // Actions
  513. // ---------------------------------------------------------------------
  514. if (key == "action") {
  515. if (data.action == "reload") doReload(1000);
  516. return;
  517. }
  518. // ---------------------------------------------------------------------
  519. // RFBridge
  520. // ---------------------------------------------------------------------
  521. if (key == "rfbCount") {
  522. for (var i=0; i<data.rfbCount; i++) addRfbNode();
  523. return;
  524. }
  525. if (key == "rfb") {
  526. var nodes = data.rfb;
  527. for (var i in nodes) {
  528. var node = nodes[i];
  529. var element = $("input[name=rfbcode][data-id=" + node["id"] + "][data-status=" + node["status"] + "]");
  530. if (element.length) element.val(node["data"]);
  531. }
  532. return;
  533. }
  534. // ---------------------------------------------------------------------
  535. // Lights
  536. // ---------------------------------------------------------------------
  537. if (key == "rgb") {
  538. initColorRGB();
  539. $("input[name='color']").wheelColorPicker('setValue', data[key], true);
  540. return;
  541. }
  542. if (key == "hsv") {
  543. initColorHSV();
  544. // wheelColorPicker expects HSV to be between 0 and 1 all of them
  545. var chunks = data[key].split(",");
  546. var obj = {};
  547. obj.h = chunks[0] / 360;
  548. obj.s = chunks[1] / 100;
  549. obj.v = chunks[2] / 100;
  550. $("input[name='color']").wheelColorPicker('setColor', obj);
  551. return;
  552. }
  553. if (key == "brightness") {
  554. var slider = $("#brightness");
  555. if (slider.length) slider.val(data[key]);
  556. var span = $("span.brightness");
  557. if (span.length) span.html(data[key]);
  558. return;
  559. }
  560. if (key == "channels") {
  561. var len = data[key].length;
  562. initChannels(len);
  563. for (var i=0; i<len; i++) {
  564. var slider = $("input.slider[data=" + i + "]");
  565. if (slider.length) slider.val(data[key][i]);
  566. var span = $("span.slider[data=" + i + "]");
  567. if (span.length) span.html(data[key][i]);
  568. }
  569. return;
  570. }
  571. if (key == "useWhite") {
  572. useWhite = data[key];
  573. }
  574. // ---------------------------------------------------------------------
  575. // Sensors
  576. // ---------------------------------------------------------------------
  577. if (key == "sensors") {
  578. initSensors(data[key]);
  579. for (var i=0; i<data[key].length; i++) {
  580. var element = $("input[name=sensor][data=" + i + "]");
  581. if (element.length) element.val(data[key][i].value + data[key][i].units);
  582. }
  583. return;
  584. }
  585. // ---------------------------------------------------------------------
  586. // WiFi
  587. // ---------------------------------------------------------------------
  588. if (key == "maxNetworks") {
  589. maxNetworks = parseInt(data.maxNetworks);
  590. return;
  591. }
  592. if (key == "wifi") {
  593. var networks = data.wifi;
  594. for (var i in networks) {
  595. // add a new row
  596. var line = addNetwork();
  597. // fill in the blanks
  598. var wifi = data.wifi[i];
  599. Object.keys(wifi).forEach(function(key) {
  600. var element = $("input[name=" + key + "]", line);
  601. if (element.length) element.val(wifi[key]);
  602. });
  603. }
  604. return;
  605. }
  606. // ---------------------------------------------------------------------
  607. // Relays
  608. // ---------------------------------------------------------------------
  609. if (key == "relayStatus") {
  610. initRelays(data[key]);
  611. return;
  612. }
  613. // Relay groups
  614. if (key == "relayGroups") {
  615. var groups = data.relayGroups;
  616. for (var i in groups) {
  617. // add a new row
  618. var line = addRelayGroup();
  619. // fill in the blanks
  620. var group = data.relayGroups[i];
  621. Object.keys(group).forEach(function(key) {
  622. var element = $("input[name=" + key + "]", line);
  623. if (element.length) element.val(group[key]);
  624. });
  625. }
  626. return;
  627. }
  628. // ---------------------------------------------------------------------
  629. // Domoticz
  630. // ---------------------------------------------------------------------
  631. // Domoticz - Relays
  632. if (key == "dczRelayIdx") {
  633. createRelayIdxs(data[key]);
  634. return;
  635. }
  636. // Domoticz - Sensors
  637. if (key == "dczSensors") {
  638. createSensorIdxs(data[key]);
  639. return;
  640. }
  641. // ---------------------------------------------------------------------
  642. // General
  643. // ---------------------------------------------------------------------
  644. // Messages
  645. if (key == "message") {
  646. window.alert(messages[data.message]);
  647. return;
  648. }
  649. // Enable options
  650. if (key.endsWith("Visible")) {
  651. var module = key.slice(0,-7);
  652. $(".module-" + module).show();
  653. return;
  654. }
  655. // Pre-process
  656. if (key == "network") {
  657. data.network = data.network.toUpperCase();
  658. }
  659. if (key == "mqttStatus") {
  660. data.mqttStatus = data.mqttStatus ? "CONNECTED" : "NOT CONNECTED";
  661. }
  662. if (key == "ntpStatus") {
  663. data.ntpStatus = data.ntpStatus ? "SYNC'D" : "NOT SYNC'D";
  664. }
  665. if (key == "uptime") {
  666. var uptime = parseInt(data[key]);
  667. var seconds = uptime % 60; uptime = parseInt(uptime / 60);
  668. var minutes = uptime % 60; uptime = parseInt(uptime / 60);
  669. var hours = uptime % 24; uptime = parseInt(uptime / 24);
  670. var days = uptime;
  671. data[key] = days + 'd ' + zeroPad(hours, 2) + 'h ' + zeroPad(minutes, 2) + 'm ' + zeroPad(seconds, 2) + 's';
  672. }
  673. // ---------------------------------------------------------------------
  674. // Matching
  675. // ---------------------------------------------------------------------
  676. // Look for INPUTs
  677. var element = $("input[name=" + key + "]");
  678. if (element.length > 0) {
  679. if (element.attr('type') == 'checkbox') {
  680. element
  681. .prop("checked", data[key])
  682. .iphoneStyle("refresh");
  683. } else if (element.attr('type') == 'radio') {
  684. element.val([data[key]]);
  685. } else {
  686. var pre = element.attr("pre") || "";
  687. var post = element.attr("post") || "";
  688. element.val(pre + data[key] + post);
  689. }
  690. return;
  691. }
  692. // Look for SPANs
  693. var element = $("span[name=" + key + "]");
  694. if (element.length > 0) {
  695. var pre = element.attr("pre") || "";
  696. var post = element.attr("post") || "";
  697. element.html(pre + data[key] + post);
  698. return;
  699. }
  700. // Look for SELECTs
  701. var element = $("select[name=" + key + "]");
  702. if (element.length > 0) {
  703. element.val(data[key]);
  704. return;
  705. }
  706. });
  707. // Auto generate an APIKey if none defined yet
  708. if ($("input[name='apiKey']").val() == "") {
  709. generateAPIKey();
  710. }
  711. resetOriginals();
  712. }
  713. function hasChanged() {
  714. var newValue, originalValue;
  715. if ($(this).attr('type') == 'checkbox') {
  716. newValue = $(this).prop("checked")
  717. originalValue = $(this).attr("original") == "true";
  718. } else {
  719. newValue = $(this).val();
  720. originalValue = $(this).attr("original");
  721. }
  722. var hasChanged = $(this).attr("hasChanged") || 0;
  723. var action = $(this).attr("action");
  724. if (typeof originalValue == 'undefined') return;
  725. if (action == 'none') return;
  726. if (newValue != originalValue) {
  727. if (hasChanged == 0) {
  728. ++numChanged;
  729. if (action == "reconnect") ++numReconnect;
  730. if (action == "reboot") ++numReboot;
  731. if (action == "reload") ++numReload;
  732. $(this).attr("hasChanged", 1);
  733. }
  734. } else {
  735. if (hasChanged == 1) {
  736. --numChanged;
  737. if (action == "reconnect") --numReconnect;
  738. if (action == "reboot") --numReboot;
  739. if (action == "reload") --numReload;
  740. $(this).attr("hasChanged", 0);
  741. }
  742. }
  743. }
  744. function resetOriginals() {
  745. $("input").each(function() {
  746. $(this).attr("original", $(this).val());
  747. })
  748. $("select").each(function() {
  749. $(this).attr("original", $(this).val());
  750. })
  751. numReboot = numReconnect = numReload = 0;
  752. }
  753. // -----------------------------------------------------------------------------
  754. // Init & connect
  755. // -----------------------------------------------------------------------------
  756. function connect(host) {
  757. if (typeof host === 'undefined') {
  758. host = window.location.href.replace('#', '');
  759. } else {
  760. if (!host.startsWith("http")) {
  761. host = 'http://' + host + '/';
  762. }
  763. }
  764. if (!host.startsWith("http")) return;
  765. webhost = host;
  766. wshost = host.replace('http', 'ws') + 'ws';
  767. if (websock) websock.close();
  768. websock = new WebSocket(wshost);
  769. websock.onopen = function(evt) {
  770. console.log("Connected");
  771. };
  772. websock.onclose = function(evt) {
  773. console.log("Disconnected");
  774. };
  775. websock.onerror = function(evt) {
  776. console.log("Error: ", evt);
  777. };
  778. websock.onmessage = function(evt) {
  779. var data = getJson(evt.data);
  780. if (data) processData(data);
  781. };
  782. }
  783. function init() {
  784. initMessages();
  785. $("#menuLink").on('click', toggleMenu);
  786. $(".pure-menu-link").on('click', showPanel);
  787. $('progress').attr({ value: 0, max: 100 });
  788. $(".button-update").on('click', doUpdate);
  789. $(".button-update-password").on('click', doUpdatePassword);
  790. $(".button-reboot").on('click', doReboot);
  791. $(".button-reconnect").on('click', doReconnect);
  792. $(".button-settings-backup").on('click', doBackup);
  793. $(".button-settings-restore").on('click', doRestore);
  794. $('#uploader').on('change', onFileUpload);
  795. $(".button-upgrade").on('click', doUpgrade);
  796. $(".button-apikey").on('click', generateAPIKey);
  797. $(".button-upgrade-browse").on('click', function() {
  798. $("input[name='upgrade']")[0].click();
  799. return false;
  800. });
  801. $("input[name='upgrade']").change(function (){
  802. var fileName = $(this).val();
  803. $("input[name='filename']").val(fileName.replace(/^.*[\\\/]/, ''));
  804. });
  805. $(".button-add-network").on('click', function() {
  806. $("div.more", addNetwork()).toggle();
  807. });
  808. $(document).on('change', 'input', hasChanged);
  809. $(document).on('change', 'select', hasChanged);
  810. connect();
  811. }
  812. $(init);