1
0

settings.js 90 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192
  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. // Get save button
  1141. const saveAutoPlayButton = document.getElementById('saveAutoPlaySettings');
  1142. // Function to save settings
  1143. async function saveSettings(showFeedback = false) {
  1144. const originalButtonHTML = saveAutoPlayButton ? saveAutoPlayButton.innerHTML : '';
  1145. if (showFeedback && saveAutoPlayButton) {
  1146. saveAutoPlayButton.disabled = true;
  1147. saveAutoPlayButton.innerHTML = '<span class="material-icons text-lg animate-spin">refresh</span><span class="truncate">Saving...</span>';
  1148. }
  1149. try {
  1150. const response = await fetch('/api/auto_play-mode', {
  1151. method: 'POST',
  1152. headers: { 'Content-Type': 'application/json' },
  1153. body: JSON.stringify({
  1154. enabled: auto_playToggle.checked,
  1155. playlist: auto_playPlaylistSelect.value || null,
  1156. run_mode: auto_playRunModeSelect.value,
  1157. pause_time: parseFloat(auto_playPauseTimeInput.value) || 0,
  1158. clear_pattern: auto_playClearPatternSelect.value,
  1159. shuffle: auto_playShuffleToggle.checked
  1160. })
  1161. });
  1162. if (!response.ok) {
  1163. throw new Error('Failed to save settings');
  1164. }
  1165. if (showFeedback && saveAutoPlayButton) {
  1166. saveAutoPlayButton.innerHTML = '<span class="material-icons text-lg">check</span><span class="truncate">Saved!</span>';
  1167. showStatusMessage('Auto-play settings saved successfully', 'success');
  1168. setTimeout(() => {
  1169. saveAutoPlayButton.innerHTML = originalButtonHTML;
  1170. saveAutoPlayButton.disabled = false;
  1171. }, 2000);
  1172. }
  1173. } catch (error) {
  1174. logMessage(`Error saving auto_play settings: ${error.message}`, LOG_TYPE.ERROR);
  1175. if (showFeedback && saveAutoPlayButton) {
  1176. showStatusMessage(`Failed to save settings: ${error.message}`, 'error');
  1177. saveAutoPlayButton.innerHTML = originalButtonHTML;
  1178. saveAutoPlayButton.disabled = false;
  1179. }
  1180. }
  1181. }
  1182. // Toggle auto_play settings visibility and save
  1183. auto_playToggle.addEventListener('change', async () => {
  1184. auto_playSettings.style.display = auto_playToggle.checked ? 'block' : 'none';
  1185. await saveSettings(false); // Auto-save toggle state without full feedback
  1186. const statusText = auto_playToggle.checked ? 'enabled' : 'disabled';
  1187. showStatusMessage(`Auto-play ${statusText}`, 'success');
  1188. });
  1189. // Save button click handler
  1190. if (saveAutoPlayButton) {
  1191. saveAutoPlayButton.addEventListener('click', () => saveSettings(true));
  1192. }
  1193. }
  1194. // Initialize auto_play mode when DOM is ready
  1195. document.addEventListener('DOMContentLoaded', function() {
  1196. initializeauto_playMode();
  1197. initializeStillSandsMode();
  1198. initializeHomingConfig();
  1199. });
  1200. // Still Sands Mode Functions
  1201. async function initializeStillSandsMode() {
  1202. logMessage('Initializing Still Sands mode', LOG_TYPE.INFO);
  1203. const stillSandsToggle = document.getElementById('scheduledPauseToggle');
  1204. const stillSandsSettings = document.getElementById('scheduledPauseSettings');
  1205. const addTimeSlotButton = document.getElementById('addTimeSlotButton');
  1206. const saveStillSandsButton = document.getElementById('savePauseSettings');
  1207. const timeSlotsContainer = document.getElementById('timeSlotsContainer');
  1208. const wledControlToggle = document.getElementById('stillSandsWledControl');
  1209. const finishPatternToggle = document.getElementById('stillSandsFinishPattern');
  1210. const timezoneSelect = document.getElementById('stillSandsTimezone');
  1211. // Check if elements exist
  1212. if (!stillSandsToggle || !stillSandsSettings || !addTimeSlotButton || !saveStillSandsButton || !timeSlotsContainer) {
  1213. logMessage('Still Sands elements not found, skipping initialization', LOG_TYPE.WARNING);
  1214. logMessage(`Found elements: toggle=${!!stillSandsToggle}, settings=${!!stillSandsSettings}, addBtn=${!!addTimeSlotButton}, saveBtn=${!!saveStillSandsButton}, container=${!!timeSlotsContainer}`, LOG_TYPE.WARNING);
  1215. return;
  1216. }
  1217. logMessage('All Still Sands elements found successfully', LOG_TYPE.INFO);
  1218. // Track time slots
  1219. let timeSlots = [];
  1220. let slotIdCounter = 0;
  1221. // Load current Still Sands settings from initial data
  1222. try {
  1223. // Use the data loaded during page initialization, fallback to API if not available
  1224. let data;
  1225. if (window.initialStillSandsData) {
  1226. data = window.initialStillSandsData;
  1227. // Clear the global variable after use
  1228. delete window.initialStillSandsData;
  1229. } else {
  1230. // Fallback to API call if initial data not available
  1231. const response = await fetch('/api/scheduled-pause');
  1232. data = await response.json();
  1233. }
  1234. stillSandsToggle.checked = data.enabled || false;
  1235. if (data.enabled) {
  1236. stillSandsSettings.style.display = 'block';
  1237. }
  1238. // Load WLED control setting
  1239. if (wledControlToggle) {
  1240. wledControlToggle.checked = data.control_wled || false;
  1241. }
  1242. // Load finish pattern setting
  1243. if (finishPatternToggle) {
  1244. finishPatternToggle.checked = data.finish_pattern || false;
  1245. }
  1246. // Load timezone setting
  1247. if (timezoneSelect) {
  1248. timezoneSelect.value = data.timezone || '';
  1249. }
  1250. // Load existing time slots
  1251. timeSlots = data.time_slots || [];
  1252. // Assign IDs to loaded slots BEFORE rendering
  1253. if (timeSlots.length > 0) {
  1254. slotIdCounter = 0;
  1255. timeSlots.forEach(slot => {
  1256. slot.id = ++slotIdCounter;
  1257. });
  1258. }
  1259. renderTimeSlots();
  1260. } catch (error) {
  1261. logMessage(`Error loading Still Sands settings: ${error.message}`, LOG_TYPE.ERROR);
  1262. // Initialize with empty settings if load fails
  1263. timeSlots = [];
  1264. renderTimeSlots();
  1265. }
  1266. // Function to validate time format (HH:MM)
  1267. function isValidTime(timeString) {
  1268. const timeRegex = /^([01]?[0-9]|2[0-3]):[0-5][0-9]$/;
  1269. return timeRegex.test(timeString);
  1270. }
  1271. // Function to create a new time slot element
  1272. function createTimeSlotElement(slot) {
  1273. const slotDiv = document.createElement('div');
  1274. slotDiv.className = 'time-slot-item';
  1275. slotDiv.dataset.slotId = slot.id;
  1276. slotDiv.innerHTML = `
  1277. <div class="flex items-center gap-3">
  1278. <div class="flex-1 grid grid-cols-1 md:grid-cols-2 gap-3">
  1279. <div class="flex flex-col gap-1">
  1280. <label class="text-slate-700 dark:text-slate-300 text-xs font-medium">Start Time</label>
  1281. <input
  1282. type="time"
  1283. 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"
  1284. value="${slot.start_time || ''}"
  1285. required
  1286. />
  1287. </div>
  1288. <div class="flex flex-col gap-1">
  1289. <label class="text-slate-700 dark:text-slate-300 text-xs font-medium">End Time</label>
  1290. <input
  1291. type="time"
  1292. 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"
  1293. value="${slot.end_time || ''}"
  1294. required
  1295. />
  1296. </div>
  1297. </div>
  1298. <div class="flex flex-col gap-1">
  1299. <label class="text-slate-700 dark:text-slate-300 text-xs font-medium">Days</label>
  1300. <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">
  1301. <option value="daily" ${slot.days === 'daily' ? 'selected' : ''}>Daily</option>
  1302. <option value="weekdays" ${slot.days === 'weekdays' ? 'selected' : ''}>Weekdays</option>
  1303. <option value="weekends" ${slot.days === 'weekends' ? 'selected' : ''}>Weekends</option>
  1304. <option value="custom" ${slot.days === 'custom' ? 'selected' : ''}>Custom</option>
  1305. </select>
  1306. </div>
  1307. <button
  1308. type="button"
  1309. 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"
  1310. title="Remove time slot"
  1311. >
  1312. <span class="material-icons text-base">delete</span>
  1313. </button>
  1314. </div>
  1315. <div class="custom-days-container mt-2" style="display: ${slot.days === 'custom' ? 'block' : 'none'};">
  1316. <label class="text-slate-700 dark:text-slate-300 text-xs font-medium mb-1 block">Select Days</label>
  1317. <div class="flex flex-wrap gap-2">
  1318. ${['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday'].map(day => `
  1319. <label class="flex items-center gap-1 text-xs">
  1320. <input
  1321. type="checkbox"
  1322. name="custom-days-${slot.id}"
  1323. value="${day}"
  1324. ${slot.custom_days && slot.custom_days.includes(day) ? 'checked' : ''}
  1325. class="rounded border-slate-300 text-sky-600 focus:ring-sky-500"
  1326. />
  1327. <span class="text-slate-700 dark:text-slate-300 capitalize">${day.substring(0, 3)}</span>
  1328. </label>
  1329. `).join('')}
  1330. </div>
  1331. </div>
  1332. `;
  1333. // Add event listeners for this slot
  1334. const startTimeInput = slotDiv.querySelector('.start-time');
  1335. const endTimeInput = slotDiv.querySelector('.end-time');
  1336. const daysSelect = slotDiv.querySelector('.days-select');
  1337. const customDaysContainer = slotDiv.querySelector('.custom-days-container');
  1338. const removeButton = slotDiv.querySelector('.remove-slot-btn');
  1339. // Show/hide custom days based on selection
  1340. daysSelect.addEventListener('change', () => {
  1341. customDaysContainer.style.display = daysSelect.value === 'custom' ? 'block' : 'none';
  1342. updateTimeSlot(slot.id);
  1343. });
  1344. // Update slot data when inputs change
  1345. startTimeInput.addEventListener('change', () => updateTimeSlot(slot.id));
  1346. endTimeInput.addEventListener('change', () => updateTimeSlot(slot.id));
  1347. // Handle custom day checkboxes
  1348. customDaysContainer.addEventListener('change', () => updateTimeSlot(slot.id));
  1349. // Remove slot button
  1350. removeButton.addEventListener('click', () => {
  1351. removeTimeSlot(slot.id);
  1352. });
  1353. return slotDiv;
  1354. }
  1355. // Function to render all time slots
  1356. function renderTimeSlots() {
  1357. timeSlotsContainer.innerHTML = '';
  1358. if (timeSlots.length === 0) {
  1359. timeSlotsContainer.innerHTML = `
  1360. <div class="text-center py-8 text-slate-500 dark:text-slate-400">
  1361. <span class="material-icons text-4xl mb-2 block">schedule</span>
  1362. <p>No time slots configured</p>
  1363. <p class="text-xs mt-1">Click "Add Time Slot" to create a pause schedule</p>
  1364. </div>
  1365. `;
  1366. return;
  1367. }
  1368. timeSlots.forEach(slot => {
  1369. const slotElement = createTimeSlotElement(slot);
  1370. timeSlotsContainer.appendChild(slotElement);
  1371. });
  1372. }
  1373. // Function to add a new time slot
  1374. function addTimeSlot() {
  1375. const newSlot = {
  1376. id: ++slotIdCounter,
  1377. start_time: '22:00',
  1378. end_time: '08:00',
  1379. days: 'daily',
  1380. custom_days: []
  1381. };
  1382. timeSlots.push(newSlot);
  1383. renderTimeSlots();
  1384. }
  1385. // Function to remove a time slot
  1386. function removeTimeSlot(slotId) {
  1387. timeSlots = timeSlots.filter(slot => slot.id !== slotId);
  1388. renderTimeSlots();
  1389. }
  1390. // Function to update a time slot's data
  1391. function updateTimeSlot(slotId) {
  1392. const slotElement = timeSlotsContainer.querySelector(`[data-slot-id="${slotId}"]`);
  1393. if (!slotElement) return;
  1394. const slot = timeSlots.find(s => s.id === slotId);
  1395. if (!slot) return;
  1396. // Update slot data from inputs
  1397. slot.start_time = slotElement.querySelector('.start-time').value;
  1398. slot.end_time = slotElement.querySelector('.end-time').value;
  1399. slot.days = slotElement.querySelector('.days-select').value;
  1400. // Update custom days if applicable
  1401. if (slot.days === 'custom') {
  1402. const checkedDays = Array.from(slotElement.querySelectorAll(`input[name="custom-days-${slotId}"]:checked`))
  1403. .map(cb => cb.value);
  1404. slot.custom_days = checkedDays;
  1405. } else {
  1406. slot.custom_days = [];
  1407. }
  1408. }
  1409. // Function to validate all time slots
  1410. function validateTimeSlots() {
  1411. const errors = [];
  1412. timeSlots.forEach((slot, index) => {
  1413. if (!slot.start_time || !isValidTime(slot.start_time)) {
  1414. errors.push(`Time slot ${index + 1}: Invalid start time`);
  1415. }
  1416. if (!slot.end_time || !isValidTime(slot.end_time)) {
  1417. errors.push(`Time slot ${index + 1}: Invalid end time`);
  1418. }
  1419. if (slot.days === 'custom' && (!slot.custom_days || slot.custom_days.length === 0)) {
  1420. errors.push(`Time slot ${index + 1}: Please select at least one day for custom schedule`);
  1421. }
  1422. });
  1423. return errors;
  1424. }
  1425. // Function to save settings
  1426. async function saveStillSandsSettings() {
  1427. // Update all slots from current form values
  1428. timeSlots.forEach(slot => updateTimeSlot(slot.id));
  1429. // Validate time slots
  1430. const validationErrors = validateTimeSlots();
  1431. if (validationErrors.length > 0) {
  1432. showStatusMessage(`Validation errors: ${validationErrors.join(', ')}`, 'error');
  1433. return;
  1434. }
  1435. // Update button UI to show loading state
  1436. const originalButtonHTML = saveStillSandsButton.innerHTML;
  1437. saveStillSandsButton.disabled = true;
  1438. saveStillSandsButton.innerHTML = '<span class="material-icons text-lg animate-spin">refresh</span><span class="truncate">Saving...</span>';
  1439. try {
  1440. const response = await fetch('/api/scheduled-pause', {
  1441. method: 'POST',
  1442. headers: { 'Content-Type': 'application/json' },
  1443. body: JSON.stringify({
  1444. enabled: stillSandsToggle.checked,
  1445. control_wled: wledControlToggle ? wledControlToggle.checked : false,
  1446. finish_pattern: finishPatternToggle ? finishPatternToggle.checked : false,
  1447. timezone: timezoneSelect ? (timezoneSelect.value || null) : null,
  1448. time_slots: timeSlots.map(slot => ({
  1449. start_time: slot.start_time,
  1450. end_time: slot.end_time,
  1451. days: slot.days,
  1452. custom_days: slot.custom_days
  1453. }))
  1454. })
  1455. });
  1456. if (!response.ok) {
  1457. const errorData = await response.json();
  1458. throw new Error(errorData.detail || 'Failed to save Still Sands settings');
  1459. }
  1460. // Show success state temporarily
  1461. saveStillSandsButton.innerHTML = '<span class="material-icons text-lg">check</span><span class="truncate">Saved!</span>';
  1462. showStatusMessage('Still Sands settings saved successfully', 'success');
  1463. // Restore button after 2 seconds
  1464. setTimeout(() => {
  1465. saveStillSandsButton.innerHTML = originalButtonHTML;
  1466. saveStillSandsButton.disabled = false;
  1467. }, 2000);
  1468. } catch (error) {
  1469. logMessage(`Error saving Still Sands settings: ${error.message}`, LOG_TYPE.ERROR);
  1470. showStatusMessage(`Failed to save settings: ${error.message}`, 'error');
  1471. // Restore button immediately on error
  1472. saveStillSandsButton.innerHTML = originalButtonHTML;
  1473. saveStillSandsButton.disabled = false;
  1474. }
  1475. }
  1476. // Note: Slot IDs are now assigned during initialization above, before first render
  1477. // Event listeners
  1478. stillSandsToggle.addEventListener('change', async () => {
  1479. logMessage(`Still Sands toggle changed: ${stillSandsToggle.checked}`, LOG_TYPE.INFO);
  1480. stillSandsSettings.style.display = stillSandsToggle.checked ? 'block' : 'none';
  1481. logMessage(`Settings display set to: ${stillSandsSettings.style.display}`, LOG_TYPE.INFO);
  1482. // Auto-save when toggle changes
  1483. try {
  1484. await saveStillSandsSettings();
  1485. const statusText = stillSandsToggle.checked ? 'enabled' : 'disabled';
  1486. showStatusMessage(`Still Sands ${statusText} successfully`, 'success');
  1487. } catch (error) {
  1488. logMessage(`Error saving Still Sands toggle: ${error.message}`, LOG_TYPE.ERROR);
  1489. showStatusMessage(`Failed to save Still Sands setting: ${error.message}`, 'error');
  1490. }
  1491. });
  1492. addTimeSlotButton.addEventListener('click', addTimeSlot);
  1493. saveStillSandsButton.addEventListener('click', saveStillSandsSettings);
  1494. // Add listener for WLED control toggle
  1495. if (wledControlToggle) {
  1496. wledControlToggle.addEventListener('change', async () => {
  1497. logMessage(`WLED control toggle changed: ${wledControlToggle.checked}`, LOG_TYPE.INFO);
  1498. // Auto-save when WLED control changes
  1499. await saveStillSandsSettings();
  1500. });
  1501. }
  1502. // Add listener for finish pattern toggle
  1503. if (finishPatternToggle) {
  1504. finishPatternToggle.addEventListener('change', async () => {
  1505. logMessage(`Finish pattern toggle changed: ${finishPatternToggle.checked}`, LOG_TYPE.INFO);
  1506. // Auto-save when finish pattern setting changes
  1507. await saveStillSandsSettings();
  1508. });
  1509. }
  1510. // Add listener for timezone select
  1511. if (timezoneSelect) {
  1512. timezoneSelect.addEventListener('change', async () => {
  1513. logMessage(`Timezone changed: ${timezoneSelect.value || 'System Default'}`, LOG_TYPE.INFO);
  1514. // Auto-save when timezone changes
  1515. await saveStillSandsSettings();
  1516. });
  1517. }
  1518. }
  1519. // Homing Configuration
  1520. async function initializeHomingConfig() {
  1521. logMessage('Initializing homing configuration', LOG_TYPE.INFO);
  1522. const homingModeCrash = document.getElementById('homingModeCrash');
  1523. const homingModeSensor = document.getElementById('homingModeSensor');
  1524. const angularOffsetInput = document.getElementById('angularOffsetInput');
  1525. const compassOffsetContainer = document.getElementById('compassOffsetContainer');
  1526. const saveHomingConfigButton = document.getElementById('saveHomingConfig');
  1527. const homingInfoContent = document.getElementById('homingInfoContent');
  1528. const autoHomeEnabledToggle = document.getElementById('autoHomeEnabledToggle');
  1529. const autoHomeSettings = document.getElementById('autoHomeSettings');
  1530. const autoHomeAfterPatternsInput = document.getElementById('autoHomeAfterPatternsInput');
  1531. // Check if elements exist
  1532. if (!homingModeCrash || !homingModeSensor || !angularOffsetInput || !saveHomingConfigButton || !homingInfoContent || !compassOffsetContainer) {
  1533. logMessage('Homing configuration elements not found, skipping initialization', LOG_TYPE.WARNING);
  1534. return;
  1535. }
  1536. logMessage('Homing configuration elements found successfully', LOG_TYPE.INFO);
  1537. // Function to get selected homing mode
  1538. function getSelectedMode() {
  1539. return homingModeCrash.checked ? 0 : 1;
  1540. }
  1541. // Function to update info box and visibility based on selected mode
  1542. function updateHomingInfo() {
  1543. const mode = getSelectedMode();
  1544. // Show/hide compass offset based on mode
  1545. if (mode === 0) {
  1546. compassOffsetContainer.style.display = 'none';
  1547. homingInfoContent.innerHTML = `
  1548. <p class="font-medium text-blue-800">Crash Homing Mode:</p>
  1549. <ul class="mt-1 space-y-1 text-blue-700">
  1550. <li>• Y axis moves -22mm (or -30mm for mini) until physical stop</li>
  1551. <li>• Theta set to 0, rho set to 0</li>
  1552. <li>• No x0 y0 command sent</li>
  1553. <li>• No hardware sensors required</li>
  1554. </ul>
  1555. `;
  1556. } else {
  1557. compassOffsetContainer.style.display = 'block';
  1558. homingInfoContent.innerHTML = `
  1559. <p class="font-medium text-blue-800">Sensor Homing Mode:</p>
  1560. <ul class="mt-1 space-y-1 text-blue-700">
  1561. <li>• Requires hardware limit switches</li>
  1562. <li>• Requires additional configuration</li>
  1563. </ul>
  1564. `;
  1565. }
  1566. }
  1567. // Load current homing configuration
  1568. try {
  1569. const response = await fetch('/api/homing-config');
  1570. const data = await response.json();
  1571. // Set radio button based on mode
  1572. if (data.homing_mode === 1) {
  1573. homingModeSensor.checked = true;
  1574. } else {
  1575. homingModeCrash.checked = true;
  1576. }
  1577. angularOffsetInput.value = data.angular_homing_offset_degrees || 0;
  1578. // Load auto-home settings
  1579. if (autoHomeEnabledToggle) {
  1580. autoHomeEnabledToggle.checked = data.auto_home_enabled || false;
  1581. if (autoHomeSettings) {
  1582. autoHomeSettings.style.display = data.auto_home_enabled ? 'block' : 'none';
  1583. }
  1584. }
  1585. if (autoHomeAfterPatternsInput) {
  1586. autoHomeAfterPatternsInput.value = data.auto_home_after_patterns || 5;
  1587. }
  1588. updateHomingInfo();
  1589. 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);
  1590. } catch (error) {
  1591. logMessage(`Error loading homing configuration: ${error.message}`, LOG_TYPE.ERROR);
  1592. // Initialize with defaults if load fails
  1593. homingModeCrash.checked = true;
  1594. angularOffsetInput.value = 0;
  1595. if (autoHomeEnabledToggle) autoHomeEnabledToggle.checked = false;
  1596. if (autoHomeAfterPatternsInput) autoHomeAfterPatternsInput.value = 5;
  1597. updateHomingInfo();
  1598. }
  1599. // Function to save homing configuration
  1600. async function saveHomingConfig() {
  1601. // Update button UI to show loading state
  1602. const originalButtonHTML = saveHomingConfigButton.innerHTML;
  1603. saveHomingConfigButton.disabled = true;
  1604. saveHomingConfigButton.innerHTML = '<span class="material-icons text-lg animate-spin">refresh</span><span class="truncate">Saving...</span>';
  1605. try {
  1606. const requestBody = {
  1607. homing_mode: getSelectedMode(),
  1608. angular_homing_offset_degrees: parseFloat(angularOffsetInput.value) || 0
  1609. };
  1610. // Include auto-home settings if elements exist
  1611. if (autoHomeEnabledToggle) {
  1612. requestBody.auto_home_enabled = autoHomeEnabledToggle.checked;
  1613. }
  1614. if (autoHomeAfterPatternsInput) {
  1615. const afterPatterns = parseInt(autoHomeAfterPatternsInput.value);
  1616. if (!isNaN(afterPatterns) && afterPatterns >= 1) {
  1617. requestBody.auto_home_after_patterns = afterPatterns;
  1618. }
  1619. }
  1620. const response = await fetch('/api/homing-config', {
  1621. method: 'POST',
  1622. headers: { 'Content-Type': 'application/json' },
  1623. body: JSON.stringify(requestBody)
  1624. });
  1625. if (!response.ok) {
  1626. const errorData = await response.json();
  1627. throw new Error(errorData.detail || 'Failed to save homing configuration');
  1628. }
  1629. // Show success state temporarily
  1630. saveHomingConfigButton.innerHTML = '<span class="material-icons text-lg">check</span><span class="truncate">Saved!</span>';
  1631. showStatusMessage('Homing configuration saved successfully', 'success');
  1632. // Restore button after 2 seconds
  1633. setTimeout(() => {
  1634. saveHomingConfigButton.innerHTML = originalButtonHTML;
  1635. saveHomingConfigButton.disabled = false;
  1636. }, 2000);
  1637. } catch (error) {
  1638. logMessage(`Error saving homing configuration: ${error.message}`, LOG_TYPE.ERROR);
  1639. showStatusMessage(`Failed to save homing configuration: ${error.message}`, 'error');
  1640. // Restore button immediately on error
  1641. saveHomingConfigButton.innerHTML = originalButtonHTML;
  1642. saveHomingConfigButton.disabled = false;
  1643. }
  1644. }
  1645. // Event listeners
  1646. homingModeCrash.addEventListener('change', updateHomingInfo);
  1647. homingModeSensor.addEventListener('change', updateHomingInfo);
  1648. saveHomingConfigButton.addEventListener('click', saveHomingConfig);
  1649. // Auto-home toggle event listener
  1650. if (autoHomeEnabledToggle && autoHomeSettings) {
  1651. autoHomeEnabledToggle.addEventListener('change', () => {
  1652. autoHomeSettings.style.display = autoHomeEnabledToggle.checked ? 'block' : 'none';
  1653. });
  1654. }
  1655. }
  1656. // Toggle password visibility helper
  1657. function togglePasswordVisibility(inputId, button) {
  1658. const input = document.getElementById(inputId);
  1659. if (!input || !button) return;
  1660. const icon = button.querySelector('.material-icons');
  1661. if (input.type === 'password') {
  1662. input.type = 'text';
  1663. if (icon) icon.textContent = 'visibility';
  1664. } else {
  1665. input.type = 'password';
  1666. if (icon) icon.textContent = 'visibility_off';
  1667. }
  1668. }
  1669. // MQTT Configuration
  1670. async function initializeMqttConfig() {
  1671. logMessage('Initializing MQTT configuration', LOG_TYPE.INFO);
  1672. const mqttEnableToggle = document.getElementById('mqttEnableToggle');
  1673. const mqttSettings = document.getElementById('mqttSettings');
  1674. const mqttStatusBanner = document.getElementById('mqttStatusBanner');
  1675. const mqttConnectedBanner = document.getElementById('mqttConnectedBanner');
  1676. const mqttDisconnectedBanner = document.getElementById('mqttDisconnectedBanner');
  1677. const mqttBrokerInput = document.getElementById('mqttBrokerInput');
  1678. const mqttPortInput = document.getElementById('mqttPortInput');
  1679. const mqttUsernameInput = document.getElementById('mqttUsernameInput');
  1680. const mqttPasswordInput = document.getElementById('mqttPasswordInput');
  1681. const mqttDeviceNameInput = document.getElementById('mqttDeviceNameInput');
  1682. const mqttDeviceIdInput = document.getElementById('mqttDeviceIdInput');
  1683. const mqttClientIdInput = document.getElementById('mqttClientIdInput');
  1684. const mqttDiscoveryPrefixInput = document.getElementById('mqttDiscoveryPrefixInput');
  1685. const testMqttButton = document.getElementById('testMqttConnection');
  1686. const mqttTestResult = document.getElementById('mqttTestResult');
  1687. const saveMqttButton = document.getElementById('saveMqttConfig');
  1688. const mqttRestartNotice = document.getElementById('mqttRestartNotice');
  1689. // Check if elements exist
  1690. if (!mqttEnableToggle || !mqttSettings || !saveMqttButton) {
  1691. logMessage('MQTT configuration elements not found, skipping initialization', LOG_TYPE.WARNING);
  1692. return;
  1693. }
  1694. logMessage('MQTT configuration elements found successfully', LOG_TYPE.INFO);
  1695. // Track if settings have changed (to show restart notice)
  1696. let originalConfig = null;
  1697. let configChanged = false;
  1698. // Function to update UI based on enabled state
  1699. function updateMqttSettingsVisibility() {
  1700. mqttSettings.style.display = mqttEnableToggle.checked ? 'block' : 'none';
  1701. if (mqttStatusBanner) {
  1702. mqttStatusBanner.classList.toggle('hidden', !mqttEnableToggle.checked);
  1703. }
  1704. }
  1705. // Function to update connection status banners
  1706. function updateConnectionStatus(connected) {
  1707. if (mqttConnectedBanner && mqttDisconnectedBanner) {
  1708. if (connected) {
  1709. mqttConnectedBanner.classList.remove('hidden');
  1710. mqttDisconnectedBanner.classList.add('hidden');
  1711. } else {
  1712. mqttConnectedBanner.classList.add('hidden');
  1713. mqttDisconnectedBanner.classList.remove('hidden');
  1714. }
  1715. }
  1716. }
  1717. // Function to check if config has changed
  1718. function checkConfigChanged() {
  1719. if (!originalConfig) return false;
  1720. const currentConfig = {
  1721. enabled: mqttEnableToggle.checked,
  1722. broker: mqttBrokerInput.value,
  1723. port: parseInt(mqttPortInput.value) || 1883,
  1724. username: mqttUsernameInput.value,
  1725. password: mqttPasswordInput.value,
  1726. device_name: mqttDeviceNameInput.value,
  1727. device_id: mqttDeviceIdInput.value,
  1728. client_id: mqttClientIdInput.value,
  1729. discovery_prefix: mqttDiscoveryPrefixInput.value
  1730. };
  1731. return JSON.stringify(currentConfig) !== JSON.stringify(originalConfig);
  1732. }
  1733. // Function to show/hide restart notice
  1734. function updateRestartNotice() {
  1735. configChanged = checkConfigChanged();
  1736. if (mqttRestartNotice) {
  1737. mqttRestartNotice.classList.toggle('hidden', !configChanged);
  1738. }
  1739. }
  1740. // Load current MQTT configuration
  1741. try {
  1742. const response = await fetch('/api/mqtt-config');
  1743. const data = await response.json();
  1744. mqttEnableToggle.checked = data.enabled || false;
  1745. mqttBrokerInput.value = data.broker || '';
  1746. mqttPortInput.value = data.port || 1883;
  1747. mqttUsernameInput.value = data.username || '';
  1748. // Note: Password is not returned from API for security
  1749. mqttDeviceNameInput.value = data.device_name || 'Dune Weaver';
  1750. mqttDeviceIdInput.value = data.device_id || 'dune_weaver';
  1751. mqttClientIdInput.value = data.client_id || 'dune_weaver';
  1752. mqttDiscoveryPrefixInput.value = data.discovery_prefix || 'homeassistant';
  1753. // Store original config for change detection
  1754. originalConfig = {
  1755. enabled: data.enabled || false,
  1756. broker: data.broker || '',
  1757. port: data.port || 1883,
  1758. username: data.username || '',
  1759. password: '', // We don't have the original password
  1760. device_name: data.device_name || 'Dune Weaver',
  1761. device_id: data.device_id || 'dune_weaver',
  1762. client_id: data.client_id || 'dune_weaver',
  1763. discovery_prefix: data.discovery_prefix || 'homeassistant'
  1764. };
  1765. updateMqttSettingsVisibility();
  1766. // Update connection status if MQTT is enabled
  1767. if (data.enabled) {
  1768. updateConnectionStatus(data.connected || false);
  1769. }
  1770. logMessage(`Loaded MQTT config: enabled=${data.enabled}, broker=${data.broker}`, LOG_TYPE.INFO);
  1771. } catch (error) {
  1772. logMessage(`Error loading MQTT configuration: ${error.message}`, LOG_TYPE.ERROR);
  1773. // Initialize with defaults if load fails
  1774. mqttEnableToggle.checked = false;
  1775. updateMqttSettingsVisibility();
  1776. }
  1777. // Function to save MQTT configuration
  1778. async function saveMqttConfig() {
  1779. // Validate required fields if MQTT is enabled
  1780. if (mqttEnableToggle.checked && !mqttBrokerInput.value.trim()) {
  1781. showStatusMessage('MQTT broker address is required when MQTT is enabled', 'error');
  1782. mqttBrokerInput.focus();
  1783. return;
  1784. }
  1785. // Update button UI to show loading state
  1786. const originalButtonHTML = saveMqttButton.innerHTML;
  1787. saveMqttButton.disabled = true;
  1788. saveMqttButton.innerHTML = '<span class="material-icons text-lg animate-spin">refresh</span><span class="truncate">Saving...</span>';
  1789. try {
  1790. const requestBody = {
  1791. enabled: mqttEnableToggle.checked,
  1792. broker: mqttBrokerInput.value.trim(),
  1793. port: parseInt(mqttPortInput.value) || 1883,
  1794. username: mqttUsernameInput.value.trim() || null,
  1795. device_name: mqttDeviceNameInput.value.trim() || 'Dune Weaver',
  1796. device_id: mqttDeviceIdInput.value.trim() || 'dune_weaver',
  1797. client_id: mqttClientIdInput.value.trim() || 'dune_weaver',
  1798. discovery_prefix: mqttDiscoveryPrefixInput.value.trim() || 'homeassistant'
  1799. };
  1800. // Only include password if it was changed (not empty)
  1801. if (mqttPasswordInput.value) {
  1802. requestBody.password = mqttPasswordInput.value;
  1803. }
  1804. const response = await fetch('/api/mqtt-config', {
  1805. method: 'POST',
  1806. headers: { 'Content-Type': 'application/json' },
  1807. body: JSON.stringify(requestBody)
  1808. });
  1809. if (!response.ok) {
  1810. const errorData = await response.json();
  1811. throw new Error(errorData.detail || 'Failed to save MQTT configuration');
  1812. }
  1813. const data = await response.json();
  1814. // Update original config for change detection
  1815. originalConfig = {
  1816. enabled: requestBody.enabled,
  1817. broker: requestBody.broker,
  1818. port: requestBody.port,
  1819. username: requestBody.username || '',
  1820. password: '', // Reset password tracking
  1821. device_name: requestBody.device_name,
  1822. device_id: requestBody.device_id,
  1823. client_id: requestBody.client_id,
  1824. discovery_prefix: requestBody.discovery_prefix
  1825. };
  1826. // Clear password field after save
  1827. mqttPasswordInput.value = '';
  1828. // Show success state temporarily
  1829. saveMqttButton.innerHTML = '<span class="material-icons text-lg">check</span><span class="truncate">Saved!</span>';
  1830. showStatusMessage('MQTT configuration saved successfully. Restart the application to apply changes.', 'success');
  1831. // Show restart notice
  1832. if (mqttRestartNotice) {
  1833. mqttRestartNotice.classList.remove('hidden');
  1834. }
  1835. // Restore button after 2 seconds
  1836. setTimeout(() => {
  1837. saveMqttButton.innerHTML = originalButtonHTML;
  1838. saveMqttButton.disabled = false;
  1839. }, 2000);
  1840. } catch (error) {
  1841. logMessage(`Error saving MQTT configuration: ${error.message}`, LOG_TYPE.ERROR);
  1842. showStatusMessage(`Failed to save MQTT configuration: ${error.message}`, 'error');
  1843. // Restore button immediately on error
  1844. saveMqttButton.innerHTML = originalButtonHTML;
  1845. saveMqttButton.disabled = false;
  1846. }
  1847. }
  1848. // Function to test MQTT connection
  1849. async function testMqttConnection() {
  1850. // Validate broker address
  1851. if (!mqttBrokerInput.value.trim()) {
  1852. showStatusMessage('Please enter a broker address to test', 'error');
  1853. mqttBrokerInput.focus();
  1854. return;
  1855. }
  1856. // Update button UI to show loading state
  1857. const originalButtonHTML = testMqttButton.innerHTML;
  1858. testMqttButton.disabled = true;
  1859. testMqttButton.innerHTML = '<span class="material-icons text-lg animate-spin">refresh</span><span class="truncate">Testing...</span>';
  1860. // Clear previous result
  1861. if (mqttTestResult) {
  1862. mqttTestResult.innerHTML = '';
  1863. }
  1864. try {
  1865. const requestBody = {
  1866. broker: mqttBrokerInput.value.trim(),
  1867. port: parseInt(mqttPortInput.value) || 1883,
  1868. username: mqttUsernameInput.value.trim() || null,
  1869. password: mqttPasswordInput.value || null
  1870. };
  1871. const response = await fetch('/api/mqtt-test', {
  1872. method: 'POST',
  1873. headers: { 'Content-Type': 'application/json' },
  1874. body: JSON.stringify(requestBody)
  1875. });
  1876. const data = await response.json();
  1877. if (data.success) {
  1878. if (mqttTestResult) {
  1879. mqttTestResult.innerHTML = '<span class="material-icons text-green-600 mr-1">check_circle</span><span class="text-green-600">Connection successful!</span>';
  1880. }
  1881. showStatusMessage('MQTT connection test successful', 'success');
  1882. } else {
  1883. if (mqttTestResult) {
  1884. mqttTestResult.innerHTML = `<span class="material-icons text-red-600 mr-1">error</span><span class="text-red-600">${data.error || 'Connection failed'}</span>`;
  1885. }
  1886. showStatusMessage(`MQTT test failed: ${data.error || 'Connection failed'}`, 'error');
  1887. }
  1888. } catch (error) {
  1889. logMessage(`Error testing MQTT connection: ${error.message}`, LOG_TYPE.ERROR);
  1890. if (mqttTestResult) {
  1891. mqttTestResult.innerHTML = `<span class="material-icons text-red-600 mr-1">error</span><span class="text-red-600">Test failed: ${error.message}</span>`;
  1892. }
  1893. showStatusMessage(`MQTT test failed: ${error.message}`, 'error');
  1894. } finally {
  1895. // Restore button
  1896. testMqttButton.innerHTML = originalButtonHTML;
  1897. testMqttButton.disabled = false;
  1898. }
  1899. }
  1900. // Event listeners
  1901. mqttEnableToggle.addEventListener('change', () => {
  1902. updateMqttSettingsVisibility();
  1903. updateRestartNotice();
  1904. });
  1905. // Track changes to show restart notice
  1906. [mqttBrokerInput, mqttPortInput, mqttUsernameInput, mqttPasswordInput,
  1907. mqttDeviceNameInput, mqttDeviceIdInput, mqttClientIdInput, mqttDiscoveryPrefixInput].forEach(input => {
  1908. if (input) {
  1909. input.addEventListener('input', updateRestartNotice);
  1910. }
  1911. });
  1912. testMqttButton.addEventListener('click', testMqttConnection);
  1913. saveMqttButton.addEventListener('click', saveMqttConfig);
  1914. }
  1915. // Initialize MQTT config when DOM is ready
  1916. document.addEventListener('DOMContentLoaded', function() {
  1917. initializeMqttConfig();
  1918. });