settings.js 74 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790
  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/preferred-port', {
  198. method: 'POST',
  199. headers: { 'Content-Type': 'application/json' },
  200. body: JSON.stringify({ preferred_port: preferredPort })
  201. });
  202. if (response.ok) {
  203. const data = await response.json();
  204. const currentPreferredPort = document.getElementById('currentPreferredPort');
  205. const preferredPortDisplay = document.getElementById('preferredPortDisplay');
  206. if (data.preferred_port) {
  207. showStatusMessage(`Preferred port set to: ${data.preferred_port}`, 'success');
  208. if (currentPreferredPort && preferredPortDisplay) {
  209. preferredPortDisplay.textContent = `Currently set to: ${data.preferred_port}`;
  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
  321. Promise.all([
  322. // Check connection status
  323. fetch('/serial_status').then(response => response.json()).catch(() => ({ connected: false })),
  324. // Load LED configuration (replaces old WLED-only loading)
  325. fetch('/get_led_config').then(response => response.json()).catch(() => ({ provider: 'none', wled_ip: null })),
  326. // Load current version and check for updates
  327. fetch('/api/version').then(response => response.json()).catch(() => ({ current: '1.0.0', latest: '1.0.0', update_available: false })),
  328. // Load available serial ports
  329. fetch('/list_serial_ports').then(response => response.json()).catch(() => []),
  330. // Load available pattern files for clear pattern selection
  331. getCachedPatternFiles().catch(() => []),
  332. // Load current custom clear patterns
  333. fetch('/api/custom_clear_patterns').then(response => response.json()).catch(() => ({ custom_clear_from_in: null, custom_clear_from_out: null })),
  334. // Load current clear pattern speed
  335. fetch('/api/clear_pattern_speed').then(response => response.json()).catch(() => ({ clear_pattern_speed: 200 })),
  336. // Load current app name
  337. fetch('/api/app-name').then(response => response.json()).catch(() => ({ app_name: 'Dune Weaver' })),
  338. // Load Still Sands settings
  339. fetch('/api/scheduled-pause').then(response => response.json()).catch(() => ({ enabled: false, time_slots: [] })),
  340. // Load preferred port setting
  341. fetch('/api/preferred-port').then(response => response.json()).catch(() => ({ preferred_port: null }))
  342. ]).then(([statusData, ledConfigData, updateData, ports, patterns, clearPatterns, clearSpeedData, appNameData, scheduledPauseData, preferredPortData]) => {
  343. // Update connection status
  344. setCachedConnectionStatus(statusData);
  345. updateConnectionUI(statusData);
  346. // Update LED configuration
  347. const providerRadio = document.getElementById(`ledProvider${providerToCamelCase(ledConfigData.provider)}`);
  348. if (providerRadio) {
  349. providerRadio.checked = true;
  350. } else {
  351. document.getElementById('ledProviderNone').checked = true;
  352. }
  353. if (ledConfigData.wled_ip) {
  354. const wledIpInput = document.getElementById('wledIpInput');
  355. if (wledIpInput) wledIpInput.value = ledConfigData.wled_ip;
  356. }
  357. // Load DW LED settings
  358. if (ledConfigData.dw_led_num_leds) {
  359. const numLedsInput = document.getElementById('dwLedNumLeds');
  360. if (numLedsInput) numLedsInput.value = ledConfigData.dw_led_num_leds;
  361. }
  362. if (ledConfigData.dw_led_gpio_pin) {
  363. const gpioPinInput = document.getElementById('dwLedGpioPin');
  364. if (gpioPinInput) gpioPinInput.value = ledConfigData.dw_led_gpio_pin;
  365. }
  366. if (ledConfigData.dw_led_pixel_order) {
  367. const pixelOrderInput = document.getElementById('dwLedPixelOrder');
  368. if (pixelOrderInput) pixelOrderInput.value = ledConfigData.dw_led_pixel_order;
  369. }
  370. updateLedProviderUI()
  371. // Update version display
  372. const currentVersionText = document.getElementById('currentVersionText');
  373. const latestVersionText = document.getElementById('latestVersionText');
  374. const updateButton = document.getElementById('updateSoftware');
  375. const updateIcon = document.getElementById('updateIcon');
  376. const updateText = document.getElementById('updateText');
  377. if (currentVersionText) {
  378. currentVersionText.textContent = updateData.current;
  379. }
  380. if (latestVersionText) {
  381. if (updateData.error) {
  382. latestVersionText.textContent = 'Error checking updates';
  383. latestVersionText.className = 'text-red-500 text-sm font-normal leading-normal';
  384. } else {
  385. latestVersionText.textContent = updateData.latest;
  386. latestVersionText.className = 'text-slate-500 text-sm font-normal leading-normal';
  387. }
  388. }
  389. // Update button state
  390. if (updateButton && updateIcon && updateText) {
  391. if (updateData.update_available) {
  392. updateButton.disabled = false;
  393. 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';
  394. updateIcon.textContent = 'download';
  395. updateText.textContent = 'Update';
  396. } else {
  397. updateButton.disabled = true;
  398. 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';
  399. updateIcon.textContent = 'check';
  400. updateText.textContent = 'Up to date';
  401. }
  402. }
  403. // Update port selection
  404. const portSelect = document.getElementById('portSelect');
  405. if (portSelect) {
  406. // Clear existing options except the first one
  407. while (portSelect.options.length > 1) {
  408. portSelect.remove(1);
  409. }
  410. // Add new options
  411. ports.forEach(port => {
  412. const option = document.createElement('option');
  413. option.value = port;
  414. option.textContent = port;
  415. portSelect.appendChild(option);
  416. });
  417. // If there's exactly one port available, select it
  418. if (ports.length === 1) {
  419. portSelect.value = ports[0];
  420. }
  421. }
  422. // Update preferred port selection
  423. const preferredPortSelect = document.getElementById('preferredPortSelect');
  424. const currentPreferredPort = document.getElementById('currentPreferredPort');
  425. const preferredPortDisplay = document.getElementById('preferredPortDisplay');
  426. if (preferredPortSelect) {
  427. // Clear existing options except the first one (no preference)
  428. while (preferredPortSelect.options.length > 1) {
  429. preferredPortSelect.remove(1);
  430. }
  431. // Add all available ports
  432. ports.forEach(port => {
  433. const option = document.createElement('option');
  434. option.value = port;
  435. option.textContent = port;
  436. preferredPortSelect.appendChild(option);
  437. });
  438. // Set the current preferred port value
  439. if (preferredPortData && preferredPortData.preferred_port) {
  440. // Check if the preferred port is in the available ports
  441. const isAvailable = ports.includes(preferredPortData.preferred_port);
  442. if (isAvailable) {
  443. preferredPortSelect.value = preferredPortData.preferred_port;
  444. } else {
  445. // Add the preferred port as an option (it might not be currently available)
  446. const option = document.createElement('option');
  447. option.value = preferredPortData.preferred_port;
  448. option.textContent = `${preferredPortData.preferred_port} (not currently available)`;
  449. preferredPortSelect.appendChild(option);
  450. preferredPortSelect.value = preferredPortData.preferred_port;
  451. }
  452. // Show the current preferred port indicator
  453. if (currentPreferredPort && preferredPortDisplay) {
  454. preferredPortDisplay.textContent = `Currently set to: ${preferredPortData.preferred_port}`;
  455. currentPreferredPort.classList.remove('hidden');
  456. }
  457. }
  458. }
  459. // Initialize autocomplete for clear patterns
  460. const clearFromInInput = document.getElementById('customClearFromInInput');
  461. const clearFromOutInput = document.getElementById('customClearFromOutInput');
  462. if (clearFromInInput && clearFromOutInput && patterns && Array.isArray(patterns)) {
  463. // Store patterns globally for autocomplete
  464. window.availablePatterns = patterns;
  465. // Set current values if they exist
  466. if (clearPatterns && clearPatterns.custom_clear_from_in) {
  467. clearFromInInput.value = clearPatterns.custom_clear_from_in;
  468. }
  469. if (clearPatterns && clearPatterns.custom_clear_from_out) {
  470. clearFromOutInput.value = clearPatterns.custom_clear_from_out;
  471. }
  472. // Initialize autocomplete for both inputs
  473. initializeAutocomplete('customClearFromInInput', 'clearFromInSuggestions', 'clearFromInClear', patterns);
  474. initializeAutocomplete('customClearFromOutInput', 'clearFromOutSuggestions', 'clearFromOutClear', patterns);
  475. console.log('Autocomplete initialized with', patterns.length, 'patterns');
  476. }
  477. // Set clear pattern speed
  478. const clearPatternSpeedInput = document.getElementById('clearPatternSpeedInput');
  479. const effectiveClearSpeed = document.getElementById('effectiveClearSpeed');
  480. if (clearPatternSpeedInput && clearSpeedData) {
  481. // Only set value if clear_pattern_speed is not null
  482. if (clearSpeedData.clear_pattern_speed !== null && clearSpeedData.clear_pattern_speed !== undefined) {
  483. clearPatternSpeedInput.value = clearSpeedData.clear_pattern_speed;
  484. if (effectiveClearSpeed) {
  485. effectiveClearSpeed.textContent = `Current: ${clearSpeedData.clear_pattern_speed} steps/min`;
  486. }
  487. } else {
  488. // Leave empty to show placeholder for default
  489. clearPatternSpeedInput.value = '';
  490. if (effectiveClearSpeed && clearSpeedData.effective_speed) {
  491. effectiveClearSpeed.textContent = `Using default pattern speed: ${clearSpeedData.effective_speed} steps/min`;
  492. }
  493. }
  494. }
  495. // Update app name
  496. const appNameInput = document.getElementById('appNameInput');
  497. if (appNameInput && appNameData.app_name) {
  498. appNameInput.value = appNameData.app_name;
  499. }
  500. // Store Still Sands data for later initialization
  501. window.initialStillSandsData = scheduledPauseData;
  502. }).catch(error => {
  503. logMessage(`Error initializing settings page: ${error.message}`, LOG_TYPE.ERROR);
  504. });
  505. // Set up event listeners
  506. setupEventListeners();
  507. });
  508. // Setup event listeners
  509. function setupEventListeners() {
  510. // Save App Name
  511. const saveAppNameButton = document.getElementById('saveAppName');
  512. const appNameInput = document.getElementById('appNameInput');
  513. if (saveAppNameButton && appNameInput) {
  514. saveAppNameButton.addEventListener('click', async () => {
  515. const appName = appNameInput.value.trim() || 'Dune Weaver';
  516. try {
  517. const response = await fetch('/api/app-name', {
  518. method: 'POST',
  519. headers: { 'Content-Type': 'application/json' },
  520. body: JSON.stringify({ app_name: appName })
  521. });
  522. if (response.ok) {
  523. const data = await response.json();
  524. showStatusMessage('Application name updated successfully. Refresh the page to see changes.', 'success');
  525. // Update the page title and header immediately
  526. document.title = `Settings - ${data.app_name}`;
  527. const headerTitle = document.querySelector('h1.text-gray-800');
  528. if (headerTitle) {
  529. // Update just the text content, preserving the connection status dot
  530. const textNode = headerTitle.childNodes[0];
  531. if (textNode && textNode.nodeType === Node.TEXT_NODE) {
  532. textNode.textContent = data.app_name;
  533. }
  534. }
  535. } else {
  536. throw new Error('Failed to save application name');
  537. }
  538. } catch (error) {
  539. showStatusMessage(`Failed to save application name: ${error.message}`, 'error');
  540. }
  541. });
  542. // Handle Enter key in app name input
  543. appNameInput.addEventListener('keypress', (e) => {
  544. if (e.key === 'Enter') {
  545. saveAppNameButton.click();
  546. }
  547. });
  548. }
  549. // LED provider selection change handlers
  550. const ledProviderRadios = document.querySelectorAll('input[name="ledProvider"]');
  551. ledProviderRadios.forEach(radio => {
  552. radio.addEventListener('change', updateLedProviderUI);
  553. });
  554. // Save LED configuration
  555. const saveLedConfig = document.getElementById('saveLedConfig');
  556. if (saveLedConfig) {
  557. saveLedConfig.addEventListener('click', async () => {
  558. const provider = document.querySelector('input[name="ledProvider"]:checked')?.value || 'none';
  559. let requestBody = { provider };
  560. if (provider === 'wled') {
  561. const wledIp = document.getElementById('wledIpInput')?.value;
  562. if (!wledIp) {
  563. showStatusMessage('Please enter a WLED IP address', 'error');
  564. return;
  565. }
  566. requestBody.ip_address = wledIp;
  567. } else if (provider === 'dw_leds') {
  568. const numLeds = parseInt(document.getElementById('dwLedNumLeds')?.value) || 60;
  569. const gpioPin = parseInt(document.getElementById('dwLedGpioPin')?.value) || 12;
  570. const pixelOrder = document.getElementById('dwLedPixelOrder')?.value || 'GRB';
  571. requestBody.num_leds = numLeds;
  572. requestBody.gpio_pin = gpioPin;
  573. requestBody.pixel_order = pixelOrder;
  574. }
  575. try {
  576. const response = await fetch('/set_led_config', {
  577. method: 'POST',
  578. headers: { 'Content-Type': 'application/json' },
  579. body: JSON.stringify(requestBody)
  580. });
  581. if (response.ok) {
  582. const data = await response.json();
  583. if (provider === 'wled' && data.wled_ip) {
  584. localStorage.setItem('wled_ip', data.wled_ip);
  585. showStatusMessage('WLED configured successfully', 'success');
  586. } else if (provider === 'dw_leds') {
  587. // Check if there's a warning (hardware not available but settings saved)
  588. if (data.warning) {
  589. showStatusMessage(
  590. `Settings saved for testing. Hardware issue: ${data.warning}`,
  591. 'warning'
  592. );
  593. } else {
  594. showStatusMessage(
  595. `DW LEDs configured: ${data.dw_led_num_leds} LEDs on GPIO${data.dw_led_gpio_pin}`,
  596. 'success'
  597. );
  598. }
  599. } else if (provider === 'none') {
  600. localStorage.removeItem('wled_ip');
  601. showStatusMessage('LED controller disabled', 'success');
  602. }
  603. } else {
  604. // Extract error detail from response
  605. const errorData = await response.json().catch(() => ({}));
  606. const errorMessage = errorData.detail || 'Failed to save LED configuration';
  607. showStatusMessage(errorMessage, 'error');
  608. }
  609. } catch (error) {
  610. showStatusMessage(`Failed to save LED configuration: ${error.message}`, 'error');
  611. }
  612. });
  613. }
  614. // Update software
  615. const updateSoftware = document.getElementById('updateSoftware');
  616. if (updateSoftware) {
  617. updateSoftware.addEventListener('click', async () => {
  618. if (updateSoftware.disabled) {
  619. return;
  620. }
  621. try {
  622. const response = await fetch('/api/update', {
  623. method: 'POST'
  624. });
  625. const data = await response.json();
  626. if (data.success) {
  627. showStatusMessage('Software update started successfully', 'success');
  628. } else if (data.manual_update_url) {
  629. // Show modal with manual update instructions, but use wiki link
  630. const wikiData = {
  631. ...data,
  632. manual_update_url: 'https://github.com/tuanchris/dune-weaver/wiki/Updating-software'
  633. };
  634. showUpdateInstructionsModal(wikiData);
  635. } else {
  636. showStatusMessage(data.message || 'No updates available', 'info');
  637. }
  638. } catch (error) {
  639. logMessage(`Error updating software: ${error.message}`, LOG_TYPE.ERROR);
  640. showStatusMessage('Failed to check for updates', 'error');
  641. }
  642. });
  643. }
  644. // Connect button
  645. const connectButton = document.getElementById('connectButton');
  646. if (connectButton) {
  647. connectButton.addEventListener('click', async () => {
  648. const portSelect = document.getElementById('portSelect');
  649. if (!portSelect || !portSelect.value) {
  650. logMessage('Please select a port first', LOG_TYPE.WARNING);
  651. return;
  652. }
  653. try {
  654. const response = await fetch('/connect', {
  655. method: 'POST',
  656. headers: { 'Content-Type': 'application/json' },
  657. body: JSON.stringify({ port: portSelect.value })
  658. });
  659. if (response.ok) {
  660. logMessage('Connected successfully', LOG_TYPE.SUCCESS);
  661. await updateSerialStatus(true); // Force update after connecting
  662. } else {
  663. throw new Error('Failed to connect');
  664. }
  665. } catch (error) {
  666. logMessage(`Error connecting to device: ${error.message}`, LOG_TYPE.ERROR);
  667. }
  668. });
  669. }
  670. // Disconnect button
  671. const disconnectButton = document.getElementById('disconnectButton');
  672. if (disconnectButton) {
  673. disconnectButton.addEventListener('click', async () => {
  674. try {
  675. const response = await fetch('/disconnect', {
  676. method: 'POST'
  677. });
  678. if (response.ok) {
  679. logMessage('Device disconnected successfully', LOG_TYPE.SUCCESS);
  680. await updateSerialStatus(true); // Force update after disconnecting
  681. } else {
  682. throw new Error('Failed to disconnect device');
  683. }
  684. } catch (error) {
  685. logMessage(`Error disconnecting device: ${error.message}`, LOG_TYPE.ERROR);
  686. }
  687. });
  688. }
  689. // Save preferred port button
  690. const savePreferredPortButton = document.getElementById('savePreferredPort');
  691. if (savePreferredPortButton) {
  692. savePreferredPortButton.addEventListener('click', savePreferredPort);
  693. }
  694. // Save custom clear patterns button
  695. const saveClearPatterns = document.getElementById('saveClearPatterns');
  696. if (saveClearPatterns) {
  697. saveClearPatterns.addEventListener('click', async () => {
  698. const clearFromInInput = document.getElementById('customClearFromInInput');
  699. const clearFromOutInput = document.getElementById('customClearFromOutInput');
  700. if (!clearFromInInput || !clearFromOutInput) {
  701. return;
  702. }
  703. // Validate that the entered patterns exist (if not empty)
  704. const inValue = clearFromInInput.value.trim();
  705. const outValue = clearFromOutInput.value.trim();
  706. if (inValue && window.availablePatterns && !window.availablePatterns.includes(inValue)) {
  707. showStatusMessage(`Pattern not found: ${inValue}`, 'error');
  708. return;
  709. }
  710. if (outValue && window.availablePatterns && !window.availablePatterns.includes(outValue)) {
  711. showStatusMessage(`Pattern not found: ${outValue}`, 'error');
  712. return;
  713. }
  714. try {
  715. const response = await fetch('/api/custom_clear_patterns', {
  716. method: 'POST',
  717. headers: { 'Content-Type': 'application/json' },
  718. body: JSON.stringify({
  719. custom_clear_from_in: inValue || null,
  720. custom_clear_from_out: outValue || null
  721. })
  722. });
  723. if (response.ok) {
  724. showStatusMessage('Clear patterns saved successfully', 'success');
  725. } else {
  726. const error = await response.json();
  727. throw new Error(error.detail || 'Failed to save clear patterns');
  728. }
  729. } catch (error) {
  730. showStatusMessage(`Failed to save clear patterns: ${error.message}`, 'error');
  731. }
  732. });
  733. }
  734. // Save clear pattern speed button
  735. const saveClearSpeed = document.getElementById('saveClearSpeed');
  736. if (saveClearSpeed) {
  737. saveClearSpeed.addEventListener('click', async () => {
  738. const clearPatternSpeedInput = document.getElementById('clearPatternSpeedInput');
  739. if (!clearPatternSpeedInput) {
  740. return;
  741. }
  742. let speed;
  743. if (clearPatternSpeedInput.value === '' || clearPatternSpeedInput.value === null) {
  744. // Empty value means use default (None)
  745. speed = null;
  746. } else {
  747. speed = parseInt(clearPatternSpeedInput.value);
  748. // Validate speed only if it's not null
  749. if (isNaN(speed) || speed < 50 || speed > 2000) {
  750. showStatusMessage('Clear pattern speed must be between 50 and 2000, or leave empty for default', 'error');
  751. return;
  752. }
  753. }
  754. try {
  755. const response = await fetch('/api/clear_pattern_speed', {
  756. method: 'POST',
  757. headers: { 'Content-Type': 'application/json' },
  758. body: JSON.stringify({ clear_pattern_speed: speed })
  759. });
  760. if (response.ok) {
  761. const data = await response.json();
  762. if (speed === null) {
  763. showStatusMessage(`Clear pattern speed set to default (${data.effective_speed} steps/min)`, 'success');
  764. } else {
  765. showStatusMessage(`Clear pattern speed set to ${speed} steps/min`, 'success');
  766. }
  767. // Update the effective speed display
  768. const effectiveClearSpeed = document.getElementById('effectiveClearSpeed');
  769. if (effectiveClearSpeed) {
  770. if (speed === null) {
  771. effectiveClearSpeed.textContent = `Using default pattern speed: ${data.effective_speed} steps/min`;
  772. } else {
  773. effectiveClearSpeed.textContent = `Current: ${speed} steps/min`;
  774. }
  775. }
  776. } else {
  777. const error = await response.json();
  778. throw new Error(error.detail || 'Failed to save clear pattern speed');
  779. }
  780. } catch (error) {
  781. showStatusMessage(`Failed to save clear pattern speed: ${error.message}`, 'error');
  782. }
  783. });
  784. }
  785. }
  786. // Button click handlers
  787. document.addEventListener('DOMContentLoaded', function() {
  788. // Home button
  789. const homeButton = document.getElementById('homeButton');
  790. if (homeButton) {
  791. homeButton.addEventListener('click', async () => {
  792. try {
  793. const response = await fetch('/send_home', {
  794. method: 'POST',
  795. headers: {
  796. 'Content-Type': 'application/json'
  797. }
  798. });
  799. const data = await response.json();
  800. if (data.success) {
  801. updateStatus('Moving to home position...');
  802. }
  803. } catch (error) {
  804. console.error('Error sending home command:', error);
  805. updateStatus('Error: Failed to move to home position');
  806. }
  807. });
  808. }
  809. // Stop button
  810. const stopButton = document.getElementById('stopButton');
  811. if (stopButton) {
  812. stopButton.addEventListener('click', async () => {
  813. try {
  814. const response = await fetch('/stop_execution', {
  815. method: 'POST',
  816. headers: {
  817. 'Content-Type': 'application/json'
  818. }
  819. });
  820. const data = await response.json();
  821. if (data.success) {
  822. updateStatus('Execution stopped');
  823. }
  824. } catch (error) {
  825. console.error('Error stopping execution:', error);
  826. updateStatus('Error: Failed to stop execution');
  827. }
  828. });
  829. }
  830. // Move to Center button
  831. const centerButton = document.getElementById('centerButton');
  832. if (centerButton) {
  833. centerButton.addEventListener('click', async () => {
  834. try {
  835. const response = await fetch('/move_to_center', {
  836. method: 'POST',
  837. headers: {
  838. 'Content-Type': 'application/json'
  839. }
  840. });
  841. const data = await response.json();
  842. if (data.success) {
  843. updateStatus('Moving to center position...');
  844. }
  845. } catch (error) {
  846. console.error('Error moving to center:', error);
  847. updateStatus('Error: Failed to move to center');
  848. }
  849. });
  850. }
  851. // Move to Perimeter button
  852. const perimeterButton = document.getElementById('perimeterButton');
  853. if (perimeterButton) {
  854. perimeterButton.addEventListener('click', async () => {
  855. try {
  856. const response = await fetch('/move_to_perimeter', {
  857. method: 'POST',
  858. headers: {
  859. 'Content-Type': 'application/json'
  860. }
  861. });
  862. const data = await response.json();
  863. if (data.success) {
  864. updateStatus('Moving to perimeter position...');
  865. }
  866. } catch (error) {
  867. console.error('Error moving to perimeter:', error);
  868. updateStatus('Error: Failed to move to perimeter');
  869. }
  870. });
  871. }
  872. });
  873. // Function to update status
  874. function updateStatus(message) {
  875. const statusElement = document.querySelector('.text-slate-800.text-base.font-medium.leading-normal');
  876. if (statusElement) {
  877. statusElement.textContent = message;
  878. // Reset status after 3 seconds if it's a temporary message
  879. if (message.includes('Moving') || message.includes('Execution')) {
  880. setTimeout(() => {
  881. statusElement.textContent = 'Status';
  882. }, 3000);
  883. }
  884. }
  885. }
  886. // Function to show status messages (using existing base.js showStatusMessage if available)
  887. function showStatusMessage(message, type) {
  888. if (typeof window.showStatusMessage === 'function') {
  889. window.showStatusMessage(message, type);
  890. } else {
  891. // Fallback to console logging
  892. console.log(`[${type}] ${message}`);
  893. }
  894. }
  895. // Function to show update instructions modal
  896. function showUpdateInstructionsModal(data) {
  897. // Create modal HTML
  898. const modal = document.createElement('div');
  899. modal.id = 'updateInstructionsModal';
  900. modal.className = 'fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4';
  901. modal.innerHTML = `
  902. <div class="bg-white dark:bg-gray-800 rounded-lg shadow-xl w-full max-w-md">
  903. <div class="p-6">
  904. <div class="text-center mb-4">
  905. <h2 class="text-xl font-semibold text-gray-800 dark:text-gray-200 mb-2">Manual Update Required</h2>
  906. <p class="text-gray-600 dark:text-gray-400 text-sm">
  907. ${data.message}
  908. </p>
  909. </div>
  910. <div class="text-gray-700 dark:text-gray-300 text-sm mb-6">
  911. <p class="mb-3">${data.instructions}</p>
  912. </div>
  913. <div class="flex gap-3 justify-center">
  914. <button id="openGitHubRelease" class="px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-lg transition-colors">
  915. View Update Instructions
  916. </button>
  917. <button id="closeUpdateModal" class="px-4 py-2 bg-gray-600 hover:bg-gray-700 text-white rounded-lg transition-colors">
  918. Close
  919. </button>
  920. </div>
  921. </div>
  922. </div>
  923. `;
  924. document.body.appendChild(modal);
  925. // Add event listeners
  926. const openGitHubButton = modal.querySelector('#openGitHubRelease');
  927. const closeButton = modal.querySelector('#closeUpdateModal');
  928. openGitHubButton.addEventListener('click', () => {
  929. window.open(data.manual_update_url, '_blank');
  930. document.body.removeChild(modal);
  931. });
  932. closeButton.addEventListener('click', () => {
  933. document.body.removeChild(modal);
  934. });
  935. // Close on outside click
  936. modal.addEventListener('click', (e) => {
  937. if (e.target === modal) {
  938. document.body.removeChild(modal);
  939. }
  940. });
  941. }
  942. // Autocomplete functionality
  943. function initializeAutocomplete(inputId, suggestionsId, clearButtonId, patterns) {
  944. const input = document.getElementById(inputId);
  945. const suggestionsDiv = document.getElementById(suggestionsId);
  946. const clearButton = document.getElementById(clearButtonId);
  947. let selectedIndex = -1;
  948. if (!input || !suggestionsDiv) return;
  949. // Function to update clear button visibility
  950. function updateClearButton() {
  951. if (clearButton) {
  952. if (input.value.trim()) {
  953. clearButton.classList.remove('hidden');
  954. } else {
  955. clearButton.classList.add('hidden');
  956. }
  957. }
  958. }
  959. // Format pattern name for display
  960. function formatPatternName(pattern) {
  961. return pattern.replace('.thr', '').replace(/_/g, ' ');
  962. }
  963. // Filter patterns based on input
  964. function filterPatterns(searchTerm) {
  965. if (!searchTerm) return patterns.slice(0, 20); // Show first 20 when empty
  966. const term = searchTerm.toLowerCase();
  967. return patterns.filter(pattern => {
  968. const name = pattern.toLowerCase();
  969. return name.includes(term);
  970. }).sort((a, b) => {
  971. // Prioritize patterns that start with the search term
  972. const aStarts = a.toLowerCase().startsWith(term);
  973. const bStarts = b.toLowerCase().startsWith(term);
  974. if (aStarts && !bStarts) return -1;
  975. if (!aStarts && bStarts) return 1;
  976. return a.localeCompare(b);
  977. }).slice(0, 20); // Limit to 20 results
  978. }
  979. // Highlight matching text
  980. function highlightMatch(text, searchTerm) {
  981. if (!searchTerm) return text;
  982. const regex = new RegExp(`(${searchTerm.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')})`, 'gi');
  983. return text.replace(regex, '<mark>$1</mark>');
  984. }
  985. // Show suggestions
  986. function showSuggestions(searchTerm) {
  987. const filtered = filterPatterns(searchTerm);
  988. if (filtered.length === 0 && searchTerm) {
  989. suggestionsDiv.innerHTML = '<div class="suggestion-item" style="cursor: default; color: #9ca3af;">No patterns found</div>';
  990. suggestionsDiv.classList.remove('hidden');
  991. return;
  992. }
  993. suggestionsDiv.innerHTML = filtered.map((pattern, index) => {
  994. const displayName = formatPatternName(pattern);
  995. const highlighted = highlightMatch(displayName, searchTerm);
  996. return `<div class="suggestion-item" data-value="${pattern}" data-index="${index}">${highlighted}</div>`;
  997. }).join('');
  998. suggestionsDiv.classList.remove('hidden');
  999. selectedIndex = -1;
  1000. }
  1001. // Hide suggestions
  1002. function hideSuggestions() {
  1003. setTimeout(() => {
  1004. suggestionsDiv.classList.add('hidden');
  1005. selectedIndex = -1;
  1006. }, 200);
  1007. }
  1008. // Select suggestion
  1009. function selectSuggestion(value) {
  1010. input.value = value;
  1011. hideSuggestions();
  1012. updateClearButton();
  1013. }
  1014. // Handle keyboard navigation
  1015. function handleKeyboard(e) {
  1016. const items = suggestionsDiv.querySelectorAll('.suggestion-item[data-value]');
  1017. if (e.key === 'ArrowDown') {
  1018. e.preventDefault();
  1019. selectedIndex = Math.min(selectedIndex + 1, items.length - 1);
  1020. updateSelection(items);
  1021. } else if (e.key === 'ArrowUp') {
  1022. e.preventDefault();
  1023. selectedIndex = Math.max(selectedIndex - 1, -1);
  1024. updateSelection(items);
  1025. } else if (e.key === 'Enter') {
  1026. e.preventDefault();
  1027. if (selectedIndex >= 0 && items[selectedIndex]) {
  1028. selectSuggestion(items[selectedIndex].dataset.value);
  1029. } else if (items.length === 1) {
  1030. selectSuggestion(items[0].dataset.value);
  1031. }
  1032. } else if (e.key === 'Escape') {
  1033. hideSuggestions();
  1034. }
  1035. }
  1036. // Update visual selection
  1037. function updateSelection(items) {
  1038. items.forEach((item, index) => {
  1039. if (index === selectedIndex) {
  1040. item.classList.add('selected');
  1041. item.scrollIntoView({ block: 'nearest' });
  1042. } else {
  1043. item.classList.remove('selected');
  1044. }
  1045. });
  1046. }
  1047. // Event listeners
  1048. input.addEventListener('input', (e) => {
  1049. const value = e.target.value.trim();
  1050. updateClearButton();
  1051. if (value.length > 0 || e.target === document.activeElement) {
  1052. showSuggestions(value);
  1053. } else {
  1054. hideSuggestions();
  1055. }
  1056. });
  1057. input.addEventListener('focus', () => {
  1058. const value = input.value.trim();
  1059. showSuggestions(value);
  1060. });
  1061. input.addEventListener('blur', hideSuggestions);
  1062. input.addEventListener('keydown', handleKeyboard);
  1063. // Click handler for suggestions
  1064. suggestionsDiv.addEventListener('click', (e) => {
  1065. const item = e.target.closest('.suggestion-item[data-value]');
  1066. if (item) {
  1067. selectSuggestion(item.dataset.value);
  1068. }
  1069. });
  1070. // Mouse hover handler
  1071. suggestionsDiv.addEventListener('mouseover', (e) => {
  1072. const item = e.target.closest('.suggestion-item[data-value]');
  1073. if (item) {
  1074. selectedIndex = parseInt(item.dataset.index);
  1075. const items = suggestionsDiv.querySelectorAll('.suggestion-item[data-value]');
  1076. updateSelection(items);
  1077. }
  1078. });
  1079. // Clear button handler
  1080. if (clearButton) {
  1081. clearButton.addEventListener('click', () => {
  1082. input.value = '';
  1083. updateClearButton();
  1084. hideSuggestions();
  1085. input.focus();
  1086. });
  1087. }
  1088. // Initialize clear button visibility
  1089. updateClearButton();
  1090. }
  1091. // auto_play Mode Functions
  1092. async function initializeauto_playMode() {
  1093. const auto_playToggle = document.getElementById('auto_playModeToggle');
  1094. const auto_playSettings = document.getElementById('auto_playSettings');
  1095. const auto_playPlaylistSelect = document.getElementById('auto_playPlaylistSelect');
  1096. const auto_playRunModeSelect = document.getElementById('auto_playRunModeSelect');
  1097. const auto_playPauseTimeInput = document.getElementById('auto_playPauseTimeInput');
  1098. const auto_playClearPatternSelect = document.getElementById('auto_playClearPatternSelect');
  1099. const auto_playShuffleToggle = document.getElementById('auto_playShuffleToggle');
  1100. // Load current auto_play settings
  1101. try {
  1102. const response = await fetch('/api/auto_play-mode');
  1103. const data = await response.json();
  1104. auto_playToggle.checked = data.enabled;
  1105. if (data.enabled) {
  1106. auto_playSettings.style.display = 'block';
  1107. }
  1108. // Set current values
  1109. auto_playRunModeSelect.value = data.run_mode || 'loop';
  1110. auto_playPauseTimeInput.value = data.pause_time || 5.0;
  1111. auto_playClearPatternSelect.value = data.clear_pattern || 'adaptive';
  1112. auto_playShuffleToggle.checked = data.shuffle || false;
  1113. // Load playlists for selection
  1114. const playlistsResponse = await fetch('/list_all_playlists');
  1115. const playlists = await playlistsResponse.json();
  1116. // Clear and populate playlist select
  1117. auto_playPlaylistSelect.innerHTML = '<option value="">Select a playlist...</option>';
  1118. playlists.forEach(playlist => {
  1119. const option = document.createElement('option');
  1120. option.value = playlist;
  1121. option.textContent = playlist;
  1122. if (playlist === data.playlist) {
  1123. option.selected = true;
  1124. }
  1125. auto_playPlaylistSelect.appendChild(option);
  1126. });
  1127. } catch (error) {
  1128. logMessage(`Error loading auto_play settings: ${error.message}`, LOG_TYPE.ERROR);
  1129. }
  1130. // Function to save settings
  1131. async function saveSettings() {
  1132. try {
  1133. const response = await fetch('/api/auto_play-mode', {
  1134. method: 'POST',
  1135. headers: { 'Content-Type': 'application/json' },
  1136. body: JSON.stringify({
  1137. enabled: auto_playToggle.checked,
  1138. playlist: auto_playPlaylistSelect.value || null,
  1139. run_mode: auto_playRunModeSelect.value,
  1140. pause_time: parseFloat(auto_playPauseTimeInput.value) || 0,
  1141. clear_pattern: auto_playClearPatternSelect.value,
  1142. shuffle: auto_playShuffleToggle.checked
  1143. })
  1144. });
  1145. if (!response.ok) {
  1146. throw new Error('Failed to save settings');
  1147. }
  1148. } catch (error) {
  1149. logMessage(`Error saving auto_play settings: ${error.message}`, LOG_TYPE.ERROR);
  1150. }
  1151. }
  1152. // Toggle auto_play settings visibility and save
  1153. auto_playToggle.addEventListener('change', async () => {
  1154. auto_playSettings.style.display = auto_playToggle.checked ? 'block' : 'none';
  1155. await saveSettings();
  1156. });
  1157. // Save when any setting changes
  1158. auto_playPlaylistSelect.addEventListener('change', saveSettings);
  1159. auto_playRunModeSelect.addEventListener('change', saveSettings);
  1160. auto_playPauseTimeInput.addEventListener('change', saveSettings);
  1161. auto_playPauseTimeInput.addEventListener('input', saveSettings); // Save as user types
  1162. auto_playClearPatternSelect.addEventListener('change', saveSettings);
  1163. auto_playShuffleToggle.addEventListener('change', saveSettings);
  1164. }
  1165. // Initialize auto_play mode when DOM is ready
  1166. document.addEventListener('DOMContentLoaded', function() {
  1167. initializeauto_playMode();
  1168. initializeStillSandsMode();
  1169. initializeHomingConfig();
  1170. });
  1171. // Still Sands Mode Functions
  1172. async function initializeStillSandsMode() {
  1173. logMessage('Initializing Still Sands mode', LOG_TYPE.INFO);
  1174. const stillSandsToggle = document.getElementById('scheduledPauseToggle');
  1175. const stillSandsSettings = document.getElementById('scheduledPauseSettings');
  1176. const addTimeSlotButton = document.getElementById('addTimeSlotButton');
  1177. const saveStillSandsButton = document.getElementById('savePauseSettings');
  1178. const timeSlotsContainer = document.getElementById('timeSlotsContainer');
  1179. const wledControlToggle = document.getElementById('stillSandsWledControl');
  1180. // Check if elements exist
  1181. if (!stillSandsToggle || !stillSandsSettings || !addTimeSlotButton || !saveStillSandsButton || !timeSlotsContainer) {
  1182. logMessage('Still Sands elements not found, skipping initialization', LOG_TYPE.WARNING);
  1183. logMessage(`Found elements: toggle=${!!stillSandsToggle}, settings=${!!stillSandsSettings}, addBtn=${!!addTimeSlotButton}, saveBtn=${!!saveStillSandsButton}, container=${!!timeSlotsContainer}`, LOG_TYPE.WARNING);
  1184. return;
  1185. }
  1186. logMessage('All Still Sands elements found successfully', LOG_TYPE.INFO);
  1187. // Track time slots
  1188. let timeSlots = [];
  1189. let slotIdCounter = 0;
  1190. // Load current Still Sands settings from initial data
  1191. try {
  1192. // Use the data loaded during page initialization, fallback to API if not available
  1193. let data;
  1194. if (window.initialStillSandsData) {
  1195. data = window.initialStillSandsData;
  1196. // Clear the global variable after use
  1197. delete window.initialStillSandsData;
  1198. } else {
  1199. // Fallback to API call if initial data not available
  1200. const response = await fetch('/api/scheduled-pause');
  1201. data = await response.json();
  1202. }
  1203. stillSandsToggle.checked = data.enabled || false;
  1204. if (data.enabled) {
  1205. stillSandsSettings.style.display = 'block';
  1206. }
  1207. // Load WLED control setting
  1208. if (wledControlToggle) {
  1209. wledControlToggle.checked = data.control_wled || false;
  1210. }
  1211. // Load existing time slots
  1212. timeSlots = data.time_slots || [];
  1213. // Assign IDs to loaded slots BEFORE rendering
  1214. if (timeSlots.length > 0) {
  1215. slotIdCounter = 0;
  1216. timeSlots.forEach(slot => {
  1217. slot.id = ++slotIdCounter;
  1218. });
  1219. }
  1220. renderTimeSlots();
  1221. } catch (error) {
  1222. logMessage(`Error loading Still Sands settings: ${error.message}`, LOG_TYPE.ERROR);
  1223. // Initialize with empty settings if load fails
  1224. timeSlots = [];
  1225. renderTimeSlots();
  1226. }
  1227. // Function to validate time format (HH:MM)
  1228. function isValidTime(timeString) {
  1229. const timeRegex = /^([01]?[0-9]|2[0-3]):[0-5][0-9]$/;
  1230. return timeRegex.test(timeString);
  1231. }
  1232. // Function to create a new time slot element
  1233. function createTimeSlotElement(slot) {
  1234. const slotDiv = document.createElement('div');
  1235. slotDiv.className = 'time-slot-item';
  1236. slotDiv.dataset.slotId = slot.id;
  1237. slotDiv.innerHTML = `
  1238. <div class="flex items-center gap-3">
  1239. <div class="flex-1 grid grid-cols-1 md:grid-cols-2 gap-3">
  1240. <div class="flex flex-col gap-1">
  1241. <label class="text-slate-700 dark:text-slate-300 text-xs font-medium">Start Time</label>
  1242. <input
  1243. type="time"
  1244. 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"
  1245. value="${slot.start_time || ''}"
  1246. required
  1247. />
  1248. </div>
  1249. <div class="flex flex-col gap-1">
  1250. <label class="text-slate-700 dark:text-slate-300 text-xs font-medium">End Time</label>
  1251. <input
  1252. type="time"
  1253. 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"
  1254. value="${slot.end_time || ''}"
  1255. required
  1256. />
  1257. </div>
  1258. </div>
  1259. <div class="flex flex-col gap-1">
  1260. <label class="text-slate-700 dark:text-slate-300 text-xs font-medium">Days</label>
  1261. <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">
  1262. <option value="daily" ${slot.days === 'daily' ? 'selected' : ''}>Daily</option>
  1263. <option value="weekdays" ${slot.days === 'weekdays' ? 'selected' : ''}>Weekdays</option>
  1264. <option value="weekends" ${slot.days === 'weekends' ? 'selected' : ''}>Weekends</option>
  1265. <option value="custom" ${slot.days === 'custom' ? 'selected' : ''}>Custom</option>
  1266. </select>
  1267. </div>
  1268. <button
  1269. type="button"
  1270. 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"
  1271. title="Remove time slot"
  1272. >
  1273. <span class="material-icons text-base">delete</span>
  1274. </button>
  1275. </div>
  1276. <div class="custom-days-container mt-2" style="display: ${slot.days === 'custom' ? 'block' : 'none'};">
  1277. <label class="text-slate-700 dark:text-slate-300 text-xs font-medium mb-1 block">Select Days</label>
  1278. <div class="flex flex-wrap gap-2">
  1279. ${['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday'].map(day => `
  1280. <label class="flex items-center gap-1 text-xs">
  1281. <input
  1282. type="checkbox"
  1283. name="custom-days-${slot.id}"
  1284. value="${day}"
  1285. ${slot.custom_days && slot.custom_days.includes(day) ? 'checked' : ''}
  1286. class="rounded border-slate-300 text-sky-600 focus:ring-sky-500"
  1287. />
  1288. <span class="text-slate-700 dark:text-slate-300 capitalize">${day.substring(0, 3)}</span>
  1289. </label>
  1290. `).join('')}
  1291. </div>
  1292. </div>
  1293. `;
  1294. // Add event listeners for this slot
  1295. const startTimeInput = slotDiv.querySelector('.start-time');
  1296. const endTimeInput = slotDiv.querySelector('.end-time');
  1297. const daysSelect = slotDiv.querySelector('.days-select');
  1298. const customDaysContainer = slotDiv.querySelector('.custom-days-container');
  1299. const removeButton = slotDiv.querySelector('.remove-slot-btn');
  1300. // Show/hide custom days based on selection
  1301. daysSelect.addEventListener('change', () => {
  1302. customDaysContainer.style.display = daysSelect.value === 'custom' ? 'block' : 'none';
  1303. updateTimeSlot(slot.id);
  1304. });
  1305. // Update slot data when inputs change
  1306. startTimeInput.addEventListener('change', () => updateTimeSlot(slot.id));
  1307. endTimeInput.addEventListener('change', () => updateTimeSlot(slot.id));
  1308. // Handle custom day checkboxes
  1309. customDaysContainer.addEventListener('change', () => updateTimeSlot(slot.id));
  1310. // Remove slot button
  1311. removeButton.addEventListener('click', () => {
  1312. removeTimeSlot(slot.id);
  1313. });
  1314. return slotDiv;
  1315. }
  1316. // Function to render all time slots
  1317. function renderTimeSlots() {
  1318. timeSlotsContainer.innerHTML = '';
  1319. if (timeSlots.length === 0) {
  1320. timeSlotsContainer.innerHTML = `
  1321. <div class="text-center py-8 text-slate-500 dark:text-slate-400">
  1322. <span class="material-icons text-4xl mb-2 block">schedule</span>
  1323. <p>No time slots configured</p>
  1324. <p class="text-xs mt-1">Click "Add Time Slot" to create a pause schedule</p>
  1325. </div>
  1326. `;
  1327. return;
  1328. }
  1329. timeSlots.forEach(slot => {
  1330. const slotElement = createTimeSlotElement(slot);
  1331. timeSlotsContainer.appendChild(slotElement);
  1332. });
  1333. }
  1334. // Function to add a new time slot
  1335. function addTimeSlot() {
  1336. const newSlot = {
  1337. id: ++slotIdCounter,
  1338. start_time: '22:00',
  1339. end_time: '08:00',
  1340. days: 'daily',
  1341. custom_days: []
  1342. };
  1343. timeSlots.push(newSlot);
  1344. renderTimeSlots();
  1345. }
  1346. // Function to remove a time slot
  1347. function removeTimeSlot(slotId) {
  1348. timeSlots = timeSlots.filter(slot => slot.id !== slotId);
  1349. renderTimeSlots();
  1350. }
  1351. // Function to update a time slot's data
  1352. function updateTimeSlot(slotId) {
  1353. const slotElement = timeSlotsContainer.querySelector(`[data-slot-id="${slotId}"]`);
  1354. if (!slotElement) return;
  1355. const slot = timeSlots.find(s => s.id === slotId);
  1356. if (!slot) return;
  1357. // Update slot data from inputs
  1358. slot.start_time = slotElement.querySelector('.start-time').value;
  1359. slot.end_time = slotElement.querySelector('.end-time').value;
  1360. slot.days = slotElement.querySelector('.days-select').value;
  1361. // Update custom days if applicable
  1362. if (slot.days === 'custom') {
  1363. const checkedDays = Array.from(slotElement.querySelectorAll(`input[name="custom-days-${slotId}"]:checked`))
  1364. .map(cb => cb.value);
  1365. slot.custom_days = checkedDays;
  1366. } else {
  1367. slot.custom_days = [];
  1368. }
  1369. }
  1370. // Function to validate all time slots
  1371. function validateTimeSlots() {
  1372. const errors = [];
  1373. timeSlots.forEach((slot, index) => {
  1374. if (!slot.start_time || !isValidTime(slot.start_time)) {
  1375. errors.push(`Time slot ${index + 1}: Invalid start time`);
  1376. }
  1377. if (!slot.end_time || !isValidTime(slot.end_time)) {
  1378. errors.push(`Time slot ${index + 1}: Invalid end time`);
  1379. }
  1380. if (slot.days === 'custom' && (!slot.custom_days || slot.custom_days.length === 0)) {
  1381. errors.push(`Time slot ${index + 1}: Please select at least one day for custom schedule`);
  1382. }
  1383. });
  1384. return errors;
  1385. }
  1386. // Function to save settings
  1387. async function saveStillSandsSettings() {
  1388. // Update all slots from current form values
  1389. timeSlots.forEach(slot => updateTimeSlot(slot.id));
  1390. // Validate time slots
  1391. const validationErrors = validateTimeSlots();
  1392. if (validationErrors.length > 0) {
  1393. showStatusMessage(`Validation errors: ${validationErrors.join(', ')}`, 'error');
  1394. return;
  1395. }
  1396. // Update button UI to show loading state
  1397. const originalButtonHTML = saveStillSandsButton.innerHTML;
  1398. saveStillSandsButton.disabled = true;
  1399. saveStillSandsButton.innerHTML = '<span class="material-icons text-lg animate-spin">refresh</span><span class="truncate">Saving...</span>';
  1400. try {
  1401. const response = await fetch('/api/scheduled-pause', {
  1402. method: 'POST',
  1403. headers: { 'Content-Type': 'application/json' },
  1404. body: JSON.stringify({
  1405. enabled: stillSandsToggle.checked,
  1406. control_wled: wledControlToggle ? wledControlToggle.checked : false,
  1407. time_slots: timeSlots.map(slot => ({
  1408. start_time: slot.start_time,
  1409. end_time: slot.end_time,
  1410. days: slot.days,
  1411. custom_days: slot.custom_days
  1412. }))
  1413. })
  1414. });
  1415. if (!response.ok) {
  1416. const errorData = await response.json();
  1417. throw new Error(errorData.detail || 'Failed to save Still Sands settings');
  1418. }
  1419. // Show success state temporarily
  1420. saveStillSandsButton.innerHTML = '<span class="material-icons text-lg">check</span><span class="truncate">Saved!</span>';
  1421. showStatusMessage('Still Sands settings saved successfully', 'success');
  1422. // Restore button after 2 seconds
  1423. setTimeout(() => {
  1424. saveStillSandsButton.innerHTML = originalButtonHTML;
  1425. saveStillSandsButton.disabled = false;
  1426. }, 2000);
  1427. } catch (error) {
  1428. logMessage(`Error saving Still Sands settings: ${error.message}`, LOG_TYPE.ERROR);
  1429. showStatusMessage(`Failed to save settings: ${error.message}`, 'error');
  1430. // Restore button immediately on error
  1431. saveStillSandsButton.innerHTML = originalButtonHTML;
  1432. saveStillSandsButton.disabled = false;
  1433. }
  1434. }
  1435. // Note: Slot IDs are now assigned during initialization above, before first render
  1436. // Event listeners
  1437. stillSandsToggle.addEventListener('change', async () => {
  1438. logMessage(`Still Sands toggle changed: ${stillSandsToggle.checked}`, LOG_TYPE.INFO);
  1439. stillSandsSettings.style.display = stillSandsToggle.checked ? 'block' : 'none';
  1440. logMessage(`Settings display set to: ${stillSandsSettings.style.display}`, LOG_TYPE.INFO);
  1441. // Auto-save when toggle changes
  1442. try {
  1443. await saveStillSandsSettings();
  1444. const statusText = stillSandsToggle.checked ? 'enabled' : 'disabled';
  1445. showStatusMessage(`Still Sands ${statusText} successfully`, 'success');
  1446. } catch (error) {
  1447. logMessage(`Error saving Still Sands toggle: ${error.message}`, LOG_TYPE.ERROR);
  1448. showStatusMessage(`Failed to save Still Sands setting: ${error.message}`, 'error');
  1449. }
  1450. });
  1451. addTimeSlotButton.addEventListener('click', addTimeSlot);
  1452. saveStillSandsButton.addEventListener('click', saveStillSandsSettings);
  1453. // Add listener for WLED control toggle
  1454. if (wledControlToggle) {
  1455. wledControlToggle.addEventListener('change', async () => {
  1456. logMessage(`WLED control toggle changed: ${wledControlToggle.checked}`, LOG_TYPE.INFO);
  1457. // Auto-save when WLED control changes
  1458. await saveStillSandsSettings();
  1459. });
  1460. }
  1461. }
  1462. // Homing Configuration
  1463. async function initializeHomingConfig() {
  1464. logMessage('Initializing homing configuration', LOG_TYPE.INFO);
  1465. const homingModeCrash = document.getElementById('homingModeCrash');
  1466. const homingModeSensor = document.getElementById('homingModeSensor');
  1467. const angularOffsetInput = document.getElementById('angularOffsetInput');
  1468. const compassOffsetContainer = document.getElementById('compassOffsetContainer');
  1469. const saveHomingConfigButton = document.getElementById('saveHomingConfig');
  1470. const homingInfoContent = document.getElementById('homingInfoContent');
  1471. // Check if elements exist
  1472. if (!homingModeCrash || !homingModeSensor || !angularOffsetInput || !saveHomingConfigButton || !homingInfoContent || !compassOffsetContainer) {
  1473. logMessage('Homing configuration elements not found, skipping initialization', LOG_TYPE.WARNING);
  1474. return;
  1475. }
  1476. logMessage('Homing configuration elements found successfully', LOG_TYPE.INFO);
  1477. // Function to get selected homing mode
  1478. function getSelectedMode() {
  1479. return homingModeCrash.checked ? 0 : 1;
  1480. }
  1481. // Function to update info box and visibility based on selected mode
  1482. function updateHomingInfo() {
  1483. const mode = getSelectedMode();
  1484. // Show/hide compass offset based on mode
  1485. if (mode === 0) {
  1486. compassOffsetContainer.style.display = 'none';
  1487. homingInfoContent.innerHTML = `
  1488. <p class="font-medium text-blue-800">Crash Homing Mode:</p>
  1489. <ul class="mt-1 space-y-1 text-blue-700">
  1490. <li>• Y axis moves -22mm (or -30mm for mini) until physical stop</li>
  1491. <li>• Theta set to 0, rho set to 0</li>
  1492. <li>• No x0 y0 command sent</li>
  1493. <li>• No hardware sensors required</li>
  1494. </ul>
  1495. `;
  1496. } else {
  1497. compassOffsetContainer.style.display = 'block';
  1498. homingInfoContent.innerHTML = `
  1499. <p class="font-medium text-blue-800">Sensor Homing Mode:</p>
  1500. <ul class="mt-1 space-y-1 text-blue-700">
  1501. <li>• Requires hardware limit switches</li>
  1502. <li>• Requires additional configuration</li>
  1503. </ul>
  1504. `;
  1505. }
  1506. }
  1507. // Load current homing configuration
  1508. try {
  1509. const response = await fetch('/api/homing-config');
  1510. const data = await response.json();
  1511. // Set radio button based on mode
  1512. if (data.homing_mode === 1) {
  1513. homingModeSensor.checked = true;
  1514. } else {
  1515. homingModeCrash.checked = true;
  1516. }
  1517. angularOffsetInput.value = data.angular_homing_offset_degrees || 0;
  1518. updateHomingInfo();
  1519. logMessage(`Loaded homing config: mode=${data.homing_mode}, offset=${data.angular_homing_offset_degrees}°`, LOG_TYPE.INFO);
  1520. } catch (error) {
  1521. logMessage(`Error loading homing configuration: ${error.message}`, LOG_TYPE.ERROR);
  1522. // Initialize with defaults if load fails
  1523. homingModeCrash.checked = true;
  1524. angularOffsetInput.value = 0;
  1525. updateHomingInfo();
  1526. }
  1527. // Function to save homing configuration
  1528. async function saveHomingConfig() {
  1529. // Update button UI to show loading state
  1530. const originalButtonHTML = saveHomingConfigButton.innerHTML;
  1531. saveHomingConfigButton.disabled = true;
  1532. saveHomingConfigButton.innerHTML = '<span class="material-icons text-lg animate-spin">refresh</span><span class="truncate">Saving...</span>';
  1533. try {
  1534. const response = await fetch('/api/homing-config', {
  1535. method: 'POST',
  1536. headers: { 'Content-Type': 'application/json' },
  1537. body: JSON.stringify({
  1538. homing_mode: getSelectedMode(),
  1539. angular_homing_offset_degrees: parseFloat(angularOffsetInput.value) || 0
  1540. })
  1541. });
  1542. if (!response.ok) {
  1543. const errorData = await response.json();
  1544. throw new Error(errorData.detail || 'Failed to save homing configuration');
  1545. }
  1546. // Show success state temporarily
  1547. saveHomingConfigButton.innerHTML = '<span class="material-icons text-lg">check</span><span class="truncate">Saved!</span>';
  1548. showStatusMessage('Homing configuration saved successfully', 'success');
  1549. // Restore button after 2 seconds
  1550. setTimeout(() => {
  1551. saveHomingConfigButton.innerHTML = originalButtonHTML;
  1552. saveHomingConfigButton.disabled = false;
  1553. }, 2000);
  1554. } catch (error) {
  1555. logMessage(`Error saving homing configuration: ${error.message}`, LOG_TYPE.ERROR);
  1556. showStatusMessage(`Failed to save homing configuration: ${error.message}`, 'error');
  1557. // Restore button immediately on error
  1558. saveHomingConfigButton.innerHTML = originalButtonHTML;
  1559. saveHomingConfigButton.disabled = false;
  1560. }
  1561. }
  1562. // Event listeners
  1563. homingModeCrash.addEventListener('change', updateHomingInfo);
  1564. homingModeSensor.addEventListener('change', updateHomingInfo);
  1565. saveHomingConfigButton.addEventListener('click', saveHomingConfig);
  1566. }