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.

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