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.

716 lines
20 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
  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. function addRfbNode() {
  299. var numNodes = $("#rfbNodes > fieldset").length;
  300. var template = $("#rfbNodeTemplate").children();
  301. var line = $(template).clone();
  302. var status = true;
  303. $("span", line).html(numNodes+1);
  304. $(line).find("input").each(function() {
  305. $(this).attr("data_id", numNodes);
  306. $(this).attr("data_status", status ? 1 : 0);
  307. status = !status;
  308. });
  309. $(line).find(".button-rfb-learn").on('click', rfbLearn);
  310. $(line).find(".button-rfb-forget").on('click', rfbForget);
  311. $(line).find(".button-rfb-send").on('click', rfbSend);
  312. line.appendTo("#rfbNodes");
  313. return line;
  314. }
  315. function rfbLearn() {
  316. var parent = $(this).parents(".pure-g");
  317. var input = $("input", parent);
  318. websock.send(JSON.stringify({'action': 'rfblearn', 'data' : {'id' : input.attr("data_id"), 'status': input.attr("data_status")}}));
  319. }
  320. function rfbForget() {
  321. var parent = $(this).parents(".pure-g");
  322. var input = $("input", parent);
  323. websock.send(JSON.stringify({'action': 'rfbforget', 'data' : {'id' : input.attr("data_id"), 'status': input.attr("data_status")}}));
  324. }
  325. function rfbSend() {
  326. var parent = $(this).parents(".pure-g");
  327. var input = $("input", parent);
  328. websock.send(JSON.stringify({'action': 'rfbsend', 'data' : {'id' : input.attr("data_id"), 'status': input.attr("data_status"), 'data': input.val()}}));
  329. }
  330. function forgetCredentials() {
  331. $.ajax({
  332. 'method': 'GET',
  333. 'url': '/',
  334. 'async': false,
  335. 'username': "logmeout",
  336. 'password': "123456",
  337. 'headers': { "Authorization": "Basic xxx" }
  338. }).done(function(data) {
  339. return false;
  340. // If we don't get an error, we actually got an error as we expect an 401!
  341. }).fail(function(){
  342. // We expect to get an 401 Unauthorized error! In this case we are successfully
  343. // logged out and we redirect the user.
  344. return true;
  345. });
  346. }
  347. function processData(data) {
  348. // title
  349. if ("app" in data) {
  350. var title = data.app;
  351. if ("version" in data) {
  352. title = title + " " + data.version;
  353. }
  354. $(".pure-menu-heading").html(title);
  355. if ("hostname" in data) {
  356. title = data.hostname + " - " + title;
  357. }
  358. document.title = title;
  359. }
  360. Object.keys(data).forEach(function(key) {
  361. // Web Modes
  362. if (key == "webMode") {
  363. password = data.webMode == 1;
  364. $("#layout").toggle(data.webMode == 0);
  365. $("#password").toggle(data.webMode == 1);
  366. $("#credentials").hide();
  367. }
  368. // Actions
  369. if (key == "action") {
  370. if (data.action == "reload") {
  371. if (password) forgetCredentials();
  372. setTimeout(function() {
  373. window.location = "/";
  374. }, 1000);
  375. }
  376. if (data.action == "rfbLearn") {
  377. // Nothing to do?
  378. }
  379. if (data.action == "rfbTimeout") {
  380. // Nothing to do?
  381. }
  382. return;
  383. }
  384. if (key == "rfbCount") {
  385. for (var i=0; i<data.rfbCount; i++) addRfbNode();
  386. return;
  387. }
  388. if (key == "rfb") {
  389. var nodes = data.rfb;
  390. for (var i in nodes) {
  391. var node = nodes[i];
  392. var element = $("input[name=rfbcode][data_id=" + node["id"] + "][data_status=" + node["status"] + "]");
  393. if (element.length) element.val(node["data"]);
  394. }
  395. return;
  396. }
  397. if (key == "color") {
  398. initColor();
  399. $("input[name='color']").wheelColorPicker('setValue', data[key], true);
  400. return;
  401. }
  402. if (key == "brightness") {
  403. var slider = $("#brightness");
  404. if (slider.length) slider.get(0).noUiSlider.set(data[key]);
  405. return;
  406. }
  407. if (key == "channels") {
  408. var len = data[key].length;
  409. initChannels(len);
  410. for (var i=0; i<len; i++) {
  411. var slider = $("div.channels[data=" + i + "]");
  412. if (slider.length) slider.get(0).noUiSlider.set(data[key][i]);
  413. }
  414. return;
  415. }
  416. if (key == "useWhite") {
  417. useWhite = data[key];
  418. }
  419. if (key == "maxNetworks") {
  420. maxNetworks = parseInt(data.maxNetworks);
  421. return;
  422. }
  423. // Wifi
  424. if (key == "wifi") {
  425. var networks = data.wifi;
  426. for (var i in networks) {
  427. // add a new row
  428. var line = addNetwork();
  429. // fill in the blanks
  430. var wifi = data.wifi[i];
  431. Object.keys(wifi).forEach(function(key) {
  432. var element = $("input[name=" + key + "]", line);
  433. if (element.length) element.val(wifi[key]);
  434. });
  435. }
  436. return;
  437. }
  438. // Relay status
  439. if (key == "relayStatus") {
  440. var relays = data.relayStatus;
  441. createRelays(relays.length);
  442. for (var relayID in relays) {
  443. var element = $(".relayStatus[data=" + relayID + "]");
  444. if (element.length > 0) {
  445. element
  446. .prop("checked", relays[relayID])
  447. .iphoneStyle("refresh");
  448. }
  449. }
  450. return;
  451. }
  452. // Domoticz
  453. if (key == "dczRelayIdx") {
  454. var idxs = data.dczRelayIdx;
  455. createIdxs(idxs.length);
  456. for (var i in idxs) {
  457. var element = $(".dczRelayIdx[data=" + i + "]");
  458. if (element.length > 0) element.val(idxs[i]);
  459. }
  460. return;
  461. }
  462. // Messages
  463. if (key == "message") {
  464. window.alert(data.message);
  465. return;
  466. }
  467. // Enable options
  468. if (key.endsWith("Visible")) {
  469. var module = key.slice(0,-7);
  470. $(".module-" + module).show();
  471. return;
  472. }
  473. // Pre-process
  474. if (key == "network") {
  475. data.network = data.network.toUpperCase();
  476. }
  477. if (key == "mqttStatus") {
  478. data.mqttStatus = data.mqttStatus ? "CONNECTED" : "NOT CONNECTED";
  479. }
  480. if (key == "ntpStatus") {
  481. data.ntpStatus = data.ntpStatus ? "SYNC'D" : "NOT SYNC'D";
  482. }
  483. if (key == "tmpUnits") {
  484. $("span#tmpUnit").html(data[key] == 1 ? "ºF" : "ºC");
  485. }
  486. // Look for INPUTs
  487. var element = $("input[name=" + key + "]");
  488. if (element.length > 0) {
  489. if (element.attr('type') == 'checkbox') {
  490. element
  491. .prop("checked", data[key])
  492. .iphoneStyle("refresh");
  493. } else if (element.attr('type') == 'radio') {
  494. element.val([data[key]]);
  495. } else {
  496. var pre = element.attr("pre") || "";
  497. var post = element.attr("post") || "";
  498. element.val(pre + data[key] + post);
  499. }
  500. return;
  501. }
  502. // Look for SPANs
  503. var element = $("span[name=" + key + "]");
  504. if (element.length > 0) {
  505. var pre = element.attr("pre") || "";
  506. var post = element.attr("post") || "";
  507. element.html(pre + data[key] + post);
  508. return;
  509. }
  510. // Look for SELECTs
  511. var element = $("select[name=" + key + "]");
  512. if (element.length > 0) {
  513. element.val(data[key]);
  514. return;
  515. }
  516. });
  517. // Auto generate an APIKey if none defined yet
  518. if ($("input[name='apiKey']").val() == "") {
  519. doGenerateAPIKey();
  520. }
  521. }
  522. function getJson(str) {
  523. try {
  524. return JSON.parse(str);
  525. } catch (e) {
  526. return false;
  527. }
  528. }
  529. function connect(h, p) {
  530. if (typeof h === 'undefined') {
  531. h = window.location.hostname;
  532. }
  533. if (typeof p === 'undefined') {
  534. p = location.port;
  535. }
  536. host = h;
  537. port = p;
  538. if (websock) websock.close();
  539. websock = new WebSocket('ws://' + host + ':' + port + '/ws');
  540. websock.onopen = function(evt) {
  541. console.log("Connected");
  542. };
  543. websock.onclose = function(evt) {
  544. console.log("Disconnected");
  545. };
  546. websock.onerror = function(evt) {
  547. console.log("Error: ", evt);
  548. };
  549. websock.onmessage = function(evt) {
  550. var data = getJson(evt.data);
  551. if (data) processData(data);
  552. };
  553. }
  554. function init() {
  555. $("#menuLink").on('click', toggleMenu);
  556. $(".button-update").on('click', doUpdate);
  557. $(".button-update-password").on('click', doUpdatePassword);
  558. $(".button-reset").on('click', doReset);
  559. $(".button-reconnect").on('click', doReconnect);
  560. $(".button-settings-backup").on('click', backupSettings);
  561. $(".button-settings-restore").on('click', restoreSettings);
  562. $('#uploader').on('change', onFileUpload);
  563. $(".button-apikey").on('click', doGenerateAPIKey);
  564. $(".button-upgrade").on('click', doUpgrade);
  565. $(".button-upgrade-browse").on('click', function() {
  566. $("input[name='upgrade']")[0].click();
  567. return false;
  568. });
  569. $("input[name='upgrade']").change(function (){
  570. var fileName = $(this).val();
  571. $("input[name='filename']").val(fileName.replace(/^.*[\\\/]/, ''));
  572. });
  573. $('progress').attr({ value: 0, max: 100 });
  574. $(".pure-menu-link").on('click', showPanel);
  575. $(".button-add-network").on('click', function() {
  576. $("div.more", addNetwork()).toggle();
  577. });
  578. var host = window.location.hostname;
  579. var port = location.port;
  580. $.ajax({
  581. 'method': 'GET',
  582. 'url': 'http://' + host + ':' + port + '/auth'
  583. }).done(function(data) {
  584. connect();
  585. }).fail(function(){
  586. $("#credentials").show();
  587. });
  588. }
  589. $(init);