settings.js 89 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152
  1. // Constants for log message types
  2. const LOG_TYPE = {
  3. SUCCESS: 'success',
  4. WARNING: 'warning',
  5. ERROR: 'error',
  6. INFO: 'info',
  7. DEBUG: 'debug'
  8. };
  9. // Helper function to convert provider name to camelCase for ID lookup
  10. // e.g., "dw_leds" -> "DwLeds", "wled" -> "Wled", "none" -> "None"
  11. function providerToCamelCase(provider) {
  12. return provider.split('_').map(word =>
  13. word.charAt(0).toUpperCase() + word.slice(1)
  14. ).join('');
  15. }
  16. // Constants for cache
  17. const CACHE_KEYS = {
  18. CONNECTION_STATUS: 'connection_status',
  19. LAST_UPDATE: 'last_status_update'
  20. };
  21. const CACHE_DURATION = 5000; // 5 seconds cache duration
  22. // Function to log messages
  23. function logMessage(message, type = LOG_TYPE.DEBUG) {
  24. console.log(`[${type}] ${message}`);
  25. }
  26. // Function to get cached connection status
  27. function getCachedConnectionStatus() {
  28. const cachedData = localStorage.getItem(CACHE_KEYS.CONNECTION_STATUS);
  29. const lastUpdate = localStorage.getItem(CACHE_KEYS.LAST_UPDATE);
  30. if (cachedData && lastUpdate) {
  31. const now = Date.now();
  32. const cacheAge = now - parseInt(lastUpdate);
  33. if (cacheAge < CACHE_DURATION) {
  34. return JSON.parse(cachedData);
  35. }
  36. }
  37. return null;
  38. }
  39. // Function to set cached connection status
  40. function setCachedConnectionStatus(data) {
  41. localStorage.setItem(CACHE_KEYS.CONNECTION_STATUS, JSON.stringify(data));
  42. localStorage.setItem(CACHE_KEYS.LAST_UPDATE, Date.now().toString());
  43. }
  44. // Function to update serial connection status
  45. async function updateSerialStatus(forceUpdate = false) {
  46. try {
  47. // Check cache first unless force update is requested
  48. if (!forceUpdate) {
  49. const cachedData = getCachedConnectionStatus();
  50. if (cachedData) {
  51. updateConnectionUI(cachedData);
  52. return;
  53. }
  54. }
  55. const response = await fetch('/serial_status');
  56. if (response.ok) {
  57. const data = await response.json();
  58. setCachedConnectionStatus(data);
  59. updateConnectionUI(data);
  60. }
  61. } catch (error) {
  62. logMessage(`Error checking serial status: ${error.message}`, LOG_TYPE.ERROR);
  63. }
  64. }
  65. // Function to update UI based on connection status
  66. function updateConnectionUI(data) {
  67. const statusElement = document.getElementById('serialStatus');
  68. const iconElement = document.querySelector('.material-icons.text-3xl');
  69. const disconnectButton = document.getElementById('disconnectButton');
  70. const portSelectionDiv = document.getElementById('portSelectionDiv');
  71. if (statusElement && iconElement) {
  72. if (data.connected) {
  73. statusElement.textContent = `Connected to ${data.port || 'unknown port'}`;
  74. statusElement.className = 'text-green-500 text-sm font-medium leading-normal';
  75. iconElement.textContent = 'usb';
  76. if (disconnectButton) {
  77. disconnectButton.hidden = false;
  78. }
  79. if (portSelectionDiv) {
  80. portSelectionDiv.hidden = true;
  81. }
  82. } else {
  83. statusElement.textContent = 'Disconnected';
  84. statusElement.className = 'text-red-500 text-sm font-medium leading-normal';
  85. iconElement.textContent = 'usb_off';
  86. if (disconnectButton) {
  87. disconnectButton.hidden = true;
  88. }
  89. if (portSelectionDiv) {
  90. portSelectionDiv.hidden = false;
  91. }
  92. }
  93. }
  94. }
  95. // Function to update available serial ports
  96. async function updateSerialPorts() {
  97. try {
  98. const response = await fetch('/list_serial_ports');
  99. if (response.ok) {
  100. const ports = await response.json();
  101. const portsElement = document.getElementById('availablePorts');
  102. const portSelect = document.getElementById('portSelect');
  103. const preferredPortSelect = document.getElementById('preferredPortSelect');
  104. if (portsElement) {
  105. portsElement.textContent = ports.length > 0 ? ports.join(', ') : 'No ports available';
  106. }
  107. if (portSelect) {
  108. // Clear existing options except the first one
  109. while (portSelect.options.length > 1) {
  110. portSelect.remove(1);
  111. }
  112. // Add new options
  113. ports.forEach(port => {
  114. const option = document.createElement('option');
  115. option.value = port;
  116. option.textContent = port;
  117. portSelect.appendChild(option);
  118. });
  119. // If there's exactly one port available, select and connect to it
  120. if (ports.length === 1) {
  121. portSelect.value = ports[0];
  122. // Trigger connect button click
  123. const connectButton = document.getElementById('connectButton');
  124. if (connectButton) {
  125. connectButton.click();
  126. }
  127. }
  128. }
  129. // Also update the preferred port select dropdown
  130. if (preferredPortSelect) {
  131. // Store current selection
  132. const currentPreferred = preferredPortSelect.value;
  133. // Clear existing options except the first one (no preference)
  134. while (preferredPortSelect.options.length > 1) {
  135. preferredPortSelect.remove(1);
  136. }
  137. // Add all available ports
  138. ports.forEach(port => {
  139. const option = document.createElement('option');
  140. option.value = port;
  141. option.textContent = port;
  142. preferredPortSelect.appendChild(option);
  143. });
  144. // Restore selection if it's still available
  145. if (currentPreferred && ports.includes(currentPreferred)) {
  146. preferredPortSelect.value = currentPreferred;
  147. }
  148. }
  149. }
  150. } catch (error) {
  151. logMessage(`Error fetching serial ports: ${error.message}`, LOG_TYPE.ERROR);
  152. }
  153. }
  154. // Function to load and display preferred port setting
  155. async function loadPreferredPort() {
  156. try {
  157. const response = await fetch('/api/preferred-port');
  158. if (response.ok) {
  159. const data = await response.json();
  160. const preferredPortSelect = document.getElementById('preferredPortSelect');
  161. const currentPreferredPort = document.getElementById('currentPreferredPort');
  162. const preferredPortDisplay = document.getElementById('preferredPortDisplay');
  163. if (preferredPortSelect && data.preferred_port) {
  164. // Check if the preferred port is in the options
  165. const optionExists = Array.from(preferredPortSelect.options).some(
  166. opt => opt.value === data.preferred_port
  167. );
  168. if (optionExists) {
  169. preferredPortSelect.value = data.preferred_port;
  170. } else {
  171. // Add the preferred port as an option (it might not be currently available)
  172. const option = document.createElement('option');
  173. option.value = data.preferred_port;
  174. option.textContent = `${data.preferred_port} (not currently available)`;
  175. preferredPortSelect.appendChild(option);
  176. preferredPortSelect.value = data.preferred_port;
  177. }
  178. }
  179. // Show current preferred port indicator
  180. if (currentPreferredPort && preferredPortDisplay && data.preferred_port) {
  181. preferredPortDisplay.textContent = `Currently set to: ${data.preferred_port}`;
  182. currentPreferredPort.classList.remove('hidden');
  183. } else if (currentPreferredPort) {
  184. currentPreferredPort.classList.add('hidden');
  185. }
  186. }
  187. } catch (error) {
  188. logMessage(`Error loading preferred port: ${error.message}`, LOG_TYPE.ERROR);
  189. }
  190. }
  191. // Function to save preferred port setting
  192. async function savePreferredPort() {
  193. const preferredPortSelect = document.getElementById('preferredPortSelect');
  194. if (!preferredPortSelect) return;
  195. const preferredPort = preferredPortSelect.value || null;
  196. try {
  197. const response = await fetch('/api/settings', {
  198. method: 'PATCH',
  199. headers: { 'Content-Type': 'application/json' },
  200. body: JSON.stringify({ connection: { preferred_port: preferredPort } })
  201. });
  202. if (response.ok) {
  203. await response.json();
  204. const currentPreferredPort = document.getElementById('currentPreferredPort');
  205. const preferredPortDisplay = document.getElementById('preferredPortDisplay');
  206. if (preferredPort) {
  207. showStatusMessage(`Preferred port set to: ${preferredPort}`, 'success');
  208. if (currentPreferredPort && preferredPortDisplay) {
  209. preferredPortDisplay.textContent = `Currently set to: ${preferredPort}`;
  210. currentPreferredPort.classList.remove('hidden');
  211. }
  212. } else {
  213. showStatusMessage('Preferred port cleared - will auto-detect on startup', 'success');
  214. if (currentPreferredPort) {
  215. currentPreferredPort.classList.add('hidden');
  216. }
  217. }
  218. } else {
  219. throw new Error('Failed to save preferred port');
  220. }
  221. } catch (error) {
  222. showStatusMessage(`Failed to save preferred port: ${error.message}`, 'error');
  223. }
  224. }
  225. function setWledButtonState(isSet) {
  226. const saveWledConfig = document.getElementById('saveWledConfig');
  227. if (!saveWledConfig) return;
  228. if (isSet) {
  229. saveWledConfig.className = 'flex items-center justify-center gap-2 min-w-[100px] max-w-[480px] cursor-pointer rounded-lg h-10 px-4 bg-red-600 hover:bg-red-700 text-white text-sm font-medium leading-normal tracking-[0.015em] transition-colors';
  230. saveWledConfig.innerHTML = '<span class="material-icons text-lg">close</span><span class="truncate">Clear WLED IP</span>';
  231. } else {
  232. saveWledConfig.className = 'flex items-center justify-center gap-2 min-w-[100px] max-w-[480px] cursor-pointer rounded-lg h-10 px-4 bg-sky-600 hover:bg-sky-700 text-white text-sm font-medium leading-normal tracking-[0.015em] transition-colors';
  233. saveWledConfig.innerHTML = '<span class="material-icons text-lg">save</span><span class="truncate">Save Configuration</span>';
  234. }
  235. }
  236. // Handle LED provider selection and show/hide appropriate config sections
  237. function updateLedProviderUI() {
  238. const provider = document.querySelector('input[name="ledProvider"]:checked')?.value || 'none';
  239. const wledConfig = document.getElementById('wledConfig');
  240. const dwLedsConfig = document.getElementById('dwLedsConfig');
  241. if (wledConfig && dwLedsConfig) {
  242. if (provider === 'wled') {
  243. wledConfig.classList.remove('hidden');
  244. dwLedsConfig.classList.add('hidden');
  245. } else if (provider === 'dw_leds') {
  246. wledConfig.classList.add('hidden');
  247. dwLedsConfig.classList.remove('hidden');
  248. } else {
  249. wledConfig.classList.add('hidden');
  250. dwLedsConfig.classList.add('hidden');
  251. }
  252. }
  253. }
  254. // Load LED configuration from server
  255. async function loadLedConfig() {
  256. try {
  257. const response = await fetch('/get_led_config');
  258. if (response.ok) {
  259. const data = await response.json();
  260. // Set provider radio button
  261. const providerRadio = document.getElementById(`ledProvider${providerToCamelCase(data.provider)}`);
  262. if (providerRadio) {
  263. providerRadio.checked = true;
  264. } else {
  265. document.getElementById('ledProviderNone').checked = true;
  266. }
  267. // Set WLED IP if configured
  268. if (data.wled_ip) {
  269. const wledIpInput = document.getElementById('wledIpInput');
  270. if (wledIpInput) {
  271. wledIpInput.value = data.wled_ip;
  272. }
  273. }
  274. // Set DW LED configuration if configured
  275. if (data.dw_led_num_leds) {
  276. const numLedsInput = document.getElementById('dwLedNumLeds');
  277. if (numLedsInput) {
  278. numLedsInput.value = data.dw_led_num_leds;
  279. }
  280. }
  281. if (data.dw_led_gpio_pin) {
  282. const gpioPinInput = document.getElementById('dwLedGpioPin');
  283. if (gpioPinInput) {
  284. gpioPinInput.value = data.dw_led_gpio_pin;
  285. }
  286. }
  287. if (data.dw_led_pixel_order) {
  288. const pixelOrderInput = document.getElementById('dwLedPixelOrder');
  289. if (pixelOrderInput) {
  290. pixelOrderInput.value = data.dw_led_pixel_order;
  291. }
  292. }
  293. // Update UI to show correct config section
  294. updateLedProviderUI();
  295. }
  296. } catch (error) {
  297. logMessage(`Error loading LED config: ${error.message}`, LOG_TYPE.ERROR);
  298. }
  299. }
  300. // Initialize settings page
  301. document.addEventListener('DOMContentLoaded', async () => {
  302. // Initialize UI with default disconnected state
  303. updateConnectionUI({ connected: false });
  304. // Handle scroll to section if hash is present in URL
  305. if (window.location.hash) {
  306. setTimeout(() => {
  307. const targetSection = document.querySelector(window.location.hash);
  308. if (targetSection) {
  309. targetSection.scrollIntoView({ behavior: 'smooth', block: 'start' });
  310. // Add a subtle highlight animation
  311. targetSection.style.transition = 'background-color 0.5s ease';
  312. const originalBg = targetSection.style.backgroundColor;
  313. targetSection.style.backgroundColor = 'rgba(14, 165, 233, 0.1)';
  314. setTimeout(() => {
  315. targetSection.style.backgroundColor = originalBg;
  316. }, 2000);
  317. }
  318. }, 300); // Delay to ensure page is fully loaded
  319. }
  320. // Load all data asynchronously using unified settings endpoint
  321. Promise.all([
  322. // Unified settings endpoint (replaces multiple individual fetches)
  323. fetch('/api/settings').then(response => response.json()).catch(() => ({})),
  324. // Non-settings operational endpoints (kept separate)
  325. fetch('/serial_status').then(response => response.json()).catch(() => ({ connected: false })),
  326. fetch('/api/version').then(response => response.json()).catch(() => ({ current: '1.0.0', latest: '1.0.0', update_available: false })),
  327. fetch('/list_serial_ports').then(response => response.json()).catch(() => []),
  328. getCachedPatternFiles().catch(() => [])
  329. ]).then(([settings, statusData, updateData, ports, patterns]) => {
  330. // Map unified settings to legacy variable names for backward compatibility with existing UI code
  331. const ledConfigData = {
  332. provider: settings.led?.provider || 'none',
  333. wled_ip: settings.led?.wled_ip || null,
  334. dw_led_num_leds: settings.led?.dw_led?.num_leds,
  335. dw_led_gpio_pin: settings.led?.dw_led?.gpio_pin,
  336. dw_led_pixel_order: settings.led?.dw_led?.pixel_order
  337. };
  338. const clearPatterns = {
  339. custom_clear_from_in: settings.patterns?.custom_clear_from_in,
  340. custom_clear_from_out: settings.patterns?.custom_clear_from_out
  341. };
  342. const clearSpeedData = {
  343. clear_pattern_speed: settings.patterns?.clear_pattern_speed,
  344. effective_speed: settings.patterns?.clear_pattern_speed // Will be handled by UI
  345. };
  346. const appNameData = { app_name: settings.app?.name || 'Dune Weaver' };
  347. const scheduledPauseData = settings.scheduled_pause || { enabled: false, time_slots: [] };
  348. const preferredPortData = { preferred_port: settings.connection?.preferred_port };
  349. // Store full settings for other initialization functions
  350. window.unifiedSettings = settings;
  351. // Update connection status
  352. setCachedConnectionStatus(statusData);
  353. updateConnectionUI(statusData);
  354. // Update LED configuration
  355. const providerRadio = document.getElementById(`ledProvider${providerToCamelCase(ledConfigData.provider)}`);
  356. if (providerRadio) {
  357. providerRadio.checked = true;
  358. } else {
  359. document.getElementById('ledProviderNone').checked = true;
  360. }
  361. if (ledConfigData.wled_ip) {
  362. const wledIpInput = document.getElementById('wledIpInput');
  363. if (wledIpInput) wledIpInput.value = ledConfigData.wled_ip;
  364. }
  365. // Load DW LED settings
  366. if (ledConfigData.dw_led_num_leds) {
  367. const numLedsInput = document.getElementById('dwLedNumLeds');
  368. if (numLedsInput) numLedsInput.value = ledConfigData.dw_led_num_leds;
  369. }
  370. if (ledConfigData.dw_led_gpio_pin) {
  371. const gpioPinInput = document.getElementById('dwLedGpioPin');
  372. if (gpioPinInput) gpioPinInput.value = ledConfigData.dw_led_gpio_pin;
  373. }
  374. if (ledConfigData.dw_led_pixel_order) {
  375. const pixelOrderInput = document.getElementById('dwLedPixelOrder');
  376. if (pixelOrderInput) pixelOrderInput.value = ledConfigData.dw_led_pixel_order;
  377. }
  378. updateLedProviderUI()
  379. // Update version display
  380. const currentVersionText = document.getElementById('currentVersionText');
  381. const latestVersionText = document.getElementById('latestVersionText');
  382. const updateButton = document.getElementById('updateSoftware');
  383. const updateIcon = document.getElementById('updateIcon');
  384. const updateText = document.getElementById('updateText');
  385. if (currentVersionText) {
  386. currentVersionText.textContent = updateData.current;
  387. }
  388. if (latestVersionText) {
  389. if (updateData.error) {
  390. latestVersionText.textContent = 'Error checking updates';
  391. latestVersionText.className = 'text-red-500 text-sm font-normal leading-normal';
  392. } else {
  393. latestVersionText.textContent = updateData.latest;
  394. latestVersionText.className = 'text-slate-500 text-sm font-normal leading-normal';
  395. }
  396. }
  397. // Update button state
  398. if (updateButton && updateIcon && updateText) {
  399. if (updateData.update_available) {
  400. updateButton.disabled = false;
  401. updateButton.className = 'flex items-center justify-center gap-1.5 min-w-[84px] cursor-pointer rounded-lg h-9 px-3 bg-emerald-500 hover:bg-emerald-600 text-white text-xs font-medium leading-normal tracking-[0.015em] transition-colors';
  402. updateIcon.textContent = 'download';
  403. updateText.textContent = 'Update';
  404. } else {
  405. updateButton.disabled = true;
  406. updateButton.className = 'flex items-center justify-center gap-1.5 min-w-[84px] cursor-pointer rounded-lg h-9 px-3 bg-gray-400 text-white text-xs font-medium leading-normal tracking-[0.015em] transition-colors disabled:opacity-50 disabled:cursor-not-allowed';
  407. updateIcon.textContent = 'check';
  408. updateText.textContent = 'Up to date';
  409. }
  410. }
  411. // Update port selection
  412. const portSelect = document.getElementById('portSelect');
  413. if (portSelect) {
  414. // Clear existing options except the first one
  415. while (portSelect.options.length > 1) {
  416. portSelect.remove(1);
  417. }
  418. // Add new options
  419. ports.forEach(port => {
  420. const option = document.createElement('option');
  421. option.value = port;
  422. option.textContent = port;
  423. portSelect.appendChild(option);
  424. });
  425. // If there's exactly one port available, select it
  426. if (ports.length === 1) {
  427. portSelect.value = ports[0];
  428. }
  429. }
  430. // Update preferred port selection
  431. const preferredPortSelect = document.getElementById('preferredPortSelect');
  432. const currentPreferredPort = document.getElementById('currentPreferredPort');
  433. const preferredPortDisplay = document.getElementById('preferredPortDisplay');
  434. if (preferredPortSelect) {
  435. // Clear existing options except the first one (no preference)
  436. while (preferredPortSelect.options.length > 1) {
  437. preferredPortSelect.remove(1);
  438. }
  439. // Add all available ports
  440. ports.forEach(port => {
  441. const option = document.createElement('option');
  442. option.value = port;
  443. option.textContent = port;
  444. preferredPortSelect.appendChild(option);
  445. });
  446. // Set the current preferred port value
  447. if (preferredPortData && preferredPortData.preferred_port) {
  448. // Check if the preferred port is in the available ports
  449. const isAvailable = ports.includes(preferredPortData.preferred_port);
  450. if (isAvailable) {
  451. preferredPortSelect.value = preferredPortData.preferred_port;
  452. } else {
  453. // Add the preferred port as an option (it might not be currently available)
  454. const option = document.createElement('option');
  455. option.value = preferredPortData.preferred_port;
  456. option.textContent = `${preferredPortData.preferred_port} (not currently available)`;
  457. preferredPortSelect.appendChild(option);
  458. preferredPortSelect.value = preferredPortData.preferred_port;
  459. }
  460. // Show the current preferred port indicator
  461. if (currentPreferredPort && preferredPortDisplay) {
  462. preferredPortDisplay.textContent = `Currently set to: ${preferredPortData.preferred_port}`;
  463. currentPreferredPort.classList.remove('hidden');
  464. }
  465. }
  466. }
  467. // Initialize autocomplete for clear patterns
  468. const clearFromInInput = document.getElementById('customClearFromInInput');
  469. const clearFromOutInput = document.getElementById('customClearFromOutInput');
  470. if (clearFromInInput && clearFromOutInput && patterns && Array.isArray(patterns)) {
  471. // Store patterns globally for autocomplete
  472. window.availablePatterns = patterns;
  473. // Set current values if they exist
  474. if (clearPatterns && clearPatterns.custom_clear_from_in) {
  475. clearFromInInput.value = clearPatterns.custom_clear_from_in;
  476. }
  477. if (clearPatterns && clearPatterns.custom_clear_from_out) {
  478. clearFromOutInput.value = clearPatterns.custom_clear_from_out;
  479. }
  480. // Initialize autocomplete for both inputs
  481. initializeAutocomplete('customClearFromInInput', 'clearFromInSuggestions', 'clearFromInClear', patterns);
  482. initializeAutocomplete('customClearFromOutInput', 'clearFromOutSuggestions', 'clearFromOutClear', patterns);
  483. console.log('Autocomplete initialized with', patterns.length, 'patterns');
  484. }
  485. // Set clear pattern speed
  486. const clearPatternSpeedInput = document.getElementById('clearPatternSpeedInput');
  487. const effectiveClearSpeed = document.getElementById('effectiveClearSpeed');
  488. if (clearPatternSpeedInput && clearSpeedData) {
  489. // Only set value if clear_pattern_speed is not null
  490. if (clearSpeedData.clear_pattern_speed !== null && clearSpeedData.clear_pattern_speed !== undefined) {
  491. clearPatternSpeedInput.value = clearSpeedData.clear_pattern_speed;
  492. if (effectiveClearSpeed) {
  493. effectiveClearSpeed.textContent = `Current: ${clearSpeedData.clear_pattern_speed} steps/min`;
  494. }
  495. } else {
  496. // Leave empty to show placeholder for default
  497. clearPatternSpeedInput.value = '';
  498. if (effectiveClearSpeed && clearSpeedData.effective_speed) {
  499. effectiveClearSpeed.textContent = `Using default pattern speed: ${clearSpeedData.effective_speed} steps/min`;
  500. }
  501. }
  502. }
  503. // Update app name
  504. const appNameInput = document.getElementById('appNameInput');
  505. if (appNameInput && appNameData.app_name) {
  506. appNameInput.value = appNameData.app_name;
  507. }
  508. // Store Still Sands data for later initialization
  509. window.initialStillSandsData = scheduledPauseData;
  510. }).catch(error => {
  511. logMessage(`Error initializing settings page: ${error.message}`, LOG_TYPE.ERROR);
  512. });
  513. // Set up event listeners
  514. setupEventListeners();
  515. });
  516. // Setup event listeners
  517. function setupEventListeners() {
  518. // Save App Name
  519. const saveAppNameButton = document.getElementById('saveAppName');
  520. const appNameInput = document.getElementById('appNameInput');
  521. if (saveAppNameButton && appNameInput) {
  522. saveAppNameButton.addEventListener('click', async () => {
  523. const appName = appNameInput.value.trim() || 'Dune Weaver';
  524. try {
  525. const response = await fetch('/api/settings', {
  526. method: 'PATCH',
  527. headers: { 'Content-Type': 'application/json' },
  528. body: JSON.stringify({ app: { name: appName } })
  529. });
  530. if (response.ok) {
  531. await response.json();
  532. showStatusMessage('Application name updated successfully. Refresh the page to see changes.', 'success');
  533. // Update the page title and header immediately
  534. document.title = `Settings - ${appName}`;
  535. const headerTitle = document.querySelector('h1.text-gray-800');
  536. if (headerTitle) {
  537. // Update just the text content, preserving the connection status dot
  538. const textNode = headerTitle.childNodes[0];
  539. if (textNode && textNode.nodeType === Node.TEXT_NODE) {
  540. textNode.textContent = data.app_name;
  541. }
  542. }
  543. } else {
  544. throw new Error('Failed to save application name');
  545. }
  546. } catch (error) {
  547. showStatusMessage(`Failed to save application name: ${error.message}`, 'error');
  548. }
  549. });
  550. // Handle Enter key in app name input
  551. appNameInput.addEventListener('keypress', (e) => {
  552. if (e.key === 'Enter') {
  553. saveAppNameButton.click();
  554. }
  555. });
  556. }
  557. // LED provider selection change handlers
  558. const ledProviderRadios = document.querySelectorAll('input[name="ledProvider"]');
  559. ledProviderRadios.forEach(radio => {
  560. radio.addEventListener('change', updateLedProviderUI);
  561. });
  562. // Save LED configuration
  563. const saveLedConfig = document.getElementById('saveLedConfig');
  564. if (saveLedConfig) {
  565. saveLedConfig.addEventListener('click', async () => {
  566. const provider = document.querySelector('input[name="ledProvider"]:checked')?.value || 'none';
  567. let requestBody = { provider };
  568. if (provider === 'wled') {
  569. const wledIp = document.getElementById('wledIpInput')?.value;
  570. if (!wledIp) {
  571. showStatusMessage('Please enter a WLED IP address', 'error');
  572. return;
  573. }
  574. requestBody.ip_address = wledIp;
  575. } else if (provider === 'dw_leds') {
  576. const numLeds = parseInt(document.getElementById('dwLedNumLeds')?.value) || 60;
  577. const gpioPin = parseInt(document.getElementById('dwLedGpioPin')?.value) || 12;
  578. const pixelOrder = document.getElementById('dwLedPixelOrder')?.value || 'GRB';
  579. requestBody.num_leds = numLeds;
  580. requestBody.gpio_pin = gpioPin;
  581. requestBody.pixel_order = pixelOrder;
  582. }
  583. try {
  584. const response = await fetch('/set_led_config', {
  585. method: 'POST',
  586. headers: { 'Content-Type': 'application/json' },
  587. body: JSON.stringify(requestBody)
  588. });
  589. if (response.ok) {
  590. const data = await response.json();
  591. if (provider === 'wled' && data.wled_ip) {
  592. localStorage.setItem('wled_ip', data.wled_ip);
  593. showStatusMessage('WLED configured successfully', 'success');
  594. } else if (provider === 'dw_leds') {
  595. // Check if there's a warning (hardware not available but settings saved)
  596. if (data.warning) {
  597. showStatusMessage(
  598. `Settings saved for testing. Hardware issue: ${data.warning}`,
  599. 'warning'
  600. );
  601. } else {
  602. showStatusMessage(
  603. `DW LEDs configured: ${data.dw_led_num_leds} LEDs on GPIO${data.dw_led_gpio_pin}`,
  604. 'success'
  605. );
  606. }
  607. } else if (provider === 'none') {
  608. localStorage.removeItem('wled_ip');
  609. showStatusMessage('LED controller disabled', 'success');
  610. }
  611. } else {
  612. // Extract error detail from response
  613. const errorData = await response.json().catch(() => ({}));
  614. const errorMessage = errorData.detail || 'Failed to save LED configuration';
  615. showStatusMessage(errorMessage, 'error');
  616. }
  617. } catch (error) {
  618. showStatusMessage(`Failed to save LED configuration: ${error.message}`, 'error');
  619. }
  620. });
  621. }
  622. // Update software
  623. const updateSoftware = document.getElementById('updateSoftware');
  624. if (updateSoftware) {
  625. updateSoftware.addEventListener('click', async () => {
  626. if (updateSoftware.disabled) {
  627. return;
  628. }
  629. try {
  630. const response = await fetch('/api/update', {
  631. method: 'POST'
  632. });
  633. const data = await response.json();
  634. if (data.success) {
  635. showStatusMessage('Software update started successfully', 'success');
  636. } else if (data.manual_update_url) {
  637. // Show modal with manual update instructions, but use wiki link
  638. const wikiData = {
  639. ...data,
  640. manual_update_url: 'https://github.com/tuanchris/dune-weaver/wiki/Updating-software'
  641. };
  642. showUpdateInstructionsModal(wikiData);
  643. } else {
  644. showStatusMessage(data.message || 'No updates available', 'info');
  645. }
  646. } catch (error) {
  647. logMessage(`Error updating software: ${error.message}`, LOG_TYPE.ERROR);
  648. showStatusMessage('Failed to check for updates', 'error');
  649. }
  650. });
  651. }
  652. // Connect button
  653. const connectButton = document.getElementById('connectButton');
  654. if (connectButton) {
  655. connectButton.addEventListener('click', async () => {
  656. const portSelect = document.getElementById('portSelect');
  657. if (!portSelect || !portSelect.value) {
  658. logMessage('Please select a port first', LOG_TYPE.WARNING);
  659. return;
  660. }
  661. try {
  662. const response = await fetch('/connect', {
  663. method: 'POST',
  664. headers: { 'Content-Type': 'application/json' },
  665. body: JSON.stringify({ port: portSelect.value })
  666. });
  667. if (response.ok) {
  668. logMessage('Connected successfully', LOG_TYPE.SUCCESS);
  669. await updateSerialStatus(true); // Force update after connecting
  670. } else {
  671. throw new Error('Failed to connect');
  672. }
  673. } catch (error) {
  674. logMessage(`Error connecting to device: ${error.message}`, LOG_TYPE.ERROR);
  675. }
  676. });
  677. }
  678. // Disconnect button
  679. const disconnectButton = document.getElementById('disconnectButton');
  680. if (disconnectButton) {
  681. disconnectButton.addEventListener('click', async () => {
  682. try {
  683. const response = await fetch('/disconnect', {
  684. method: 'POST'
  685. });
  686. if (response.ok) {
  687. logMessage('Device disconnected successfully', LOG_TYPE.SUCCESS);
  688. await updateSerialStatus(true); // Force update after disconnecting
  689. } else {
  690. throw new Error('Failed to disconnect device');
  691. }
  692. } catch (error) {
  693. logMessage(`Error disconnecting device: ${error.message}`, LOG_TYPE.ERROR);
  694. }
  695. });
  696. }
  697. // Save preferred port button
  698. const savePreferredPortButton = document.getElementById('savePreferredPort');
  699. if (savePreferredPortButton) {
  700. savePreferredPortButton.addEventListener('click', savePreferredPort);
  701. }
  702. // Save custom clear patterns button
  703. const saveClearPatterns = document.getElementById('saveClearPatterns');
  704. if (saveClearPatterns) {
  705. saveClearPatterns.addEventListener('click', async () => {
  706. const clearFromInInput = document.getElementById('customClearFromInInput');
  707. const clearFromOutInput = document.getElementById('customClearFromOutInput');
  708. if (!clearFromInInput || !clearFromOutInput) {
  709. return;
  710. }
  711. // Validate that the entered patterns exist (if not empty)
  712. const inValue = clearFromInInput.value.trim();
  713. const outValue = clearFromOutInput.value.trim();
  714. if (inValue && window.availablePatterns && !window.availablePatterns.includes(inValue)) {
  715. showStatusMessage(`Pattern not found: ${inValue}`, 'error');
  716. return;
  717. }
  718. if (outValue && window.availablePatterns && !window.availablePatterns.includes(outValue)) {
  719. showStatusMessage(`Pattern not found: ${outValue}`, 'error');
  720. return;
  721. }
  722. try {
  723. const response = await fetch('/api/settings', {
  724. method: 'PATCH',
  725. headers: { 'Content-Type': 'application/json' },
  726. body: JSON.stringify({
  727. patterns: {
  728. custom_clear_from_in: inValue || null,
  729. custom_clear_from_out: outValue || null
  730. }
  731. })
  732. });
  733. if (response.ok) {
  734. showStatusMessage('Clear patterns saved successfully', 'success');
  735. } else {
  736. const error = await response.json();
  737. throw new Error(error.detail || 'Failed to save clear patterns');
  738. }
  739. } catch (error) {
  740. showStatusMessage(`Failed to save clear patterns: ${error.message}`, 'error');
  741. }
  742. });
  743. }
  744. // Save clear pattern speed button
  745. const saveClearSpeed = document.getElementById('saveClearSpeed');
  746. if (saveClearSpeed) {
  747. saveClearSpeed.addEventListener('click', async () => {
  748. const clearPatternSpeedInput = document.getElementById('clearPatternSpeedInput');
  749. if (!clearPatternSpeedInput) {
  750. return;
  751. }
  752. let speed;
  753. if (clearPatternSpeedInput.value === '' || clearPatternSpeedInput.value === null) {
  754. // Empty value means use default (None)
  755. speed = null;
  756. } else {
  757. speed = parseInt(clearPatternSpeedInput.value);
  758. // Validate speed only if it's not null
  759. if (isNaN(speed) || speed < 50 || speed > 2000) {
  760. showStatusMessage('Clear pattern speed must be between 50 and 2000, or leave empty for default', 'error');
  761. return;
  762. }
  763. }
  764. try {
  765. const response = await fetch('/api/settings', {
  766. method: 'PATCH',
  767. headers: { 'Content-Type': 'application/json' },
  768. body: JSON.stringify({ patterns: { clear_pattern_speed: speed } })
  769. });
  770. if (response.ok) {
  771. await response.json();
  772. if (speed === null) {
  773. showStatusMessage('Clear pattern speed set to default', 'success');
  774. } else {
  775. showStatusMessage(`Clear pattern speed set to ${speed} steps/min`, 'success');
  776. }
  777. // Update the effective speed display
  778. const effectiveClearSpeed = document.getElementById('effectiveClearSpeed');
  779. if (effectiveClearSpeed) {
  780. if (speed === null) {
  781. effectiveClearSpeed.textContent = `Using default pattern speed: ${data.effective_speed} steps/min`;
  782. } else {
  783. effectiveClearSpeed.textContent = `Current: ${speed} steps/min`;
  784. }
  785. }
  786. } else {
  787. const error = await response.json();
  788. throw new Error(error.detail || 'Failed to save clear pattern speed');
  789. }
  790. } catch (error) {
  791. showStatusMessage(`Failed to save clear pattern speed: ${error.message}`, 'error');
  792. }
  793. });
  794. }
  795. }
  796. // Button click handlers
  797. document.addEventListener('DOMContentLoaded', function() {
  798. // Home button
  799. const homeButton = document.getElementById('homeButton');
  800. if (homeButton) {
  801. homeButton.addEventListener('click', async () => {
  802. try {
  803. const response = await fetch('/send_home', {
  804. method: 'POST',
  805. headers: {
  806. 'Content-Type': 'application/json'
  807. }
  808. });
  809. const data = await response.json();
  810. if (data.success) {
  811. updateStatus('Moving to home position...');
  812. }
  813. } catch (error) {
  814. console.error('Error sending home command:', error);
  815. updateStatus('Error: Failed to move to home position');
  816. }
  817. });
  818. }
  819. // Stop button
  820. const stopButton = document.getElementById('stopButton');
  821. if (stopButton) {
  822. stopButton.addEventListener('click', async () => {
  823. try {
  824. const response = await fetch('/stop_execution', {
  825. method: 'POST',
  826. headers: {
  827. 'Content-Type': 'application/json'
  828. }
  829. });
  830. const data = await response.json();
  831. if (data.success) {
  832. updateStatus('Execution stopped');
  833. }
  834. } catch (error) {
  835. console.error('Error stopping execution:', error);
  836. updateStatus('Error: Failed to stop execution');
  837. }
  838. });
  839. }
  840. // Move to Center button
  841. const centerButton = document.getElementById('centerButton');
  842. if (centerButton) {
  843. centerButton.addEventListener('click', async () => {
  844. try {
  845. const response = await fetch('/move_to_center', {
  846. method: 'POST',
  847. headers: {
  848. 'Content-Type': 'application/json'
  849. }
  850. });
  851. const data = await response.json();
  852. if (data.success) {
  853. updateStatus('Moving to center position...');
  854. }
  855. } catch (error) {
  856. console.error('Error moving to center:', error);
  857. updateStatus('Error: Failed to move to center');
  858. }
  859. });
  860. }
  861. // Move to Perimeter button
  862. const perimeterButton = document.getElementById('perimeterButton');
  863. if (perimeterButton) {
  864. perimeterButton.addEventListener('click', async () => {
  865. try {
  866. const response = await fetch('/move_to_perimeter', {
  867. method: 'POST',
  868. headers: {
  869. 'Content-Type': 'application/json'
  870. }
  871. });
  872. const data = await response.json();
  873. if (data.success) {
  874. updateStatus('Moving to perimeter position...');
  875. }
  876. } catch (error) {
  877. console.error('Error moving to perimeter:', error);
  878. updateStatus('Error: Failed to move to perimeter');
  879. }
  880. });
  881. }
  882. });
  883. // Function to update status
  884. function updateStatus(message) {
  885. const statusElement = document.querySelector('.text-slate-800.text-base.font-medium.leading-normal');
  886. if (statusElement) {
  887. statusElement.textContent = message;
  888. // Reset status after 3 seconds if it's a temporary message
  889. if (message.includes('Moving') || message.includes('Execution')) {
  890. setTimeout(() => {
  891. statusElement.textContent = 'Status';
  892. }, 3000);
  893. }
  894. }
  895. }
  896. // Function to show status messages (using existing base.js showStatusMessage if available)
  897. function showStatusMessage(message, type) {
  898. if (typeof window.showStatusMessage === 'function') {
  899. window.showStatusMessage(message, type);
  900. } else {
  901. // Fallback to console logging
  902. console.log(`[${type}] ${message}`);
  903. }
  904. }
  905. // Function to show update instructions modal
  906. function showUpdateInstructionsModal(data) {
  907. // Create modal HTML
  908. const modal = document.createElement('div');
  909. modal.id = 'updateInstructionsModal';
  910. modal.className = 'fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4';
  911. modal.innerHTML = `
  912. <div class="bg-white dark:bg-gray-800 rounded-lg shadow-xl w-full max-w-md">
  913. <div class="p-6">
  914. <div class="text-center mb-4">
  915. <h2 class="text-xl font-semibold text-gray-800 dark:text-gray-200 mb-2">Manual Update Required</h2>
  916. <p class="text-gray-600 dark:text-gray-400 text-sm">
  917. ${data.message}
  918. </p>
  919. </div>
  920. <div class="text-gray-700 dark:text-gray-300 text-sm mb-6">
  921. <p class="mb-3">${data.instructions}</p>
  922. </div>
  923. <div class="flex gap-3 justify-center">
  924. <button id="openGitHubRelease" class="px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-lg transition-colors">
  925. View Update Instructions
  926. </button>
  927. <button id="closeUpdateModal" class="px-4 py-2 bg-gray-600 hover:bg-gray-700 text-white rounded-lg transition-colors">
  928. Close
  929. </button>
  930. </div>
  931. </div>
  932. </div>
  933. `;
  934. document.body.appendChild(modal);
  935. // Add event listeners
  936. const openGitHubButton = modal.querySelector('#openGitHubRelease');
  937. const closeButton = modal.querySelector('#closeUpdateModal');
  938. openGitHubButton.addEventListener('click', () => {
  939. window.open(data.manual_update_url, '_blank');
  940. document.body.removeChild(modal);
  941. });
  942. closeButton.addEventListener('click', () => {
  943. document.body.removeChild(modal);
  944. });
  945. // Close on outside click
  946. modal.addEventListener('click', (e) => {
  947. if (e.target === modal) {
  948. document.body.removeChild(modal);
  949. }
  950. });
  951. }
  952. // Autocomplete functionality
  953. function initializeAutocomplete(inputId, suggestionsId, clearButtonId, patterns) {
  954. const input = document.getElementById(inputId);
  955. const suggestionsDiv = document.getElementById(suggestionsId);
  956. const clearButton = document.getElementById(clearButtonId);
  957. let selectedIndex = -1;
  958. if (!input || !suggestionsDiv) return;
  959. // Function to update clear button visibility
  960. function updateClearButton() {
  961. if (clearButton) {
  962. if (input.value.trim()) {
  963. clearButton.classList.remove('hidden');
  964. } else {
  965. clearButton.classList.add('hidden');
  966. }
  967. }
  968. }
  969. // Format pattern name for display
  970. function formatPatternName(pattern) {
  971. return pattern.replace('.thr', '').replace(/_/g, ' ');
  972. }
  973. // Filter patterns based on input
  974. function filterPatterns(searchTerm) {
  975. if (!searchTerm) return patterns.slice(0, 20); // Show first 20 when empty
  976. const term = searchTerm.toLowerCase();
  977. return patterns.filter(pattern => {
  978. const name = pattern.toLowerCase();
  979. return name.includes(term);
  980. }).sort((a, b) => {
  981. // Prioritize patterns that start with the search term
  982. const aStarts = a.toLowerCase().startsWith(term);
  983. const bStarts = b.toLowerCase().startsWith(term);
  984. if (aStarts && !bStarts) return -1;
  985. if (!aStarts && bStarts) return 1;
  986. return a.localeCompare(b);
  987. }).slice(0, 20); // Limit to 20 results
  988. }
  989. // Highlight matching text
  990. function highlightMatch(text, searchTerm) {
  991. if (!searchTerm) return text;
  992. const regex = new RegExp(`(${searchTerm.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')})`, 'gi');
  993. return text.replace(regex, '<mark>$1</mark>');
  994. }
  995. // Show suggestions
  996. function showSuggestions(searchTerm) {
  997. const filtered = filterPatterns(searchTerm);
  998. if (filtered.length === 0 && searchTerm) {
  999. suggestionsDiv.innerHTML = '<div class="suggestion-item" style="cursor: default; color: #9ca3af;">No patterns found</div>';
  1000. suggestionsDiv.classList.remove('hidden');
  1001. return;
  1002. }
  1003. suggestionsDiv.innerHTML = filtered.map((pattern, index) => {
  1004. const displayName = formatPatternName(pattern);
  1005. const highlighted = highlightMatch(displayName, searchTerm);
  1006. return `<div class="suggestion-item" data-value="${pattern}" data-index="${index}">${highlighted}</div>`;
  1007. }).join('');
  1008. suggestionsDiv.classList.remove('hidden');
  1009. selectedIndex = -1;
  1010. }
  1011. // Hide suggestions
  1012. function hideSuggestions() {
  1013. setTimeout(() => {
  1014. suggestionsDiv.classList.add('hidden');
  1015. selectedIndex = -1;
  1016. }, 200);
  1017. }
  1018. // Select suggestion
  1019. function selectSuggestion(value) {
  1020. input.value = value;
  1021. hideSuggestions();
  1022. updateClearButton();
  1023. }
  1024. // Handle keyboard navigation
  1025. function handleKeyboard(e) {
  1026. const items = suggestionsDiv.querySelectorAll('.suggestion-item[data-value]');
  1027. if (e.key === 'ArrowDown') {
  1028. e.preventDefault();
  1029. selectedIndex = Math.min(selectedIndex + 1, items.length - 1);
  1030. updateSelection(items);
  1031. } else if (e.key === 'ArrowUp') {
  1032. e.preventDefault();
  1033. selectedIndex = Math.max(selectedIndex - 1, -1);
  1034. updateSelection(items);
  1035. } else if (e.key === 'Enter') {
  1036. e.preventDefault();
  1037. if (selectedIndex >= 0 && items[selectedIndex]) {
  1038. selectSuggestion(items[selectedIndex].dataset.value);
  1039. } else if (items.length === 1) {
  1040. selectSuggestion(items[0].dataset.value);
  1041. }
  1042. } else if (e.key === 'Escape') {
  1043. hideSuggestions();
  1044. }
  1045. }
  1046. // Update visual selection
  1047. function updateSelection(items) {
  1048. items.forEach((item, index) => {
  1049. if (index === selectedIndex) {
  1050. item.classList.add('selected');
  1051. item.scrollIntoView({ block: 'nearest' });
  1052. } else {
  1053. item.classList.remove('selected');
  1054. }
  1055. });
  1056. }
  1057. // Event listeners
  1058. input.addEventListener('input', (e) => {
  1059. const value = e.target.value.trim();
  1060. updateClearButton();
  1061. if (value.length > 0 || e.target === document.activeElement) {
  1062. showSuggestions(value);
  1063. } else {
  1064. hideSuggestions();
  1065. }
  1066. });
  1067. input.addEventListener('focus', () => {
  1068. const value = input.value.trim();
  1069. showSuggestions(value);
  1070. });
  1071. input.addEventListener('blur', hideSuggestions);
  1072. input.addEventListener('keydown', handleKeyboard);
  1073. // Click handler for suggestions
  1074. suggestionsDiv.addEventListener('click', (e) => {
  1075. const item = e.target.closest('.suggestion-item[data-value]');
  1076. if (item) {
  1077. selectSuggestion(item.dataset.value);
  1078. }
  1079. });
  1080. // Mouse hover handler
  1081. suggestionsDiv.addEventListener('mouseover', (e) => {
  1082. const item = e.target.closest('.suggestion-item[data-value]');
  1083. if (item) {
  1084. selectedIndex = parseInt(item.dataset.index);
  1085. const items = suggestionsDiv.querySelectorAll('.suggestion-item[data-value]');
  1086. updateSelection(items);
  1087. }
  1088. });
  1089. // Clear button handler
  1090. if (clearButton) {
  1091. clearButton.addEventListener('click', () => {
  1092. input.value = '';
  1093. updateClearButton();
  1094. hideSuggestions();
  1095. input.focus();
  1096. });
  1097. }
  1098. // Initialize clear button visibility
  1099. updateClearButton();
  1100. }
  1101. // auto_play Mode Functions
  1102. async function initializeauto_playMode() {
  1103. const auto_playToggle = document.getElementById('auto_playModeToggle');
  1104. const auto_playSettings = document.getElementById('auto_playSettings');
  1105. const auto_playPlaylistSelect = document.getElementById('auto_playPlaylistSelect');
  1106. const auto_playRunModeSelect = document.getElementById('auto_playRunModeSelect');
  1107. const auto_playPauseTimeInput = document.getElementById('auto_playPauseTimeInput');
  1108. const auto_playClearPatternSelect = document.getElementById('auto_playClearPatternSelect');
  1109. const auto_playShuffleToggle = document.getElementById('auto_playShuffleToggle');
  1110. // Load current auto_play settings
  1111. try {
  1112. const response = await fetch('/api/auto_play-mode');
  1113. const data = await response.json();
  1114. auto_playToggle.checked = data.enabled;
  1115. if (data.enabled) {
  1116. auto_playSettings.style.display = 'block';
  1117. }
  1118. // Set current values
  1119. auto_playRunModeSelect.value = data.run_mode || 'loop';
  1120. auto_playPauseTimeInput.value = data.pause_time || 5.0;
  1121. auto_playClearPatternSelect.value = data.clear_pattern || 'adaptive';
  1122. auto_playShuffleToggle.checked = data.shuffle || false;
  1123. // Load playlists for selection
  1124. const playlistsResponse = await fetch('/list_all_playlists');
  1125. const playlists = await playlistsResponse.json();
  1126. // Clear and populate playlist select
  1127. auto_playPlaylistSelect.innerHTML = '<option value="">Select a playlist...</option>';
  1128. playlists.forEach(playlist => {
  1129. const option = document.createElement('option');
  1130. option.value = playlist;
  1131. option.textContent = playlist;
  1132. if (playlist === data.playlist) {
  1133. option.selected = true;
  1134. }
  1135. auto_playPlaylistSelect.appendChild(option);
  1136. });
  1137. } catch (error) {
  1138. logMessage(`Error loading auto_play settings: ${error.message}`, LOG_TYPE.ERROR);
  1139. }
  1140. // Function to save settings
  1141. async function saveSettings() {
  1142. try {
  1143. const response = await fetch('/api/auto_play-mode', {
  1144. method: 'POST',
  1145. headers: { 'Content-Type': 'application/json' },
  1146. body: JSON.stringify({
  1147. enabled: auto_playToggle.checked,
  1148. playlist: auto_playPlaylistSelect.value || null,
  1149. run_mode: auto_playRunModeSelect.value,
  1150. pause_time: parseFloat(auto_playPauseTimeInput.value) || 0,
  1151. clear_pattern: auto_playClearPatternSelect.value,
  1152. shuffle: auto_playShuffleToggle.checked
  1153. })
  1154. });
  1155. if (!response.ok) {
  1156. throw new Error('Failed to save settings');
  1157. }
  1158. } catch (error) {
  1159. logMessage(`Error saving auto_play settings: ${error.message}`, LOG_TYPE.ERROR);
  1160. }
  1161. }
  1162. // Toggle auto_play settings visibility and save
  1163. auto_playToggle.addEventListener('change', async () => {
  1164. auto_playSettings.style.display = auto_playToggle.checked ? 'block' : 'none';
  1165. await saveSettings();
  1166. });
  1167. // Save when any setting changes
  1168. auto_playPlaylistSelect.addEventListener('change', saveSettings);
  1169. auto_playRunModeSelect.addEventListener('change', saveSettings);
  1170. auto_playPauseTimeInput.addEventListener('change', saveSettings);
  1171. auto_playPauseTimeInput.addEventListener('input', saveSettings); // Save as user types
  1172. auto_playClearPatternSelect.addEventListener('change', saveSettings);
  1173. auto_playShuffleToggle.addEventListener('change', saveSettings);
  1174. }
  1175. // Initialize auto_play mode when DOM is ready
  1176. document.addEventListener('DOMContentLoaded', function() {
  1177. initializeauto_playMode();
  1178. initializeStillSandsMode();
  1179. initializeHomingConfig();
  1180. });
  1181. // Still Sands Mode Functions
  1182. async function initializeStillSandsMode() {
  1183. logMessage('Initializing Still Sands mode', LOG_TYPE.INFO);
  1184. const stillSandsToggle = document.getElementById('scheduledPauseToggle');
  1185. const stillSandsSettings = document.getElementById('scheduledPauseSettings');
  1186. const addTimeSlotButton = document.getElementById('addTimeSlotButton');
  1187. const saveStillSandsButton = document.getElementById('savePauseSettings');
  1188. const timeSlotsContainer = document.getElementById('timeSlotsContainer');
  1189. const wledControlToggle = document.getElementById('stillSandsWledControl');
  1190. const finishPatternToggle = document.getElementById('stillSandsFinishPattern');
  1191. // Check if elements exist
  1192. if (!stillSandsToggle || !stillSandsSettings || !addTimeSlotButton || !saveStillSandsButton || !timeSlotsContainer) {
  1193. logMessage('Still Sands elements not found, skipping initialization', LOG_TYPE.WARNING);
  1194. logMessage(`Found elements: toggle=${!!stillSandsToggle}, settings=${!!stillSandsSettings}, addBtn=${!!addTimeSlotButton}, saveBtn=${!!saveStillSandsButton}, container=${!!timeSlotsContainer}`, LOG_TYPE.WARNING);
  1195. return;
  1196. }
  1197. logMessage('All Still Sands elements found successfully', LOG_TYPE.INFO);
  1198. // Track time slots
  1199. let timeSlots = [];
  1200. let slotIdCounter = 0;
  1201. // Load current Still Sands settings from initial data
  1202. try {
  1203. // Use the data loaded during page initialization, fallback to API if not available
  1204. let data;
  1205. if (window.initialStillSandsData) {
  1206. data = window.initialStillSandsData;
  1207. // Clear the global variable after use
  1208. delete window.initialStillSandsData;
  1209. } else {
  1210. // Fallback to API call if initial data not available
  1211. const response = await fetch('/api/scheduled-pause');
  1212. data = await response.json();
  1213. }
  1214. stillSandsToggle.checked = data.enabled || false;
  1215. if (data.enabled) {
  1216. stillSandsSettings.style.display = 'block';
  1217. }
  1218. // Load WLED control setting
  1219. if (wledControlToggle) {
  1220. wledControlToggle.checked = data.control_wled || false;
  1221. }
  1222. // Load finish pattern setting
  1223. if (finishPatternToggle) {
  1224. finishPatternToggle.checked = data.finish_pattern || false;
  1225. }
  1226. // Load existing time slots
  1227. timeSlots = data.time_slots || [];
  1228. // Assign IDs to loaded slots BEFORE rendering
  1229. if (timeSlots.length > 0) {
  1230. slotIdCounter = 0;
  1231. timeSlots.forEach(slot => {
  1232. slot.id = ++slotIdCounter;
  1233. });
  1234. }
  1235. renderTimeSlots();
  1236. } catch (error) {
  1237. logMessage(`Error loading Still Sands settings: ${error.message}`, LOG_TYPE.ERROR);
  1238. // Initialize with empty settings if load fails
  1239. timeSlots = [];
  1240. renderTimeSlots();
  1241. }
  1242. // Function to validate time format (HH:MM)
  1243. function isValidTime(timeString) {
  1244. const timeRegex = /^([01]?[0-9]|2[0-3]):[0-5][0-9]$/;
  1245. return timeRegex.test(timeString);
  1246. }
  1247. // Function to create a new time slot element
  1248. function createTimeSlotElement(slot) {
  1249. const slotDiv = document.createElement('div');
  1250. slotDiv.className = 'time-slot-item';
  1251. slotDiv.dataset.slotId = slot.id;
  1252. slotDiv.innerHTML = `
  1253. <div class="flex items-center gap-3">
  1254. <div class="flex-1 grid grid-cols-1 md:grid-cols-2 gap-3">
  1255. <div class="flex flex-col gap-1">
  1256. <label class="text-slate-700 dark:text-slate-300 text-xs font-medium">Start Time</label>
  1257. <input
  1258. type="time"
  1259. class="start-time form-input resize-none overflow-hidden rounded-lg text-slate-900 focus:outline-0 focus:ring-2 focus:ring-sky-500 border border-slate-300 bg-white focus:border-sky-500 h-9 px-3 text-sm font-normal leading-normal transition-colors"
  1260. value="${slot.start_time || ''}"
  1261. required
  1262. />
  1263. </div>
  1264. <div class="flex flex-col gap-1">
  1265. <label class="text-slate-700 dark:text-slate-300 text-xs font-medium">End Time</label>
  1266. <input
  1267. type="time"
  1268. class="end-time form-input resize-none overflow-hidden rounded-lg text-slate-900 focus:outline-0 focus:ring-2 focus:ring-sky-500 border border-slate-300 bg-white focus:border-sky-500 h-9 px-3 text-sm font-normal leading-normal transition-colors"
  1269. value="${slot.end_time || ''}"
  1270. required
  1271. />
  1272. </div>
  1273. </div>
  1274. <div class="flex flex-col gap-1">
  1275. <label class="text-slate-700 dark:text-slate-300 text-xs font-medium">Days</label>
  1276. <select class="days-select form-select resize-none overflow-hidden rounded-lg text-slate-900 focus:outline-0 focus:ring-2 focus:ring-sky-500 border border-slate-300 bg-white focus:border-sky-500 h-9 px-3 text-sm font-normal transition-colors">
  1277. <option value="daily" ${slot.days === 'daily' ? 'selected' : ''}>Daily</option>
  1278. <option value="weekdays" ${slot.days === 'weekdays' ? 'selected' : ''}>Weekdays</option>
  1279. <option value="weekends" ${slot.days === 'weekends' ? 'selected' : ''}>Weekends</option>
  1280. <option value="custom" ${slot.days === 'custom' ? 'selected' : ''}>Custom</option>
  1281. </select>
  1282. </div>
  1283. <button
  1284. type="button"
  1285. class="remove-slot-btn flex items-center justify-center w-9 h-9 text-red-600 hover:text-red-700 hover:bg-red-50 dark:hover:bg-red-900/20 rounded-lg transition-colors"
  1286. title="Remove time slot"
  1287. >
  1288. <span class="material-icons text-base">delete</span>
  1289. </button>
  1290. </div>
  1291. <div class="custom-days-container mt-2" style="display: ${slot.days === 'custom' ? 'block' : 'none'};">
  1292. <label class="text-slate-700 dark:text-slate-300 text-xs font-medium mb-1 block">Select Days</label>
  1293. <div class="flex flex-wrap gap-2">
  1294. ${['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday'].map(day => `
  1295. <label class="flex items-center gap-1 text-xs">
  1296. <input
  1297. type="checkbox"
  1298. name="custom-days-${slot.id}"
  1299. value="${day}"
  1300. ${slot.custom_days && slot.custom_days.includes(day) ? 'checked' : ''}
  1301. class="rounded border-slate-300 text-sky-600 focus:ring-sky-500"
  1302. />
  1303. <span class="text-slate-700 dark:text-slate-300 capitalize">${day.substring(0, 3)}</span>
  1304. </label>
  1305. `).join('')}
  1306. </div>
  1307. </div>
  1308. `;
  1309. // Add event listeners for this slot
  1310. const startTimeInput = slotDiv.querySelector('.start-time');
  1311. const endTimeInput = slotDiv.querySelector('.end-time');
  1312. const daysSelect = slotDiv.querySelector('.days-select');
  1313. const customDaysContainer = slotDiv.querySelector('.custom-days-container');
  1314. const removeButton = slotDiv.querySelector('.remove-slot-btn');
  1315. // Show/hide custom days based on selection
  1316. daysSelect.addEventListener('change', () => {
  1317. customDaysContainer.style.display = daysSelect.value === 'custom' ? 'block' : 'none';
  1318. updateTimeSlot(slot.id);
  1319. });
  1320. // Update slot data when inputs change
  1321. startTimeInput.addEventListener('change', () => updateTimeSlot(slot.id));
  1322. endTimeInput.addEventListener('change', () => updateTimeSlot(slot.id));
  1323. // Handle custom day checkboxes
  1324. customDaysContainer.addEventListener('change', () => updateTimeSlot(slot.id));
  1325. // Remove slot button
  1326. removeButton.addEventListener('click', () => {
  1327. removeTimeSlot(slot.id);
  1328. });
  1329. return slotDiv;
  1330. }
  1331. // Function to render all time slots
  1332. function renderTimeSlots() {
  1333. timeSlotsContainer.innerHTML = '';
  1334. if (timeSlots.length === 0) {
  1335. timeSlotsContainer.innerHTML = `
  1336. <div class="text-center py-8 text-slate-500 dark:text-slate-400">
  1337. <span class="material-icons text-4xl mb-2 block">schedule</span>
  1338. <p>No time slots configured</p>
  1339. <p class="text-xs mt-1">Click "Add Time Slot" to create a pause schedule</p>
  1340. </div>
  1341. `;
  1342. return;
  1343. }
  1344. timeSlots.forEach(slot => {
  1345. const slotElement = createTimeSlotElement(slot);
  1346. timeSlotsContainer.appendChild(slotElement);
  1347. });
  1348. }
  1349. // Function to add a new time slot
  1350. function addTimeSlot() {
  1351. const newSlot = {
  1352. id: ++slotIdCounter,
  1353. start_time: '22:00',
  1354. end_time: '08:00',
  1355. days: 'daily',
  1356. custom_days: []
  1357. };
  1358. timeSlots.push(newSlot);
  1359. renderTimeSlots();
  1360. }
  1361. // Function to remove a time slot
  1362. function removeTimeSlot(slotId) {
  1363. timeSlots = timeSlots.filter(slot => slot.id !== slotId);
  1364. renderTimeSlots();
  1365. }
  1366. // Function to update a time slot's data
  1367. function updateTimeSlot(slotId) {
  1368. const slotElement = timeSlotsContainer.querySelector(`[data-slot-id="${slotId}"]`);
  1369. if (!slotElement) return;
  1370. const slot = timeSlots.find(s => s.id === slotId);
  1371. if (!slot) return;
  1372. // Update slot data from inputs
  1373. slot.start_time = slotElement.querySelector('.start-time').value;
  1374. slot.end_time = slotElement.querySelector('.end-time').value;
  1375. slot.days = slotElement.querySelector('.days-select').value;
  1376. // Update custom days if applicable
  1377. if (slot.days === 'custom') {
  1378. const checkedDays = Array.from(slotElement.querySelectorAll(`input[name="custom-days-${slotId}"]:checked`))
  1379. .map(cb => cb.value);
  1380. slot.custom_days = checkedDays;
  1381. } else {
  1382. slot.custom_days = [];
  1383. }
  1384. }
  1385. // Function to validate all time slots
  1386. function validateTimeSlots() {
  1387. const errors = [];
  1388. timeSlots.forEach((slot, index) => {
  1389. if (!slot.start_time || !isValidTime(slot.start_time)) {
  1390. errors.push(`Time slot ${index + 1}: Invalid start time`);
  1391. }
  1392. if (!slot.end_time || !isValidTime(slot.end_time)) {
  1393. errors.push(`Time slot ${index + 1}: Invalid end time`);
  1394. }
  1395. if (slot.days === 'custom' && (!slot.custom_days || slot.custom_days.length === 0)) {
  1396. errors.push(`Time slot ${index + 1}: Please select at least one day for custom schedule`);
  1397. }
  1398. });
  1399. return errors;
  1400. }
  1401. // Function to save settings
  1402. async function saveStillSandsSettings() {
  1403. // Update all slots from current form values
  1404. timeSlots.forEach(slot => updateTimeSlot(slot.id));
  1405. // Validate time slots
  1406. const validationErrors = validateTimeSlots();
  1407. if (validationErrors.length > 0) {
  1408. showStatusMessage(`Validation errors: ${validationErrors.join(', ')}`, 'error');
  1409. return;
  1410. }
  1411. // Update button UI to show loading state
  1412. const originalButtonHTML = saveStillSandsButton.innerHTML;
  1413. saveStillSandsButton.disabled = true;
  1414. saveStillSandsButton.innerHTML = '<span class="material-icons text-lg animate-spin">refresh</span><span class="truncate">Saving...</span>';
  1415. try {
  1416. const response = await fetch('/api/scheduled-pause', {
  1417. method: 'POST',
  1418. headers: { 'Content-Type': 'application/json' },
  1419. body: JSON.stringify({
  1420. enabled: stillSandsToggle.checked,
  1421. control_wled: wledControlToggle ? wledControlToggle.checked : false,
  1422. finish_pattern: finishPatternToggle ? finishPatternToggle.checked : false,
  1423. time_slots: timeSlots.map(slot => ({
  1424. start_time: slot.start_time,
  1425. end_time: slot.end_time,
  1426. days: slot.days,
  1427. custom_days: slot.custom_days
  1428. }))
  1429. })
  1430. });
  1431. if (!response.ok) {
  1432. const errorData = await response.json();
  1433. throw new Error(errorData.detail || 'Failed to save Still Sands settings');
  1434. }
  1435. // Show success state temporarily
  1436. saveStillSandsButton.innerHTML = '<span class="material-icons text-lg">check</span><span class="truncate">Saved!</span>';
  1437. showStatusMessage('Still Sands settings saved successfully', 'success');
  1438. // Restore button after 2 seconds
  1439. setTimeout(() => {
  1440. saveStillSandsButton.innerHTML = originalButtonHTML;
  1441. saveStillSandsButton.disabled = false;
  1442. }, 2000);
  1443. } catch (error) {
  1444. logMessage(`Error saving Still Sands settings: ${error.message}`, LOG_TYPE.ERROR);
  1445. showStatusMessage(`Failed to save settings: ${error.message}`, 'error');
  1446. // Restore button immediately on error
  1447. saveStillSandsButton.innerHTML = originalButtonHTML;
  1448. saveStillSandsButton.disabled = false;
  1449. }
  1450. }
  1451. // Note: Slot IDs are now assigned during initialization above, before first render
  1452. // Event listeners
  1453. stillSandsToggle.addEventListener('change', async () => {
  1454. logMessage(`Still Sands toggle changed: ${stillSandsToggle.checked}`, LOG_TYPE.INFO);
  1455. stillSandsSettings.style.display = stillSandsToggle.checked ? 'block' : 'none';
  1456. logMessage(`Settings display set to: ${stillSandsSettings.style.display}`, LOG_TYPE.INFO);
  1457. // Auto-save when toggle changes
  1458. try {
  1459. await saveStillSandsSettings();
  1460. const statusText = stillSandsToggle.checked ? 'enabled' : 'disabled';
  1461. showStatusMessage(`Still Sands ${statusText} successfully`, 'success');
  1462. } catch (error) {
  1463. logMessage(`Error saving Still Sands toggle: ${error.message}`, LOG_TYPE.ERROR);
  1464. showStatusMessage(`Failed to save Still Sands setting: ${error.message}`, 'error');
  1465. }
  1466. });
  1467. addTimeSlotButton.addEventListener('click', addTimeSlot);
  1468. saveStillSandsButton.addEventListener('click', saveStillSandsSettings);
  1469. // Add listener for WLED control toggle
  1470. if (wledControlToggle) {
  1471. wledControlToggle.addEventListener('change', async () => {
  1472. logMessage(`WLED control toggle changed: ${wledControlToggle.checked}`, LOG_TYPE.INFO);
  1473. // Auto-save when WLED control changes
  1474. await saveStillSandsSettings();
  1475. });
  1476. }
  1477. // Add listener for finish pattern toggle
  1478. if (finishPatternToggle) {
  1479. finishPatternToggle.addEventListener('change', async () => {
  1480. logMessage(`Finish pattern toggle changed: ${finishPatternToggle.checked}`, LOG_TYPE.INFO);
  1481. // Auto-save when finish pattern setting changes
  1482. await saveStillSandsSettings();
  1483. });
  1484. }
  1485. }
  1486. // Homing Configuration
  1487. async function initializeHomingConfig() {
  1488. logMessage('Initializing homing configuration', LOG_TYPE.INFO);
  1489. const homingModeCrash = document.getElementById('homingModeCrash');
  1490. const homingModeSensor = document.getElementById('homingModeSensor');
  1491. const angularOffsetInput = document.getElementById('angularOffsetInput');
  1492. const compassOffsetContainer = document.getElementById('compassOffsetContainer');
  1493. const saveHomingConfigButton = document.getElementById('saveHomingConfig');
  1494. const homingInfoContent = document.getElementById('homingInfoContent');
  1495. const autoHomeEnabledToggle = document.getElementById('autoHomeEnabledToggle');
  1496. const autoHomeSettings = document.getElementById('autoHomeSettings');
  1497. const autoHomeAfterPatternsInput = document.getElementById('autoHomeAfterPatternsInput');
  1498. // Check if elements exist
  1499. if (!homingModeCrash || !homingModeSensor || !angularOffsetInput || !saveHomingConfigButton || !homingInfoContent || !compassOffsetContainer) {
  1500. logMessage('Homing configuration elements not found, skipping initialization', LOG_TYPE.WARNING);
  1501. return;
  1502. }
  1503. logMessage('Homing configuration elements found successfully', LOG_TYPE.INFO);
  1504. // Function to get selected homing mode
  1505. function getSelectedMode() {
  1506. return homingModeCrash.checked ? 0 : 1;
  1507. }
  1508. // Function to update info box and visibility based on selected mode
  1509. function updateHomingInfo() {
  1510. const mode = getSelectedMode();
  1511. // Show/hide compass offset based on mode
  1512. if (mode === 0) {
  1513. compassOffsetContainer.style.display = 'none';
  1514. homingInfoContent.innerHTML = `
  1515. <p class="font-medium text-blue-800">Crash Homing Mode:</p>
  1516. <ul class="mt-1 space-y-1 text-blue-700">
  1517. <li>• Y axis moves -22mm (or -30mm for mini) until physical stop</li>
  1518. <li>• Theta set to 0, rho set to 0</li>
  1519. <li>• No x0 y0 command sent</li>
  1520. <li>• No hardware sensors required</li>
  1521. </ul>
  1522. `;
  1523. } else {
  1524. compassOffsetContainer.style.display = 'block';
  1525. homingInfoContent.innerHTML = `
  1526. <p class="font-medium text-blue-800">Sensor Homing Mode:</p>
  1527. <ul class="mt-1 space-y-1 text-blue-700">
  1528. <li>• Requires hardware limit switches</li>
  1529. <li>• Requires additional configuration</li>
  1530. </ul>
  1531. `;
  1532. }
  1533. }
  1534. // Load current homing configuration
  1535. try {
  1536. const response = await fetch('/api/homing-config');
  1537. const data = await response.json();
  1538. // Set radio button based on mode
  1539. if (data.homing_mode === 1) {
  1540. homingModeSensor.checked = true;
  1541. } else {
  1542. homingModeCrash.checked = true;
  1543. }
  1544. angularOffsetInput.value = data.angular_homing_offset_degrees || 0;
  1545. // Load auto-home settings
  1546. if (autoHomeEnabledToggle) {
  1547. autoHomeEnabledToggle.checked = data.auto_home_enabled || false;
  1548. if (autoHomeSettings) {
  1549. autoHomeSettings.style.display = data.auto_home_enabled ? 'block' : 'none';
  1550. }
  1551. }
  1552. if (autoHomeAfterPatternsInput) {
  1553. autoHomeAfterPatternsInput.value = data.auto_home_after_patterns || 5;
  1554. }
  1555. updateHomingInfo();
  1556. logMessage(`Loaded homing config: mode=${data.homing_mode}, offset=${data.angular_homing_offset_degrees}°, auto_home=${data.auto_home_enabled}, after=${data.auto_home_after_patterns}`, LOG_TYPE.INFO);
  1557. } catch (error) {
  1558. logMessage(`Error loading homing configuration: ${error.message}`, LOG_TYPE.ERROR);
  1559. // Initialize with defaults if load fails
  1560. homingModeCrash.checked = true;
  1561. angularOffsetInput.value = 0;
  1562. if (autoHomeEnabledToggle) autoHomeEnabledToggle.checked = false;
  1563. if (autoHomeAfterPatternsInput) autoHomeAfterPatternsInput.value = 5;
  1564. updateHomingInfo();
  1565. }
  1566. // Function to save homing configuration
  1567. async function saveHomingConfig() {
  1568. // Update button UI to show loading state
  1569. const originalButtonHTML = saveHomingConfigButton.innerHTML;
  1570. saveHomingConfigButton.disabled = true;
  1571. saveHomingConfigButton.innerHTML = '<span class="material-icons text-lg animate-spin">refresh</span><span class="truncate">Saving...</span>';
  1572. try {
  1573. const requestBody = {
  1574. homing_mode: getSelectedMode(),
  1575. angular_homing_offset_degrees: parseFloat(angularOffsetInput.value) || 0
  1576. };
  1577. // Include auto-home settings if elements exist
  1578. if (autoHomeEnabledToggle) {
  1579. requestBody.auto_home_enabled = autoHomeEnabledToggle.checked;
  1580. }
  1581. if (autoHomeAfterPatternsInput) {
  1582. const afterPatterns = parseInt(autoHomeAfterPatternsInput.value);
  1583. if (!isNaN(afterPatterns) && afterPatterns >= 1) {
  1584. requestBody.auto_home_after_patterns = afterPatterns;
  1585. }
  1586. }
  1587. const response = await fetch('/api/homing-config', {
  1588. method: 'POST',
  1589. headers: { 'Content-Type': 'application/json' },
  1590. body: JSON.stringify(requestBody)
  1591. });
  1592. if (!response.ok) {
  1593. const errorData = await response.json();
  1594. throw new Error(errorData.detail || 'Failed to save homing configuration');
  1595. }
  1596. // Show success state temporarily
  1597. saveHomingConfigButton.innerHTML = '<span class="material-icons text-lg">check</span><span class="truncate">Saved!</span>';
  1598. showStatusMessage('Homing configuration saved successfully', 'success');
  1599. // Restore button after 2 seconds
  1600. setTimeout(() => {
  1601. saveHomingConfigButton.innerHTML = originalButtonHTML;
  1602. saveHomingConfigButton.disabled = false;
  1603. }, 2000);
  1604. } catch (error) {
  1605. logMessage(`Error saving homing configuration: ${error.message}`, LOG_TYPE.ERROR);
  1606. showStatusMessage(`Failed to save homing configuration: ${error.message}`, 'error');
  1607. // Restore button immediately on error
  1608. saveHomingConfigButton.innerHTML = originalButtonHTML;
  1609. saveHomingConfigButton.disabled = false;
  1610. }
  1611. }
  1612. // Event listeners
  1613. homingModeCrash.addEventListener('change', updateHomingInfo);
  1614. homingModeSensor.addEventListener('change', updateHomingInfo);
  1615. saveHomingConfigButton.addEventListener('click', saveHomingConfig);
  1616. // Auto-home toggle event listener
  1617. if (autoHomeEnabledToggle && autoHomeSettings) {
  1618. autoHomeEnabledToggle.addEventListener('change', () => {
  1619. autoHomeSettings.style.display = autoHomeEnabledToggle.checked ? 'block' : 'none';
  1620. });
  1621. }
  1622. }
  1623. // Toggle password visibility helper
  1624. function togglePasswordVisibility(inputId, button) {
  1625. const input = document.getElementById(inputId);
  1626. if (!input || !button) return;
  1627. const icon = button.querySelector('.material-icons');
  1628. if (input.type === 'password') {
  1629. input.type = 'text';
  1630. if (icon) icon.textContent = 'visibility';
  1631. } else {
  1632. input.type = 'password';
  1633. if (icon) icon.textContent = 'visibility_off';
  1634. }
  1635. }
  1636. // MQTT Configuration
  1637. async function initializeMqttConfig() {
  1638. logMessage('Initializing MQTT configuration', LOG_TYPE.INFO);
  1639. const mqttEnableToggle = document.getElementById('mqttEnableToggle');
  1640. const mqttSettings = document.getElementById('mqttSettings');
  1641. const mqttStatusBanner = document.getElementById('mqttStatusBanner');
  1642. const mqttConnectedBanner = document.getElementById('mqttConnectedBanner');
  1643. const mqttDisconnectedBanner = document.getElementById('mqttDisconnectedBanner');
  1644. const mqttBrokerInput = document.getElementById('mqttBrokerInput');
  1645. const mqttPortInput = document.getElementById('mqttPortInput');
  1646. const mqttUsernameInput = document.getElementById('mqttUsernameInput');
  1647. const mqttPasswordInput = document.getElementById('mqttPasswordInput');
  1648. const mqttDeviceNameInput = document.getElementById('mqttDeviceNameInput');
  1649. const mqttDeviceIdInput = document.getElementById('mqttDeviceIdInput');
  1650. const mqttClientIdInput = document.getElementById('mqttClientIdInput');
  1651. const mqttDiscoveryPrefixInput = document.getElementById('mqttDiscoveryPrefixInput');
  1652. const testMqttButton = document.getElementById('testMqttConnection');
  1653. const mqttTestResult = document.getElementById('mqttTestResult');
  1654. const saveMqttButton = document.getElementById('saveMqttConfig');
  1655. const mqttRestartNotice = document.getElementById('mqttRestartNotice');
  1656. // Check if elements exist
  1657. if (!mqttEnableToggle || !mqttSettings || !saveMqttButton) {
  1658. logMessage('MQTT configuration elements not found, skipping initialization', LOG_TYPE.WARNING);
  1659. return;
  1660. }
  1661. logMessage('MQTT configuration elements found successfully', LOG_TYPE.INFO);
  1662. // Track if settings have changed (to show restart notice)
  1663. let originalConfig = null;
  1664. let configChanged = false;
  1665. // Function to update UI based on enabled state
  1666. function updateMqttSettingsVisibility() {
  1667. mqttSettings.style.display = mqttEnableToggle.checked ? 'block' : 'none';
  1668. if (mqttStatusBanner) {
  1669. mqttStatusBanner.classList.toggle('hidden', !mqttEnableToggle.checked);
  1670. }
  1671. }
  1672. // Function to update connection status banners
  1673. function updateConnectionStatus(connected) {
  1674. if (mqttConnectedBanner && mqttDisconnectedBanner) {
  1675. if (connected) {
  1676. mqttConnectedBanner.classList.remove('hidden');
  1677. mqttDisconnectedBanner.classList.add('hidden');
  1678. } else {
  1679. mqttConnectedBanner.classList.add('hidden');
  1680. mqttDisconnectedBanner.classList.remove('hidden');
  1681. }
  1682. }
  1683. }
  1684. // Function to check if config has changed
  1685. function checkConfigChanged() {
  1686. if (!originalConfig) return false;
  1687. const currentConfig = {
  1688. enabled: mqttEnableToggle.checked,
  1689. broker: mqttBrokerInput.value,
  1690. port: parseInt(mqttPortInput.value) || 1883,
  1691. username: mqttUsernameInput.value,
  1692. password: mqttPasswordInput.value,
  1693. device_name: mqttDeviceNameInput.value,
  1694. device_id: mqttDeviceIdInput.value,
  1695. client_id: mqttClientIdInput.value,
  1696. discovery_prefix: mqttDiscoveryPrefixInput.value
  1697. };
  1698. return JSON.stringify(currentConfig) !== JSON.stringify(originalConfig);
  1699. }
  1700. // Function to show/hide restart notice
  1701. function updateRestartNotice() {
  1702. configChanged = checkConfigChanged();
  1703. if (mqttRestartNotice) {
  1704. mqttRestartNotice.classList.toggle('hidden', !configChanged);
  1705. }
  1706. }
  1707. // Load current MQTT configuration
  1708. try {
  1709. const response = await fetch('/api/mqtt-config');
  1710. const data = await response.json();
  1711. mqttEnableToggle.checked = data.enabled || false;
  1712. mqttBrokerInput.value = data.broker || '';
  1713. mqttPortInput.value = data.port || 1883;
  1714. mqttUsernameInput.value = data.username || '';
  1715. // Note: Password is not returned from API for security
  1716. mqttDeviceNameInput.value = data.device_name || 'Dune Weaver';
  1717. mqttDeviceIdInput.value = data.device_id || 'dune_weaver';
  1718. mqttClientIdInput.value = data.client_id || 'dune_weaver';
  1719. mqttDiscoveryPrefixInput.value = data.discovery_prefix || 'homeassistant';
  1720. // Store original config for change detection
  1721. originalConfig = {
  1722. enabled: data.enabled || false,
  1723. broker: data.broker || '',
  1724. port: data.port || 1883,
  1725. username: data.username || '',
  1726. password: '', // We don't have the original password
  1727. device_name: data.device_name || 'Dune Weaver',
  1728. device_id: data.device_id || 'dune_weaver',
  1729. client_id: data.client_id || 'dune_weaver',
  1730. discovery_prefix: data.discovery_prefix || 'homeassistant'
  1731. };
  1732. updateMqttSettingsVisibility();
  1733. // Update connection status if MQTT is enabled
  1734. if (data.enabled) {
  1735. updateConnectionStatus(data.connected || false);
  1736. }
  1737. logMessage(`Loaded MQTT config: enabled=${data.enabled}, broker=${data.broker}`, LOG_TYPE.INFO);
  1738. } catch (error) {
  1739. logMessage(`Error loading MQTT configuration: ${error.message}`, LOG_TYPE.ERROR);
  1740. // Initialize with defaults if load fails
  1741. mqttEnableToggle.checked = false;
  1742. updateMqttSettingsVisibility();
  1743. }
  1744. // Function to save MQTT configuration
  1745. async function saveMqttConfig() {
  1746. // Validate required fields if MQTT is enabled
  1747. if (mqttEnableToggle.checked && !mqttBrokerInput.value.trim()) {
  1748. showStatusMessage('MQTT broker address is required when MQTT is enabled', 'error');
  1749. mqttBrokerInput.focus();
  1750. return;
  1751. }
  1752. // Update button UI to show loading state
  1753. const originalButtonHTML = saveMqttButton.innerHTML;
  1754. saveMqttButton.disabled = true;
  1755. saveMqttButton.innerHTML = '<span class="material-icons text-lg animate-spin">refresh</span><span class="truncate">Saving...</span>';
  1756. try {
  1757. const requestBody = {
  1758. enabled: mqttEnableToggle.checked,
  1759. broker: mqttBrokerInput.value.trim(),
  1760. port: parseInt(mqttPortInput.value) || 1883,
  1761. username: mqttUsernameInput.value.trim() || null,
  1762. device_name: mqttDeviceNameInput.value.trim() || 'Dune Weaver',
  1763. device_id: mqttDeviceIdInput.value.trim() || 'dune_weaver',
  1764. client_id: mqttClientIdInput.value.trim() || 'dune_weaver',
  1765. discovery_prefix: mqttDiscoveryPrefixInput.value.trim() || 'homeassistant'
  1766. };
  1767. // Only include password if it was changed (not empty)
  1768. if (mqttPasswordInput.value) {
  1769. requestBody.password = mqttPasswordInput.value;
  1770. }
  1771. const response = await fetch('/api/mqtt-config', {
  1772. method: 'POST',
  1773. headers: { 'Content-Type': 'application/json' },
  1774. body: JSON.stringify(requestBody)
  1775. });
  1776. if (!response.ok) {
  1777. const errorData = await response.json();
  1778. throw new Error(errorData.detail || 'Failed to save MQTT configuration');
  1779. }
  1780. const data = await response.json();
  1781. // Update original config for change detection
  1782. originalConfig = {
  1783. enabled: requestBody.enabled,
  1784. broker: requestBody.broker,
  1785. port: requestBody.port,
  1786. username: requestBody.username || '',
  1787. password: '', // Reset password tracking
  1788. device_name: requestBody.device_name,
  1789. device_id: requestBody.device_id,
  1790. client_id: requestBody.client_id,
  1791. discovery_prefix: requestBody.discovery_prefix
  1792. };
  1793. // Clear password field after save
  1794. mqttPasswordInput.value = '';
  1795. // Show success state temporarily
  1796. saveMqttButton.innerHTML = '<span class="material-icons text-lg">check</span><span class="truncate">Saved!</span>';
  1797. showStatusMessage('MQTT configuration saved successfully. Restart the application to apply changes.', 'success');
  1798. // Show restart notice
  1799. if (mqttRestartNotice) {
  1800. mqttRestartNotice.classList.remove('hidden');
  1801. }
  1802. // Restore button after 2 seconds
  1803. setTimeout(() => {
  1804. saveMqttButton.innerHTML = originalButtonHTML;
  1805. saveMqttButton.disabled = false;
  1806. }, 2000);
  1807. } catch (error) {
  1808. logMessage(`Error saving MQTT configuration: ${error.message}`, LOG_TYPE.ERROR);
  1809. showStatusMessage(`Failed to save MQTT configuration: ${error.message}`, 'error');
  1810. // Restore button immediately on error
  1811. saveMqttButton.innerHTML = originalButtonHTML;
  1812. saveMqttButton.disabled = false;
  1813. }
  1814. }
  1815. // Function to test MQTT connection
  1816. async function testMqttConnection() {
  1817. // Validate broker address
  1818. if (!mqttBrokerInput.value.trim()) {
  1819. showStatusMessage('Please enter a broker address to test', 'error');
  1820. mqttBrokerInput.focus();
  1821. return;
  1822. }
  1823. // Update button UI to show loading state
  1824. const originalButtonHTML = testMqttButton.innerHTML;
  1825. testMqttButton.disabled = true;
  1826. testMqttButton.innerHTML = '<span class="material-icons text-lg animate-spin">refresh</span><span class="truncate">Testing...</span>';
  1827. // Clear previous result
  1828. if (mqttTestResult) {
  1829. mqttTestResult.innerHTML = '';
  1830. }
  1831. try {
  1832. const requestBody = {
  1833. broker: mqttBrokerInput.value.trim(),
  1834. port: parseInt(mqttPortInput.value) || 1883,
  1835. username: mqttUsernameInput.value.trim() || null,
  1836. password: mqttPasswordInput.value || null
  1837. };
  1838. const response = await fetch('/api/mqtt-test', {
  1839. method: 'POST',
  1840. headers: { 'Content-Type': 'application/json' },
  1841. body: JSON.stringify(requestBody)
  1842. });
  1843. const data = await response.json();
  1844. if (data.success) {
  1845. if (mqttTestResult) {
  1846. mqttTestResult.innerHTML = '<span class="material-icons text-green-600 mr-1">check_circle</span><span class="text-green-600">Connection successful!</span>';
  1847. }
  1848. showStatusMessage('MQTT connection test successful', 'success');
  1849. } else {
  1850. if (mqttTestResult) {
  1851. mqttTestResult.innerHTML = `<span class="material-icons text-red-600 mr-1">error</span><span class="text-red-600">${data.error || 'Connection failed'}</span>`;
  1852. }
  1853. showStatusMessage(`MQTT test failed: ${data.error || 'Connection failed'}`, 'error');
  1854. }
  1855. } catch (error) {
  1856. logMessage(`Error testing MQTT connection: ${error.message}`, LOG_TYPE.ERROR);
  1857. if (mqttTestResult) {
  1858. mqttTestResult.innerHTML = `<span class="material-icons text-red-600 mr-1">error</span><span class="text-red-600">Test failed: ${error.message}</span>`;
  1859. }
  1860. showStatusMessage(`MQTT test failed: ${error.message}`, 'error');
  1861. } finally {
  1862. // Restore button
  1863. testMqttButton.innerHTML = originalButtonHTML;
  1864. testMqttButton.disabled = false;
  1865. }
  1866. }
  1867. // Event listeners
  1868. mqttEnableToggle.addEventListener('change', () => {
  1869. updateMqttSettingsVisibility();
  1870. updateRestartNotice();
  1871. });
  1872. // Track changes to show restart notice
  1873. [mqttBrokerInput, mqttPortInput, mqttUsernameInput, mqttPasswordInput,
  1874. mqttDeviceNameInput, mqttDeviceIdInput, mqttClientIdInput, mqttDiscoveryPrefixInput].forEach(input => {
  1875. if (input) {
  1876. input.addEventListener('input', updateRestartNotice);
  1877. }
  1878. });
  1879. testMqttButton.addEventListener('click', testMqttConnection);
  1880. saveMqttButton.addEventListener('click', saveMqttConfig);
  1881. }
  1882. // Initialize MQTT config when DOM is ready
  1883. document.addEventListener('DOMContentLoaded', function() {
  1884. initializeMqttConfig();
  1885. });