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.

2387 lines
68 KiB

8 years ago
7 years ago
providers: relays, lights and buttons refactoring (#2414) - gpio module now tracks the known providers (right now, hardware and mcp expander) - refactored relay struct to use 'Provider' implementing setup,notify,change,boot instead of just BasePin actions - refactored button module to use gpio provider instead of referencing types itself - removed dual & stm code from buttons, migrate both to relay module - added status notify and change callbacks for relayStatus (i.e. 'notify' when relay status was called, but not changed. and 'changed' when it did) - relays runtime configuration keys - relay command now shows configured relays and current & target statuses - refactor the code using relayStatus(0, blah) under LIGHT_PROVIDER check to use lightState instead - remove rfbridge code form relay module. implement through a basic state listener in the rfbridge module, depend on RELAY_SUPPORT - allow to bind rf codes to real relays - drop tuya-specific lights provider, remove tuya code from relays and lights modules - integrate tuya via relay listeners and providers, use lights custom provider - implement channel transitions for tuya. disabled by default, and transition time and step are overridden to 2000 + 100. needs to be set to some value below the total time (i.e. `total transition time / step time == number of steps`, we need to figure out a correct time that serial comms could handle) - lights custom provider (global, not per-pin) and state listeners - remove lights code from relay module. implement through providers & listeners in the lights module, depend on RELAY_SUPPORT - lights per-channel relay provider (unused atm), depend on RELAY_SUPPORT - refactored channel transition - calculate step only once, make sure time + step values are sane, generate quick transitions with very small delay (10ms hardcoded) for transitions during OFF state i.e. we no longer waste 500ms (or whatever transition time is set to) on boot doing nothing - transition time + step parameter for the lightUpdate - report mask parameter for the lightUpdate - minor fixes across the board resolve #2222
3 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
providers: relays, lights and buttons refactoring (#2414) - gpio module now tracks the known providers (right now, hardware and mcp expander) - refactored relay struct to use 'Provider' implementing setup,notify,change,boot instead of just BasePin actions - refactored button module to use gpio provider instead of referencing types itself - removed dual & stm code from buttons, migrate both to relay module - added status notify and change callbacks for relayStatus (i.e. 'notify' when relay status was called, but not changed. and 'changed' when it did) - relays runtime configuration keys - relay command now shows configured relays and current & target statuses - refactor the code using relayStatus(0, blah) under LIGHT_PROVIDER check to use lightState instead - remove rfbridge code form relay module. implement through a basic state listener in the rfbridge module, depend on RELAY_SUPPORT - allow to bind rf codes to real relays - drop tuya-specific lights provider, remove tuya code from relays and lights modules - integrate tuya via relay listeners and providers, use lights custom provider - implement channel transitions for tuya. disabled by default, and transition time and step are overridden to 2000 + 100. needs to be set to some value below the total time (i.e. `total transition time / step time == number of steps`, we need to figure out a correct time that serial comms could handle) - lights custom provider (global, not per-pin) and state listeners - remove lights code from relay module. implement through providers & listeners in the lights module, depend on RELAY_SUPPORT - lights per-channel relay provider (unused atm), depend on RELAY_SUPPORT - refactored channel transition - calculate step only once, make sure time + step values are sane, generate quick transitions with very small delay (10ms hardcoded) for transitions during OFF state i.e. we no longer waste 500ms (or whatever transition time is set to) on boot doing nothing - transition time + step parameter for the lightUpdate - report mask parameter for the lightUpdate - minor fixes across the board resolve #2222
3 years ago
6 years ago
6 years ago
7 years ago
6 years ago
7 years ago
7 years ago
7 years ago
6 years ago
7 years ago
6 years ago
6 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
8 years ago
8 years ago
6 years ago
6 years ago
5 years ago
5 years ago
5 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
providers: relays, lights and buttons refactoring (#2414) - gpio module now tracks the known providers (right now, hardware and mcp expander) - refactored relay struct to use 'Provider' implementing setup,notify,change,boot instead of just BasePin actions - refactored button module to use gpio provider instead of referencing types itself - removed dual & stm code from buttons, migrate both to relay module - added status notify and change callbacks for relayStatus (i.e. 'notify' when relay status was called, but not changed. and 'changed' when it did) - relays runtime configuration keys - relay command now shows configured relays and current & target statuses - refactor the code using relayStatus(0, blah) under LIGHT_PROVIDER check to use lightState instead - remove rfbridge code form relay module. implement through a basic state listener in the rfbridge module, depend on RELAY_SUPPORT - allow to bind rf codes to real relays - drop tuya-specific lights provider, remove tuya code from relays and lights modules - integrate tuya via relay listeners and providers, use lights custom provider - implement channel transitions for tuya. disabled by default, and transition time and step are overridden to 2000 + 100. needs to be set to some value below the total time (i.e. `total transition time / step time == number of steps`, we need to figure out a correct time that serial comms could handle) - lights custom provider (global, not per-pin) and state listeners - remove lights code from relay module. implement through providers & listeners in the lights module, depend on RELAY_SUPPORT - lights per-channel relay provider (unused atm), depend on RELAY_SUPPORT - refactored channel transition - calculate step only once, make sure time + step values are sane, generate quick transitions with very small delay (10ms hardcoded) for transitions during OFF state i.e. we no longer waste 500ms (or whatever transition time is set to) on boot doing nothing - transition time + step parameter for the lightUpdate - report mask parameter for the lightUpdate - minor fixes across the board resolve #2222
3 years ago
providers: relays, lights and buttons refactoring (#2414) - gpio module now tracks the known providers (right now, hardware and mcp expander) - refactored relay struct to use 'Provider' implementing setup,notify,change,boot instead of just BasePin actions - refactored button module to use gpio provider instead of referencing types itself - removed dual & stm code from buttons, migrate both to relay module - added status notify and change callbacks for relayStatus (i.e. 'notify' when relay status was called, but not changed. and 'changed' when it did) - relays runtime configuration keys - relay command now shows configured relays and current & target statuses - refactor the code using relayStatus(0, blah) under LIGHT_PROVIDER check to use lightState instead - remove rfbridge code form relay module. implement through a basic state listener in the rfbridge module, depend on RELAY_SUPPORT - allow to bind rf codes to real relays - drop tuya-specific lights provider, remove tuya code from relays and lights modules - integrate tuya via relay listeners and providers, use lights custom provider - implement channel transitions for tuya. disabled by default, and transition time and step are overridden to 2000 + 100. needs to be set to some value below the total time (i.e. `total transition time / step time == number of steps`, we need to figure out a correct time that serial comms could handle) - lights custom provider (global, not per-pin) and state listeners - remove lights code from relay module. implement through providers & listeners in the lights module, depend on RELAY_SUPPORT - lights per-channel relay provider (unused atm), depend on RELAY_SUPPORT - refactored channel transition - calculate step only once, make sure time + step values are sane, generate quick transitions with very small delay (10ms hardcoded) for transitions during OFF state i.e. we no longer waste 500ms (or whatever transition time is set to) on boot doing nothing - transition time + step parameter for the lightUpdate - report mask parameter for the lightUpdate - minor fixes across the board resolve #2222
3 years ago
providers: relays, lights and buttons refactoring (#2414) - gpio module now tracks the known providers (right now, hardware and mcp expander) - refactored relay struct to use 'Provider' implementing setup,notify,change,boot instead of just BasePin actions - refactored button module to use gpio provider instead of referencing types itself - removed dual & stm code from buttons, migrate both to relay module - added status notify and change callbacks for relayStatus (i.e. 'notify' when relay status was called, but not changed. and 'changed' when it did) - relays runtime configuration keys - relay command now shows configured relays and current & target statuses - refactor the code using relayStatus(0, blah) under LIGHT_PROVIDER check to use lightState instead - remove rfbridge code form relay module. implement through a basic state listener in the rfbridge module, depend on RELAY_SUPPORT - allow to bind rf codes to real relays - drop tuya-specific lights provider, remove tuya code from relays and lights modules - integrate tuya via relay listeners and providers, use lights custom provider - implement channel transitions for tuya. disabled by default, and transition time and step are overridden to 2000 + 100. needs to be set to some value below the total time (i.e. `total transition time / step time == number of steps`, we need to figure out a correct time that serial comms could handle) - lights custom provider (global, not per-pin) and state listeners - remove lights code from relay module. implement through providers & listeners in the lights module, depend on RELAY_SUPPORT - lights per-channel relay provider (unused atm), depend on RELAY_SUPPORT - refactored channel transition - calculate step only once, make sure time + step values are sane, generate quick transitions with very small delay (10ms hardcoded) for transitions during OFF state i.e. we no longer waste 500ms (or whatever transition time is set to) on boot doing nothing - transition time + step parameter for the lightUpdate - report mask parameter for the lightUpdate - minor fixes across the board resolve #2222
3 years ago
providers: relays, lights and buttons refactoring (#2414) - gpio module now tracks the known providers (right now, hardware and mcp expander) - refactored relay struct to use 'Provider' implementing setup,notify,change,boot instead of just BasePin actions - refactored button module to use gpio provider instead of referencing types itself - removed dual & stm code from buttons, migrate both to relay module - added status notify and change callbacks for relayStatus (i.e. 'notify' when relay status was called, but not changed. and 'changed' when it did) - relays runtime configuration keys - relay command now shows configured relays and current & target statuses - refactor the code using relayStatus(0, blah) under LIGHT_PROVIDER check to use lightState instead - remove rfbridge code form relay module. implement through a basic state listener in the rfbridge module, depend on RELAY_SUPPORT - allow to bind rf codes to real relays - drop tuya-specific lights provider, remove tuya code from relays and lights modules - integrate tuya via relay listeners and providers, use lights custom provider - implement channel transitions for tuya. disabled by default, and transition time and step are overridden to 2000 + 100. needs to be set to some value below the total time (i.e. `total transition time / step time == number of steps`, we need to figure out a correct time that serial comms could handle) - lights custom provider (global, not per-pin) and state listeners - remove lights code from relay module. implement through providers & listeners in the lights module, depend on RELAY_SUPPORT - lights per-channel relay provider (unused atm), depend on RELAY_SUPPORT - refactored channel transition - calculate step only once, make sure time + step values are sane, generate quick transitions with very small delay (10ms hardcoded) for transitions during OFF state i.e. we no longer waste 500ms (or whatever transition time is set to) on boot doing nothing - transition time + step parameter for the lightUpdate - report mask parameter for the lightUpdate - minor fixes across the board resolve #2222
3 years ago
6 years ago
6 years ago
6 years ago
6 years ago
providers: relays, lights and buttons refactoring (#2414) - gpio module now tracks the known providers (right now, hardware and mcp expander) - refactored relay struct to use 'Provider' implementing setup,notify,change,boot instead of just BasePin actions - refactored button module to use gpio provider instead of referencing types itself - removed dual & stm code from buttons, migrate both to relay module - added status notify and change callbacks for relayStatus (i.e. 'notify' when relay status was called, but not changed. and 'changed' when it did) - relays runtime configuration keys - relay command now shows configured relays and current & target statuses - refactor the code using relayStatus(0, blah) under LIGHT_PROVIDER check to use lightState instead - remove rfbridge code form relay module. implement through a basic state listener in the rfbridge module, depend on RELAY_SUPPORT - allow to bind rf codes to real relays - drop tuya-specific lights provider, remove tuya code from relays and lights modules - integrate tuya via relay listeners and providers, use lights custom provider - implement channel transitions for tuya. disabled by default, and transition time and step are overridden to 2000 + 100. needs to be set to some value below the total time (i.e. `total transition time / step time == number of steps`, we need to figure out a correct time that serial comms could handle) - lights custom provider (global, not per-pin) and state listeners - remove lights code from relay module. implement through providers & listeners in the lights module, depend on RELAY_SUPPORT - lights per-channel relay provider (unused atm), depend on RELAY_SUPPORT - refactored channel transition - calculate step only once, make sure time + step values are sane, generate quick transitions with very small delay (10ms hardcoded) for transitions during OFF state i.e. we no longer waste 500ms (or whatever transition time is set to) on boot doing nothing - transition time + step parameter for the lightUpdate - report mask parameter for the lightUpdate - minor fixes across the board resolve #2222
3 years ago
6 years ago
6 years ago
6 years ago
8 years ago
6 years ago
8 years ago
6 years ago
8 years ago
8 years ago
8 years ago
8 years ago
6 years ago
8 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
8 years ago
  1. var debug = false;
  2. var websock;
  3. var password = false;
  4. var maxNetworks;
  5. var free_size = 0;
  6. var urls = {};
  7. var numChanged = 0;
  8. var numReboot = 0;
  9. var numReconnect = 0;
  10. var numReload = 0;
  11. var configurationSaved = false;
  12. var ws_pingpong;
  13. //removeIf(!light)
  14. var colorPicker;
  15. var useWhite = false;
  16. var useCCT = false;
  17. //endRemoveIf(!light)
  18. var now = 0;
  19. var ago = 0;
  20. //removeIf(!rfm69)
  21. var packets;
  22. var filters = [];
  23. //endRemoveIf(!rfm69)
  24. //removeIf(!sensor)
  25. var Magnitudes = [];
  26. var MagnitudeErrors = {};
  27. var MagnitudeNames = {};
  28. var MagnitudeTypePrefixes = {};
  29. var MagnitudePrefixTypes = {};
  30. //endRemoveIf(!sensor)
  31. // -----------------------------------------------------------------------------
  32. // Utils
  33. // -----------------------------------------------------------------------------
  34. $.fn.enterKey = function (fnc) {
  35. return this.each(function () {
  36. $(this).keypress(function (ev) {
  37. var keycode = parseInt(ev.keyCode ? ev.keyCode : ev.which, 10);
  38. if (13 === keycode) {
  39. return fnc.call(this, ev);
  40. }
  41. });
  42. });
  43. };
  44. function followScroll(id, threshold) {
  45. if (threshold === undefined) {
  46. threshold = 90;
  47. }
  48. var elem = document.getElementById(id);
  49. var offset = (elem.scrollTop + elem.offsetHeight) / elem.scrollHeight * 100;
  50. if (offset > threshold) {
  51. elem.scrollTop = elem.scrollHeight;
  52. }
  53. }
  54. function fromSchema(source, schema) {
  55. if (schema.length !== source.length) {
  56. throw "Schema mismatch!";
  57. }
  58. var target = {};
  59. schema.forEach(function(key, index) {
  60. target[key] = source[index];
  61. });
  62. return target;
  63. }
  64. function keepTime() {
  65. $("span[name='ago']").html(ago);
  66. ago++;
  67. if (0 === now) { return; }
  68. var date = new Date(now * 1000);
  69. var text = date.toISOString().substring(0, 19).replace("T", " ");
  70. $("input[name='now']").val(text);
  71. $("span[name='now']").html(text);
  72. now++;
  73. }
  74. function zeroPad(number, positions) {
  75. return number.toString().padStart(positions, "0");
  76. }
  77. function validatePassword(password) {
  78. // http://www.the-art-of-web.com/javascript/validate-password/
  79. // at least one lowercase and one uppercase letter or number
  80. // at least eight characters (letters, numbers or special characters)
  81. // MUST be 8..63 printable ASCII characters. See:
  82. // https://en.wikipedia.org/wiki/Wi-Fi_Protected_Access#Target_users_(authentication_key_distribution)
  83. // https://github.com/xoseperez/espurna/issues/1151
  84. var re_password = /^(?=.*[A-Z\d])(?=.*[a-z])[\w~!@#$%^&*\(\)<>,.\?;:{}\[\]\\|]{8,63}$/;
  85. return (
  86. (password !== undefined)
  87. && (typeof password === "string")
  88. && (password.length > 0)
  89. && re_password.test(password)
  90. );
  91. }
  92. function validateFormPasswords(form) {
  93. var passwords = $("input[name='adminPass0'],input[name='adminPass1']", form);
  94. var adminPass1 = passwords.first().val(),
  95. adminPass2 = passwords.last().val();
  96. var formValidity = passwords.first()[0].checkValidity();
  97. if (formValidity && (adminPass1.length === 0) && (adminPass2.length === 0)) {
  98. return true;
  99. }
  100. var validPass1 = validatePassword(adminPass1),
  101. validPass2 = validatePassword(adminPass2);
  102. if (formValidity && validPass1 && validPass2) {
  103. return true;
  104. }
  105. if (!formValidity || (adminPass1.length > 0 && !validPass1)) {
  106. alert("The password you have entered is not valid, it must be 8..63 characters and have at least 1 lowercase and 1 uppercase / number!");
  107. }
  108. if (adminPass1 !== adminPass2) {
  109. alert("Passwords are different!");
  110. }
  111. return false;
  112. }
  113. function validateFormHostname(form) {
  114. // RFCs mandate that a hostname's labels may contain only
  115. // the ASCII letters 'a' through 'z' (case-insensitive),
  116. // the digits '0' through '9', and the hyphen.
  117. // Hostname labels cannot begin or end with a hyphen.
  118. // No other symbols, punctuation characters, or blank spaces are permitted.
  119. // Negative lookbehind does not work in Javascript
  120. // var re_hostname = new RegExp('^(?!-)[A-Za-z0-9-]{1,32}(?<!-)$');
  121. var re_hostname = new RegExp('^(?!-)[A-Za-z0-9-]{0,31}[A-Za-z0-9]$');
  122. var hostname = $("input[name='hostname']", form);
  123. if ("true" !== hostname.attr("hasChanged")) {
  124. return true;
  125. }
  126. if (re_hostname.test(hostname.val())) {
  127. return true;
  128. }
  129. alert("Hostname cannot be empty and may only contain the ASCII letters ('A' through 'Z' and 'a' through 'z'), the digits '0' through '9', and the hyphen ('-')! They can neither start or end with an hyphen.");
  130. return false;
  131. }
  132. function validateForm(form) {
  133. return validateFormPasswords(form) && validateFormHostname(form);
  134. }
  135. // Observe all group settings to selectively update originals based on the current data
  136. var groupSettingsObserver = new MutationObserver(function(mutations) {
  137. mutations.forEach(function(mutation) {
  138. // If any new elements are added, set "settings-target" element as changed to forcibly send the data
  139. var targets = $(mutation.target).attr("data-settings-target");
  140. if (targets !== undefined) {
  141. mutation.addedNodes.forEach(function(node) {
  142. var overrides = [];
  143. targets.split(" ").forEach(function(target) {
  144. var elem = $("[name='" + target + "']", node);
  145. if (!elem.length) return;
  146. var value = getValue(elem);
  147. if ((value === null) || (value === elem[0].defaultValue)) {
  148. overrides.push(elem);
  149. }
  150. });
  151. setOriginalsFromValues($("input,select", node));
  152. overrides.forEach(function(elem) {
  153. elem.attr("hasChanged", "true");
  154. if (elem.prop("tagName") === "SELECT") {
  155. elem.prop("value", 0);
  156. }
  157. });
  158. });
  159. }
  160. // If anything was removed, forcibly send **all** of the group to avoid having any outdated keys
  161. // TODO: hide instead of remove?
  162. var changed = $(mutation.target).attr("hasChanged") === "true";
  163. if (changed || mutation.removedNodes.length) {
  164. $(mutation.target).attr("hasChanged", "true");
  165. $("input,select", mutation.target.childNodes).attr("hasChanged", "true");
  166. }
  167. });
  168. });
  169. function bitsetToValues(bitset) {
  170. var values = [];
  171. for (var index = 0; index < 31; ++index) {
  172. if (bitset & (1 << index)) {
  173. values.push(String(index));
  174. }
  175. }
  176. return values;
  177. }
  178. function valuesToBitset(values) {
  179. var result = 0;
  180. for (var value of values) {
  181. result |= 1 << parseInt(value);
  182. }
  183. return result;
  184. }
  185. function getValue(element) {
  186. if ($(element).attr("type") === "checkbox") {
  187. return $(element).prop("checked") ? 1 : 0;
  188. } else if ($(element).attr("type") === "radio") {
  189. if (!$(element).prop("checked")) {
  190. return null;
  191. }
  192. } else if ($(element).attr("multiple") !== undefined) {
  193. return valuesToBitset($(element).val());
  194. }
  195. return $(element).val();
  196. }
  197. function getData(form, changed, cleanup) {
  198. // Populate two sets of data, ones that had been changed and ones that stayed the same
  199. var data = {};
  200. var changed_data = [];
  201. if (cleanup === undefined) {
  202. cleanup = true;
  203. }
  204. if (changed === undefined) {
  205. changed = true;
  206. }
  207. $("input,select", form).each(function() {
  208. if ($(this).attr("data-settings-ignore") === "true") {
  209. return;
  210. }
  211. var name = $(this).attr("name");
  212. if (name === undefined) {
  213. return;
  214. }
  215. var real_name = $(this).attr("data-settings-real-name");
  216. if (real_name !== undefined) {
  217. name = real_name;
  218. }
  219. var value = getValue(this);
  220. if (null !== value) {
  221. var haschanged = ("true" === $(this).attr("hasChanged"));
  222. var indexed = changed_data.indexOf(name) >= 0;
  223. if ((haschanged || !changed) && !indexed) {
  224. changed_data.push(name);
  225. }
  226. // make sure to group keys from templates (or, manually flagged as such)
  227. var is_group = $(this).attr("data-settings-group") !== undefined;
  228. if (is_group) {
  229. if (name in data) {
  230. data[name].push(value);
  231. } else {
  232. data[name] = [value];
  233. }
  234. } else {
  235. data[name] = value;
  236. }
  237. }
  238. });
  239. // Finally, filter out only fields that had changed.
  240. // Note: We need to preserve dynamic lists like schedules, wifi etc.
  241. // so we don't accidentally break when user deletes entry in the middle
  242. var resulting_data = {};
  243. for (var value in data) {
  244. if (changed_data.indexOf(value) >= 0) {
  245. resulting_data[value] = data[value];
  246. }
  247. }
  248. // Hack: clean-up leftover arrays.
  249. // When empty, the receiving side will prune all keys greater than the current one.
  250. if (cleanup) {
  251. $(".settings-group").each(function() {
  252. var haschanged = ("true" === $(this).attr("hasChanged"));
  253. if (haschanged && !this.children.length) {
  254. var targets = this.dataset.settingsTarget;
  255. if (targets === undefined) return;
  256. targets.split(" ").forEach(function(target) {
  257. resulting_data[target] = [];
  258. });
  259. }
  260. });
  261. }
  262. return resulting_data;
  263. }
  264. function randomString(length, args) {
  265. if (typeof args === "undefined") {
  266. args = {
  267. lowercase: true,
  268. uppercase: true,
  269. numbers: true,
  270. special: true
  271. }
  272. }
  273. var mask = "";
  274. if (args.lowercase) { mask += "abcdefghijklmnopqrstuvwxyz"; }
  275. if (args.uppercase) { mask += "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; }
  276. if (args.numbers || args.hex) { mask += "0123456789"; }
  277. if (args.hex) { mask += "ABCDEF"; }
  278. if (args.special) { mask += "~`!@#$%^&*()_+-={}[]:\";'<>?,./|\\"; }
  279. var source = new Uint32Array(length);
  280. var result = new Array(length);
  281. window.crypto.getRandomValues(source).forEach(function(value, i) {
  282. result[i] = mask[value % mask.length];
  283. });
  284. return result.join("");
  285. }
  286. function generateAPIKey() {
  287. var apikey = randomString(16, {hex: true});
  288. $("input[name='apiKey']")
  289. .val(apikey)
  290. .attr("original", "-".repeat(16))
  291. .attr("haschanged", "true");
  292. return false;
  293. }
  294. function generatePassword() {
  295. var password = "";
  296. do {
  297. password = randomString(10);
  298. } while (!validatePassword(password));
  299. return password;
  300. }
  301. function toggleVisiblePassword() {
  302. var elem = this.previousElementSibling;
  303. if (elem.type === "password") {
  304. elem.type = "text";
  305. } else {
  306. elem.type = "password";
  307. }
  308. return false;
  309. }
  310. function doGeneratePassword() {
  311. var elems = $("input", $("#formPassword"));
  312. elems
  313. .val(generatePassword())
  314. .attr("haschanged", "true")
  315. .each(function() {
  316. this.type = "text";
  317. });
  318. return false;
  319. }
  320. function moduleVisible(module) {
  321. if (module == "sch") {
  322. $("li.module-" + module).css("display", "inherit");
  323. $("div.module-" + module).css("display", "flex");
  324. return;
  325. }
  326. $(".module-" + module).css("display", "inherit");
  327. }
  328. //removeIf(!thermostat)
  329. function checkTempRangeMin() {
  330. var min = parseInt($("#tempRangeMinInput").val(), 10);
  331. var max = parseInt($("#tempRangeMaxInput").val(), 10);
  332. if (min > max - 1) {
  333. $("#tempRangeMinInput").val(max - 1);
  334. }
  335. }
  336. function checkTempRangeMax() {
  337. var min = parseInt($("#tempRangeMinInput").val(), 10);
  338. var max = parseInt($("#tempRangeMaxInput").val(), 10);
  339. if (max < min + 1) {
  340. $("#tempRangeMaxInput").val(min + 1);
  341. }
  342. }
  343. function doResetThermostatCounters(ask) {
  344. var question = (typeof ask === "undefined" || false === ask) ?
  345. null :
  346. "Are you sure you want to reset burning counters?";
  347. return doAction(question, "thermostat_reset_counters");
  348. }
  349. //endRemoveIf(!thermostat)
  350. function initSelectGPIO(select) {
  351. // TODO: properly lock used GPIOs via locking and apply the mask here
  352. var mapping = [
  353. [153, "NONE"],
  354. [0, "0 (FLASH)"],
  355. [1, "1 (U0TXD)"],
  356. [2, "2 (U1TXD)"],
  357. [3, "3 (U0RXD)"],
  358. [4, "4 (SDA)"],
  359. [5, "5 (SCL)"],
  360. [9, "9 (SDD2)"],
  361. [10, "10 (SDD3)"],
  362. [12, "12 (MTDI)"],
  363. [13, "13 (MTCK)"],
  364. [14, "14 (MTMS)"],
  365. [15, "15 (MTDO)"],
  366. [16, "16 (WAKE)"],
  367. ];
  368. for (n in mapping) {
  369. var elem = $('<option value="' + mapping[n][0] + '">');
  370. elem.html(mapping[n][1]);
  371. elem.appendTo(select);
  372. }
  373. }
  374. function fillTemplateLineFromCfg(line, id, cfg) {
  375. for (var [key, value] of Object.entries(cfg)) {
  376. var span = $(`span.${key}`, line);
  377. if (span.length) {
  378. span.html(cfg[key]);
  379. continue;
  380. }
  381. var input = $(`input[name='${key}']`, line);
  382. if (input.length) {
  383. if (input.is("[type='checkbox']")) {
  384. var realId = key + id;
  385. input.prop("checked", cfg[key])
  386. .attr("id", realId)
  387. .attr("name", realId)
  388. .next().attr("for", realId);
  389. } else {
  390. input.val(cfg[key]);
  391. }
  392. continue;
  393. }
  394. var select = $(`select[name='${key}']`, line);
  395. if (select.length) {
  396. select.prop("value", cfg[key]);
  397. continue;
  398. }
  399. }
  400. setOriginalsFromValues($("input,select", line));
  401. }
  402. // -----------------------------------------------------------------------------
  403. // Actions
  404. // -----------------------------------------------------------------------------
  405. function send(json) {
  406. if (debug) console.log(json);
  407. websock.send(json);
  408. }
  409. function sendAction(action, data) {
  410. send(JSON.stringify({action: action, data: data}));
  411. }
  412. function sendConfig(data) {
  413. send(JSON.stringify({config: data}));
  414. }
  415. function setOriginalsFromValues(elems) {
  416. if (typeof elems == "undefined") {
  417. elems = $("input,select");
  418. }
  419. elems.each(function() {
  420. var value;
  421. if ($(this).attr("type") === "checkbox") {
  422. value = $(this).prop("checked");
  423. } else {
  424. value = $(this).val();
  425. }
  426. $(this).attr("original", value);
  427. hasChanged.call(this);
  428. });
  429. }
  430. function resetOriginals() {
  431. setOriginalsFromValues();
  432. $(".settings-group").attr("haschanged", "false")
  433. numReboot = numReconnect = numReload = 0;
  434. configurationSaved = false;
  435. }
  436. function doReload(milliseconds) {
  437. setTimeout(function() {
  438. window.location.reload();
  439. }, parseInt(milliseconds, 10));
  440. }
  441. /**
  442. * Check a file object to see if it is a valid firmware image
  443. * The file first byte should be 0xE9
  444. * @param {file} file File object
  445. * @param {Function} callback Function to call back with the result
  446. */
  447. function checkFirmware(file, callback) {
  448. var reader = new FileReader();
  449. reader.onloadend = function(evt) {
  450. if (FileReader.DONE === evt.target.readyState) {
  451. var magic = evt.target.result.charCodeAt(0);
  452. if ((0x1F === magic) && (0x8B === evt.target.result.charCodeAt(1))) {
  453. callback(true);
  454. return;
  455. }
  456. if (0xE9 !== magic) {
  457. alert("Binary image does not start with a magic byte");
  458. callback(false);
  459. return;
  460. }
  461. var modes = ['QIO', 'QOUT', 'DIO', 'DOUT'];
  462. var flash_mode = evt.target.result.charCodeAt(2);
  463. if (0x03 !== flash_mode) {
  464. var response = window.confirm("Binary image is using " + modes[flash_mode] + " flash mode! Make sure that the device supports it before proceeding.");
  465. callback(response);
  466. } else {
  467. callback(true);
  468. }
  469. }
  470. };
  471. var blob = file.slice(0, 3);
  472. reader.readAsBinaryString(blob);
  473. }
  474. function doUpgrade() {
  475. var file = $("input[name='upgrade']")[0].files[0];
  476. if (typeof file === "undefined") {
  477. alert("First you have to select a file from your computer.");
  478. return false;
  479. }
  480. if (file.size > free_size) {
  481. alert("Image it too large to fit in the available space for OTA. Consider doing a two-step update.");
  482. return false;
  483. }
  484. checkFirmware(file, function(ok) {
  485. if (!ok) {
  486. return;
  487. }
  488. var data = new FormData();
  489. data.append("upgrade", file, file.name);
  490. var xhr = new XMLHttpRequest();
  491. var msg_ok = "Firmware image uploaded, board rebooting. This page will be refreshed in 5 seconds.";
  492. var msg_err = "There was an error trying to upload the new image, please try again: ";
  493. var network_error = function(e) {
  494. alert(msg_err + " xhr request " + e.type);
  495. };
  496. xhr.addEventListener("error", network_error, false);
  497. xhr.addEventListener("abort", network_error, false);
  498. xhr.addEventListener("load", function(e) {
  499. $("#upgrade-progress").hide();
  500. if ("OK" === xhr.responseText) {
  501. alert(msg_ok);
  502. doReload(5000);
  503. } else {
  504. alert(msg_err + xhr.status.toString() + " " + xhr.statusText + ", " + xhr.responseText);
  505. }
  506. }, false);
  507. xhr.upload.addEventListener("progress", function(e) {
  508. $("#upgrade-progress").show();
  509. if (e.lengthComputable) {
  510. $("progress").attr({ value: e.loaded, max: e.total });
  511. }
  512. }, false);
  513. xhr.open("POST", urls.upgrade.href);
  514. xhr.send(data);
  515. });
  516. return false;
  517. }
  518. function doUpdatePassword() {
  519. var form = $("#formPassword");
  520. if (validateFormPasswords(form)) {
  521. sendConfig(getData(form, true, false));
  522. }
  523. return false;
  524. }
  525. function checkChanges() {
  526. if (numChanged > 0) {
  527. var response = window.confirm("Some changes have not been saved yet, do you want to save them first?");
  528. if (response) {
  529. doUpdate();
  530. }
  531. }
  532. }
  533. function doAction(question, action) {
  534. checkChanges();
  535. if (question) {
  536. var response = window.confirm(question);
  537. if (false === response) {
  538. return false;
  539. }
  540. }
  541. sendAction(action, {});
  542. doReload(5000);
  543. return false;
  544. }
  545. function doReboot(ask) {
  546. var question = (typeof ask === "undefined" || false === ask) ?
  547. null :
  548. "Are you sure you want to reboot the device?";
  549. return doAction(question, "reboot");
  550. }
  551. function doReconnect(ask) {
  552. var question = (typeof ask === "undefined" || false === ask) ?
  553. null :
  554. "Are you sure you want to disconnect from the current WIFI network?";
  555. return doAction(question, "reconnect");
  556. }
  557. function doCheckOriginals() {
  558. var response;
  559. if (numReboot > 0) {
  560. response = window.confirm("You have to reboot the board for the changes to take effect, do you want to do it now?");
  561. if (response) { doReboot(false); }
  562. } else if (numReconnect > 0) {
  563. response = window.confirm("You have to reconnect to the WiFi for the changes to take effect, do you want to do it now?");
  564. if (response) { doReconnect(false); }
  565. } else if (numReload > 0) {
  566. response = window.confirm("You have to reload the page to see the latest changes, do you want to do it now?");
  567. if (response) { doReload(0); }
  568. }
  569. resetOriginals();
  570. }
  571. function waitForSave(){
  572. if (!configurationSaved) {
  573. setTimeout(waitForSave, 1000);
  574. } else {
  575. doCheckOriginals();
  576. }
  577. }
  578. function doUpdate() {
  579. // Since we have 2-page config, make sure we select the active one
  580. var forms = $(".form-settings");
  581. if (validateForm(forms)) {
  582. sendConfig(getData(forms));
  583. //removeIf(!sensor)
  584. // Energy reset is handled via these keys
  585. // TODO: replace these with actions, not settings
  586. $(".pwrExpected").val(0);
  587. $("input[name='snsResetCalibration']").prop("checked", false);
  588. $("input[name='pwrResetCalibration']").prop("checked", false);
  589. $("input[name='pwrResetE']").prop("checked", false);
  590. //endRemoveIf(!sensor)
  591. numChanged = 0;
  592. waitForSave();
  593. }
  594. return false;
  595. }
  596. function doBackup() {
  597. document.getElementById("downloader").src = urls.config.href;
  598. return false;
  599. }
  600. function onFileUpload(event) {
  601. var inputFiles = this.files;
  602. if (typeof inputFiles === "undefined" || inputFiles.length === 0) {
  603. return false;
  604. }
  605. var inputFile = inputFiles[0];
  606. this.value = "";
  607. var response = window.confirm("Previous settings will be overwritten. Are you sure you want to restore this settings?");
  608. if (!response) {
  609. return false;
  610. }
  611. var reader = new FileReader();
  612. reader.onload = function(e) {
  613. try {
  614. var data = JSON.parse(e.target.result);
  615. sendAction("restore", data);
  616. } catch (e) {
  617. window.alert(e);
  618. }
  619. };
  620. reader.readAsText(inputFile);
  621. return false;
  622. }
  623. function doRestore() {
  624. if (typeof window.FileReader !== "function") {
  625. alert("The file API isn't supported on this browser yet.");
  626. } else {
  627. $("#uploader").click();
  628. }
  629. return false;
  630. }
  631. function doFactoryReset() {
  632. var response = window.confirm("Are you sure you want to restore to factory settings?");
  633. if (!response) {
  634. return false;
  635. }
  636. sendAction("factory_reset", {});
  637. doReload(5000);
  638. return false;
  639. }
  640. function doToggle(id, value) {
  641. sendAction("relay", {id: id, status: value ? 1 : 0 });
  642. return false;
  643. }
  644. function doScan() {
  645. $("#scanResult").html("");
  646. $("div.scan.loading").show();
  647. $("#button-wifi-scan").attr("disabled", true);
  648. sendAction("scan", {});
  649. return false;
  650. }
  651. function doDebugCommand() {
  652. var el = $("input[name='dbgcmd']");
  653. var command = el.val();
  654. el.val("");
  655. sendAction("dbgcmd", {command: command});
  656. followScroll("weblog", 0);
  657. return false;
  658. }
  659. function doDebugClear() {
  660. $("#weblog").text("");
  661. return false;
  662. }
  663. //removeIf(!rfm69)
  664. function doClearCounts() {
  665. sendAction("clear-counts", {});
  666. return false;
  667. }
  668. function doClearMessages() {
  669. packets.clear().draw(false);
  670. return false;
  671. }
  672. function doFilter(e) {
  673. var index = packets.cell(this).index();
  674. if (index == 'undefined') return;
  675. var c = index.column;
  676. var column = packets.column(c);
  677. if (filters[c]) {
  678. filters[c] = false;
  679. column.search("");
  680. $(column.header()).removeClass("filtered");
  681. } else {
  682. filters[c] = true;
  683. var data = packets.row(this).data();
  684. if (e.which == 1) {
  685. column.search('^' + data[c] + '$', true, false );
  686. } else {
  687. column.search('^((?!(' + data[c] + ')).)*$', true, false );
  688. }
  689. $(column.header()).addClass("filtered");
  690. }
  691. column.draw();
  692. return false;
  693. }
  694. function doClearFilters() {
  695. for (var i = 0; i < packets.columns()[0].length; i++) {
  696. if (filters[i]) {
  697. filters[i] = false;
  698. var column = packets.column(i);
  699. column.search("");
  700. $(column.header()).removeClass("filtered");
  701. column.draw();
  702. }
  703. }
  704. return false;
  705. }
  706. //endRemoveIf(!rfm69)
  707. function delParent() {
  708. var parent = $(this).parent().parent();
  709. $(parent).remove();
  710. }
  711. // -----------------------------------------------------------------------------
  712. // Visualization
  713. // -----------------------------------------------------------------------------
  714. function toggleMenu() {
  715. $("#layout").toggleClass("active");
  716. $("#menu").toggleClass("active");
  717. $("#menuLink").toggleClass("active");
  718. }
  719. function showPanel() {
  720. $(".panel").hide();
  721. if ($("#layout").hasClass("active")) { toggleMenu(); }
  722. $("#" + $(this).attr("data")).show();
  723. }
  724. function loadTemplate(name) {
  725. let template = $(`#${name}.template`);
  726. let clone = $(template).clone();
  727. return clone.children();
  728. }
  729. function loadConfigTemplate(name) {
  730. let template = loadTemplate(name);
  731. $("input,select", template)
  732. .attr("data-settings-group", "");
  733. return template;
  734. }
  735. // -----------------------------------------------------------------------------
  736. // Relays & magnitudes mapping
  737. // -----------------------------------------------------------------------------
  738. function createRelayList(data, container, template_name) {
  739. var current = $("#" + container + " > div").length;
  740. if (current > 0) { return; }
  741. var template = loadConfigTemplate(template_name);
  742. for (var i in data) {
  743. var line = $(template).clone();
  744. $("label", line).html("Switch #" + i);
  745. setOriginalsFromValues($("input", line));
  746. line.appendTo("#" + container);
  747. }
  748. }
  749. //removeIf(!sensor)
  750. function createMagnitudeList(data, container, template_name) {
  751. var current = $("#" + container + " > div").length;
  752. if (current > 0) { return; }
  753. var template = loadConfigTemplate(template_name);
  754. var size = data.size;
  755. for (var i=0; i<size; ++i) {
  756. var line = $(template).clone();
  757. $("label", line).html(MagnitudeNames[data.type[i]] + " #" + parseInt(data.index[i], 10));
  758. $("div.hint", line).html(Magnitudes[i].description);
  759. setOriginalsFromValues($("input", line));
  760. line.appendTo("#" + container);
  761. }
  762. }
  763. //endRemoveIf(!sensor)
  764. function addFromTemplate(template, target) {
  765. var line = loadConfigTemplate(template);
  766. $("button", line)
  767. .on('click', delParent);
  768. setOriginalsFromValues($("input", line));
  769. line.appendTo("#" + target);
  770. }
  771. // -----------------------------------------------------------------------------
  772. // RPN Rules
  773. // -----------------------------------------------------------------------------
  774. function addRPNRule() {
  775. addFromTemplate("rpnRuleTemplate", "rpnRules");
  776. }
  777. function addRPNTopic() {
  778. addFromTemplate("rpnRuleTemplate", "rpnTopics");
  779. }
  780. // -----------------------------------------------------------------------------
  781. // RFM69
  782. // -----------------------------------------------------------------------------
  783. //removeIf(!rfm69)
  784. function addMapping() {
  785. addFromTemplate("nodeTemplate", "mapping");
  786. }
  787. //endRemoveIf(!rfm69)
  788. // -----------------------------------------------------------------------------
  789. // Wifi
  790. // -----------------------------------------------------------------------------
  791. function numNetworks() {
  792. return $("#networks > div").length;
  793. }
  794. function delNetwork() {
  795. var parent = $(this).parents(".pure-g");
  796. $(parent).remove();
  797. }
  798. function moreNetwork() {
  799. var parent = $(this).parents(".pure-g");
  800. $(".more", parent).toggle();
  801. }
  802. function addNetwork(network) {
  803. var number = numNetworks();
  804. if (number >= maxNetworks) {
  805. alert("Max number of networks reached");
  806. return null;
  807. }
  808. if (network === undefined) {
  809. network = {};
  810. }
  811. var line = loadConfigTemplate("networkTemplate");
  812. $(".password-reveal", line).on("click", toggleVisiblePassword);
  813. $(line).find(".button-del-network").on("click", delNetwork);
  814. $(line).find(".button-more-network").on("click", moreNetwork);
  815. Object.entries(network).forEach(function(pair) {
  816. // XXX: UI deleting this network will only re-use stored values.
  817. var key = pair[0],
  818. val = pair[1];
  819. if (key === "stored") {
  820. $(line).find(".button-del-network").prop("disabled", val);
  821. return;
  822. }
  823. $("input[name='" + key + "']", line).val(val);
  824. });
  825. line.appendTo("#networks");
  826. return line;
  827. }
  828. // -----------------------------------------------------------------------------
  829. // Relays scheduler
  830. // -----------------------------------------------------------------------------
  831. function numSchedules() {
  832. return $("#schedules > div").length;
  833. }
  834. function maxSchedules() {
  835. var value = $("#schedules").attr("data-settings-max");
  836. return parseInt(value === undefined ? 0 : value, 10);
  837. }
  838. function delSchedule() {
  839. var parent = $(this).parents(".pure-g");
  840. $(parent).remove();
  841. }
  842. function moreSchedule() {
  843. var parent = $(this).parents(".pure-g");
  844. $("div.more", parent).toggle();
  845. }
  846. function addSchedule(cfg, payload) {
  847. var id = numSchedules();
  848. if (id >= maxSchedules()) {
  849. alert("Max number of schedules reached");
  850. return null;
  851. }
  852. if (cfg === undefined) {
  853. return null;
  854. }
  855. if (payload === undefined) {
  856. payload = {};
  857. }
  858. var line = loadConfigTemplate("scheduleTemplate");
  859. var type = "none";
  860. switch(cfg.schType) {
  861. case 1:
  862. type = "switch";
  863. break;
  864. case 2:
  865. type = "light";
  866. break;
  867. case 3:
  868. type = "curtain";
  869. break;
  870. }
  871. $("#schActionDiv", line)
  872. .append(loadConfigTemplate(type + "ActionTemplate"));
  873. $(".button-del-schedule", line)
  874. .on("click", delSchedule);
  875. $(".button-more-schedule", line)
  876. .on("click", moreSchedule);
  877. $("input[type='checkbox']", line)
  878. .prop("checked", false);
  879. fillTemplateLineFromCfg(line, id, cfg);
  880. line.appendTo("#schedules");
  881. return line;
  882. }
  883. // -----------------------------------------------------------------------------
  884. // Relays
  885. // -----------------------------------------------------------------------------
  886. function initRelay(id, cfg, payload) {
  887. var line = loadConfigTemplate("relayTemplate");
  888. $("span.relayName", line)
  889. .text(cfg.relayName)
  890. .attr("data-id", id)
  891. .attr("title", payload["desc"][id]);
  892. $("input[type='checkbox']", line)
  893. .prop('checked', false)
  894. .prop('disabled', true)
  895. .attr("data-id", id)
  896. .prop("id", "relay" + id)
  897. .on("change", function (event) {
  898. var target= parseInt($(event.target).attr("data-id"), 10);
  899. var status = $(event.target).prop("checked");
  900. doToggle(target, status);
  901. });
  902. $("label.toggle", line)
  903. .prop("for", "relay" + id);
  904. line.appendTo("#relays");
  905. }
  906. function updateRelays(data) {
  907. var size = data.size;
  908. for (var i=0; i<size; ++i) {
  909. var elem = $("input[name='relay'][data-id='" + i + "']");
  910. elem.prop("checked", data.status[i]);
  911. var lock = {
  912. 0: false,
  913. 1: !data.status[i],
  914. 2: data.status[i]
  915. };
  916. elem.prop("disabled", lock[data.lock[i]]); // RELAY_LOCK_DISABLED=0
  917. }
  918. }
  919. function createCheckboxes() {
  920. $("input[type='checkbox']").each(function() {
  921. let name = $(this).prop("name")
  922. if ($(this).prop("name")) {
  923. $(this).prop("id", $(this).prop("name"));
  924. }
  925. $(this)
  926. .parent().addClass("toggleWrapper");
  927. $(this)
  928. .after('<label for="' + $(this).prop("name") + '" class="toggle"><span class="toggle__handler"></span></label>')
  929. });
  930. }
  931. function initRelayConfig(id, cfg, payload) {
  932. var line = loadConfigTemplate("relayConfigTemplate");
  933. fillTemplateLineFromCfg(line, id, cfg);
  934. line.appendTo("#relayConfig");
  935. // Populate the relay SELECTs on the configuration panel
  936. $("select.isrelay").append(
  937. $("<option></option>")
  938. .attr("value", id)
  939. .text(name)
  940. );
  941. }
  942. // -----------------------------------------------------------------------------
  943. // Sensors & Magnitudes
  944. // -----------------------------------------------------------------------------
  945. //removeIf(!sensor)
  946. function initMagnitudes(data) {
  947. // check if already initialized (each magnitude is inside div.pure-g)
  948. var done = $("#magnitudes > div").length;
  949. if (done > 0) { return; }
  950. var size = data.size;
  951. for (var i=0; i<size; ++i) {
  952. var magnitude = {
  953. "name": MagnitudeNames[data.type[i]] + " #" + parseInt(data.index[i], 10),
  954. "units": data.units[i],
  955. "description": data.description[i]
  956. };
  957. Magnitudes.push(magnitude);
  958. var line = loadConfigTemplate("magnitudeTemplate");
  959. $("label", line).html(magnitude.name);
  960. $("input", line).attr("data", i);
  961. $("div.sns-desc", line).html(magnitude.description);
  962. $("div.sns-info", line).hide();
  963. line.appendTo("#magnitudes");
  964. }
  965. }
  966. //endRemoveIf(!sensor)
  967. // -----------------------------------------------------------------------------
  968. // Curtains
  969. // -----------------------------------------------------------------------------
  970. //removeIf(!curtain)
  971. //Create the controls for one curtain. It is called when curtain is updated (so created the first time)
  972. //Let this there as we plan to have more than one curtain per switch
  973. function initCurtain(data) {
  974. var current = $("#curtains > div").length;
  975. if (current > 0) { return; }
  976. // add and init curtain template, prepare multi switches
  977. var line = loadConfigTemplate("curtainTemplate");
  978. $(line).find(".button-curtain-open").on("click", function() {
  979. sendAction("curtainAction", {button: 1});
  980. $(this).css('background', 'red');
  981. });
  982. $(line).find(".button-curtain-pause").on("click", function() {
  983. sendAction("curtainAction", {button: 0});
  984. $(this).css('background', 'red');
  985. });
  986. $(line).find(".button-curtain-close").on("click", function() {
  987. sendAction("curtainAction", {button: 2});
  988. $(this).css('background', 'red');
  989. });
  990. line.appendTo("#curtains");
  991. // init curtain slider
  992. $("#curtainSet").on("change", function() {
  993. var value = $(this).val();
  994. var parent = $(this).parents(".pure-g");
  995. $("span", parent).html(value);
  996. sendAction("curtainAction", {position: value});
  997. });
  998. }
  999. function initCurtainConfig(data) {
  1000. var current = $("#curtainConfig > legend").length; // there is a legend per relay
  1001. if (current > 0) { return; }
  1002. // Populate the curtain select
  1003. $("select.iscurtain").append(
  1004. $("<option></option>")
  1005. .attr("value", "0")
  1006. .text("Curtain #" + "0")
  1007. );
  1008. }
  1009. //endRemoveIf(!curtain)
  1010. // -----------------------------------------------------------------------------
  1011. // Lights
  1012. // -----------------------------------------------------------------------------
  1013. //removeIf(!light)
  1014. function colorToHsvString(color) {
  1015. var h = String(Math.round(color.hsv.h));
  1016. var s = String(Math.round(color.hsv.s));
  1017. var v = String(Math.round(color.hsv.v));
  1018. return h + "," + s + "," + v;
  1019. }
  1020. function hsvStringToColor(hsv) {
  1021. var parts = hsv.split(",");
  1022. return {
  1023. h: parseInt(parts[0]),
  1024. s: parseInt(parts[1]),
  1025. v: parseInt(parts[2])
  1026. };
  1027. }
  1028. function colorSlider(type) {
  1029. return {component: iro.ui.Slider, options: {sliderType: type}};
  1030. }
  1031. function colorWheel() {
  1032. return {component: iro.ui.Wheel, options: {}};
  1033. }
  1034. function colorBox() {
  1035. return {component: iro.ui.Box, options: {}};
  1036. }
  1037. function updateColor(mode, value) {
  1038. if (colorPicker) {
  1039. if (mode === "rgb") {
  1040. colorPicker.color.hexString = value;
  1041. } else if (mode === "hsv") {
  1042. colorPicker.color.hsv = hsvStringToColor(value);
  1043. }
  1044. return;
  1045. }
  1046. // TODO: useRGB -> ltWheel?
  1047. // TODO: always show wheel + sliders like before?
  1048. var layout = []
  1049. if (mode === "rgb") {
  1050. layout.push(colorWheel());
  1051. layout.push(colorSlider("value"));
  1052. } else if (mode === "hsv") {
  1053. layout.push(colorBox());
  1054. layout.push(colorSlider("hue"));
  1055. }
  1056. var options = {
  1057. color: (mode === "rgb") ? value : hsvStringToColor(value),
  1058. layout: layout
  1059. };
  1060. colorPicker = new iro.ColorPicker("#color", options);
  1061. colorPicker.on("input:change", function(color) {
  1062. if (mode === "rgb") {
  1063. sendAction("color", {rgb: color.hexString});
  1064. } else if (mode === "hsv") {
  1065. sendAction("color", {hsv: colorToHsvString(color)});
  1066. }
  1067. });
  1068. }
  1069. function initCCT() {
  1070. // check if already initialized
  1071. var done = $("#cct > div").length;
  1072. if (done > 0) { return; }
  1073. $("#miredsTemplate").children().clone().appendTo("#cct");
  1074. $("#mireds").on("change", function() {
  1075. var value = $(this).val();
  1076. var parent = $(this).parents(".pure-g");
  1077. $("span", parent).html(value);
  1078. sendAction("mireds", {mireds: value});
  1079. });
  1080. }
  1081. function initChannels(num) {
  1082. // check if already initialized
  1083. var done = $("#channels > div").length > 0;
  1084. if (done) { return; }
  1085. // calculate channels to create
  1086. var max = num;
  1087. if (colorPicker) {
  1088. max = num % 3;
  1089. if ((max > 0) & useWhite) {
  1090. max--;
  1091. if (useCCT) {
  1092. max--;
  1093. }
  1094. }
  1095. }
  1096. var start = num - max;
  1097. var onChannelSliderChange = function() {
  1098. var id = $(this).attr("data");
  1099. var value = $(this).val();
  1100. var parent = $(this).parents(".pure-g");
  1101. $("span", parent).html(value);
  1102. sendAction("channel", {id: id, value: value});
  1103. };
  1104. // add channel templates
  1105. var i = 0;
  1106. for (i=0; i<max; i++) {
  1107. var channel_id = start + i;
  1108. var line = loadTemplate("channelTemplate");
  1109. $("span.slider", line).attr("data", channel_id);
  1110. $("input.slider", line).attr("data", channel_id).on("change", onChannelSliderChange);
  1111. $("label", line).html("Channel #" + channel_id);
  1112. line.appendTo("#channels");
  1113. }
  1114. // Init channel dropdowns
  1115. for (i=0; i<num; i++) {
  1116. $("select.islight").append(
  1117. $("<option></option>").attr("value",i).text("Channel #" + i));
  1118. }
  1119. // add brightness template
  1120. var line = loadTemplate("brightnessTemplate");
  1121. line.appendTo("#channels");
  1122. // init bright slider
  1123. $("#brightness").on("change", function() {
  1124. var value = $(this).val();
  1125. var parent = $(this).parents(".pure-g");
  1126. $("span", parent).html(value);
  1127. sendAction("brightness", {value: value});
  1128. });
  1129. }
  1130. //endRemoveIf(!light)
  1131. // -----------------------------------------------------------------------------
  1132. // RFBridge
  1133. // -----------------------------------------------------------------------------
  1134. //removeIf(!rfbridge)
  1135. function rfbLearn() {
  1136. var parent = $(this).parents(".pure-g");
  1137. var input = $("input", parent);
  1138. sendAction("rfblearn", {id: input.attr("data-id"), status: input.attr("data-status")});
  1139. }
  1140. function rfbForget() {
  1141. var parent = $(this).parents(".pure-g");
  1142. var input = $("input", parent);
  1143. sendAction("rfbforget", {id: input.attr("data-id"), status: input.attr("data-status")});
  1144. }
  1145. function rfbSend() {
  1146. var parent = $(this).parents(".pure-g");
  1147. var input = $("input", parent);
  1148. sendAction("rfbsend", {id: input.attr("data-id"), status: input.attr("data-status"), data: input.val()});
  1149. }
  1150. function addRfbNode() {
  1151. var numNodes = $("#rfbNodes > legend").length;
  1152. var line = loadTemplate("rfbNodeTemplate");
  1153. $("span", line).html(numNodes);
  1154. $(line).find("input").each(function() {
  1155. this.dataset["id"] = numNodes;
  1156. });
  1157. $(line).find(".button-rfb-learn").on("click", rfbLearn);
  1158. $(line).find(".button-rfb-forget").on("click", rfbForget);
  1159. $(line).find(".button-rfb-send").on("click", rfbSend);
  1160. line.appendTo("#rfbNodes");
  1161. return line;
  1162. }
  1163. //endRemoveIf(!rfbridge)
  1164. // -----------------------------------------------------------------------------
  1165. // LightFox
  1166. // -----------------------------------------------------------------------------
  1167. //removeIf(!lightfox)
  1168. function lightfoxLearn() {
  1169. sendAction("lightfoxLearn", {});
  1170. }
  1171. function lightfoxClear() {
  1172. sendAction("lightfoxClear", {});
  1173. }
  1174. function initLightfox(data, relayCount) {
  1175. var numNodes = data.length;
  1176. var i, j;
  1177. for (i=0; i<numNodes; i++) {
  1178. var $line = loadTemplate("lightfoxNodeTemplate");
  1179. $line.find("label > span").text(data[i]["id"]);
  1180. $line.find("select").each(function() {
  1181. $(this).attr("name", "btnRelay" + data[i]["id"]);
  1182. for (j=0; j < relayCount; j++) {
  1183. $(this).append($("<option >").attr("value", j).text("Switch #" + j));
  1184. }
  1185. $(this).val(data[i]["relay"]);
  1186. status = !status;
  1187. });
  1188. setOriginalsFromValues($("input,select", $line));
  1189. $line.appendTo("#lightfoxNodes");
  1190. }
  1191. var $panel = $("#panel-lightfox")
  1192. $(".button-lightfox-learn").off("click").click(lightfoxLearn);
  1193. $(".button-lightfox-clear").off("click").click(lightfoxClear);
  1194. }
  1195. //endRemoveIf(!lightfox)
  1196. // -----------------------------------------------------------------------------
  1197. // Processing
  1198. // -----------------------------------------------------------------------------
  1199. function processData(data) {
  1200. if (debug) console.log(data);
  1201. // title
  1202. if ("app_name" in data) {
  1203. var title = data.app_name;
  1204. if ("app_version" in data) {
  1205. $("span[name=title]").html(data.app_version);
  1206. title = title + " " + data.app_version;
  1207. }
  1208. if ("hostname" in data) {
  1209. title = data.hostname + " - " + title;
  1210. }
  1211. document.title = title;
  1212. }
  1213. Object.keys(data).forEach(function(key) {
  1214. var i;
  1215. var value = data[key];
  1216. // ---------------------------------------------------------------------
  1217. // Web mode
  1218. // ---------------------------------------------------------------------
  1219. if ("webMode" === key) {
  1220. password = (1 === value);
  1221. $("#layout").toggle(!password);
  1222. $("#password").toggle(password);
  1223. }
  1224. // ---------------------------------------------------------------------
  1225. // Actions
  1226. // ---------------------------------------------------------------------
  1227. if ("action" === key) {
  1228. if ("reload" === data.action) {
  1229. doReload(1000);
  1230. }
  1231. return;
  1232. }
  1233. // ---------------------------------------------------------------------
  1234. // RFBridge
  1235. // ---------------------------------------------------------------------
  1236. //removeIf(!rfbridge)
  1237. if ("rfbCount" === key) {
  1238. for (i=0; i<data.rfbCount; i++) { addRfbNode(); }
  1239. return;
  1240. }
  1241. if ("rfb" === key) {
  1242. var rfb = data.rfb;
  1243. var size = rfb.size;
  1244. var start = rfb.start;
  1245. var processOn = ((rfb.on !== undefined) && (rfb.on.length > 0));
  1246. var processOff = ((rfb.off !== undefined) && (rfb.off.length > 0));
  1247. for (let i = 0; i < size; ++i) {
  1248. let selector = template`input[name='rfbcode'][data-id='${id}'][data-status='${status}']`;
  1249. let id = i + start;
  1250. if (processOn) {
  1251. $(selector({"id": id, "status": 1}))
  1252. .val(rfb.on[i]);
  1253. }
  1254. if (processOff) {
  1255. $(selector({"id": id, "status": 0}))
  1256. .val(rfb.off[i]);
  1257. }
  1258. }
  1259. return;
  1260. }
  1261. //endRemoveIf(!rfbridge)
  1262. // ---------------------------------------------------------------------
  1263. // LightFox
  1264. // ---------------------------------------------------------------------
  1265. //removeIf(!lightfox)
  1266. if ("lightfoxButtons" === key) {
  1267. initLightfox(data["lightfoxButtons"], data["lightfoxRelayCount"]);
  1268. return;
  1269. }
  1270. //endRemoveIf(!lightfox)
  1271. // ---------------------------------------------------------------------
  1272. // RFM69
  1273. // ---------------------------------------------------------------------
  1274. //removeIf(!rfm69)
  1275. if (key == "packet") {
  1276. var packet = data.packet;
  1277. var d = new Date();
  1278. packets.row.add([
  1279. d.toLocaleTimeString('en-US', { hour12: false }),
  1280. packet.senderID,
  1281. packet.packetID,
  1282. packet.targetID,
  1283. packet.key,
  1284. packet.value,
  1285. packet.rssi,
  1286. packet.duplicates,
  1287. packet.missing,
  1288. ]).draw(false);
  1289. return;
  1290. }
  1291. if (key == "mapping") {
  1292. for (var i in data.mapping) {
  1293. // add a new row
  1294. addMapping();
  1295. // get group
  1296. var line = $("#mapping .pure-g")[i];
  1297. // fill in the blanks
  1298. var mapping = data.mapping[i];
  1299. Object.keys(mapping).forEach(function(key) {
  1300. var id = "input[name=" + key + "]";
  1301. if ($(id, line).length) $(id, line).val(mapping[key]);
  1302. });
  1303. setOriginalsFromValues($("input", line));
  1304. }
  1305. return;
  1306. }
  1307. //endRemoveIf(!rfm69)
  1308. // ---------------------------------------------------------------------
  1309. // RPN Rules
  1310. // ---------------------------------------------------------------------
  1311. if (key == "rpnRules") {
  1312. for (var i in data.rpnRules) {
  1313. // add a new row
  1314. addRPNRule();
  1315. // get group
  1316. var line = $("#rpnRules .pure-g")[i];
  1317. // fill in the blanks
  1318. var rule = data.rpnRules[i];
  1319. $("input", line).val(rule);
  1320. setOriginalsFromValues($("input", line));
  1321. }
  1322. return;
  1323. }
  1324. if (key == "rpnTopics") {
  1325. for (var i in data.rpnTopics) {
  1326. // add a new row
  1327. addRPNTopic();
  1328. // get group
  1329. var line = $("#rpnTopics .pure-g")[i];
  1330. // fill in the blanks
  1331. var topic = data.rpnTopics[i];
  1332. var name = data.rpnNames[i];
  1333. $("input[name='rpnTopic']", line).val(topic);
  1334. $("input[name='rpnName']", line).val(name);
  1335. setOriginalsFromValues($("input", line));
  1336. }
  1337. return;
  1338. }
  1339. if (key == "rpnNames") return;
  1340. // ---------------------------------------------------------------------
  1341. // Curtains
  1342. // ---------------------------------------------------------------------
  1343. //removeIf(!curtain)
  1344. function applyCurtain(a, b) {
  1345. $("#curtainGetPicture").css('background', 'linear-gradient(' + a + ', black ' + b + '%, #a0d6ff ' + b + '%)');
  1346. }
  1347. if ("curtainState" === key) {
  1348. initCurtain();
  1349. switch(value.type) {
  1350. case '0': //Roller
  1351. default:
  1352. applyCurtain('180deg', value.get);
  1353. break;
  1354. case '1': //One side left to right
  1355. applyCurtain('90deg', value.get);
  1356. break;
  1357. case '2': //One side right to left
  1358. applyCurtain('270deg', value.get);
  1359. break;
  1360. case '3': //Two sides
  1361. $("#curtainGetPicture").css('background', 'linear-gradient(90deg, black ' + value.get/2 + '%, #a0d6ff ' + value.get/2 + '% ' + (100 - value.get/2) + '%, black ' + (100 - value.get/2) + '%)');
  1362. break;
  1363. }
  1364. $("#curtainSet").val(value.set);
  1365. if(!value.moving) {
  1366. $("button.curtain-button").css('background', 'rgb(66, 184, 221)');
  1367. } else {
  1368. if(!value.button)
  1369. $("button.button-curtain-pause").css('background', 'rgb(192, 0, 0)');
  1370. else if(value.button == 1) {
  1371. $("button.button-curtain-close").css('background', 'rgb(66, 184, 221)');
  1372. $("button.button-curtain-open").css('background', 'rgb(192, 0, 0)');
  1373. }
  1374. else if(value.button == 2) {
  1375. $("button.button-curtain-open").css('background', 'rgb(66, 184, 221)');
  1376. $("button.button-curtain-close").css('background', 'rgb(192, 0, 0)');
  1377. }
  1378. }
  1379. return;
  1380. }
  1381. //endRemoveIf(!curtain)
  1382. // ---------------------------------------------------------------------
  1383. // Lights
  1384. // ---------------------------------------------------------------------
  1385. //removeIf(!light)
  1386. if ("lightstate" === key) {
  1387. $("#color").toggle(value);
  1388. return;
  1389. }
  1390. if (("rgb" === key) || ("hsv" === key)) {
  1391. updateColor(key, value);
  1392. return;
  1393. }
  1394. if ("brightness" === key) {
  1395. $("#brightness").val(value);
  1396. $("span.brightness").html(value);
  1397. return;
  1398. }
  1399. if ("channels" === key) {
  1400. var len = value.length;
  1401. initChannels(len);
  1402. for (i in value) {
  1403. var ch = value[i];
  1404. $("input.slider[data=" + i + "]").val(ch);
  1405. $("span.slider[data=" + i + "]").html(ch);
  1406. }
  1407. return;
  1408. }
  1409. if ("mireds" === key) {
  1410. $("#mireds").attr("min", value["cold"]);
  1411. $("#mireds").attr("max", value["warm"]);
  1412. $("#mireds").val(value["value"]);
  1413. $("span.mireds").html(value["value"]);
  1414. return;
  1415. }
  1416. if ("useWhite" === key) {
  1417. useWhite = value;
  1418. }
  1419. if ("useCCT" === key) {
  1420. initCCT();
  1421. useCCT = value;
  1422. }
  1423. //endRemoveIf(!light)
  1424. // ---------------------------------------------------------------------
  1425. // Sensors & Magnitudes
  1426. // ---------------------------------------------------------------------
  1427. //removeIf(!sensor)
  1428. if ("snsErrors" === key) {
  1429. for (var index in value) {
  1430. var type = value[index][0];
  1431. var name = value[index][1];
  1432. MagnitudeErrors[type] = name;
  1433. }
  1434. return;
  1435. }
  1436. if ("snsMagnitudes" === key) {
  1437. for (var index in value) {
  1438. var type = value[index][0];
  1439. var prefix = value[index][1];
  1440. var name = value[index][2];
  1441. MagnitudeNames[type] = name;
  1442. MagnitudeTypePrefixes[type] = prefix;
  1443. MagnitudePrefixTypes[prefix] = type;
  1444. moduleVisible(prefix);
  1445. }
  1446. return;
  1447. }
  1448. if ("magnitudesConfig" === key) {
  1449. initMagnitudes(value);
  1450. return;
  1451. }
  1452. if ("magnitudes" === key) {
  1453. for (var i=0; i<value.size; ++i) {
  1454. var inputElem = $("input[name='magnitude'][data='" + i + "']");
  1455. var infoElem = inputElem.parent().parent().find("div.sns-info");
  1456. var error = value.error[i] || 0;
  1457. var text = (0 === error)
  1458. ? value.value[i] + Magnitudes[i].units
  1459. : MagnitudeErrors[error];
  1460. inputElem.val(text);
  1461. if (value.info !== undefined) {
  1462. var info = value.info[i] || 0;
  1463. infoElem.toggle(info != 0);
  1464. infoElem.text(info);
  1465. }
  1466. }
  1467. return;
  1468. }
  1469. if ("pzemVisible" === key) {
  1470. $("input[name='snsSave']").prop("disabled", true);
  1471. $("input[name='snsSave']")
  1472. .parent().parent().find(".hint")
  1473. .text("PZEM004 module saves the energy data on it's own")
  1474. return;
  1475. }
  1476. //endRemoveIf(!sensor)
  1477. // ---------------------------------------------------------------------
  1478. // WiFi
  1479. // ---------------------------------------------------------------------
  1480. if ("wifi" === key) {
  1481. maxNetworks = parseInt(value["max"], 10);
  1482. value["networks"].forEach(function(network) {
  1483. addNetwork(fromSchema(network, value.schema));
  1484. });
  1485. return;
  1486. }
  1487. if ("scanResult" === key) {
  1488. $("div.scan.loading").hide();
  1489. $("#button-wifi-scan").attr("disabled", false);
  1490. $("#scanResult").show();
  1491. }
  1492. // -----------------------------------------------------------------------------
  1493. // Relays scheduler
  1494. // -----------------------------------------------------------------------------
  1495. if ("schConfig" === key) {
  1496. $("#schedules")
  1497. .attr("data-settings-max", value.max);
  1498. let schema = value.schema;
  1499. value["schedules"].forEach((entries, id) => {
  1500. let cfg = fromSchema(entries, id);
  1501. addSchedule(cfg, value);
  1502. });
  1503. return;
  1504. }
  1505. // ---------------------------------------------------------------------
  1506. // Relays
  1507. // ---------------------------------------------------------------------
  1508. if ("relayConfig" === key) {
  1509. if ($("#relays > div").length) {
  1510. return;
  1511. }
  1512. if ($("#relayConfig > legend").length) {
  1513. return;
  1514. }
  1515. let schema = value.schema;
  1516. value["relays"].forEach((entries, id) => {
  1517. let cfg = fromSchema(entries, schema);
  1518. var name = cfg["relayName"];
  1519. if (!cfg.relayName.length) {
  1520. cfg.relayName = "Switch #" + id;
  1521. }
  1522. initRelay(id, cfg, value);
  1523. initRelayConfig(id, cfg, value);
  1524. });
  1525. return;
  1526. }
  1527. if ("relayState" === key) {
  1528. updateRelays(value);
  1529. return;
  1530. }
  1531. // ---------------------------------------------------------------------
  1532. // Curtain(s)
  1533. // ---------------------------------------------------------------------
  1534. //removeIf(!curtain)
  1535. // Relay configuration
  1536. if ("curtainConfig" === key) {
  1537. initCurtainConfig(value);
  1538. return;
  1539. }
  1540. //endRemoveIf(!curtain)
  1541. // ---------------------------------------------------------------------
  1542. // LEDs
  1543. // ---------------------------------------------------------------------
  1544. if ("led" === key) {
  1545. if($("#ledConfig > div").length > 0) return;
  1546. var schema = value["schema"];
  1547. value["list"].forEach(function(led_data, index) {
  1548. var line = loadConfigTemplate("ledConfigTemplate");
  1549. $("span.id", line).html(index);
  1550. $("select", line).attr("data", index);
  1551. $("input", line).attr("data", index);
  1552. var led = fromSchema(led_data, schema);
  1553. $("select[name='ledGPIO']", line).val(led.GPIO);
  1554. // XXX: checkbox implementation depends on unique id
  1555. // $("input[name='ledInv']", line).val(led.Inv);
  1556. $("select[name='ledMode']", line).val(led.Mode);
  1557. $("input[name='ledRelay']", line).val(led.Relay);
  1558. setOriginalsFromValues($("input,select", line));
  1559. line.appendTo("#ledConfig");
  1560. });
  1561. return;
  1562. }
  1563. // ---------------------------------------------------------------------
  1564. // Domoticz
  1565. // ---------------------------------------------------------------------
  1566. // Domoticz - Relays
  1567. if ("dczRelays" === key) {
  1568. createRelayList(value, "dczRelays", "dczRelayTemplate");
  1569. return;
  1570. }
  1571. // Domoticz - Magnitudes
  1572. //removeIf(!sensor)
  1573. if ("dczMagnitudes" === key) {
  1574. createMagnitudeList(value, "dczMagnitudes", "dczMagnitudeTemplate");
  1575. return;
  1576. }
  1577. //endRemoveIf(!sensor)
  1578. // ---------------------------------------------------------------------
  1579. // Thingspeak
  1580. // ---------------------------------------------------------------------
  1581. // Thingspeak - Relays
  1582. if ("tspkRelays" === key) {
  1583. createRelayList(value, "tspkRelays", "tspkRelayTemplate");
  1584. return;
  1585. }
  1586. // Thingspeak - Magnitudes
  1587. //removeIf(!sensor)
  1588. if ("tspkMagnitudes" === key) {
  1589. createMagnitudeList(value, "tspkMagnitudes", "tspkMagnitudeTemplate");
  1590. return;
  1591. }
  1592. //endRemoveIf(!sensor)
  1593. // ---------------------------------------------------------------------
  1594. // HTTP API
  1595. // ---------------------------------------------------------------------
  1596. // Auto generate an APIKey if none defined yet
  1597. if ("apiVisible" === key) {
  1598. if (data.apiKey === undefined || data.apiKey === "") {
  1599. generateAPIKey();
  1600. }
  1601. }
  1602. // ---------------------------------------------------------------------
  1603. // General
  1604. // ---------------------------------------------------------------------
  1605. if ("saved" === key) {
  1606. configurationSaved = value;
  1607. return;
  1608. }
  1609. if ("message" === key) {
  1610. window.alert(value);
  1611. return;
  1612. }
  1613. // Web log
  1614. if ("weblog" === key) {
  1615. send("{}");
  1616. var msg = value["msg"];
  1617. var pre = value["pre"];
  1618. for (var i=0; i < msg.length; ++i) {
  1619. if (pre[i]) {
  1620. $("#weblog").append(new Text(pre[i]));
  1621. }
  1622. $("#weblog").append(new Text(msg[i]));
  1623. }
  1624. followScroll("weblog");
  1625. return;
  1626. }
  1627. // Enable options
  1628. var position = key.indexOf("Visible");
  1629. if (position > 0 && position === key.length - 7) {
  1630. var module = key.slice(0,-7);
  1631. moduleVisible(module);
  1632. return;
  1633. }
  1634. if ("deviceip" === key) {
  1635. var a_href = $("span[name='" + key + "']").parent();
  1636. a_href.attr("href", "//" + value);
  1637. a_href.next().attr("href", "telnet://" + value);
  1638. }
  1639. if ("now" === key) {
  1640. now = parseInt(value, 10);
  1641. return;
  1642. }
  1643. if ("free_size" === key) {
  1644. free_size = parseInt(value, 10);
  1645. }
  1646. // Pre-process
  1647. if ("mqttStatus" === key) {
  1648. value = value ? "CONNECTED" : "NOT CONNECTED";
  1649. }
  1650. if ("ntpStatus" === key) {
  1651. value = value ? "SYNC'D" : "NOT SYNC'D";
  1652. }
  1653. if ("uptime" === key) {
  1654. ago = 0;
  1655. var uptime = parseInt(value, 10);
  1656. var seconds = uptime % 60; uptime = parseInt(uptime / 60, 10);
  1657. var minutes = uptime % 60; uptime = parseInt(uptime / 60, 10);
  1658. var hours = uptime % 24; uptime = parseInt(uptime / 24, 10);
  1659. var days = uptime;
  1660. value = days + "d " + zeroPad(hours, 2) + "h " + zeroPad(minutes, 2) + "m " + zeroPad(seconds, 2) + "s";
  1661. }
  1662. //removeIf(!thermostat)
  1663. if ("tmpUnits" == key) {
  1664. $("span.tmpUnit").html(data[key] == 3 ? "ºF" : "ºC");
  1665. }
  1666. //endRemoveIf(!thermostat)
  1667. // ---------------------------------------------------------------------
  1668. // Matching
  1669. // ---------------------------------------------------------------------
  1670. var elems = [];
  1671. var pre;
  1672. var post;
  1673. // Look for INPUTs
  1674. var input = $("input[name='" + key + "']");
  1675. if (input.length > 0) {
  1676. if (input.attr("type") === "checkbox") {
  1677. input.prop("checked", value);
  1678. } else if (input.attr("type") === "radio") {
  1679. input.val([value]);
  1680. } else {
  1681. pre = input.attr("pre") || "";
  1682. post = input.attr("post") || "";
  1683. input.val(pre + value + post);
  1684. }
  1685. elems.push(input);
  1686. }
  1687. // Look for SPANs
  1688. var span = $("span[name='" + key + "']");
  1689. if (span.length > 0) {
  1690. if (Array.isArray(value)) {
  1691. value.forEach(function(elem) {
  1692. span.append(elem);
  1693. span.append('</br>');
  1694. elems.push(span);
  1695. });
  1696. } else {
  1697. pre = span.attr("pre") || "";
  1698. post = span.attr("post") || "";
  1699. span.html(pre + value + post);
  1700. elems.push(span);
  1701. }
  1702. }
  1703. // Look for SELECTs
  1704. var select = $("select[name='" + key + "']");
  1705. if (select.length > 0) {
  1706. if (select.attr("multiple") !== undefined) {
  1707. select.val(bitsetToValues(value));
  1708. } else {
  1709. select.val(value);
  1710. }
  1711. elems.push(select);
  1712. }
  1713. setOriginalsFromValues($(elems));
  1714. });
  1715. }
  1716. function hasChanged() {
  1717. var newValue, originalValue;
  1718. if ($(this).attr("type") === "checkbox") {
  1719. newValue = $(this).prop("checked");
  1720. originalValue = ($(this).attr("original") === "true");
  1721. } else {
  1722. newValue = $(this).val();
  1723. originalValue = $(this).attr("original");
  1724. }
  1725. if ($(this).attr("multiple") !== undefined) {
  1726. newValue = newValue.join(",");
  1727. }
  1728. var hasChanged = ("true" === $(this).attr("hasChanged"));
  1729. var action = $(this).attr("action");
  1730. if (typeof originalValue === "undefined") { return; }
  1731. if ("none" === action) { return; }
  1732. if (newValue !== originalValue) {
  1733. if (!hasChanged) {
  1734. ++numChanged;
  1735. if ("reconnect" === action) { ++numReconnect; }
  1736. if ("reboot" === action) { ++numReboot; }
  1737. if ("reload" === action) { ++numReload; }
  1738. }
  1739. $(this).attr("hasChanged", true);
  1740. } else {
  1741. if (hasChanged) {
  1742. --numChanged;
  1743. if ("reconnect" === action) { --numReconnect; }
  1744. if ("reboot" === action) { --numReboot; }
  1745. if ("reload" === action) { --numReload; }
  1746. }
  1747. $(this).attr("hasChanged", false);
  1748. }
  1749. }
  1750. // -----------------------------------------------------------------------------
  1751. // Init & connect
  1752. // -----------------------------------------------------------------------------
  1753. function initUrls(root) {
  1754. var paths = ["ws", "upgrade", "config", "auth"];
  1755. urls["root"] = root;
  1756. paths.forEach(function(path) {
  1757. urls[path] = new URL(path, root);
  1758. urls[path].protocol = root.protocol;
  1759. });
  1760. if (root.protocol == "https:") {
  1761. urls.ws.protocol = "wss:";
  1762. } else {
  1763. urls.ws.protocol = "ws:";
  1764. }
  1765. }
  1766. function connectToURL(url) {
  1767. initUrls(url);
  1768. fetch(urls.auth.href, {
  1769. 'method': 'GET',
  1770. 'cors': true,
  1771. 'credentials': 'same-origin'
  1772. }).then(function(response) {
  1773. // Nothing to do, reload page and retry
  1774. if (response.status != 200) {
  1775. doReload(5000);
  1776. return;
  1777. }
  1778. // update websock object
  1779. if (websock) { websock.close(); }
  1780. websock = new WebSocket(urls.ws.href);
  1781. websock.onmessage = function(evt) {
  1782. var data = {};
  1783. try {
  1784. data = JSON.parse(evt.data
  1785. .replace(/\n/g, "\\n")
  1786. .replace(/\r/g, "\\r")
  1787. .replace(/\t/g, "\\t"));
  1788. } catch (e) {
  1789. console.log(e);
  1790. }
  1791. processData(data);
  1792. };
  1793. websock.onclose = function(evt) {
  1794. clearInterval(ws_pingpong);
  1795. if (window.confirm("Connection lost with the device, click OK to refresh the page")) {
  1796. $("#layout").toggle(false);
  1797. window.location.reload();
  1798. }
  1799. }
  1800. websock.onopen = function(evt) {
  1801. ws_pingpong = setInterval(function() { sendAction("ping", {}); }, 5000);
  1802. }
  1803. }).catch(function(error) {
  1804. console.log(error);
  1805. doReload(5000);
  1806. });
  1807. }
  1808. function connect(host) {
  1809. if (!host.startsWith("http:") && !host.startsWith("https:")) {
  1810. host = "http://" + host;
  1811. }
  1812. connectToURL(new URL(host));
  1813. }
  1814. function connectToCurrentURL() {
  1815. connectToURL(new URL(window.location));
  1816. }
  1817. $(function() {
  1818. // most of the time, we want this unconditionally for all <a href="..."></a>
  1819. $("a.external")
  1820. .attr("target", "_blank")
  1821. .attr("rel", "noopener")
  1822. .attr("tabindex", "-1");
  1823. createCheckboxes();
  1824. setInterval(function() { keepTime(); }, 1000);
  1825. $(".password-reveal").on("click", toggleVisiblePassword);
  1826. $("#menuLink").on("click", toggleMenu);
  1827. $(".pure-menu-link").on("click", showPanel);
  1828. $("progress").attr({ value: 0, max: 100 });
  1829. $("#button-wifi-scan").on("click", doScan);
  1830. $(".button-update").on("click", doUpdate);
  1831. $(".button-update-password").on("click", doUpdatePassword);
  1832. $(".button-generate-password").on("click", doGeneratePassword);
  1833. $(".button-reboot").on("click", doReboot);
  1834. $(".button-reconnect").on("click", doReconnect);
  1835. $(".button-dbgcmd").on("click", doDebugCommand);
  1836. $("input[name='dbgcmd']").enterKey(doDebugCommand);
  1837. $(".button-dbg-clear").on("click", doDebugClear);
  1838. $(".button-settings-backup").on("click", doBackup);
  1839. $(".button-settings-restore").on("click", doRestore);
  1840. $(".button-settings-factory").on("click", doFactoryReset);
  1841. $("#uploader").on("change", onFileUpload);
  1842. $(".button-upgrade").on("click", doUpgrade);
  1843. //removeIf(!garland)
  1844. $(".checkbox-garland-enable").on("change", function() {
  1845. sendAction("garland_switch", {status: $(this).prop("checked") ? 1 : 0});
  1846. });
  1847. $(".slider-garland-brightness").on("change", function() {
  1848. sendAction("garland_set_brightness", {brightness: $(this)[0].value});
  1849. });
  1850. $(".slider-garland-speed").on("change", function() {
  1851. sendAction("garland_set_speed", {speed: $(this)[0].value});
  1852. });
  1853. $(".button-garland-set-default").on("click", function() {
  1854. sendAction("garland_set_default", {});
  1855. });
  1856. //endRemoveIf(!garland)
  1857. //removeIf(!thermostat)
  1858. $(".button-thermostat-reset-counters").on('click', doResetThermostatCounters);
  1859. //endRemoveIf(!thermostat)
  1860. $(".button-apikey").on("click", generateAPIKey);
  1861. $(".button-upgrade-browse").on("click", function() {
  1862. $("input[name='upgrade']")[0].click();
  1863. return false;
  1864. });
  1865. $("input[name='upgrade']").change(function (){
  1866. var file = this.files[0];
  1867. $("input[name='filename']").val(file.name);
  1868. });
  1869. $(".button-add-network").on("click", function() {
  1870. $(".more", addNetwork()).toggle();
  1871. });
  1872. $(".button-add-switch-schedule").on("click", function() {
  1873. addSchedule({schType: 1, schSwitch: -1});
  1874. });
  1875. //removeIf(!light)
  1876. $(".button-add-light-schedule").on("click", function() {
  1877. addSchedule({schType: 2, schSwitch: -1});
  1878. });
  1879. //endRemoveIf(!light)
  1880. //removeIf(!curtain)
  1881. $(".button-add-curtain-schedule").on("click", function() {
  1882. addSchedule({schType: 3, schSwitch: -1});
  1883. });
  1884. //endRemoveIf(!curtain)
  1885. $(".button-add-rpnrule").on('click', addRPNRule);
  1886. $(".button-add-rpntopic").on('click', addRPNTopic);
  1887. $(".button-del-parent").on('click', delParent);
  1888. //removeIf(!rfm69)
  1889. $(".button-add-mapping").on('click', addMapping);
  1890. $(".button-clear-counts").on('click', doClearCounts);
  1891. $(".button-clear-messages").on('click', doClearMessages);
  1892. $(".button-clear-filters").on('click', doClearFilters);
  1893. $('#packets tbody').on('mousedown', 'td', doFilter);
  1894. packets = $('#packets').DataTable({
  1895. "paging": false
  1896. });
  1897. for (var i = 0; i < packets.columns()[0].length; i++) {
  1898. filters[i] = false;
  1899. }
  1900. //endRemoveIf(!rfm69)
  1901. $(".gpio-select").each(function(_, elem) {
  1902. initSelectGPIO(elem)
  1903. });
  1904. $(document).on("change", "input", hasChanged);
  1905. $(document).on("change", "select", hasChanged);
  1906. $("textarea").on("dblclick", function() { this.select(); });
  1907. resetOriginals();
  1908. $(".settings-group").each(function() {
  1909. groupSettingsObserver.observe(this, {childList: true});
  1910. });
  1911. // don't autoconnect when opening from filesystem
  1912. if (window.location.protocol === "file:") {
  1913. processData({"webMode": 0});
  1914. return;
  1915. }
  1916. // Check host param in query string
  1917. var search = new URLSearchParams(window.location.search),
  1918. host = search.get("host");
  1919. if (host !== null) {
  1920. connect(host);
  1921. } else {
  1922. connectToCurrentURL();
  1923. }
  1924. });