script.js 35 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331
  1. $(function() {
  2. $(document).on('change', ':file', function() {
  3. var input = $(this),
  4. label = input.val().replace(/\\/g, '/').replace(/.*\//, '');
  5. input.trigger('fileselect', [label]);
  6. });
  7. $(document).ready( function() {
  8. $(':file').on('fileselect', function(event, label) {
  9. var input = $(this).parents('.input-group').find(':text'),
  10. log = label;
  11. if( input.length ) {
  12. input.val(log);
  13. }
  14. });
  15. });
  16. });
  17. var UNIT_PARAMS = {
  18. minMireds: 153,
  19. maxMireds: 370,
  20. maxBrightness: 255
  21. };
  22. var UI_TABS = [ {
  23. tag: "tab-wifi",
  24. friendly: "Wifi",
  25. }, {
  26. tag: "tab-setup",
  27. friendly: "Setup",
  28. }, {
  29. tag: "tab-led",
  30. friendly: "LED",
  31. }, {
  32. tag: "tab-radio",
  33. friendly: "Radio",
  34. }, {
  35. tag: "tab-mqtt",
  36. friendly: "MQTT"
  37. }
  38. ];
  39. var UI_FIELDS = [ {
  40. tag: "admin_username",
  41. friendly: "Admin username",
  42. help: "Username for logging into this webpage",
  43. type: "string",
  44. tab: "tab-wifi"
  45. }, {
  46. tag: "admin_password",
  47. friendly: "Password",
  48. help: "Password for logging into this webpage",
  49. type: "string",
  50. tab: "tab-wifi"
  51. }, {
  52. tag: "hostname",
  53. friendly: "Hostname",
  54. help: "Self-reported hostname to send along with DCHP request",
  55. type: "string",
  56. tab: "tab-wifi"
  57. }, {
  58. tag: "wifi_static_ip",
  59. friendly: "Static IP Address",
  60. help: "Static IP address (leave blank to use DHCP)",
  61. type: "string",
  62. tab: "tab-wifi"
  63. }, {
  64. tag: "wifi_static_ip_netmask",
  65. friendly: "Static IP Netmask",
  66. help: "Netmask to use with Static IP",
  67. type: "string",
  68. tab: "tab-wifi"
  69. }, {
  70. tag: "wifi_static_ip_gateway",
  71. friendly: "Static IP Gateway Address",
  72. help: "IP address to use as gateway when a Static IP is speicifed",
  73. type: "string",
  74. tab: "tab-wifi"
  75. }, {
  76. tag: "wifi_mode",
  77. friendly: "WiFi Mode",
  78. help: "Try using G mode if you're having stability problems",
  79. type: "option_buttons",
  80. options: {
  81. 'b': 'B',
  82. 'g': 'G',
  83. 'n': 'N'
  84. },
  85. tab: "tab-wifi"
  86. }, {
  87. tag: "ce_pin",
  88. friendly: "CE / PKT pin",
  89. help: "Pin on ESP8266 used for 'CE' (for NRF24L01 interface) or 'PKT' (for 'PL1167/LT8900' interface)",
  90. type: "string",
  91. tab: "tab-setup"
  92. }, {
  93. tag: "csn_pin",
  94. friendly: "CSN pin",
  95. help: "Pin on ESP8266 used for 'CSN'",
  96. type: "string",
  97. tab: "tab-setup"
  98. }, {
  99. tag: "reset_pin",
  100. friendly: "RESET pin",
  101. help: "Pin on ESP8266 used for 'RESET'",
  102. type: "string",
  103. tab: "tab-setup"
  104. }, {
  105. tag: "led_pin",
  106. friendly: "LED pin",
  107. help: "Pin to use for LED status display (0=disabled); negative inverses signal (recommend -2 for on-board LED)",
  108. type: "string",
  109. tab: "tab-setup"
  110. }, {
  111. tag: "packet_repeats",
  112. friendly: "Packet repeats",
  113. help: "The number of times to repeat RF packets sent to bulbs",
  114. type: "string",
  115. tab: "tab-radio"
  116. }, {
  117. tag: "packet_repeats_per_loop",
  118. friendly: "Packet repeats per loop",
  119. help: "Number of repeats to send in a single go. Higher values mean more throughput, but less multitasking.",
  120. type: "string",
  121. tab: "tab-radio"
  122. }, {
  123. tag: "http_repeat_factor",
  124. friendly: "HTTP repeat factor",
  125. help: "Multiplicative factor on packet_repeats for requests initiated by the HTTP API. UDP API typically receives " +
  126. "duplicate packets, so more repeats should be used for HTTP",
  127. type: "string",
  128. tab: "tab-wifi"
  129. }, {
  130. tag: "auto_restart_period",
  131. friendly: "Auto-restart period",
  132. help: "Automatically restart the device every number of minutes specified. Use 0 for disabled",
  133. type: "string",
  134. tab: "tab-setup"
  135. }, {
  136. tag: "discovery_port",
  137. friendly: "Discovery port",
  138. help: "UDP port to listen for discovery packets on. Defaults to the same port used by MiLight devices, 48899. Use 0 to disable",
  139. type: "string",
  140. tab: "tab-wifi"
  141. }, {
  142. tag: "mqtt_server",
  143. friendly: "MQTT server",
  144. help: "Domain or IP address of MQTT broker. Optionally specify a port with (example) myMQTTbroker.com:1884",
  145. type: "string",
  146. tab: "tab-mqtt"
  147. }, {
  148. tag: "mqtt_topic_pattern",
  149. friendly: "MQTT topic pattern",
  150. help: "Pattern for MQTT topics to listen on. Example: lights/:device_id/:device_type/:group_id. See README for further details",
  151. type: "string",
  152. tab: "tab-mqtt"
  153. }, {
  154. tag: "mqtt_update_topic_pattern",
  155. friendly: "MQTT update topic pattern",
  156. help: "Pattern to publish MQTT updates. Packets that are received from other devices, and packets that are sent from this device will " +
  157. "result in updates being sent",
  158. type: "string",
  159. tab: "tab-mqtt"
  160. }, {
  161. tag: "mqtt_state_topic_pattern",
  162. friendly: "MQTT state topic pattern",
  163. help: "Pattern for MQTT topic to publish state to. When a group changes state, the full known state of the group will be published to this topic pattern",
  164. type: "string",
  165. tab: "tab-mqtt"
  166. }, {
  167. tag: "mqtt_username",
  168. friendly: "MQTT user name",
  169. help: "User name to log in to MQTT server",
  170. type: "string",
  171. tab: "tab-mqtt"
  172. }, {
  173. tag: "mqtt_password",
  174. friendly: "MQTT password",
  175. help: "Password to log into MQTT server",
  176. type: "string",
  177. tab: "tab-mqtt"
  178. }, {
  179. tag: "mqtt_client_status_topic",
  180. friendly: "MQTT Client Status Topic",
  181. help: "Connection status messages will be published to this topic. This includes LWT and birth. See README for further detail.",
  182. type: "string",
  183. tab: "tab-mqtt"
  184. }, {
  185. tag: "simple_mqtt_client_status",
  186. friendly: "Client Status Messages Mode",
  187. help: "In simple mode, only the strings 'connected' and 'disconnected' will be published. In detailed mode, data about the version, IP address, etc. will be included.",
  188. type: "option_buttons",
  189. options: {
  190. true: "Simple",
  191. false: "Detailed"
  192. },
  193. tab: "tab-mqtt"
  194. }, {
  195. tag: "home_assistant_discovery_prefix",
  196. friendly: "HomeAssistant MQTT Discovery Prefix",
  197. help: "If set, will enable integration with HomeAssistant's MQTT discovery functionality to allow saved aliases to be detected automatically",
  198. type: "string",
  199. tab: "tab-mqtt"
  200. }, {
  201. tag: "radio_interface_type",
  202. friendly: "Radio interface type",
  203. help: "2.4 GHz radio model. Only change this if you know you're not using an NRF24L01!",
  204. type: "option_buttons",
  205. options: {
  206. 'nRF24': 'nRF24',
  207. 'LT8900': 'PL1167/LT8900'
  208. },
  209. tab: "tab-radio"
  210. }, {
  211. tag: "rf24_power_level",
  212. friendly: "nRF24 Power Level",
  213. help: "Power level for nRF24L01",
  214. type: "option_buttons",
  215. options: {
  216. 'MIN': 'Min',
  217. 'LOW': 'Low',
  218. 'HIGH': 'High',
  219. 'MAX': 'Max'
  220. },
  221. tab: "tab-radio"
  222. }, {
  223. tag: "rf24_listen_channel",
  224. friendly: "nRF24 Listen Channel",
  225. help: "Which channels to listen for messages on the nRF24",
  226. type: "option_buttons",
  227. options: {
  228. 'LOW': 'Min',
  229. 'MID': 'Mid',
  230. 'HIGH': 'High'
  231. },
  232. tab: "tab-radio"
  233. }, {
  234. tag: "rf24_channels",
  235. friendly: "nRF24 Send Channels",
  236. help: "Which channels to send messages on for the nRF24. Using fewer channels speeds up sends.",
  237. type: "option_buttons",
  238. settings: {
  239. multiple: true,
  240. },
  241. options: {
  242. 'LOW': 'Min',
  243. 'MID': 'Mid',
  244. 'HIGH': 'High'
  245. },
  246. tab: "tab-radio"
  247. }, {
  248. tag: "listen_repeats",
  249. friendly: "Listen repeats",
  250. help: "Increasing this increases the amount of time spent listening for " +
  251. "packets. Set to 0 to disable listening. Default is 3.",
  252. type: "string",
  253. tab: "tab-wifi"
  254. }, {
  255. tag: "state_flush_interval",
  256. friendly: "State flush interval",
  257. help: "Minimum number of milliseconds between flushing state to flash. " +
  258. "Set to 0 to disable delay and immediately persist state to flash",
  259. type: "string",
  260. tab: "tab-setup"
  261. }, {
  262. tag: "mqtt_state_rate_limit",
  263. friendly: "MQTT state rate limit",
  264. help: "Minimum number of milliseconds between MQTT updates of bulb state (defaults to 500)",
  265. type: "string",
  266. tab: "tab-mqtt"
  267. }, {
  268. tag: "packet_repeat_throttle_threshold",
  269. friendly: "Packet repeat throttle threshold",
  270. help: "Controls how packet repeats are throttled. Packets sent " +
  271. "with less time between them than this value (in milliseconds) will cause " +
  272. "packet repeats to be throttled down. More than this value will unthrottle " +
  273. "up. Defaults to 200ms",
  274. type: "string",
  275. tab: "tab-radio"
  276. }, {
  277. tag: "packet_repeat_throttle_sensitivity",
  278. friendly: "Packet repeat throttle sensitivity",
  279. help: "Controls how packet repeats are throttled. " +
  280. "Higher values cause packets to be throttled up and down faster " +
  281. "(defaults to 0, maximum value 1000, 0 disables)",
  282. type: "string",
  283. tab: "tab-radio"
  284. }, {
  285. tag: "packet_repeat_minimum",
  286. friendly: "Packet repeat minimum",
  287. help: "Controls how far throttling can decrease the number " +
  288. "of repeated packets (defaults to 3)",
  289. type: "string",
  290. tab: "tab-radio"
  291. }, {
  292. tag: "group_state_fields",
  293. friendly: "Group state fields",
  294. help: "Selects which fields should be included in MQTT state updates and REST responses for bulb state",
  295. type: "group_state_fields",
  296. tab: "tab-mqtt"
  297. }, {
  298. tag: "enable_automatic_mode_switching",
  299. friendly: "Enable automatic mode switching",
  300. help: "For RGBWW bulbs (using RGB+CCT or FUT089), enables automatic switching between modes in order to affect changes to " +
  301. "temperature and saturation when otherwise it would not work",
  302. type: "option_buttons",
  303. options: {
  304. true: 'Enable',
  305. false: 'Disable'
  306. },
  307. tab: "tab-radio"
  308. }, {
  309. tag: "led_mode_wifi_config",
  310. friendly: "LED mode during wifi config",
  311. help: "LED mode when the device is in Access Point mode waiting to configure Wifi",
  312. type: "led_mode",
  313. tab: "tab-led"
  314. }, {
  315. tag: "led_mode_wifi_failed",
  316. friendly: "LED mode when wifi failed to connect",
  317. help: "LED mode when the device has failed to connect to the wifi network",
  318. type: "led_mode",
  319. tab: "tab-led"
  320. }, {
  321. tag: "led_mode_operating",
  322. friendly: "LED mode when operating",
  323. help: "LED mode when the device is in successfully running",
  324. type: "led_mode",
  325. tab: "tab-led"
  326. }, {
  327. tag: "led_mode_packet",
  328. friendly: "LED mode on packets",
  329. help: "LED mode when the device is sending or receiving packets",
  330. type: "led_mode",
  331. tab: "tab-led"
  332. }, {
  333. tag: "led_mode_packet_count",
  334. friendly: "Flash count on packets",
  335. help: "Number of times the LED will flash when packets are changing",
  336. type: "string",
  337. tab: "tab-led"
  338. }
  339. ];
  340. // TODO: sync this with GroupStateField.h
  341. var GROUP_STATE_KEYS = [
  342. "state",
  343. "status",
  344. "brightness",
  345. "level",
  346. "hue",
  347. "saturation",
  348. "color",
  349. "mode",
  350. "kelvin",
  351. "color_temp",
  352. "bulb_mode",
  353. "computed_color",
  354. "effect",
  355. "device_id",
  356. "group_id",
  357. "device_type",
  358. "oh_color"
  359. ];
  360. var LED_MODES = [
  361. "Off",
  362. "Slow toggle",
  363. "Fast toggle",
  364. "Slow blip",
  365. "Fast blip",
  366. "Flicker",
  367. "On"
  368. ];
  369. var UDP_PROTOCOL_VERSIONS = [ 5, 6 ];
  370. var DEFAULT_UDP_PROTOCL_VERSION = 5;
  371. var selectize;
  372. var aliasesSelectize;
  373. var sniffing = false;
  374. var loadingSettings = false;
  375. // When true, will not attempt to load group parameters
  376. var updatingGroupId = false;
  377. // When true, will not attempt to update group parameters
  378. var updatingAlias = false;
  379. // don't attempt websocket if we are debugging locally
  380. if (location.hostname != "") {
  381. var webSocket = new WebSocket("ws://" + location.hostname + ":81");
  382. webSocket.onmessage = function(e) {
  383. if (sniffing) {
  384. var message = e.data;
  385. $('#sniffed-traffic').prepend('<pre>' + message + '</pre>');
  386. }
  387. }
  388. }
  389. var toHex = function(v) {
  390. return "0x" + (v).toString(16).toUpperCase();
  391. }
  392. var updateGroupId = function(params) {
  393. updatingGroupId = true;
  394. selectize.setValue(params.deviceId);
  395. setGroupId(params.groupId);
  396. setMode(params.deviceType);
  397. updatingGroupId = false;
  398. refreshGroupState();
  399. }
  400. var setGroupId = function(value) {
  401. $('#groupId input[data-value="' + value + '"]').click();
  402. }
  403. var setMode = function(value) {
  404. $('#mode li[data-value="' + value + '"]').click();
  405. }
  406. var getCurrentDeviceId = function() {
  407. // return $('#deviceId option:selected').val();
  408. return parseInt(selectize.getValue());
  409. };
  410. var getCurrentGroupId = function() {
  411. return $('#groupId .active input').data('value');
  412. }
  413. var findAndSelectAlias = function() {
  414. if (!updatingGroupId) {
  415. var params = {
  416. deviceType: getCurrentMode(),
  417. deviceId: getCurrentDeviceId(),
  418. groupId: getCurrentGroupId()
  419. };
  420. var foundAlias = Object.entries(aliasesSelectize.options).filter(function(x) {
  421. return _.isEqual(x[1].savedGroupParams, params);
  422. });
  423. updatingAlias = true;
  424. if (foundAlias.length > 0) {
  425. aliasesSelectize.setValue(foundAlias[0]);
  426. } else {
  427. aliasesSelectize.clear();
  428. }
  429. updatingAlias = false;
  430. }
  431. }
  432. var activeUrl = function() {
  433. var deviceId = getCurrentDeviceId()
  434. , groupId = getCurrentGroupId()
  435. , mode = getCurrentMode();
  436. if (deviceId == "") {
  437. throw "Must enter device ID";
  438. }
  439. if (! $('#group-option').data('for').split(',').includes(mode)) {
  440. groupId = 0;
  441. }
  442. if (typeof groupId === "undefined") {
  443. throw "Must enter group ID";
  444. }
  445. return "/gateways/" + deviceId + "/" + mode + "/" + groupId;
  446. }
  447. var refreshGroupState = function() {
  448. if (! updatingGroupId) {
  449. $.getJSON(
  450. activeUrl(),
  451. function(e) {
  452. handleStateUpdate(e);
  453. }
  454. );
  455. }
  456. }
  457. var getCurrentMode = function() {
  458. return $('#mode li.active').data('value');
  459. };
  460. var updateGroup = _.throttle(
  461. function(params) {
  462. try {
  463. $.ajax({
  464. url: activeUrl() + "?blockOnQueue=true",
  465. method: 'PUT',
  466. data: JSON.stringify(params),
  467. contentType: 'application/json',
  468. success: function(e) {
  469. handleStateUpdate(e);
  470. }
  471. });
  472. } catch (e) {
  473. alert(e);
  474. }
  475. },
  476. 1000
  477. );
  478. var sendCommand = _.throttle(
  479. function(params) {
  480. $.ajax(
  481. '/system',
  482. {
  483. method: 'POST',
  484. data: JSON.stringify(params),
  485. contentType: 'application/json'
  486. }
  487. );
  488. },
  489. 1000
  490. )
  491. var gatewayServerRow = function(deviceId, port, version) {
  492. var elmt = '<tr>';
  493. elmt += '<td>';
  494. elmt += '<input name="deviceIds[]" class="form-control" value="' + deviceId + '"/>';
  495. elmt += '</td>';
  496. elmt += '<td>'
  497. elmt += '<input name="ports[]" class="form-control" value="' + port + '"/>';;
  498. elmt += '</td>';
  499. elmt += '<td>';
  500. elmt += '<div class="btn-group" data-toggle="buttons">';
  501. for (var i = 0; i < UDP_PROTOCOL_VERSIONS.length; i++) {
  502. var val = UDP_PROTOCOL_VERSIONS[i]
  503. , selected = (version == val || (val == DEFAULT_UDP_PROTOCL_VERSION && !UDP_PROTOCOL_VERSIONS.includes(version)));
  504. elmt += '<label class="btn btn-secondary' + (selected ? ' active' : '') + '">';
  505. elmt += '<input type="radio" name="versions[]" autocomplete="off" data-value="' + val + '" '
  506. + (selected ? 'checked' : '') +'> ' + val;
  507. elmt += '</label>';
  508. }
  509. elmt += '</div></td>';
  510. elmt += '<td>';
  511. elmt += '<button class="btn btn-danger remove-gateway-server">';
  512. elmt += '<i class="glyphicon glyphicon-remove"></i>';
  513. elmt += '</button>';
  514. elmt += '</td>';
  515. elmt += '</tr>';
  516. return elmt;
  517. }
  518. var loadSettings = function() {
  519. $('select.select-init').selectpicker();
  520. if (location.hostname == "") {
  521. // if deugging locally, don't try get settings
  522. return;
  523. }
  524. $.getJSON('/settings', function(val) {
  525. loadingSettings = true;
  526. Object.keys(val).forEach(function(k) {
  527. var field = $('#settings input[name="' + k + '"]');
  528. var selectVal = function(selectVal) {
  529. field.filter('[value="' + selectVal + '"]').click();
  530. };
  531. if (field.length > 0) {
  532. if (field.attr('type') === 'radio' || field.attr('type') === 'checkbox') {
  533. if (Array.isArray(val[k])) {
  534. val[k].forEach(function(x) {
  535. selectVal(x);
  536. });
  537. } else {
  538. selectVal(val[k]);
  539. }
  540. } else {
  541. field.val(val[k]);
  542. }
  543. }
  544. });
  545. if (val.hostname) {
  546. var title = "MiLight Hub: " + val.hostname;
  547. document.title = title;
  548. $('.navbar-brand').html(title);
  549. }
  550. if (val.group_id_aliases) {
  551. aliasesSelectize.clearOptions();
  552. Object.entries(val.group_id_aliases).forEach(function(entry) {
  553. var label = entry[0]
  554. , groupParams = entry[1]
  555. , savedParams = {
  556. deviceType: groupParams[0],
  557. deviceId: groupParams[1],
  558. groupId: groupParams[2]
  559. }
  560. ;
  561. aliasesSelectize.addOption({
  562. text: label,
  563. value: label,
  564. savedGroupParams: savedParams
  565. });
  566. aliasesSelectize.refreshOptions(false);
  567. });
  568. }
  569. if (val.device_ids) {
  570. selectize.clearOptions();
  571. val.device_ids.forEach(function(v) {
  572. selectize.addOption({text: toHex(v), value: v});
  573. });
  574. selectize.refreshOptions(false);
  575. }
  576. if (val.group_state_fields) {
  577. var elmt = $('select[name="group_state_fields"]');
  578. elmt.selectpicker('val', val.group_state_fields);
  579. }
  580. if (val.led_mode_wifi_config) {
  581. var elmt = $('select[name="led_mode_wifi_config"]');
  582. elmt.selectpicker('val', val.led_mode_wifi_config);
  583. }
  584. if (val.led_mode_wifi_failed) {
  585. var elmt = $('select[name="led_mode_wifi_failed"]');
  586. elmt.selectpicker('val', val.led_mode_wifi_failed);
  587. }
  588. if (val.led_mode_operating) {
  589. var elmt = $('select[name="led_mode_operating"]');
  590. elmt.selectpicker('val', val.led_mode_operating);
  591. }
  592. if (val.led_mode_packet) {
  593. var elmt = $('select[name="led_mode_packet"]');
  594. elmt.selectpicker('val', val.led_mode_packet);
  595. }
  596. var gatewayForm = $('#gateway-server-configs').html('');
  597. if (val.gateway_configs) {
  598. val.gateway_configs.forEach(function(v) {
  599. gatewayForm.append(gatewayServerRow(toHex(v[0]), v[1], v[2]));
  600. });
  601. }
  602. loadingSettings = false;
  603. });
  604. };
  605. var saveGatewayConfigs = function() {
  606. var form = $('#tab-udp-gateways')
  607. , errors = false;
  608. $('input', form).removeClass('error');
  609. var deviceIds = $('input[name="deviceIds[]"]', form).map(function(i, v) {
  610. var val = $(v).val();
  611. if (isNaN(val)) {
  612. errors = true;
  613. $(v).addClass('error');
  614. return null;
  615. } else {
  616. return val;
  617. }
  618. });
  619. var ports = $('input[name="ports[]"]', form).map(function(i, v) {
  620. var val = $(v).val();
  621. if (isNaN(val)) {
  622. errors = true;
  623. $(v).addClass('error');
  624. return null;
  625. } else {
  626. return val;
  627. }
  628. });
  629. var versions = $('.active input[name="versions[]"]', form).map(function(i, v) {
  630. return $(v).data('value');
  631. });
  632. if (!errors) {
  633. var data = [];
  634. for (var i = 0; i < deviceIds.length; i++) {
  635. data[i] = [deviceIds[i], ports[i], versions[i]];
  636. }
  637. $.ajax(
  638. '/settings',
  639. {
  640. method: 'put',
  641. contentType: 'application/json',
  642. data: JSON.stringify({gateway_configs: data})
  643. }
  644. )
  645. }
  646. };
  647. var patchSettings = function(patch) {
  648. if (!loadingSettings) {
  649. $.ajax(
  650. "/settings",
  651. {
  652. method: 'put',
  653. contentType: 'application/json',
  654. data: JSON.stringify(patch)
  655. }
  656. );
  657. }
  658. };
  659. var saveDeviceIds = function() {
  660. if (!loadingSettings) {
  661. var deviceIds = _.map(
  662. $('#deviceId')[0].selectize.options,
  663. function(option) {
  664. return option.value;
  665. }
  666. );
  667. patchSettings({device_ids: deviceIds});
  668. }
  669. };
  670. var saveDeviceAliases = function() {
  671. if (!loadingSettings) {
  672. var deviceAliases = Object.entries(aliasesSelectize.options).reduce(
  673. function(aggregate, x) {
  674. var params = x[1].savedGroupParams;
  675. aggregate[x[0]] = [
  676. params.deviceType,
  677. params.deviceId,
  678. params.groupId
  679. ]
  680. return aggregate;
  681. },
  682. {}
  683. );
  684. patchSettings({group_id_aliases: deviceAliases});
  685. }
  686. };
  687. var deleteDeviceId = function() {
  688. selectize.removeOption($(this).data('value'));
  689. selectize.refreshOptions();
  690. saveDeviceIds();
  691. };
  692. var deleteDeviceAlias = function() {
  693. aliasesSelectize.removeOption($(this).data('value'));
  694. aliasesSelectize.refreshOptions();
  695. saveDeviceAliases();
  696. };
  697. var deviceIdError = function(v) {
  698. if (!v) {
  699. $('#device-id-label').removeClass('error');
  700. } else {
  701. $('#device-id-label').addClass('error');
  702. $('#device-id-label .error-info').html(v);
  703. }
  704. };
  705. var updateModeOptions = function() {
  706. var currentMode = getCurrentMode()
  707. , modeLabel = $('#mode li[data-value="' + currentMode + '"] a').html();
  708. $('label', $('#mode').closest('.dropdown')).html(modeLabel);
  709. $('.mode-option').map(function() {
  710. if ($(this).data('for').split(',').includes(currentMode)) {
  711. $(this).show();
  712. } else {
  713. $(this)
  714. // De-select unselectable group
  715. .removeClass('active')
  716. .hide();
  717. }
  718. });
  719. };
  720. var parseVersion = function(v) {
  721. var matches = v.match(/(\d+)\.(\d+)\.(\d+)(-(.*))?/);
  722. return {
  723. major: matches[1],
  724. minor: matches[2],
  725. patch: matches[3],
  726. revision: matches[5],
  727. parts: [matches[1], matches[2], matches[3], matches[5]]
  728. };
  729. };
  730. var isNewerVersion = function(a, b) {
  731. var va = parseVersion(a)
  732. , vb = parseVersion(b);
  733. return va.parts > vb.parts;
  734. };
  735. var handleCheckForUpdates = function() {
  736. var currentVersion = null
  737. , latestRelease = null;
  738. var handleReceiveData = function() {
  739. if (currentVersion != null) {
  740. $('#current-version').html(currentVersion.version + " (" + currentVersion.variant + ")");
  741. }
  742. if (latestRelease != null) {
  743. $('#latest-version .info-key').each(function() {
  744. var value = latestRelease[$(this).data('key')];
  745. var prop = $(this).data('prop');
  746. if (prop) {
  747. $(this).prop(prop, value);
  748. } else {
  749. $(this).html(value);
  750. }
  751. });
  752. }
  753. if (currentVersion != null && latestRelease != null) {
  754. $('#latest-version .status').html('');
  755. $('#latest-version-info').show();
  756. var summary;
  757. if (isNewerVersion(latestRelease.tag_name, currentVersion.version)) {
  758. summary = "New version available!";
  759. } else {
  760. summary = "You're on the most recent version.";
  761. }
  762. $('#version-summary').html(summary);
  763. var releaseAsset = latestRelease.assets.filter(function(x) {
  764. return x.name.indexOf(currentVersion.variant) != -1;
  765. });
  766. if (releaseAsset.length > 0) {
  767. $('#firmware-link').prop('href', releaseAsset[0].browser_download_url);
  768. }
  769. }
  770. }
  771. var handleError = function(e, d) {
  772. console.log(e);
  773. console.log(d);
  774. }
  775. $('#current-version,#latest-version .status').html('<i class="spinning glyphicon glyphicon-refresh"></i>');
  776. $('#version-summary').html('');
  777. $('#latest-version-info').hide();
  778. $.ajax(
  779. '/about',
  780. {
  781. success: function(data) {
  782. currentVersion = data;
  783. handleReceiveData();
  784. },
  785. failure: handleError
  786. }
  787. );
  788. $.ajax(
  789. 'https://api.github.com/repos/sidoh/esp8266_milight_hub/releases/latest',
  790. {
  791. success: function(data) {
  792. latestRelease = data;
  793. handleReceiveData();
  794. },
  795. failure: handleError
  796. }
  797. );
  798. };
  799. var handleStateUpdate = function(state) {
  800. if (state.state) {
  801. // Set without firing an event
  802. $('input[name="status"]')
  803. .prop('checked', state.state == 'ON')
  804. .bootstrapToggle('destroy')
  805. .bootstrapToggle();
  806. }
  807. if (state.color) {
  808. // Browsers don't support HSV, but saturation from HSL doesn't match
  809. // saturation from bulb state.
  810. var hsl = rgbToHsl(state.color.r, state.color.g, state.color.b);
  811. var hsv = RGBtoHSV(state.color.r, state.color.g, state.color.b);
  812. $('input[name="saturation"]').slider('setValue', hsv.s*100);
  813. updatePreviewColor(hsl.h*360,hsl.s*100,hsl.l*100);
  814. }
  815. if (state.color_temp) {
  816. var scaledTemp
  817. = 100*(state.color_temp - UNIT_PARAMS.minMireds) / (UNIT_PARAMS.maxMireds - UNIT_PARAMS.minMireds);
  818. $('input[name="temperature"]').slider('setValue', scaledTemp);
  819. }
  820. if (state.brightness) {
  821. var scaledBrightness = state.brightness * (100 / UNIT_PARAMS.maxBrightness);
  822. $('input[name="level"]').slider('setValue', scaledBrightness);
  823. }
  824. };
  825. var updatePreviewColor = function(hue, saturation, lightness) {
  826. if (! saturation) {
  827. saturation = 100;
  828. }
  829. if (! lightness) {
  830. lightness = 50;
  831. }
  832. $('.hue-value-display').css({
  833. backgroundColor: "hsl(" + hue + "," + saturation + "%," + lightness + "%)"
  834. });
  835. };
  836. var stopSniffing = function() {
  837. var elmt = $('#sniff');
  838. sniffing = false;
  839. $('i', elmt)
  840. .removeClass('glyphicon-stop')
  841. .addClass('glyphicon-play');
  842. $('span', elmt).html('Start Sniffing');
  843. };
  844. var startSniffing = function() {
  845. var elmt = $('#sniff');
  846. sniffing = true;
  847. $('i', elmt)
  848. .removeClass('glyphicon-play')
  849. .addClass('glyphicon-stop');
  850. $('span', elmt).html('Stop Sniffing');
  851. $("#traffic-sniff").show();
  852. };
  853. var generateDropdownField = function(fieldName, options, settings) {
  854. var s = '<div class="btn-group" id="' + fieldName + '" data-toggle="buttons">';
  855. var inputType = settings.multiple ? 'checkbox' : 'radio';
  856. Object.keys(options).forEach(function(optionValue) {
  857. var optionLabel = options[optionValue];
  858. s += '<label class="btn btn-secondary">' +
  859. '<input type="' + inputType + '" id="' + fieldName + '" name="' + fieldName + '" autocomplete="off" value="' + optionValue + '" /> ' + optionLabel +
  860. '</label>';
  861. });
  862. s += '</div>';
  863. return s;
  864. };
  865. $(function() {
  866. $('.radio-option').click(function() {
  867. $(this).prev().prop('checked', true);
  868. });
  869. var hueDragging = false;
  870. var colorUpdated = function(e) {
  871. var x = e.pageX - $(this).offset().left
  872. , pct = x/(1.0*$(this).width())
  873. , hue = Math.round(360*pct)
  874. ;
  875. updatePreviewColor(hue);
  876. updateGroup({hue: hue});
  877. };
  878. $('.hue-picker-inner')
  879. .mousedown(function(e) {
  880. hueDragging = true;
  881. colorUpdated.call(this, e);
  882. })
  883. .mouseup(function(e) {
  884. hueDragging = false;
  885. })
  886. .mouseout(function(e) {
  887. hueDragging = false;
  888. })
  889. .mousemove(function(e) {
  890. if (hueDragging) {
  891. colorUpdated.call(this, e);
  892. }
  893. });
  894. $('.slider').slider();
  895. $('.raw-update').change(function() {
  896. var data = {}
  897. , val = $(this).attr('type') == 'checkbox' ? ($(this).is(':checked') ? 'on' : 'off') : $(this).val()
  898. ;
  899. data[$(this).attr('name')] = val;
  900. updateGroup(data);
  901. });
  902. $('.command-btn').click(function() {
  903. updateGroup({command: $(this).data('command')});
  904. });
  905. $('.system-btn').click(function() {
  906. sendCommand({command: $(this).data('command')});
  907. });
  908. $('#sniff').click(function(e) {
  909. e.preventDefault();
  910. if (sniffing) {
  911. stopSniffing();
  912. } else {
  913. startSniffing();
  914. }
  915. });
  916. $('#traffic-sniff-close').click(function() {
  917. stopSniffing();
  918. $('#traffic-sniff').hide();
  919. });
  920. $('body').on('click', '#add-server-btn', function(e) {
  921. e.preventDefault();
  922. $('#gateway-server-configs').append(gatewayServerRow('', ''));
  923. });
  924. $('#mode li').click(function(e) {
  925. e.preventDefault();
  926. $('li', $(this).parent()).removeClass('active');
  927. $(this).addClass('active');
  928. updateModeOptions.bind(this)();
  929. });
  930. $('body').on('click', '.remove-gateway-server', function() {
  931. $(this).closest('tr').remove();
  932. });
  933. for (var i = 0; i < 9; i++) {
  934. $('.mode-dropdown').append('<li><a href="#" data-mode-value="' + i + '">' + i + '</a></li>');
  935. }
  936. $('body').on('click', '.mode-dropdown li a', function(e) {
  937. updateGroup({mode: $(this).data('mode-value')});
  938. e.preventDefault();
  939. return false;
  940. });
  941. var onGroupParamsChange = function(e) {
  942. findAndSelectAlias();
  943. try {
  944. refreshGroupState();
  945. } catch (e) {
  946. // Skip
  947. }
  948. };
  949. $('input[name="options"],#deviceId').change(onGroupParamsChange);
  950. $('#mode li').click(onGroupParamsChange);
  951. aliasesSelectize = $('#deviceAliases').selectize({
  952. create: true,
  953. allowEmptyOption: true,
  954. openOnFocus: true,
  955. createOnBlur: true,
  956. render: {
  957. option: function(data, escape) {
  958. // Mousedown selects an option -- prevent event from bubbling up to select option
  959. // when delete button is clicked.
  960. var deleteBtn = $('<span class="selectize-delete"><a href="#"><i class="glyphicon glyphicon-trash"></i></a></span>')
  961. .mousedown(function(e) {
  962. e.preventDefault();
  963. return false;
  964. })
  965. .click(function(e) {
  966. deleteDeviceAlias.call($(this).closest('.c-selectize-item'));
  967. e.preventDefault();
  968. return false;
  969. });
  970. var elmt = $('<div class="c-selectize-item"></div>');
  971. elmt.append('<span>' + data.text + '</span>');
  972. elmt.append(deleteBtn);
  973. return elmt;
  974. }
  975. },
  976. onOptionAdd: function(v, item) {
  977. if (!item.savedGroupParams) {
  978. item.savedGroupParams = {
  979. deviceId: getCurrentDeviceId(),
  980. groupId: getCurrentGroupId(),
  981. deviceType: getCurrentMode()
  982. };
  983. }
  984. saveDeviceAliases();
  985. }
  986. })[0].selectize;
  987. selectize = $('#deviceId').selectize({
  988. create: true,
  989. sortField: 'value',
  990. allowEmptyOption: true,
  991. createOnBlur: true,
  992. render: {
  993. option: function(data, escape) {
  994. // Mousedown selects an option -- prevent event from bubbling up to select option
  995. // when delete button is clicked.
  996. var deleteBtn = $('<span class="selectize-delete"><a href="#"><i class="glyphicon glyphicon-trash"></i></a></span>')
  997. .mousedown(function(e) {
  998. e.preventDefault();
  999. return false;
  1000. })
  1001. .click(function(e) {
  1002. deleteDeviceId.call($(this).closest('.c-selectize-item'));
  1003. e.preventDefault();
  1004. return false;
  1005. });
  1006. var elmt = $('<div class="c-selectize-item"></div>');
  1007. elmt.append('<span>' + data.text + '</span>');
  1008. elmt.append(deleteBtn);
  1009. return elmt;
  1010. }
  1011. },
  1012. onOptionAdd: function(v, item) {
  1013. var unparsedValue = item.value;
  1014. item.value = parseInt(unparsedValue);
  1015. selectize.updateOption(unparsedValue, item);
  1016. selectize.addItem(item.value);
  1017. saveDeviceIds();
  1018. },
  1019. createFilter: function(v) {
  1020. if (! v.match(/^(0x[a-fA-F0-9]{1,4}|[0-9]{1,5})$/)) {
  1021. deviceIdError("Must be an integer between 0x0000 and 0xFFFF");
  1022. return false;
  1023. }
  1024. var value = parseInt(v);
  1025. if (! (0 <= v && v <= 0xFFFF)) {
  1026. deviceIdError("Must be an integer between 0x0000 and 0xFFFF");
  1027. return false;
  1028. }
  1029. deviceIdError(false);
  1030. return true;
  1031. }
  1032. });
  1033. selectize = selectize[0].selectize;
  1034. var settings = '<ul class="nav nav-tabs" id="setupTabs">';
  1035. var tabClass = 'active';
  1036. UI_TABS.forEach(function(t) {
  1037. settings += '<li class="' + tabClass + '"><a href="#' + t.tag + '" data-toggle="tab">' + t.friendly + '</a></li>';
  1038. tabClass = '';
  1039. });
  1040. settings += '<li><a href="#tab-udp-gateways" data-toggle="tab">UDP</a></li>';
  1041. settings += "</ul>";
  1042. settings += '<div class="tab-content">';
  1043. tabClass = 'active in';
  1044. UI_TABS.forEach(function(t) {
  1045. settings += '<div class="tab-pane fade ' + tabClass + '" id="' + t.tag + '">';
  1046. tabClass = '';
  1047. UI_FIELDS.forEach(function(k) {
  1048. if (k.tab == t.tag) {
  1049. var elmt = '<div class="form-entry">';
  1050. elmt += '<div>';
  1051. elmt += '<label for="' + k.tag + '">' + k.friendly + '</label>';
  1052. if (k.help) {
  1053. elmt += '<div class="field-help" data-help-text="' + k.help + '"></div>';
  1054. }
  1055. elmt += '</div>';
  1056. if (k.type == 'group_state_fields') {
  1057. elmt += '<select class="selectpicker select-init" name="group_state_fields" multiple>';
  1058. GROUP_STATE_KEYS.forEach(function(stateKey) {
  1059. elmt += '<option>' + stateKey + '</option>';
  1060. });
  1061. elmt += '</select>';
  1062. } else if (k.type == 'led_mode') {
  1063. elmt += '<select class="selectpicker select-init" name="' + k.tag + '">';
  1064. LED_MODES.forEach(function(stateKey) {
  1065. elmt += '<option>' + stateKey + '</option>';
  1066. });
  1067. elmt += '</select>';
  1068. } else if (k.type == 'option_buttons') {
  1069. elmt += generateDropdownField(k.tag, k.options, k.settings || {});
  1070. } else {
  1071. elmt += '<input type="text" class="form-control" name="' + k.tag + '"/>';
  1072. }
  1073. elmt += '</div>';
  1074. settings += elmt;
  1075. }
  1076. });
  1077. settings += "</div>";
  1078. });
  1079. // UDP gateways tab
  1080. settings += '<div class="tab-pane fade ' + tabClass + '" id="tab-udp-gateways">';
  1081. settings += $('#gateway-servers-modal .modal-body').remove().html();
  1082. settings += '</div>';
  1083. settings += "</div>";
  1084. $('#settings').prepend(settings);
  1085. $('#settings').submit(function(e) {
  1086. e.preventDefault();
  1087. // Save UDP settings separately from the rest of the stuff since input is handled differently
  1088. if ($('#tab-udp-gateways').hasClass('active')) {
  1089. saveGatewayConfigs();
  1090. } else {
  1091. var obj = $('#settings').serializeArray();
  1092. obj = obj
  1093. .reduce(function(a, x) {
  1094. var val = a[x.name];
  1095. if (! val) {
  1096. a[x.name] = x.value;
  1097. } else if (! Array.isArray(val)) {
  1098. a[x.name] = [val, x.value];
  1099. } else {
  1100. val.push(x.value);
  1101. }
  1102. return a;
  1103. },
  1104. {
  1105. // Make sure the value is always an array, even if a single item is selected
  1106. rf24_channels: []
  1107. });
  1108. // Make sure we're submitting a value for group_state_fields (will be empty
  1109. // if no values were selected).
  1110. obj = $.extend({group_state_fields: []}, obj);
  1111. $.ajax(
  1112. "/settings",
  1113. {
  1114. method: 'put',
  1115. contentType: 'application/json',
  1116. data: JSON.stringify(obj)
  1117. }
  1118. );
  1119. }
  1120. $('#settings-modal').modal('hide');
  1121. return false;
  1122. });
  1123. $('#gateway-server-form').submit(function(e) {
  1124. saveGatewayConfigs();
  1125. e.preventDefault();
  1126. $('#gateway-servers-modal').modal('hide');
  1127. return false;
  1128. });
  1129. $('.field-help').each(function() {
  1130. var elmt = $('<i></i>')
  1131. .addClass('glyphicon glyphicon-question-sign')
  1132. .tooltip({
  1133. placement: 'top',
  1134. title: $(this).data('help-text'),
  1135. container: 'body'
  1136. });
  1137. $(this).append(elmt);
  1138. });
  1139. $('#updates-btn').click(handleCheckForUpdates);
  1140. loadSettings();
  1141. updateModeOptions();
  1142. });
  1143. $(function() {
  1144. $(document).on('change', ':file', function() {
  1145. var input = $(this),
  1146. label = input.val().replace(/\\/g, '/').replace(/.*\//, '');
  1147. input.trigger('fileselect', [label]);
  1148. });
  1149. $(document).on('change', '#deviceAliases', function() {
  1150. var selectedValue = aliasesSelectize.getValue()
  1151. , selectizeItem = aliasesSelectize.options[selectedValue]
  1152. ;
  1153. if (selectizeItem && !updatingAlias) {
  1154. updateGroupId(selectizeItem.savedGroupParams);
  1155. }
  1156. });
  1157. $(document).ready( function() {
  1158. $(':file').on('fileselect', function(event, label) {
  1159. var input = $(this).parents('.input-group').find(':text'),
  1160. log = label;
  1161. if( input.length ) {
  1162. input.val(log);
  1163. }
  1164. });
  1165. });
  1166. });