settings.js 94 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285
  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. // Logo upload functionality
  745. const logoFileInput = document.getElementById('logoFileInput');
  746. const resetLogoBtn = document.getElementById('resetLogoBtn');
  747. const logoPreview = document.getElementById('logoPreview');
  748. const logoUploadStatus = document.getElementById('logoUploadStatus');
  749. if (logoFileInput) {
  750. logoFileInput.addEventListener('change', async (event) => {
  751. const file = event.target.files[0];
  752. if (!file) return;
  753. // Show uploading status
  754. if (logoUploadStatus) {
  755. logoUploadStatus.textContent = 'Uploading...';
  756. logoUploadStatus.className = 'text-xs text-slate-500';
  757. }
  758. const formData = new FormData();
  759. formData.append('file', file);
  760. try {
  761. const response = await fetch('/api/upload-logo', {
  762. method: 'POST',
  763. body: formData
  764. });
  765. if (response.ok) {
  766. const data = await response.json();
  767. // Update preview image with cache-busting query param
  768. if (logoPreview) {
  769. logoPreview.src = data.url + '?t=' + Date.now();
  770. }
  771. // Show reset button
  772. if (resetLogoBtn) {
  773. resetLogoBtn.classList.remove('hidden');
  774. }
  775. // Show success status
  776. if (logoUploadStatus) {
  777. logoUploadStatus.textContent = 'Logo uploaded successfully!';
  778. logoUploadStatus.className = 'text-xs text-green-600';
  779. setTimeout(() => {
  780. logoUploadStatus.textContent = '';
  781. }, 3000);
  782. }
  783. showStatusMessage('Logo uploaded successfully. Refresh the page to see all changes.', 'success');
  784. } else {
  785. const error = await response.json();
  786. throw new Error(error.detail || 'Failed to upload logo');
  787. }
  788. } catch (error) {
  789. if (logoUploadStatus) {
  790. logoUploadStatus.textContent = `Error: ${error.message}`;
  791. logoUploadStatus.className = 'text-xs text-red-600';
  792. }
  793. showStatusMessage(`Failed to upload logo: ${error.message}`, 'error');
  794. }
  795. // Reset file input so the same file can be re-selected
  796. logoFileInput.value = '';
  797. });
  798. }
  799. if (resetLogoBtn) {
  800. resetLogoBtn.addEventListener('click', async () => {
  801. try {
  802. const response = await fetch('/api/custom-logo', {
  803. method: 'DELETE'
  804. });
  805. if (response.ok) {
  806. // Reset preview to default logo
  807. if (logoPreview) {
  808. logoPreview.src = '/static/apple-touch-icon.png?t=' + Date.now();
  809. }
  810. // Hide reset button
  811. resetLogoBtn.classList.add('hidden');
  812. showStatusMessage('Logo reset to default. Refresh the page to see all changes.', 'success');
  813. } else {
  814. const error = await response.json();
  815. throw new Error(error.detail || 'Failed to reset logo');
  816. }
  817. } catch (error) {
  818. showStatusMessage(`Failed to reset logo: ${error.message}`, 'error');
  819. }
  820. });
  821. }
  822. // Save clear pattern speed button
  823. const saveClearSpeed = document.getElementById('saveClearSpeed');
  824. if (saveClearSpeed) {
  825. saveClearSpeed.addEventListener('click', async () => {
  826. const clearPatternSpeedInput = document.getElementById('clearPatternSpeedInput');
  827. if (!clearPatternSpeedInput) {
  828. return;
  829. }
  830. let speed;
  831. if (clearPatternSpeedInput.value === '' || clearPatternSpeedInput.value === null) {
  832. // Empty value means use default (None)
  833. speed = null;
  834. } else {
  835. speed = parseInt(clearPatternSpeedInput.value);
  836. // Validate speed only if it's not null
  837. if (isNaN(speed) || speed < 50 || speed > 2000) {
  838. showStatusMessage('Clear pattern speed must be between 50 and 2000, or leave empty for default', 'error');
  839. return;
  840. }
  841. }
  842. try {
  843. const response = await fetch('/api/settings', {
  844. method: 'PATCH',
  845. headers: { 'Content-Type': 'application/json' },
  846. body: JSON.stringify({ patterns: { clear_pattern_speed: speed } })
  847. });
  848. if (response.ok) {
  849. await response.json();
  850. if (speed === null) {
  851. showStatusMessage('Clear pattern speed set to default', 'success');
  852. } else {
  853. showStatusMessage(`Clear pattern speed set to ${speed} steps/min`, 'success');
  854. }
  855. // Update the effective speed display
  856. const effectiveClearSpeed = document.getElementById('effectiveClearSpeed');
  857. if (effectiveClearSpeed) {
  858. if (speed === null) {
  859. effectiveClearSpeed.textContent = `Using default pattern speed: ${data.effective_speed} steps/min`;
  860. } else {
  861. effectiveClearSpeed.textContent = `Current: ${speed} steps/min`;
  862. }
  863. }
  864. } else {
  865. const error = await response.json();
  866. throw new Error(error.detail || 'Failed to save clear pattern speed');
  867. }
  868. } catch (error) {
  869. showStatusMessage(`Failed to save clear pattern speed: ${error.message}`, 'error');
  870. }
  871. });
  872. }
  873. }
  874. // Button click handlers
  875. document.addEventListener('DOMContentLoaded', function() {
  876. // Home button
  877. const homeButton = document.getElementById('homeButton');
  878. if (homeButton) {
  879. homeButton.addEventListener('click', async () => {
  880. try {
  881. const response = await fetch('/send_home', {
  882. method: 'POST',
  883. headers: {
  884. 'Content-Type': 'application/json'
  885. }
  886. });
  887. const data = await response.json();
  888. if (data.success) {
  889. updateStatus('Moving to home position...');
  890. }
  891. } catch (error) {
  892. console.error('Error sending home command:', error);
  893. updateStatus('Error: Failed to move to home position');
  894. }
  895. });
  896. }
  897. // Stop button
  898. const stopButton = document.getElementById('stopButton');
  899. if (stopButton) {
  900. stopButton.addEventListener('click', async () => {
  901. try {
  902. const response = await fetch('/stop_execution', {
  903. method: 'POST',
  904. headers: {
  905. 'Content-Type': 'application/json'
  906. }
  907. });
  908. const data = await response.json();
  909. if (data.success) {
  910. updateStatus('Execution stopped');
  911. }
  912. } catch (error) {
  913. console.error('Error stopping execution:', error);
  914. updateStatus('Error: Failed to stop execution');
  915. }
  916. });
  917. }
  918. // Move to Center button
  919. const centerButton = document.getElementById('centerButton');
  920. if (centerButton) {
  921. centerButton.addEventListener('click', async () => {
  922. try {
  923. const response = await fetch('/move_to_center', {
  924. method: 'POST',
  925. headers: {
  926. 'Content-Type': 'application/json'
  927. }
  928. });
  929. const data = await response.json();
  930. if (data.success) {
  931. updateStatus('Moving to center position...');
  932. }
  933. } catch (error) {
  934. console.error('Error moving to center:', error);
  935. updateStatus('Error: Failed to move to center');
  936. }
  937. });
  938. }
  939. // Move to Perimeter button
  940. const perimeterButton = document.getElementById('perimeterButton');
  941. if (perimeterButton) {
  942. perimeterButton.addEventListener('click', async () => {
  943. try {
  944. const response = await fetch('/move_to_perimeter', {
  945. method: 'POST',
  946. headers: {
  947. 'Content-Type': 'application/json'
  948. }
  949. });
  950. const data = await response.json();
  951. if (data.success) {
  952. updateStatus('Moving to perimeter position...');
  953. }
  954. } catch (error) {
  955. console.error('Error moving to perimeter:', error);
  956. updateStatus('Error: Failed to move to perimeter');
  957. }
  958. });
  959. }
  960. });
  961. // Function to update status
  962. function updateStatus(message) {
  963. const statusElement = document.querySelector('.text-slate-800.text-base.font-medium.leading-normal');
  964. if (statusElement) {
  965. statusElement.textContent = message;
  966. // Reset status after 3 seconds if it's a temporary message
  967. if (message.includes('Moving') || message.includes('Execution')) {
  968. setTimeout(() => {
  969. statusElement.textContent = 'Status';
  970. }, 3000);
  971. }
  972. }
  973. }
  974. // Function to show status messages (using existing base.js showStatusMessage if available)
  975. function showStatusMessage(message, type) {
  976. if (typeof window.showStatusMessage === 'function') {
  977. window.showStatusMessage(message, type);
  978. } else {
  979. // Fallback to console logging
  980. console.log(`[${type}] ${message}`);
  981. }
  982. }
  983. // Function to show update instructions modal
  984. function showUpdateInstructionsModal(data) {
  985. // Create modal HTML
  986. const modal = document.createElement('div');
  987. modal.id = 'updateInstructionsModal';
  988. modal.className = 'fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4';
  989. modal.innerHTML = `
  990. <div class="bg-white dark:bg-gray-800 rounded-lg shadow-xl w-full max-w-md">
  991. <div class="p-6">
  992. <div class="text-center mb-4">
  993. <h2 class="text-xl font-semibold text-gray-800 dark:text-gray-200 mb-2">Manual Update Required</h2>
  994. <p class="text-gray-600 dark:text-gray-400 text-sm">
  995. ${data.message}
  996. </p>
  997. </div>
  998. <div class="text-gray-700 dark:text-gray-300 text-sm mb-6">
  999. <p class="mb-3">${data.instructions}</p>
  1000. </div>
  1001. <div class="flex gap-3 justify-center">
  1002. <button id="openGitHubRelease" class="px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-lg transition-colors">
  1003. View Update Instructions
  1004. </button>
  1005. <button id="closeUpdateModal" class="px-4 py-2 bg-gray-600 hover:bg-gray-700 text-white rounded-lg transition-colors">
  1006. Close
  1007. </button>
  1008. </div>
  1009. </div>
  1010. </div>
  1011. `;
  1012. document.body.appendChild(modal);
  1013. // Add event listeners
  1014. const openGitHubButton = modal.querySelector('#openGitHubRelease');
  1015. const closeButton = modal.querySelector('#closeUpdateModal');
  1016. openGitHubButton.addEventListener('click', () => {
  1017. window.open(data.manual_update_url, '_blank');
  1018. document.body.removeChild(modal);
  1019. });
  1020. closeButton.addEventListener('click', () => {
  1021. document.body.removeChild(modal);
  1022. });
  1023. // Close on outside click
  1024. modal.addEventListener('click', (e) => {
  1025. if (e.target === modal) {
  1026. document.body.removeChild(modal);
  1027. }
  1028. });
  1029. }
  1030. // Autocomplete functionality
  1031. function initializeAutocomplete(inputId, suggestionsId, clearButtonId, patterns) {
  1032. const input = document.getElementById(inputId);
  1033. const suggestionsDiv = document.getElementById(suggestionsId);
  1034. const clearButton = document.getElementById(clearButtonId);
  1035. let selectedIndex = -1;
  1036. if (!input || !suggestionsDiv) return;
  1037. // Function to update clear button visibility
  1038. function updateClearButton() {
  1039. if (clearButton) {
  1040. if (input.value.trim()) {
  1041. clearButton.classList.remove('hidden');
  1042. } else {
  1043. clearButton.classList.add('hidden');
  1044. }
  1045. }
  1046. }
  1047. // Format pattern name for display
  1048. function formatPatternName(pattern) {
  1049. return pattern.replace('.thr', '').replace(/_/g, ' ');
  1050. }
  1051. // Filter patterns based on input
  1052. function filterPatterns(searchTerm) {
  1053. if (!searchTerm) return patterns.slice(0, 20); // Show first 20 when empty
  1054. const term = searchTerm.toLowerCase();
  1055. return patterns.filter(pattern => {
  1056. const name = pattern.toLowerCase();
  1057. return name.includes(term);
  1058. }).sort((a, b) => {
  1059. // Prioritize patterns that start with the search term
  1060. const aStarts = a.toLowerCase().startsWith(term);
  1061. const bStarts = b.toLowerCase().startsWith(term);
  1062. if (aStarts && !bStarts) return -1;
  1063. if (!aStarts && bStarts) return 1;
  1064. return a.localeCompare(b);
  1065. }).slice(0, 20); // Limit to 20 results
  1066. }
  1067. // Highlight matching text
  1068. function highlightMatch(text, searchTerm) {
  1069. if (!searchTerm) return text;
  1070. const regex = new RegExp(`(${searchTerm.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')})`, 'gi');
  1071. return text.replace(regex, '<mark>$1</mark>');
  1072. }
  1073. // Show suggestions
  1074. function showSuggestions(searchTerm) {
  1075. const filtered = filterPatterns(searchTerm);
  1076. if (filtered.length === 0 && searchTerm) {
  1077. suggestionsDiv.innerHTML = '<div class="suggestion-item" style="cursor: default; color: #9ca3af;">No patterns found</div>';
  1078. suggestionsDiv.classList.remove('hidden');
  1079. return;
  1080. }
  1081. suggestionsDiv.innerHTML = filtered.map((pattern, index) => {
  1082. const displayName = formatPatternName(pattern);
  1083. const highlighted = highlightMatch(displayName, searchTerm);
  1084. return `<div class="suggestion-item" data-value="${pattern}" data-index="${index}">${highlighted}</div>`;
  1085. }).join('');
  1086. suggestionsDiv.classList.remove('hidden');
  1087. selectedIndex = -1;
  1088. }
  1089. // Hide suggestions
  1090. function hideSuggestions() {
  1091. setTimeout(() => {
  1092. suggestionsDiv.classList.add('hidden');
  1093. selectedIndex = -1;
  1094. }, 200);
  1095. }
  1096. // Select suggestion
  1097. function selectSuggestion(value) {
  1098. input.value = value;
  1099. hideSuggestions();
  1100. updateClearButton();
  1101. }
  1102. // Handle keyboard navigation
  1103. function handleKeyboard(e) {
  1104. const items = suggestionsDiv.querySelectorAll('.suggestion-item[data-value]');
  1105. if (e.key === 'ArrowDown') {
  1106. e.preventDefault();
  1107. selectedIndex = Math.min(selectedIndex + 1, items.length - 1);
  1108. updateSelection(items);
  1109. } else if (e.key === 'ArrowUp') {
  1110. e.preventDefault();
  1111. selectedIndex = Math.max(selectedIndex - 1, -1);
  1112. updateSelection(items);
  1113. } else if (e.key === 'Enter') {
  1114. e.preventDefault();
  1115. if (selectedIndex >= 0 && items[selectedIndex]) {
  1116. selectSuggestion(items[selectedIndex].dataset.value);
  1117. } else if (items.length === 1) {
  1118. selectSuggestion(items[0].dataset.value);
  1119. }
  1120. } else if (e.key === 'Escape') {
  1121. hideSuggestions();
  1122. }
  1123. }
  1124. // Update visual selection
  1125. function updateSelection(items) {
  1126. items.forEach((item, index) => {
  1127. if (index === selectedIndex) {
  1128. item.classList.add('selected');
  1129. item.scrollIntoView({ block: 'nearest' });
  1130. } else {
  1131. item.classList.remove('selected');
  1132. }
  1133. });
  1134. }
  1135. // Event listeners
  1136. input.addEventListener('input', (e) => {
  1137. const value = e.target.value.trim();
  1138. updateClearButton();
  1139. if (value.length > 0 || e.target === document.activeElement) {
  1140. showSuggestions(value);
  1141. } else {
  1142. hideSuggestions();
  1143. }
  1144. });
  1145. input.addEventListener('focus', () => {
  1146. const value = input.value.trim();
  1147. showSuggestions(value);
  1148. });
  1149. input.addEventListener('blur', hideSuggestions);
  1150. input.addEventListener('keydown', handleKeyboard);
  1151. // Click handler for suggestions
  1152. suggestionsDiv.addEventListener('click', (e) => {
  1153. const item = e.target.closest('.suggestion-item[data-value]');
  1154. if (item) {
  1155. selectSuggestion(item.dataset.value);
  1156. }
  1157. });
  1158. // Mouse hover handler
  1159. suggestionsDiv.addEventListener('mouseover', (e) => {
  1160. const item = e.target.closest('.suggestion-item[data-value]');
  1161. if (item) {
  1162. selectedIndex = parseInt(item.dataset.index);
  1163. const items = suggestionsDiv.querySelectorAll('.suggestion-item[data-value]');
  1164. updateSelection(items);
  1165. }
  1166. });
  1167. // Clear button handler
  1168. if (clearButton) {
  1169. clearButton.addEventListener('click', () => {
  1170. input.value = '';
  1171. updateClearButton();
  1172. hideSuggestions();
  1173. input.focus();
  1174. });
  1175. }
  1176. // Initialize clear button visibility
  1177. updateClearButton();
  1178. }
  1179. // auto_play Mode Functions
  1180. async function initializeauto_playMode() {
  1181. const auto_playToggle = document.getElementById('auto_playModeToggle');
  1182. const auto_playSettings = document.getElementById('auto_playSettings');
  1183. const auto_playPlaylistSelect = document.getElementById('auto_playPlaylistSelect');
  1184. const auto_playRunModeSelect = document.getElementById('auto_playRunModeSelect');
  1185. const auto_playPauseTimeInput = document.getElementById('auto_playPauseTimeInput');
  1186. const auto_playClearPatternSelect = document.getElementById('auto_playClearPatternSelect');
  1187. const auto_playShuffleToggle = document.getElementById('auto_playShuffleToggle');
  1188. // Load current auto_play settings
  1189. try {
  1190. const response = await fetch('/api/auto_play-mode');
  1191. const data = await response.json();
  1192. auto_playToggle.checked = data.enabled;
  1193. if (data.enabled) {
  1194. auto_playSettings.style.display = 'block';
  1195. }
  1196. // Set current values
  1197. auto_playRunModeSelect.value = data.run_mode || 'loop';
  1198. auto_playPauseTimeInput.value = data.pause_time || 5.0;
  1199. auto_playClearPatternSelect.value = data.clear_pattern || 'adaptive';
  1200. auto_playShuffleToggle.checked = data.shuffle || false;
  1201. // Load playlists for selection
  1202. const playlistsResponse = await fetch('/list_all_playlists');
  1203. const playlists = await playlistsResponse.json();
  1204. // Clear and populate playlist select
  1205. auto_playPlaylistSelect.innerHTML = '<option value="">Select a playlist...</option>';
  1206. playlists.forEach(playlist => {
  1207. const option = document.createElement('option');
  1208. option.value = playlist;
  1209. option.textContent = playlist;
  1210. if (playlist === data.playlist) {
  1211. option.selected = true;
  1212. }
  1213. auto_playPlaylistSelect.appendChild(option);
  1214. });
  1215. } catch (error) {
  1216. logMessage(`Error loading auto_play settings: ${error.message}`, LOG_TYPE.ERROR);
  1217. }
  1218. // Get save button
  1219. const saveAutoPlayButton = document.getElementById('saveAutoPlaySettings');
  1220. // Function to save settings
  1221. async function saveSettings(showFeedback = false) {
  1222. const originalButtonHTML = saveAutoPlayButton ? saveAutoPlayButton.innerHTML : '';
  1223. if (showFeedback && saveAutoPlayButton) {
  1224. saveAutoPlayButton.disabled = true;
  1225. saveAutoPlayButton.innerHTML = '<span class="material-icons text-lg animate-spin">refresh</span><span class="truncate">Saving...</span>';
  1226. }
  1227. try {
  1228. const response = await fetch('/api/auto_play-mode', {
  1229. method: 'POST',
  1230. headers: { 'Content-Type': 'application/json' },
  1231. body: JSON.stringify({
  1232. enabled: auto_playToggle.checked,
  1233. playlist: auto_playPlaylistSelect.value || null,
  1234. run_mode: auto_playRunModeSelect.value,
  1235. pause_time: parseFloat(auto_playPauseTimeInput.value) || 0,
  1236. clear_pattern: auto_playClearPatternSelect.value,
  1237. shuffle: auto_playShuffleToggle.checked
  1238. })
  1239. });
  1240. if (!response.ok) {
  1241. throw new Error('Failed to save settings');
  1242. }
  1243. if (showFeedback && saveAutoPlayButton) {
  1244. saveAutoPlayButton.innerHTML = '<span class="material-icons text-lg">check</span><span class="truncate">Saved!</span>';
  1245. showStatusMessage('Auto-play settings saved successfully', 'success');
  1246. setTimeout(() => {
  1247. saveAutoPlayButton.innerHTML = originalButtonHTML;
  1248. saveAutoPlayButton.disabled = false;
  1249. }, 2000);
  1250. }
  1251. } catch (error) {
  1252. logMessage(`Error saving auto_play settings: ${error.message}`, LOG_TYPE.ERROR);
  1253. if (showFeedback && saveAutoPlayButton) {
  1254. showStatusMessage(`Failed to save settings: ${error.message}`, 'error');
  1255. saveAutoPlayButton.innerHTML = originalButtonHTML;
  1256. saveAutoPlayButton.disabled = false;
  1257. }
  1258. }
  1259. }
  1260. // Toggle auto_play settings visibility and save
  1261. auto_playToggle.addEventListener('change', async () => {
  1262. auto_playSettings.style.display = auto_playToggle.checked ? 'block' : 'none';
  1263. await saveSettings(false); // Auto-save toggle state without full feedback
  1264. const statusText = auto_playToggle.checked ? 'enabled' : 'disabled';
  1265. showStatusMessage(`Auto-play ${statusText}`, 'success');
  1266. });
  1267. // Save button click handler
  1268. if (saveAutoPlayButton) {
  1269. saveAutoPlayButton.addEventListener('click', () => saveSettings(true));
  1270. }
  1271. }
  1272. // Initialize auto_play mode when DOM is ready
  1273. document.addEventListener('DOMContentLoaded', function() {
  1274. initializeauto_playMode();
  1275. initializeStillSandsMode();
  1276. initializeHomingConfig();
  1277. });
  1278. // Still Sands Mode Functions
  1279. async function initializeStillSandsMode() {
  1280. logMessage('Initializing Still Sands mode', LOG_TYPE.INFO);
  1281. const stillSandsToggle = document.getElementById('scheduledPauseToggle');
  1282. const stillSandsSettings = document.getElementById('scheduledPauseSettings');
  1283. const addTimeSlotButton = document.getElementById('addTimeSlotButton');
  1284. const saveStillSandsButton = document.getElementById('savePauseSettings');
  1285. const timeSlotsContainer = document.getElementById('timeSlotsContainer');
  1286. const wledControlToggle = document.getElementById('stillSandsWledControl');
  1287. const finishPatternToggle = document.getElementById('stillSandsFinishPattern');
  1288. const timezoneSelect = document.getElementById('stillSandsTimezone');
  1289. // Check if elements exist
  1290. if (!stillSandsToggle || !stillSandsSettings || !addTimeSlotButton || !saveStillSandsButton || !timeSlotsContainer) {
  1291. logMessage('Still Sands elements not found, skipping initialization', LOG_TYPE.WARNING);
  1292. logMessage(`Found elements: toggle=${!!stillSandsToggle}, settings=${!!stillSandsSettings}, addBtn=${!!addTimeSlotButton}, saveBtn=${!!saveStillSandsButton}, container=${!!timeSlotsContainer}`, LOG_TYPE.WARNING);
  1293. return;
  1294. }
  1295. logMessage('All Still Sands elements found successfully', LOG_TYPE.INFO);
  1296. // Track time slots
  1297. let timeSlots = [];
  1298. let slotIdCounter = 0;
  1299. // Load current Still Sands settings from initial data
  1300. try {
  1301. // Use the data loaded during page initialization, fallback to API if not available
  1302. let data;
  1303. if (window.initialStillSandsData) {
  1304. data = window.initialStillSandsData;
  1305. // Clear the global variable after use
  1306. delete window.initialStillSandsData;
  1307. } else {
  1308. // Fallback to API call if initial data not available
  1309. const response = await fetch('/api/scheduled-pause');
  1310. data = await response.json();
  1311. }
  1312. stillSandsToggle.checked = data.enabled || false;
  1313. if (data.enabled) {
  1314. stillSandsSettings.style.display = 'block';
  1315. }
  1316. // Load WLED control setting
  1317. if (wledControlToggle) {
  1318. wledControlToggle.checked = data.control_wled || false;
  1319. }
  1320. // Load finish pattern setting
  1321. if (finishPatternToggle) {
  1322. finishPatternToggle.checked = data.finish_pattern || false;
  1323. }
  1324. // Load timezone setting
  1325. if (timezoneSelect) {
  1326. timezoneSelect.value = data.timezone || '';
  1327. }
  1328. // Load existing time slots
  1329. timeSlots = data.time_slots || [];
  1330. // Assign IDs to loaded slots BEFORE rendering
  1331. if (timeSlots.length > 0) {
  1332. slotIdCounter = 0;
  1333. timeSlots.forEach(slot => {
  1334. slot.id = ++slotIdCounter;
  1335. });
  1336. }
  1337. renderTimeSlots();
  1338. } catch (error) {
  1339. logMessage(`Error loading Still Sands settings: ${error.message}`, LOG_TYPE.ERROR);
  1340. // Initialize with empty settings if load fails
  1341. timeSlots = [];
  1342. renderTimeSlots();
  1343. }
  1344. // Function to validate time format (HH:MM)
  1345. function isValidTime(timeString) {
  1346. const timeRegex = /^([01]?[0-9]|2[0-3]):[0-5][0-9]$/;
  1347. return timeRegex.test(timeString);
  1348. }
  1349. // Function to create a new time slot element
  1350. function createTimeSlotElement(slot) {
  1351. const slotDiv = document.createElement('div');
  1352. slotDiv.className = 'time-slot-item';
  1353. slotDiv.dataset.slotId = slot.id;
  1354. slotDiv.innerHTML = `
  1355. <div class="flex items-center gap-3">
  1356. <div class="flex-1 grid grid-cols-1 md:grid-cols-2 gap-3">
  1357. <div class="flex flex-col gap-1">
  1358. <label class="text-slate-700 dark:text-slate-300 text-xs font-medium">Start Time</label>
  1359. <input
  1360. type="time"
  1361. 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"
  1362. value="${slot.start_time || ''}"
  1363. required
  1364. />
  1365. </div>
  1366. <div class="flex flex-col gap-1">
  1367. <label class="text-slate-700 dark:text-slate-300 text-xs font-medium">End Time</label>
  1368. <input
  1369. type="time"
  1370. 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"
  1371. value="${slot.end_time || ''}"
  1372. required
  1373. />
  1374. </div>
  1375. </div>
  1376. <div class="flex flex-col gap-1">
  1377. <label class="text-slate-700 dark:text-slate-300 text-xs font-medium">Days</label>
  1378. <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">
  1379. <option value="daily" ${slot.days === 'daily' ? 'selected' : ''}>Daily</option>
  1380. <option value="weekdays" ${slot.days === 'weekdays' ? 'selected' : ''}>Weekdays</option>
  1381. <option value="weekends" ${slot.days === 'weekends' ? 'selected' : ''}>Weekends</option>
  1382. <option value="custom" ${slot.days === 'custom' ? 'selected' : ''}>Custom</option>
  1383. </select>
  1384. </div>
  1385. <button
  1386. type="button"
  1387. 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"
  1388. title="Remove time slot"
  1389. >
  1390. <span class="material-icons text-base">delete</span>
  1391. </button>
  1392. </div>
  1393. <div class="custom-days-container mt-2" style="display: ${slot.days === 'custom' ? 'block' : 'none'};">
  1394. <label class="text-slate-700 dark:text-slate-300 text-xs font-medium mb-1 block">Select Days</label>
  1395. <div class="flex flex-wrap gap-2">
  1396. ${['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday'].map(day => `
  1397. <label class="flex items-center gap-1 text-xs">
  1398. <input
  1399. type="checkbox"
  1400. name="custom-days-${slot.id}"
  1401. value="${day}"
  1402. ${slot.custom_days && slot.custom_days.includes(day) ? 'checked' : ''}
  1403. class="rounded border-slate-300 text-sky-600 focus:ring-sky-500"
  1404. />
  1405. <span class="text-slate-700 dark:text-slate-300 capitalize">${day.substring(0, 3)}</span>
  1406. </label>
  1407. `).join('')}
  1408. </div>
  1409. </div>
  1410. `;
  1411. // Add event listeners for this slot
  1412. const startTimeInput = slotDiv.querySelector('.start-time');
  1413. const endTimeInput = slotDiv.querySelector('.end-time');
  1414. const daysSelect = slotDiv.querySelector('.days-select');
  1415. const customDaysContainer = slotDiv.querySelector('.custom-days-container');
  1416. const removeButton = slotDiv.querySelector('.remove-slot-btn');
  1417. // Show/hide custom days based on selection
  1418. daysSelect.addEventListener('change', () => {
  1419. customDaysContainer.style.display = daysSelect.value === 'custom' ? 'block' : 'none';
  1420. updateTimeSlot(slot.id);
  1421. });
  1422. // Update slot data when inputs change
  1423. startTimeInput.addEventListener('change', () => updateTimeSlot(slot.id));
  1424. endTimeInput.addEventListener('change', () => updateTimeSlot(slot.id));
  1425. // Handle custom day checkboxes
  1426. customDaysContainer.addEventListener('change', () => updateTimeSlot(slot.id));
  1427. // Remove slot button
  1428. removeButton.addEventListener('click', () => {
  1429. removeTimeSlot(slot.id);
  1430. });
  1431. return slotDiv;
  1432. }
  1433. // Function to render all time slots
  1434. function renderTimeSlots() {
  1435. timeSlotsContainer.innerHTML = '';
  1436. if (timeSlots.length === 0) {
  1437. timeSlotsContainer.innerHTML = `
  1438. <div class="text-center py-8 text-slate-500 dark:text-slate-400">
  1439. <span class="material-icons text-4xl mb-2 block">schedule</span>
  1440. <p>No time slots configured</p>
  1441. <p class="text-xs mt-1">Click "Add Time Slot" to create a pause schedule</p>
  1442. </div>
  1443. `;
  1444. return;
  1445. }
  1446. timeSlots.forEach(slot => {
  1447. const slotElement = createTimeSlotElement(slot);
  1448. timeSlotsContainer.appendChild(slotElement);
  1449. });
  1450. }
  1451. // Function to add a new time slot
  1452. function addTimeSlot() {
  1453. const newSlot = {
  1454. id: ++slotIdCounter,
  1455. start_time: '22:00',
  1456. end_time: '08:00',
  1457. days: 'daily',
  1458. custom_days: []
  1459. };
  1460. timeSlots.push(newSlot);
  1461. renderTimeSlots();
  1462. }
  1463. // Function to remove a time slot
  1464. function removeTimeSlot(slotId) {
  1465. timeSlots = timeSlots.filter(slot => slot.id !== slotId);
  1466. renderTimeSlots();
  1467. }
  1468. // Function to update a time slot's data
  1469. function updateTimeSlot(slotId) {
  1470. const slotElement = timeSlotsContainer.querySelector(`[data-slot-id="${slotId}"]`);
  1471. if (!slotElement) return;
  1472. const slot = timeSlots.find(s => s.id === slotId);
  1473. if (!slot) return;
  1474. // Update slot data from inputs
  1475. slot.start_time = slotElement.querySelector('.start-time').value;
  1476. slot.end_time = slotElement.querySelector('.end-time').value;
  1477. slot.days = slotElement.querySelector('.days-select').value;
  1478. // Update custom days if applicable
  1479. if (slot.days === 'custom') {
  1480. const checkedDays = Array.from(slotElement.querySelectorAll(`input[name="custom-days-${slotId}"]:checked`))
  1481. .map(cb => cb.value);
  1482. slot.custom_days = checkedDays;
  1483. } else {
  1484. slot.custom_days = [];
  1485. }
  1486. }
  1487. // Function to validate all time slots
  1488. function validateTimeSlots() {
  1489. const errors = [];
  1490. timeSlots.forEach((slot, index) => {
  1491. if (!slot.start_time || !isValidTime(slot.start_time)) {
  1492. errors.push(`Time slot ${index + 1}: Invalid start time`);
  1493. }
  1494. if (!slot.end_time || !isValidTime(slot.end_time)) {
  1495. errors.push(`Time slot ${index + 1}: Invalid end time`);
  1496. }
  1497. if (slot.days === 'custom' && (!slot.custom_days || slot.custom_days.length === 0)) {
  1498. errors.push(`Time slot ${index + 1}: Please select at least one day for custom schedule`);
  1499. }
  1500. });
  1501. return errors;
  1502. }
  1503. // Function to save settings
  1504. async function saveStillSandsSettings() {
  1505. // Update all slots from current form values
  1506. timeSlots.forEach(slot => updateTimeSlot(slot.id));
  1507. // Validate time slots
  1508. const validationErrors = validateTimeSlots();
  1509. if (validationErrors.length > 0) {
  1510. showStatusMessage(`Validation errors: ${validationErrors.join(', ')}`, 'error');
  1511. return;
  1512. }
  1513. // Update button UI to show loading state
  1514. const originalButtonHTML = saveStillSandsButton.innerHTML;
  1515. saveStillSandsButton.disabled = true;
  1516. saveStillSandsButton.innerHTML = '<span class="material-icons text-lg animate-spin">refresh</span><span class="truncate">Saving...</span>';
  1517. try {
  1518. const response = await fetch('/api/scheduled-pause', {
  1519. method: 'POST',
  1520. headers: { 'Content-Type': 'application/json' },
  1521. body: JSON.stringify({
  1522. enabled: stillSandsToggle.checked,
  1523. control_wled: wledControlToggle ? wledControlToggle.checked : false,
  1524. finish_pattern: finishPatternToggle ? finishPatternToggle.checked : false,
  1525. timezone: timezoneSelect ? (timezoneSelect.value || null) : null,
  1526. time_slots: timeSlots.map(slot => ({
  1527. start_time: slot.start_time,
  1528. end_time: slot.end_time,
  1529. days: slot.days,
  1530. custom_days: slot.custom_days
  1531. }))
  1532. })
  1533. });
  1534. if (!response.ok) {
  1535. const errorData = await response.json();
  1536. throw new Error(errorData.detail || 'Failed to save Still Sands settings');
  1537. }
  1538. // Show success state temporarily
  1539. saveStillSandsButton.innerHTML = '<span class="material-icons text-lg">check</span><span class="truncate">Saved!</span>';
  1540. showStatusMessage('Still Sands settings saved successfully', 'success');
  1541. // Restore button after 2 seconds
  1542. setTimeout(() => {
  1543. saveStillSandsButton.innerHTML = originalButtonHTML;
  1544. saveStillSandsButton.disabled = false;
  1545. }, 2000);
  1546. } catch (error) {
  1547. logMessage(`Error saving Still Sands settings: ${error.message}`, LOG_TYPE.ERROR);
  1548. showStatusMessage(`Failed to save settings: ${error.message}`, 'error');
  1549. // Restore button immediately on error
  1550. saveStillSandsButton.innerHTML = originalButtonHTML;
  1551. saveStillSandsButton.disabled = false;
  1552. }
  1553. }
  1554. // Note: Slot IDs are now assigned during initialization above, before first render
  1555. // Event listeners
  1556. stillSandsToggle.addEventListener('change', async () => {
  1557. logMessage(`Still Sands toggle changed: ${stillSandsToggle.checked}`, LOG_TYPE.INFO);
  1558. stillSandsSettings.style.display = stillSandsToggle.checked ? 'block' : 'none';
  1559. logMessage(`Settings display set to: ${stillSandsSettings.style.display}`, LOG_TYPE.INFO);
  1560. // Auto-save when toggle changes
  1561. try {
  1562. await saveStillSandsSettings();
  1563. const statusText = stillSandsToggle.checked ? 'enabled' : 'disabled';
  1564. showStatusMessage(`Still Sands ${statusText} successfully`, 'success');
  1565. } catch (error) {
  1566. logMessage(`Error saving Still Sands toggle: ${error.message}`, LOG_TYPE.ERROR);
  1567. showStatusMessage(`Failed to save Still Sands setting: ${error.message}`, 'error');
  1568. }
  1569. });
  1570. addTimeSlotButton.addEventListener('click', addTimeSlot);
  1571. saveStillSandsButton.addEventListener('click', saveStillSandsSettings);
  1572. // Add listener for WLED control toggle
  1573. if (wledControlToggle) {
  1574. wledControlToggle.addEventListener('change', async () => {
  1575. logMessage(`WLED control toggle changed: ${wledControlToggle.checked}`, LOG_TYPE.INFO);
  1576. // Auto-save when WLED control changes
  1577. await saveStillSandsSettings();
  1578. });
  1579. }
  1580. // Add listener for finish pattern toggle
  1581. if (finishPatternToggle) {
  1582. finishPatternToggle.addEventListener('change', async () => {
  1583. logMessage(`Finish pattern toggle changed: ${finishPatternToggle.checked}`, LOG_TYPE.INFO);
  1584. // Auto-save when finish pattern setting changes
  1585. await saveStillSandsSettings();
  1586. });
  1587. }
  1588. // Add listener for timezone select
  1589. if (timezoneSelect) {
  1590. timezoneSelect.addEventListener('change', async () => {
  1591. logMessage(`Timezone changed: ${timezoneSelect.value || 'System Default'}`, LOG_TYPE.INFO);
  1592. // Auto-save when timezone changes
  1593. await saveStillSandsSettings();
  1594. });
  1595. }
  1596. }
  1597. // Homing Configuration
  1598. async function initializeHomingConfig() {
  1599. logMessage('Initializing homing configuration', LOG_TYPE.INFO);
  1600. const homingModeCrash = document.getElementById('homingModeCrash');
  1601. const homingModeSensor = document.getElementById('homingModeSensor');
  1602. const angularOffsetInput = document.getElementById('angularOffsetInput');
  1603. const compassOffsetContainer = document.getElementById('compassOffsetContainer');
  1604. const saveHomingConfigButton = document.getElementById('saveHomingConfig');
  1605. const homingInfoContent = document.getElementById('homingInfoContent');
  1606. const autoHomeEnabledToggle = document.getElementById('autoHomeEnabledToggle');
  1607. const autoHomeSettings = document.getElementById('autoHomeSettings');
  1608. const autoHomeAfterPatternsInput = document.getElementById('autoHomeAfterPatternsInput');
  1609. // Check if elements exist
  1610. if (!homingModeCrash || !homingModeSensor || !angularOffsetInput || !saveHomingConfigButton || !homingInfoContent || !compassOffsetContainer) {
  1611. logMessage('Homing configuration elements not found, skipping initialization', LOG_TYPE.WARNING);
  1612. return;
  1613. }
  1614. logMessage('Homing configuration elements found successfully', LOG_TYPE.INFO);
  1615. // Function to get selected homing mode
  1616. function getSelectedMode() {
  1617. return homingModeCrash.checked ? 0 : 1;
  1618. }
  1619. // Function to update info box and visibility based on selected mode
  1620. function updateHomingInfo() {
  1621. const mode = getSelectedMode();
  1622. // Show/hide compass offset based on mode
  1623. if (mode === 0) {
  1624. compassOffsetContainer.style.display = 'none';
  1625. homingInfoContent.innerHTML = `
  1626. <p class="font-medium text-blue-800">Crash Homing Mode:</p>
  1627. <ul class="mt-1 space-y-1 text-blue-700">
  1628. <li>• Y axis moves -22mm (or -30mm for mini) until physical stop</li>
  1629. <li>• Theta set to 0, rho set to 0</li>
  1630. <li>• No x0 y0 command sent</li>
  1631. <li>• No hardware sensors required</li>
  1632. </ul>
  1633. `;
  1634. } else {
  1635. compassOffsetContainer.style.display = 'block';
  1636. homingInfoContent.innerHTML = `
  1637. <p class="font-medium text-blue-800">Sensor Homing Mode:</p>
  1638. <ul class="mt-1 space-y-1 text-blue-700">
  1639. <li>• Requires hardware limit switches</li>
  1640. <li>• Requires additional configuration</li>
  1641. </ul>
  1642. `;
  1643. }
  1644. }
  1645. // Load current homing configuration
  1646. try {
  1647. const response = await fetch('/api/homing-config');
  1648. const data = await response.json();
  1649. // Set radio button based on mode
  1650. if (data.homing_mode === 1) {
  1651. homingModeSensor.checked = true;
  1652. } else {
  1653. homingModeCrash.checked = true;
  1654. }
  1655. angularOffsetInput.value = data.angular_homing_offset_degrees || 0;
  1656. // Load auto-home settings
  1657. if (autoHomeEnabledToggle) {
  1658. autoHomeEnabledToggle.checked = data.auto_home_enabled || false;
  1659. if (autoHomeSettings) {
  1660. autoHomeSettings.style.display = data.auto_home_enabled ? 'block' : 'none';
  1661. }
  1662. }
  1663. if (autoHomeAfterPatternsInput) {
  1664. autoHomeAfterPatternsInput.value = data.auto_home_after_patterns || 5;
  1665. }
  1666. updateHomingInfo();
  1667. 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);
  1668. } catch (error) {
  1669. logMessage(`Error loading homing configuration: ${error.message}`, LOG_TYPE.ERROR);
  1670. // Initialize with defaults if load fails
  1671. homingModeCrash.checked = true;
  1672. angularOffsetInput.value = 0;
  1673. if (autoHomeEnabledToggle) autoHomeEnabledToggle.checked = false;
  1674. if (autoHomeAfterPatternsInput) autoHomeAfterPatternsInput.value = 5;
  1675. updateHomingInfo();
  1676. }
  1677. // Function to save homing configuration
  1678. async function saveHomingConfig() {
  1679. // Update button UI to show loading state
  1680. const originalButtonHTML = saveHomingConfigButton.innerHTML;
  1681. saveHomingConfigButton.disabled = true;
  1682. saveHomingConfigButton.innerHTML = '<span class="material-icons text-lg animate-spin">refresh</span><span class="truncate">Saving...</span>';
  1683. try {
  1684. const requestBody = {
  1685. homing_mode: getSelectedMode(),
  1686. angular_homing_offset_degrees: parseFloat(angularOffsetInput.value) || 0
  1687. };
  1688. // Include auto-home settings if elements exist
  1689. if (autoHomeEnabledToggle) {
  1690. requestBody.auto_home_enabled = autoHomeEnabledToggle.checked;
  1691. }
  1692. if (autoHomeAfterPatternsInput) {
  1693. const afterPatterns = parseInt(autoHomeAfterPatternsInput.value);
  1694. if (!isNaN(afterPatterns) && afterPatterns >= 1) {
  1695. requestBody.auto_home_after_patterns = afterPatterns;
  1696. }
  1697. }
  1698. const response = await fetch('/api/homing-config', {
  1699. method: 'POST',
  1700. headers: { 'Content-Type': 'application/json' },
  1701. body: JSON.stringify(requestBody)
  1702. });
  1703. if (!response.ok) {
  1704. const errorData = await response.json();
  1705. throw new Error(errorData.detail || 'Failed to save homing configuration');
  1706. }
  1707. // Show success state temporarily
  1708. saveHomingConfigButton.innerHTML = '<span class="material-icons text-lg">check</span><span class="truncate">Saved!</span>';
  1709. showStatusMessage('Homing configuration saved successfully', 'success');
  1710. // Restore button after 2 seconds
  1711. setTimeout(() => {
  1712. saveHomingConfigButton.innerHTML = originalButtonHTML;
  1713. saveHomingConfigButton.disabled = false;
  1714. }, 2000);
  1715. } catch (error) {
  1716. logMessage(`Error saving homing configuration: ${error.message}`, LOG_TYPE.ERROR);
  1717. showStatusMessage(`Failed to save homing configuration: ${error.message}`, 'error');
  1718. // Restore button immediately on error
  1719. saveHomingConfigButton.innerHTML = originalButtonHTML;
  1720. saveHomingConfigButton.disabled = false;
  1721. }
  1722. }
  1723. // Event listeners
  1724. homingModeCrash.addEventListener('change', updateHomingInfo);
  1725. homingModeSensor.addEventListener('change', updateHomingInfo);
  1726. saveHomingConfigButton.addEventListener('click', saveHomingConfig);
  1727. // Auto-home toggle event listener
  1728. if (autoHomeEnabledToggle && autoHomeSettings) {
  1729. autoHomeEnabledToggle.addEventListener('change', () => {
  1730. autoHomeSettings.style.display = autoHomeEnabledToggle.checked ? 'block' : 'none';
  1731. });
  1732. }
  1733. }
  1734. // Toggle password visibility helper
  1735. function togglePasswordVisibility(inputId, button) {
  1736. const input = document.getElementById(inputId);
  1737. if (!input || !button) return;
  1738. const icon = button.querySelector('.material-icons');
  1739. if (input.type === 'password') {
  1740. input.type = 'text';
  1741. if (icon) icon.textContent = 'visibility';
  1742. } else {
  1743. input.type = 'password';
  1744. if (icon) icon.textContent = 'visibility_off';
  1745. }
  1746. }
  1747. // MQTT Configuration
  1748. async function initializeMqttConfig() {
  1749. logMessage('Initializing MQTT configuration', LOG_TYPE.INFO);
  1750. const mqttEnableToggle = document.getElementById('mqttEnableToggle');
  1751. const mqttSettings = document.getElementById('mqttSettings');
  1752. const mqttStatusBanner = document.getElementById('mqttStatusBanner');
  1753. const mqttConnectedBanner = document.getElementById('mqttConnectedBanner');
  1754. const mqttDisconnectedBanner = document.getElementById('mqttDisconnectedBanner');
  1755. const mqttBrokerInput = document.getElementById('mqttBrokerInput');
  1756. const mqttPortInput = document.getElementById('mqttPortInput');
  1757. const mqttUsernameInput = document.getElementById('mqttUsernameInput');
  1758. const mqttPasswordInput = document.getElementById('mqttPasswordInput');
  1759. const mqttDeviceNameInput = document.getElementById('mqttDeviceNameInput');
  1760. const mqttDeviceIdInput = document.getElementById('mqttDeviceIdInput');
  1761. const mqttClientIdInput = document.getElementById('mqttClientIdInput');
  1762. const mqttDiscoveryPrefixInput = document.getElementById('mqttDiscoveryPrefixInput');
  1763. const testMqttButton = document.getElementById('testMqttConnection');
  1764. const mqttTestResult = document.getElementById('mqttTestResult');
  1765. const saveMqttButton = document.getElementById('saveMqttConfig');
  1766. const mqttRestartNotice = document.getElementById('mqttRestartNotice');
  1767. // Check if elements exist
  1768. if (!mqttEnableToggle || !mqttSettings || !saveMqttButton) {
  1769. logMessage('MQTT configuration elements not found, skipping initialization', LOG_TYPE.WARNING);
  1770. return;
  1771. }
  1772. logMessage('MQTT configuration elements found successfully', LOG_TYPE.INFO);
  1773. // Track if settings have changed (to show restart notice)
  1774. let originalConfig = null;
  1775. let configChanged = false;
  1776. // Function to update UI based on enabled state
  1777. function updateMqttSettingsVisibility() {
  1778. mqttSettings.style.display = mqttEnableToggle.checked ? 'block' : 'none';
  1779. if (mqttStatusBanner) {
  1780. mqttStatusBanner.classList.toggle('hidden', !mqttEnableToggle.checked);
  1781. }
  1782. }
  1783. // Function to update connection status banners
  1784. function updateConnectionStatus(connected) {
  1785. if (mqttConnectedBanner && mqttDisconnectedBanner) {
  1786. if (connected) {
  1787. mqttConnectedBanner.classList.remove('hidden');
  1788. mqttDisconnectedBanner.classList.add('hidden');
  1789. } else {
  1790. mqttConnectedBanner.classList.add('hidden');
  1791. mqttDisconnectedBanner.classList.remove('hidden');
  1792. }
  1793. }
  1794. }
  1795. // Function to check if config has changed
  1796. function checkConfigChanged() {
  1797. if (!originalConfig) return false;
  1798. const currentConfig = {
  1799. enabled: mqttEnableToggle.checked,
  1800. broker: mqttBrokerInput.value,
  1801. port: parseInt(mqttPortInput.value) || 1883,
  1802. username: mqttUsernameInput.value,
  1803. password: mqttPasswordInput.value,
  1804. device_name: mqttDeviceNameInput.value,
  1805. device_id: mqttDeviceIdInput.value,
  1806. client_id: mqttClientIdInput.value,
  1807. discovery_prefix: mqttDiscoveryPrefixInput.value
  1808. };
  1809. return JSON.stringify(currentConfig) !== JSON.stringify(originalConfig);
  1810. }
  1811. // Function to show/hide restart notice
  1812. function updateRestartNotice() {
  1813. configChanged = checkConfigChanged();
  1814. if (mqttRestartNotice) {
  1815. mqttRestartNotice.classList.toggle('hidden', !configChanged);
  1816. }
  1817. }
  1818. // Load current MQTT configuration
  1819. try {
  1820. const response = await fetch('/api/mqtt-config');
  1821. const data = await response.json();
  1822. mqttEnableToggle.checked = data.enabled || false;
  1823. mqttBrokerInput.value = data.broker || '';
  1824. mqttPortInput.value = data.port || 1883;
  1825. mqttUsernameInput.value = data.username || '';
  1826. // Note: Password is not returned from API for security
  1827. mqttDeviceNameInput.value = data.device_name || 'Dune Weaver';
  1828. mqttDeviceIdInput.value = data.device_id || 'dune_weaver';
  1829. mqttClientIdInput.value = data.client_id || 'dune_weaver';
  1830. mqttDiscoveryPrefixInput.value = data.discovery_prefix || 'homeassistant';
  1831. // Store original config for change detection
  1832. originalConfig = {
  1833. enabled: data.enabled || false,
  1834. broker: data.broker || '',
  1835. port: data.port || 1883,
  1836. username: data.username || '',
  1837. password: '', // We don't have the original password
  1838. device_name: data.device_name || 'Dune Weaver',
  1839. device_id: data.device_id || 'dune_weaver',
  1840. client_id: data.client_id || 'dune_weaver',
  1841. discovery_prefix: data.discovery_prefix || 'homeassistant'
  1842. };
  1843. updateMqttSettingsVisibility();
  1844. // Update connection status if MQTT is enabled
  1845. if (data.enabled) {
  1846. updateConnectionStatus(data.connected || false);
  1847. }
  1848. logMessage(`Loaded MQTT config: enabled=${data.enabled}, broker=${data.broker}`, LOG_TYPE.INFO);
  1849. } catch (error) {
  1850. logMessage(`Error loading MQTT configuration: ${error.message}`, LOG_TYPE.ERROR);
  1851. // Initialize with defaults if load fails
  1852. mqttEnableToggle.checked = false;
  1853. updateMqttSettingsVisibility();
  1854. }
  1855. // Function to save MQTT configuration
  1856. async function saveMqttConfig() {
  1857. // Validate required fields if MQTT is enabled
  1858. if (mqttEnableToggle.checked && !mqttBrokerInput.value.trim()) {
  1859. showStatusMessage('MQTT broker address is required when MQTT is enabled', 'error');
  1860. mqttBrokerInput.focus();
  1861. return;
  1862. }
  1863. // Update button UI to show loading state
  1864. const originalButtonHTML = saveMqttButton.innerHTML;
  1865. saveMqttButton.disabled = true;
  1866. saveMqttButton.innerHTML = '<span class="material-icons text-lg animate-spin">refresh</span><span class="truncate">Saving...</span>';
  1867. try {
  1868. const requestBody = {
  1869. enabled: mqttEnableToggle.checked,
  1870. broker: mqttBrokerInput.value.trim(),
  1871. port: parseInt(mqttPortInput.value) || 1883,
  1872. username: mqttUsernameInput.value.trim() || null,
  1873. device_name: mqttDeviceNameInput.value.trim() || 'Dune Weaver',
  1874. device_id: mqttDeviceIdInput.value.trim() || 'dune_weaver',
  1875. client_id: mqttClientIdInput.value.trim() || 'dune_weaver',
  1876. discovery_prefix: mqttDiscoveryPrefixInput.value.trim() || 'homeassistant'
  1877. };
  1878. // Only include password if it was changed (not empty)
  1879. if (mqttPasswordInput.value) {
  1880. requestBody.password = mqttPasswordInput.value;
  1881. }
  1882. const response = await fetch('/api/mqtt-config', {
  1883. method: 'POST',
  1884. headers: { 'Content-Type': 'application/json' },
  1885. body: JSON.stringify(requestBody)
  1886. });
  1887. if (!response.ok) {
  1888. const errorData = await response.json();
  1889. throw new Error(errorData.detail || 'Failed to save MQTT configuration');
  1890. }
  1891. const data = await response.json();
  1892. // Update original config for change detection
  1893. originalConfig = {
  1894. enabled: requestBody.enabled,
  1895. broker: requestBody.broker,
  1896. port: requestBody.port,
  1897. username: requestBody.username || '',
  1898. password: '', // Reset password tracking
  1899. device_name: requestBody.device_name,
  1900. device_id: requestBody.device_id,
  1901. client_id: requestBody.client_id,
  1902. discovery_prefix: requestBody.discovery_prefix
  1903. };
  1904. // Clear password field after save
  1905. mqttPasswordInput.value = '';
  1906. // Show success state temporarily
  1907. saveMqttButton.innerHTML = '<span class="material-icons text-lg">check</span><span class="truncate">Saved!</span>';
  1908. showStatusMessage('MQTT configuration saved successfully. Restart the application to apply changes.', 'success');
  1909. // Show restart notice
  1910. if (mqttRestartNotice) {
  1911. mqttRestartNotice.classList.remove('hidden');
  1912. }
  1913. // Restore button after 2 seconds
  1914. setTimeout(() => {
  1915. saveMqttButton.innerHTML = originalButtonHTML;
  1916. saveMqttButton.disabled = false;
  1917. }, 2000);
  1918. } catch (error) {
  1919. logMessage(`Error saving MQTT configuration: ${error.message}`, LOG_TYPE.ERROR);
  1920. showStatusMessage(`Failed to save MQTT configuration: ${error.message}`, 'error');
  1921. // Restore button immediately on error
  1922. saveMqttButton.innerHTML = originalButtonHTML;
  1923. saveMqttButton.disabled = false;
  1924. }
  1925. }
  1926. // Function to test MQTT connection
  1927. async function testMqttConnection() {
  1928. // Validate broker address
  1929. if (!mqttBrokerInput.value.trim()) {
  1930. showStatusMessage('Please enter a broker address to test', 'error');
  1931. mqttBrokerInput.focus();
  1932. return;
  1933. }
  1934. // Update button UI to show loading state
  1935. const originalButtonHTML = testMqttButton.innerHTML;
  1936. testMqttButton.disabled = true;
  1937. testMqttButton.innerHTML = '<span class="material-icons text-lg animate-spin">refresh</span><span class="truncate">Testing...</span>';
  1938. // Clear previous result
  1939. if (mqttTestResult) {
  1940. mqttTestResult.innerHTML = '';
  1941. }
  1942. try {
  1943. const requestBody = {
  1944. broker: mqttBrokerInput.value.trim(),
  1945. port: parseInt(mqttPortInput.value) || 1883,
  1946. username: mqttUsernameInput.value.trim() || null,
  1947. password: mqttPasswordInput.value || null
  1948. };
  1949. const response = await fetch('/api/mqtt-test', {
  1950. method: 'POST',
  1951. headers: { 'Content-Type': 'application/json' },
  1952. body: JSON.stringify(requestBody)
  1953. });
  1954. const data = await response.json();
  1955. if (data.success) {
  1956. if (mqttTestResult) {
  1957. mqttTestResult.innerHTML = '<span class="material-icons text-green-600 mr-1">check_circle</span><span class="text-green-600">Connection successful!</span>';
  1958. }
  1959. showStatusMessage('MQTT connection test successful', 'success');
  1960. } else {
  1961. if (mqttTestResult) {
  1962. mqttTestResult.innerHTML = `<span class="material-icons text-red-600 mr-1">error</span><span class="text-red-600">${data.error || 'Connection failed'}</span>`;
  1963. }
  1964. showStatusMessage(`MQTT test failed: ${data.error || 'Connection failed'}`, 'error');
  1965. }
  1966. } catch (error) {
  1967. logMessage(`Error testing MQTT connection: ${error.message}`, LOG_TYPE.ERROR);
  1968. if (mqttTestResult) {
  1969. mqttTestResult.innerHTML = `<span class="material-icons text-red-600 mr-1">error</span><span class="text-red-600">Test failed: ${error.message}</span>`;
  1970. }
  1971. showStatusMessage(`MQTT test failed: ${error.message}`, 'error');
  1972. } finally {
  1973. // Restore button
  1974. testMqttButton.innerHTML = originalButtonHTML;
  1975. testMqttButton.disabled = false;
  1976. }
  1977. }
  1978. // Event listeners
  1979. mqttEnableToggle.addEventListener('change', () => {
  1980. updateMqttSettingsVisibility();
  1981. updateRestartNotice();
  1982. });
  1983. // Track changes to show restart notice
  1984. [mqttBrokerInput, mqttPortInput, mqttUsernameInput, mqttPasswordInput,
  1985. mqttDeviceNameInput, mqttDeviceIdInput, mqttClientIdInput, mqttDiscoveryPrefixInput].forEach(input => {
  1986. if (input) {
  1987. input.addEventListener('input', updateRestartNotice);
  1988. }
  1989. });
  1990. testMqttButton.addEventListener('click', testMqttConnection);
  1991. saveMqttButton.addEventListener('click', saveMqttConfig);
  1992. }
  1993. // Initialize MQTT config when DOM is ready
  1994. document.addEventListener('DOMContentLoaded', function() {
  1995. initializeMqttConfig();
  1996. });