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.

984 lines
28 KiB

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