settings.js 89 KB

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