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.

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