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.

405 lines
11 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
  1. var websock;
  2. var password = false;
  3. var maxNetworks;
  4. // http://www.the-art-of-web.com/javascript/validate-password/
  5. function checkPassword(str) {
  6. // at least one number, one lowercase and one uppercase letter
  7. // at least eight characters that are letters, numbers or the underscore
  8. var re = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])\w{8,}$/;
  9. return re.test(str);
  10. }
  11. function validateForm(form) {
  12. // password
  13. var adminPass1 = $("input[name='adminPass1']", form).val();
  14. if (adminPass1.length > 0 && !checkPassword(adminPass1)) {
  15. alert("The password you have entered is not valid, it must have at least 8 characters, 1 lower and 1 uppercase and 1 number!");
  16. return false;
  17. }
  18. var adminPass2 = $("input[name='adminPass2']", form).val();
  19. if (adminPass1 != adminPass2) {
  20. alert("Passwords are different!");
  21. return false;
  22. }
  23. return true;
  24. }
  25. function doUpdate() {
  26. var form = $("#formSave");
  27. if (validateForm(form)) {
  28. var data = form.serializeArray();
  29. websock.send(JSON.stringify({'config': data}));
  30. $(".powExpected").val(0);
  31. $("input[name='powExpectedReset']")
  32. .prop("checked", false)
  33. .iphoneStyle("refresh");
  34. }
  35. return false;
  36. }
  37. function doUpdatePassword() {
  38. var form = $("#formPassword");
  39. if (validateForm(form)) {
  40. var data = form.serializeArray();
  41. websock.send(JSON.stringify({'config': data}));
  42. }
  43. return false;
  44. }
  45. function doReset() {
  46. var response = window.confirm("Are you sure you want to reset the device?");
  47. if (response == false) return false;
  48. websock.send(JSON.stringify({'action': 'reset'}));
  49. return false;
  50. }
  51. function doReconnect() {
  52. var response = window.confirm("Are you sure you want to disconnect from the current WIFI network?");
  53. if (response == false) return false;
  54. websock.send(JSON.stringify({'action': 'reconnect'}));
  55. return false;
  56. }
  57. function doToggle(element, value) {
  58. var relayID = parseInt(element.attr("data"));
  59. websock.send(JSON.stringify({'action': value ? 'on' : 'off', 'relayID': relayID}));
  60. return false;
  61. }
  62. function randomString(length, chars) {
  63. var mask = '';
  64. if (chars.indexOf('a') > -1) mask += 'abcdefghijklmnopqrstuvwxyz';
  65. if (chars.indexOf('A') > -1) mask += 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
  66. if (chars.indexOf('#') > -1) mask += '0123456789';
  67. if (chars.indexOf('@') > -1) mask += 'ABCDEF';
  68. if (chars.indexOf('!') > -1) mask += '~`!@#$%^&*()_+-={}[]:";\'<>?,./|\\';
  69. var result = '';
  70. for (var i = length; i > 0; --i) result += mask[Math.round(Math.random() * (mask.length - 1))];
  71. return result;
  72. }
  73. function doGenerateAPIKey() {
  74. var apikey = randomString(16, '@#');
  75. $("input[name=\"apiKey\"]").val(apikey);
  76. return false;
  77. }
  78. function showPanel() {
  79. $(".panel").hide();
  80. $("#" + $(this).attr("data")).show();
  81. if ($("#layout").hasClass('active')) toggleMenu();
  82. $("input[type='checkbox']").iphoneStyle("calculateDimensions").iphoneStyle("refresh");
  83. };
  84. function toggleMenu() {
  85. $("#layout").toggleClass('active');
  86. $("#menu").toggleClass('active');
  87. $("#menuLink").toggleClass('active');
  88. }
  89. function createRelays(count) {
  90. var current = $("#relays > div").length;
  91. if (current > 0) return;
  92. var template = $("#relayTemplate .pure-g")[0];
  93. for (var relayID=0; relayID<count; relayID++) {
  94. var line = $(template).clone();
  95. $(line).find("input").each(function() {
  96. $(this).attr("data", relayID);
  97. });
  98. if (count > 1) $(".relay_id", line).html(" " + (relayID+1));
  99. line.appendTo("#relays");
  100. $(":checkbox", line).iphoneStyle({
  101. onChange: doToggle,
  102. resizeContainer: true,
  103. resizeHandle: true,
  104. checkedLabel: 'ON',
  105. uncheckedLabel: 'OFF'
  106. });
  107. }
  108. }
  109. function createIdxs(count) {
  110. var current = $("#idxs > div").length;
  111. if (current > 0) return;
  112. var template = $("#idxTemplate .pure-g")[0];
  113. for (var id=0; id<count; id++) {
  114. var line = $(template).clone();
  115. $(line).find("input").each(function() {
  116. $(this).attr("data", id).attr("tabindex", 40+id);
  117. });
  118. if (count > 1) $(".id", line).html(" " + id);
  119. line.appendTo("#idxs");
  120. }
  121. }
  122. function delNetwork() {
  123. var parent = $(this).parents(".pure-g");
  124. $(parent).remove();
  125. }
  126. function moreNetwork() {
  127. var parent = $(this).parents(".pure-g");
  128. $("div.more", parent).toggle();
  129. }
  130. function addNetwork() {
  131. var numNetworks = $("#networks > div").length;
  132. if (numNetworks >= maxNetworks) {
  133. alert("Max number of networks reached");
  134. return;
  135. }
  136. var tabindex = 200 + numNetworks * 10;
  137. var template = $("#networkTemplate").children();
  138. var line = $(template).clone();
  139. $(line).find("input").each(function() {
  140. $(this).attr("tabindex", tabindex++);
  141. });
  142. $(line).find(".button-del-network").on('click', delNetwork);
  143. $(line).find(".button-more-network").on('click', moreNetwork);
  144. line.appendTo("#networks");
  145. return line;
  146. }
  147. function forgetCredentials() {
  148. $.ajax({
  149. 'method': 'GET',
  150. 'url': '/',
  151. 'async': false,
  152. 'username': "logmeout",
  153. 'password': "123456",
  154. 'headers': { "Authorization": "Basic xxx" }
  155. }).done(function(data) {
  156. return false;
  157. // If we don't get an error, we actually got an error as we expect an 401!
  158. }).fail(function(){
  159. // We expect to get an 401 Unauthorized error! In this case we are successfully
  160. // logged out and we redirect the user.
  161. return true;
  162. });
  163. }
  164. function processData(data) {
  165. // title
  166. if ("app" in data) {
  167. var title = data.app;
  168. if ("version" in data) {
  169. title = title + " " + data.version;
  170. }
  171. $(".pure-menu-heading").html(title);
  172. if ("hostname" in data) {
  173. title = data.hostname + " - " + title;
  174. }
  175. document.title = title;
  176. }
  177. Object.keys(data).forEach(function(key) {
  178. // Web Modes
  179. if (key == "webMode") {
  180. password = data.webMode == 1;
  181. $("#layout").toggle(data.webMode == 0);
  182. $("#password").toggle(data.webMode == 1);
  183. }
  184. // Actions
  185. if (key == "action") {
  186. if (data.action == "reload") {
  187. if (password) forgetCredentials();
  188. setTimeout(function() {
  189. window.location = "/";
  190. }, 1000);
  191. }
  192. return;
  193. }
  194. if (key == "maxNetworks") {
  195. maxNetworks = parseInt(data.maxNetworks);
  196. return;
  197. }
  198. // Wifi
  199. if (key == "wifi") {
  200. var networks = data.wifi;
  201. for (var i in networks) {
  202. // add a new row
  203. var line = addNetwork();
  204. // fill in the blanks
  205. var wifi = data.wifi[i];
  206. Object.keys(wifi).forEach(function(key) {
  207. var element = $("input[name=" + key + "]", line);
  208. if (element.length) element.val(wifi[key]);
  209. });
  210. }
  211. return;
  212. }
  213. // Relay status
  214. if (key == "relayStatus") {
  215. var relays = data.relayStatus;
  216. createRelays(relays.length);
  217. for (var relayID in relays) {
  218. var element = $(".relayStatus[data=" + relayID + "]");
  219. if (element.length > 0) {
  220. element
  221. .prop("checked", relays[relayID])
  222. .iphoneStyle("refresh");
  223. }
  224. }
  225. return;
  226. }
  227. // Domoticz
  228. if (key == "dczRelayIdx") {
  229. var idxs = data.dczRelayIdx;
  230. createIdxs(idxs.length);
  231. for (var i in idxs) {
  232. var element = $(".dczRelayIdx[data=" + i + "]");
  233. if (element.length > 0) element.val(idxs[i]);
  234. }
  235. return;
  236. }
  237. // Messages
  238. if (key == "message") {
  239. window.alert(data.message);
  240. return;
  241. }
  242. // Enable options
  243. if (key.endsWith("Visible")) {
  244. var module = key.slice(0,-7);
  245. $(".module-" + module).show();
  246. return;
  247. }
  248. // Pre-process
  249. if (key == "network") {
  250. data.network = data.network.toUpperCase();
  251. }
  252. if (key == "mqttStatus") {
  253. data.mqttStatus = data.mqttStatus ? "CONNECTED" : "NOT CONNECTED";
  254. }
  255. if (key == "tmpUnits") {
  256. $("span#tmpUnit").html(data[key] == 1 ? "ºF" : "ºC");
  257. }
  258. // Look for INPUTs
  259. var element = $("input[name=" + key + "]");
  260. if (element.length > 0) {
  261. if (element.attr('type') == 'checkbox') {
  262. element
  263. .prop("checked", data[key])
  264. .iphoneStyle("refresh");
  265. } else if (element.attr('type') == 'radio') {
  266. element.val([data[key]]);
  267. } else {
  268. element.val(data[key]);
  269. }
  270. return;
  271. }
  272. // Look for SELECTs
  273. var element = $("select[name=" + key + "]");
  274. if (element.length > 0) {
  275. element.val(data[key]);
  276. return;
  277. }
  278. });
  279. // Auto generate an APIKey if none defined yet
  280. if ($("input[name='apiKey']").val() == "") {
  281. doGenerateAPIKey();
  282. }
  283. }
  284. function getJson(str) {
  285. try {
  286. return JSON.parse(str);
  287. } catch (e) {
  288. return false;
  289. }
  290. }
  291. function connect(host, port) {
  292. if (typeof host === 'undefined') {
  293. host = window.location.hostname;
  294. }
  295. if (typeof port === 'undefined') {
  296. port = location.port;
  297. }
  298. if (websock) websock.close();
  299. websock = new WebSocket('ws://' + host + ':' + port + '/ws');
  300. websock.onopen = function(evt) {
  301. console.log("Connected");
  302. };
  303. websock.onclose = function(evt) {
  304. console.log("Disconnected");
  305. };
  306. websock.onerror = function(evt) {
  307. console.log("Error: ", evt);
  308. };
  309. websock.onmessage = function(evt) {
  310. var data = getJson(evt.data);
  311. if (data) processData(data);
  312. };
  313. }
  314. function init() {
  315. $("#menuLink").on('click', toggleMenu);
  316. $(".button-update").on('click', doUpdate);
  317. $(".button-update-password").on('click', doUpdatePassword);
  318. $(".button-reset").on('click', doReset);
  319. $(".button-reconnect").on('click', doReconnect);
  320. $(".button-apikey").on('click', doGenerateAPIKey);
  321. $(".pure-menu-link").on('click', showPanel);
  322. $(".button-add-network").on('click', function() {
  323. $("div.more", addNetwork()).toggle();
  324. });
  325. $.ajax({
  326. 'method': 'GET',
  327. 'url': '/auth'
  328. }).done(function(data) {
  329. connect();
  330. });
  331. }
  332. $(init);