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.

717 lines
20 KiB

8 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
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 host;
  5. var port;
  6. var useWhite = false;
  7. // http://www.the-art-of-web.com/javascript/validate-password/
  8. function checkPassword(str) {
  9. // at least one number, one lowercase and one uppercase letter
  10. // at least eight characters that are letters, numbers or the underscore
  11. var re = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])\w{8,}$/;
  12. return re.test(str);
  13. }
  14. function validateForm(form) {
  15. // password
  16. var adminPass1 = $("input[name='adminPass1']", form).val();
  17. if (adminPass1.length > 0 && !checkPassword(adminPass1)) {
  18. alert("The password you have entered is not valid, it must have at least 8 characters, 1 lower and 1 uppercase and 1 number!");
  19. return false;
  20. }
  21. var adminPass2 = $("input[name='adminPass2']", form).val();
  22. if (adminPass1 != adminPass2) {
  23. alert("Passwords are different!");
  24. return false;
  25. }
  26. return true;
  27. }
  28. function doUpdate() {
  29. var form = $("#formSave");
  30. if (validateForm(form)) {
  31. var data = form.serializeArray();
  32. delete(data['filename']);
  33. websock.send(JSON.stringify({'config': data}));
  34. $(".powExpected").val(0);
  35. $("input[name='powExpectedReset']")
  36. .prop("checked", false)
  37. .iphoneStyle("refresh");
  38. }
  39. return false;
  40. }
  41. function doUpgrade() {
  42. var contents = $("input[name='upgrade']")[0].files[0];
  43. if (typeof contents == 'undefined') {
  44. alert("First you have to select a file from your computer.");
  45. return false;
  46. }
  47. var filename = $("input[name='upgrade']").val().split('\\').pop();
  48. var data = new FormData();
  49. data.append('upgrade', contents, filename);
  50. $.ajax({
  51. // Your server script to process the upload
  52. url: 'http://' + host + ':' + port + '/upgrade',
  53. type: 'POST',
  54. // Form data
  55. data: data,
  56. // Tell jQuery not to process data or worry about content-type
  57. // You *must* include these options!
  58. cache: false,
  59. contentType: false,
  60. processData: false,
  61. success: function(data, text) {
  62. $("#upgrade-progress").hide();
  63. if (data == 'OK') {
  64. alert("Firmware image uploaded, board rebooting. This page will be refreshed in 5 seconds.");
  65. setTimeout(function() {
  66. window.location = "/";
  67. }, 5000);
  68. } else {
  69. alert("There was an error trying to upload the new image, please try again.");
  70. }
  71. },
  72. // Custom XMLHttpRequest
  73. xhr: function() {
  74. $("#upgrade-progress").show();
  75. var myXhr = $.ajaxSettings.xhr();
  76. if (myXhr.upload) {
  77. // For handling the progress of the upload
  78. myXhr.upload.addEventListener('progress', function(e) {
  79. if (e.lengthComputable) {
  80. $('progress').attr({ value: e.loaded, max: e.total });
  81. }
  82. } , false);
  83. }
  84. return myXhr;
  85. },
  86. });
  87. return false;
  88. }
  89. function doUpdatePassword() {
  90. var form = $("#formPassword");
  91. if (validateForm(form)) {
  92. var data = form.serializeArray();
  93. websock.send(JSON.stringify({'config': data}));
  94. }
  95. return false;
  96. }
  97. function doReset() {
  98. var response = window.confirm("Are you sure you want to reset the device?");
  99. if (response == false) return false;
  100. websock.send(JSON.stringify({'action': 'reset'}));
  101. return false;
  102. }
  103. function doReconnect() {
  104. var response = window.confirm("Are you sure you want to disconnect from the current WIFI network?");
  105. if (response == false) return false;
  106. websock.send(JSON.stringify({'action': 'reconnect'}));
  107. return false;
  108. }
  109. function doToggle(element, value) {
  110. var relayID = parseInt(element.attr("data"));
  111. websock.send(JSON.stringify({'action': 'relay', 'data': { 'id': relayID, 'status': value ? 1 : 0 }}));
  112. return false;
  113. }
  114. function backupSettings() {
  115. document.getElementById('downloader').src = 'http://' + host + ':' + port + '/config';
  116. return false;
  117. }
  118. function onFileUpload(event) {
  119. var inputFiles = this.files;
  120. if (inputFiles == undefined || inputFiles.length == 0) return false;
  121. var inputFile = inputFiles[0];
  122. this.value = "";
  123. var response = window.confirm("Previous settings will be overwritten. Are you sure you want to restore this settings?");
  124. if (response == false) return false;
  125. var reader = new FileReader();
  126. reader.onload = function(e) {
  127. var data = getJson(e.target.result);
  128. if (data) {
  129. websock.send(JSON.stringify({'action': 'restore', 'data': data}));
  130. } else {
  131. alert("The file is not a configuration backup or is corrupted");
  132. }
  133. };
  134. reader.readAsText(inputFile);
  135. return false;
  136. }
  137. function restoreSettings() {
  138. if (typeof window.FileReader !== 'function') {
  139. alert("The file API isn't supported on this browser yet.");
  140. } else {
  141. $("#uploader").click();
  142. }
  143. return false;
  144. }
  145. function randomString(length, chars) {
  146. var mask = '';
  147. if (chars.indexOf('a') > -1) mask += 'abcdefghijklmnopqrstuvwxyz';
  148. if (chars.indexOf('A') > -1) mask += 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
  149. if (chars.indexOf('#') > -1) mask += '0123456789';
  150. if (chars.indexOf('@') > -1) mask += 'ABCDEF';
  151. if (chars.indexOf('!') > -1) mask += '~`!@#$%^&*()_+-={}[]:";\'<>?,./|\\';
  152. var result = '';
  153. for (var i = length; i > 0; --i) result += mask[Math.round(Math.random() * (mask.length - 1))];
  154. return result;
  155. }
  156. function doGenerateAPIKey() {
  157. var apikey = randomString(16, '@#');
  158. $("input[name=\"apiKey\"]").val(apikey);
  159. return false;
  160. }
  161. function showPanel() {
  162. $(".panel").hide();
  163. $("#" + $(this).attr("data")).show();
  164. if ($("#layout").hasClass('active')) toggleMenu();
  165. $("input[type='checkbox']").iphoneStyle("calculateDimensions").iphoneStyle("refresh");
  166. };
  167. function toggleMenu() {
  168. $("#layout").toggleClass('active');
  169. $("#menu").toggleClass('active');
  170. $("#menuLink").toggleClass('active');
  171. }
  172. function createRelays(count) {
  173. var current = $("#relays > div").length;
  174. if (current > 0) return;
  175. var template = $("#relayTemplate .pure-g")[0];
  176. for (var relayID=0; relayID<count; relayID++) {
  177. var line = $(template).clone();
  178. $(line).find("input").each(function() {
  179. $(this).attr("data", relayID);
  180. });
  181. if (count > 1) $(".relay_id", line).html(" " + (relayID+1));
  182. line.appendTo("#relays");
  183. $(":checkbox", line).iphoneStyle({
  184. onChange: doToggle,
  185. resizeContainer: true,
  186. resizeHandle: true,
  187. checkedLabel: 'ON',
  188. uncheckedLabel: 'OFF'
  189. });
  190. }
  191. }
  192. function createIdxs(count) {
  193. var current = $("#idxs > div").length;
  194. if (current > 0) return;
  195. var template = $("#idxTemplate .pure-g")[0];
  196. for (var id=0; id<count; id++) {
  197. var line = $(template).clone();
  198. $(line).find("input").each(function() {
  199. $(this).attr("data", id).attr("tabindex", 40+id);
  200. });
  201. if (count > 1) $(".id", line).html(" " + id);
  202. line.appendTo("#idxs");
  203. }
  204. }
  205. function delNetwork() {
  206. var parent = $(this).parents(".pure-g");
  207. $(parent).remove();
  208. }
  209. function moreNetwork() {
  210. var parent = $(this).parents(".pure-g");
  211. $("div.more", parent).toggle();
  212. }
  213. function addNetwork() {
  214. var numNetworks = $("#networks > div").length;
  215. if (numNetworks >= maxNetworks) {
  216. alert("Max number of networks reached");
  217. return;
  218. }
  219. var tabindex = 200 + numNetworks * 10;
  220. var template = $("#networkTemplate").children();
  221. var line = $(template).clone();
  222. $(line).find("input").each(function() {
  223. $(this).attr("tabindex", tabindex++);
  224. });
  225. $(line).find(".button-del-network").on('click', delNetwork);
  226. $(line).find(".button-more-network").on('click', moreNetwork);
  227. line.appendTo("#networks");
  228. return line;
  229. }
  230. function initColor() {
  231. // check if already initialized
  232. var done = $("#colors > div").length;
  233. if (done > 0) return;
  234. // add template
  235. var template = $("#colorTemplate").children();
  236. var line = $(template).clone();
  237. line.appendTo("#colors");
  238. // init color wheel
  239. $('input[name="color"]').wheelColorPicker({
  240. sliders: 'wrgbp'
  241. }).on('sliderup', function() {
  242. var value = $(this).wheelColorPicker('getValue', 'css');
  243. websock.send(JSON.stringify({'action': 'color', 'data' : value}));
  244. });
  245. // init bright slider
  246. noUiSlider.create($("#brightness").get(0), {
  247. start: 255,
  248. connect: [true, false],
  249. tooltips: true,
  250. format: {
  251. to: function (value) { return parseInt(value); },
  252. from: function (value) { return value; }
  253. },
  254. orientation: "horizontal",
  255. range: { 'min': 0, 'max': 255}
  256. }).on("change", function() {
  257. var value = parseInt(this.get());
  258. websock.send(JSON.stringify({'action': 'brightness', 'data' : value}));
  259. });
  260. }
  261. function initChannels(num) {
  262. // check if already initialized
  263. var done = $("#channels > div").length > 0;
  264. if (done) return;
  265. // does it have color channels?
  266. var colors = $("#colors > div").length > 0;
  267. // calculate channels to create
  268. var max = num;
  269. if (colors) {
  270. max = num % 3;
  271. if ((max > 0) & useWhite) max--;
  272. }
  273. var start = num - max;
  274. // add templates
  275. var template = $("#channelTemplate").children();
  276. for (var i=0; i<max; i++) {
  277. var channel_id = start + i;
  278. var line = $(template).clone();
  279. $(".slider", line).attr("data", channel_id);
  280. $("label", line).html("Channel " + (channel_id + 1));
  281. noUiSlider.create($(".slider", line).get(0), {
  282. start: 0,
  283. connect: [true, false],
  284. tooltips: true,
  285. format: {
  286. to: function (value) { return parseInt(value); },
  287. from: function (value) { return value; }
  288. },
  289. orientation: "horizontal",
  290. range: { 'min': 0, 'max': 255 }
  291. }).on("change", function() {
  292. var id = $(this.target).attr("data");
  293. var value = parseInt(this.get());
  294. websock.send(JSON.stringify({'action': 'channel', 'data': { 'id': id, 'value': value }}));
  295. });
  296. line.appendTo("#channels");
  297. }
  298. }
  299. function addRfbNode() {
  300. var numNodes = $("#rfbNodes > fieldset").length;
  301. var template = $("#rfbNodeTemplate").children();
  302. var line = $(template).clone();
  303. var status = true;
  304. $("span", line).html(numNodes+1);
  305. $(line).find("input").each(function() {
  306. $(this).attr("data_id", numNodes);
  307. $(this).attr("data_status", status ? 1 : 0);
  308. status = !status;
  309. });
  310. $(line).find(".button-rfb-learn").on('click', rfbLearn);
  311. $(line).find(".button-rfb-forget").on('click', rfbForget);
  312. $(line).find(".button-rfb-send").on('click', rfbSend);
  313. line.appendTo("#rfbNodes");
  314. return line;
  315. }
  316. function rfbLearn() {
  317. var parent = $(this).parents(".pure-g");
  318. var input = $("input", parent);
  319. websock.send(JSON.stringify({'action': 'rfblearn', 'data' : {'id' : input.attr("data_id"), 'status': input.attr("data_status")}}));
  320. }
  321. function rfbForget() {
  322. var parent = $(this).parents(".pure-g");
  323. var input = $("input", parent);
  324. websock.send(JSON.stringify({'action': 'rfbforget', 'data' : {'id' : input.attr("data_id"), 'status': input.attr("data_status")}}));
  325. }
  326. function rfbSend() {
  327. var parent = $(this).parents(".pure-g");
  328. var input = $("input", parent);
  329. websock.send(JSON.stringify({'action': 'rfbsend', 'data' : {'id' : input.attr("data_id"), 'status': input.attr("data_status"), 'data': input.val()}}));
  330. }
  331. function forgetCredentials() {
  332. $.ajax({
  333. 'method': 'GET',
  334. 'url': '/',
  335. 'async': false,
  336. 'username': "logmeout",
  337. 'password': "123456",
  338. 'headers': { "Authorization": "Basic xxx" }
  339. }).done(function(data) {
  340. return false;
  341. // If we don't get an error, we actually got an error as we expect an 401!
  342. }).fail(function(){
  343. // We expect to get an 401 Unauthorized error! In this case we are successfully
  344. // logged out and we redirect the user.
  345. return true;
  346. });
  347. }
  348. function processData(data) {
  349. // title
  350. if ("app" in data) {
  351. var title = data.app;
  352. if ("version" in data) {
  353. title = title + " " + data.version;
  354. }
  355. $(".pure-menu-heading").html(title);
  356. if ("hostname" in data) {
  357. title = data.hostname + " - " + title;
  358. }
  359. document.title = title;
  360. }
  361. Object.keys(data).forEach(function(key) {
  362. // Web Modes
  363. if (key == "webMode") {
  364. password = data.webMode == 1;
  365. $("#layout").toggle(data.webMode == 0);
  366. $("#password").toggle(data.webMode == 1);
  367. $("#credentials").hide();
  368. }
  369. // Actions
  370. if (key == "action") {
  371. if (data.action == "reload") {
  372. if (password) forgetCredentials();
  373. setTimeout(function() {
  374. window.location = "/";
  375. }, 1000);
  376. }
  377. if (data.action == "rfbLearn") {
  378. // Nothing to do?
  379. }
  380. if (data.action == "rfbTimeout") {
  381. // Nothing to do?
  382. }
  383. return;
  384. }
  385. if (key == "rfbCount") {
  386. for (var i=0; i<data.rfbCount; i++) addRfbNode();
  387. return;
  388. }
  389. if (key == "rfb") {
  390. var nodes = data.rfb;
  391. for (var i in nodes) {
  392. var node = nodes[i];
  393. var element = $("input[name=rfbcode][data_id=" + node["id"] + "][data_status=" + node["status"] + "]");
  394. if (element.length) element.val(node["data"]);
  395. }
  396. return;
  397. }
  398. if (key == "color") {
  399. initColor();
  400. $("input[name='color']").wheelColorPicker('setValue', data[key], true);
  401. return;
  402. }
  403. if (key == "brightness") {
  404. var slider = $("#brightness");
  405. if (slider.length) slider.get(0).noUiSlider.set(data[key]);
  406. return;
  407. }
  408. if (key == "channels") {
  409. var len = data[key].length;
  410. initChannels(len);
  411. for (var i=0; i<len; i++) {
  412. var slider = $("div.channels[data=" + i + "]");
  413. if (slider.length) slider.get(0).noUiSlider.set(data[key][i]);
  414. }
  415. return;
  416. }
  417. if (key == "useWhite") {
  418. useWhite = data[key];
  419. }
  420. if (key == "maxNetworks") {
  421. maxNetworks = parseInt(data.maxNetworks);
  422. return;
  423. }
  424. // Wifi
  425. if (key == "wifi") {
  426. var networks = data.wifi;
  427. for (var i in networks) {
  428. // add a new row
  429. var line = addNetwork();
  430. // fill in the blanks
  431. var wifi = data.wifi[i];
  432. Object.keys(wifi).forEach(function(key) {
  433. var element = $("input[name=" + key + "]", line);
  434. if (element.length) element.val(wifi[key]);
  435. });
  436. }
  437. return;
  438. }
  439. // Relay status
  440. if (key == "relayStatus") {
  441. var relays = data.relayStatus;
  442. createRelays(relays.length);
  443. for (var relayID in relays) {
  444. var element = $(".relayStatus[data=" + relayID + "]");
  445. if (element.length > 0) {
  446. element
  447. .prop("checked", relays[relayID])
  448. .iphoneStyle("refresh");
  449. }
  450. }
  451. return;
  452. }
  453. // Domoticz
  454. if (key == "dczRelayIdx") {
  455. var idxs = data.dczRelayIdx;
  456. createIdxs(idxs.length);
  457. for (var i in idxs) {
  458. var element = $(".dczRelayIdx[data=" + i + "]");
  459. if (element.length > 0) element.val(idxs[i]);
  460. }
  461. return;
  462. }
  463. // Messages
  464. if (key == "message") {
  465. window.alert(data.message);
  466. return;
  467. }
  468. // Enable options
  469. if (key.endsWith("Visible")) {
  470. var module = key.slice(0,-7);
  471. $(".module-" + module).show();
  472. return;
  473. }
  474. // Pre-process
  475. if (key == "network") {
  476. data.network = data.network.toUpperCase();
  477. }
  478. if (key == "mqttStatus") {
  479. data.mqttStatus = data.mqttStatus ? "CONNECTED" : "NOT CONNECTED";
  480. }
  481. if (key == "ntpStatus") {
  482. data.ntpStatus = data.ntpStatus ? "SYNC'D" : "NOT SYNC'D";
  483. }
  484. if (key == "tmpUnits") {
  485. $("span#tmpUnit").html(data[key] == 1 ? "ºF" : "ºC");
  486. }
  487. // Look for INPUTs
  488. var element = $("input[name=" + key + "]");
  489. if (element.length > 0) {
  490. if (element.attr('type') == 'checkbox') {
  491. element
  492. .prop("checked", data[key])
  493. .iphoneStyle("refresh");
  494. } else if (element.attr('type') == 'radio') {
  495. element.val([data[key]]);
  496. } else {
  497. var pre = element.attr("pre") || "";
  498. var post = element.attr("post") || "";
  499. element.val(pre + data[key] + post);
  500. }
  501. return;
  502. }
  503. // Look for SPANs
  504. var element = $("span[name=" + key + "]");
  505. if (element.length > 0) {
  506. var pre = element.attr("pre") || "";
  507. var post = element.attr("post") || "";
  508. element.html(pre + data[key] + post);
  509. return;
  510. }
  511. // Look for SELECTs
  512. var element = $("select[name=" + key + "]");
  513. if (element.length > 0) {
  514. element.val(data[key]);
  515. return;
  516. }
  517. });
  518. // Auto generate an APIKey if none defined yet
  519. if ($("input[name='apiKey']").val() == "") {
  520. doGenerateAPIKey();
  521. }
  522. }
  523. function getJson(str) {
  524. try {
  525. return JSON.parse(str);
  526. } catch (e) {
  527. return false;
  528. }
  529. }
  530. function connect(h, p) {
  531. if (typeof h === 'undefined') {
  532. h = window.location.hostname;
  533. }
  534. if (typeof p === 'undefined') {
  535. p = location.port;
  536. }
  537. host = h;
  538. port = p;
  539. if (websock) websock.close();
  540. websock = new WebSocket('ws://' + host + ':' + port + '/ws');
  541. websock.onopen = function(evt) {
  542. console.log("Connected");
  543. };
  544. websock.onclose = function(evt) {
  545. console.log("Disconnected");
  546. };
  547. websock.onerror = function(evt) {
  548. console.log("Error: ", evt);
  549. };
  550. websock.onmessage = function(evt) {
  551. var data = getJson(evt.data);
  552. if (data) processData(data);
  553. };
  554. }
  555. function init() {
  556. $("#menuLink").on('click', toggleMenu);
  557. $(".button-update").on('click', doUpdate);
  558. $(".button-update-password").on('click', doUpdatePassword);
  559. $(".button-reset").on('click', doReset);
  560. $(".button-reconnect").on('click', doReconnect);
  561. $(".button-settings-backup").on('click', backupSettings);
  562. $(".button-settings-restore").on('click', restoreSettings);
  563. $('#uploader').on('change', onFileUpload);
  564. $(".button-apikey").on('click', doGenerateAPIKey);
  565. $(".button-upgrade").on('click', doUpgrade);
  566. $(".button-upgrade-browse").on('click', function() {
  567. $("input[name='upgrade']")[0].click();
  568. return false;
  569. });
  570. $("input[name='upgrade']").change(function (){
  571. var fileName = $(this).val();
  572. $("input[name='filename']").val(fileName.replace(/^.*[\\\/]/, ''));
  573. });
  574. $('progress').attr({ value: 0, max: 100 });
  575. $(".pure-menu-link").on('click', showPanel);
  576. $(".button-add-network").on('click', function() {
  577. $("div.more", addNetwork()).toggle();
  578. });
  579. var host = window.location.hostname;
  580. var port = location.port;
  581. $.ajax({
  582. 'method': 'GET',
  583. 'url': 'http://' + host + ':' + port + '/auth'
  584. }).done(function(data) {
  585. connect();
  586. }).fail(function(){
  587. $("#credentials").show();
  588. });
  589. }
  590. $(init);