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.

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