settings.js 67 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651
  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. if (portsElement) {
  104. portsElement.textContent = ports.length > 0 ? ports.join(', ') : 'No ports available';
  105. }
  106. if (portSelect) {
  107. // Clear existing options except the first one
  108. while (portSelect.options.length > 1) {
  109. portSelect.remove(1);
  110. }
  111. // Add new options
  112. ports.forEach(port => {
  113. const option = document.createElement('option');
  114. option.value = port;
  115. option.textContent = port;
  116. portSelect.appendChild(option);
  117. });
  118. // If there's exactly one port available, select and connect to it
  119. if (ports.length === 1) {
  120. portSelect.value = ports[0];
  121. // Trigger connect button click
  122. const connectButton = document.getElementById('connectButton');
  123. if (connectButton) {
  124. connectButton.click();
  125. }
  126. }
  127. }
  128. }
  129. } catch (error) {
  130. logMessage(`Error fetching serial ports: ${error.message}`, LOG_TYPE.ERROR);
  131. }
  132. }
  133. function setWledButtonState(isSet) {
  134. const saveWledConfig = document.getElementById('saveWledConfig');
  135. if (!saveWledConfig) return;
  136. if (isSet) {
  137. 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';
  138. saveWledConfig.innerHTML = '<span class="material-icons text-lg">close</span><span class="truncate">Clear WLED IP</span>';
  139. } else {
  140. 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';
  141. saveWledConfig.innerHTML = '<span class="material-icons text-lg">save</span><span class="truncate">Save Configuration</span>';
  142. }
  143. }
  144. // Handle LED provider selection and show/hide appropriate config sections
  145. function updateLedProviderUI() {
  146. const provider = document.querySelector('input[name="ledProvider"]:checked')?.value || 'none';
  147. const wledConfig = document.getElementById('wledConfig');
  148. const dwLedsConfig = document.getElementById('dwLedsConfig');
  149. if (wledConfig && dwLedsConfig) {
  150. if (provider === 'wled') {
  151. wledConfig.classList.remove('hidden');
  152. dwLedsConfig.classList.add('hidden');
  153. } else if (provider === 'dw_leds') {
  154. wledConfig.classList.add('hidden');
  155. dwLedsConfig.classList.remove('hidden');
  156. } else {
  157. wledConfig.classList.add('hidden');
  158. dwLedsConfig.classList.add('hidden');
  159. }
  160. }
  161. }
  162. // Load LED configuration from server
  163. async function loadLedConfig() {
  164. try {
  165. const response = await fetch('/get_led_config');
  166. if (response.ok) {
  167. const data = await response.json();
  168. // Set provider radio button
  169. const providerRadio = document.getElementById(`ledProvider${providerToCamelCase(data.provider)}`);
  170. if (providerRadio) {
  171. providerRadio.checked = true;
  172. } else {
  173. document.getElementById('ledProviderNone').checked = true;
  174. }
  175. // Set WLED IP if configured
  176. if (data.wled_ip) {
  177. const wledIpInput = document.getElementById('wledIpInput');
  178. if (wledIpInput) {
  179. wledIpInput.value = data.wled_ip;
  180. }
  181. }
  182. // Set DW LED configuration if configured
  183. if (data.dw_led_num_leds) {
  184. const numLedsInput = document.getElementById('dwLedNumLeds');
  185. if (numLedsInput) {
  186. numLedsInput.value = data.dw_led_num_leds;
  187. }
  188. }
  189. if (data.dw_led_gpio_pin) {
  190. const gpioPinInput = document.getElementById('dwLedGpioPin');
  191. if (gpioPinInput) {
  192. gpioPinInput.value = data.dw_led_gpio_pin;
  193. }
  194. }
  195. if (data.dw_led_pixel_order) {
  196. const pixelOrderInput = document.getElementById('dwLedPixelOrder');
  197. if (pixelOrderInput) {
  198. pixelOrderInput.value = data.dw_led_pixel_order;
  199. }
  200. }
  201. // Update UI to show correct config section
  202. updateLedProviderUI();
  203. }
  204. } catch (error) {
  205. logMessage(`Error loading LED config: ${error.message}`, LOG_TYPE.ERROR);
  206. }
  207. }
  208. // Initialize settings page
  209. document.addEventListener('DOMContentLoaded', async () => {
  210. // Initialize UI with default disconnected state
  211. updateConnectionUI({ connected: false });
  212. // Load all data asynchronously
  213. Promise.all([
  214. // Check connection status
  215. fetch('/serial_status').then(response => response.json()).catch(() => ({ connected: false })),
  216. // Load LED configuration (replaces old WLED-only loading)
  217. fetch('/get_led_config').then(response => response.json()).catch(() => ({ provider: 'none', wled_ip: null })),
  218. // Load current version and check for updates
  219. fetch('/api/version').then(response => response.json()).catch(() => ({ current: '1.0.0', latest: '1.0.0', update_available: false })),
  220. // Load available serial ports
  221. fetch('/list_serial_ports').then(response => response.json()).catch(() => []),
  222. // Load available pattern files for clear pattern selection
  223. getCachedPatternFiles().catch(() => []),
  224. // Load current custom clear patterns
  225. fetch('/api/custom_clear_patterns').then(response => response.json()).catch(() => ({ custom_clear_from_in: null, custom_clear_from_out: null })),
  226. // Load current clear pattern speed
  227. fetch('/api/clear_pattern_speed').then(response => response.json()).catch(() => ({ clear_pattern_speed: 200 })),
  228. // Load current app name
  229. fetch('/api/app-name').then(response => response.json()).catch(() => ({ app_name: 'Dune Weaver' })),
  230. // Load Still Sands settings
  231. fetch('/api/scheduled-pause').then(response => response.json()).catch(() => ({ enabled: false, time_slots: [] }))
  232. ]).then(([statusData, ledConfigData, updateData, ports, patterns, clearPatterns, clearSpeedData, appNameData, scheduledPauseData]) => {
  233. // Update connection status
  234. setCachedConnectionStatus(statusData);
  235. updateConnectionUI(statusData);
  236. // Update LED configuration
  237. const providerRadio = document.getElementById(`ledProvider${providerToCamelCase(ledConfigData.provider)}`);
  238. if (providerRadio) {
  239. providerRadio.checked = true;
  240. } else {
  241. document.getElementById('ledProviderNone').checked = true;
  242. }
  243. if (ledConfigData.wled_ip) {
  244. const wledIpInput = document.getElementById('wledIpInput');
  245. if (wledIpInput) wledIpInput.value = ledConfigData.wled_ip;
  246. }
  247. // Load DW LED settings
  248. if (ledConfigData.dw_led_num_leds) {
  249. const numLedsInput = document.getElementById('dwLedNumLeds');
  250. if (numLedsInput) numLedsInput.value = ledConfigData.dw_led_num_leds;
  251. }
  252. if (ledConfigData.dw_led_gpio_pin) {
  253. const gpioPinInput = document.getElementById('dwLedGpioPin');
  254. if (gpioPinInput) gpioPinInput.value = ledConfigData.dw_led_gpio_pin;
  255. }
  256. if (ledConfigData.dw_led_pixel_order) {
  257. const pixelOrderInput = document.getElementById('dwLedPixelOrder');
  258. if (pixelOrderInput) pixelOrderInput.value = ledConfigData.dw_led_pixel_order;
  259. }
  260. updateLedProviderUI()
  261. // Update version display
  262. const currentVersionText = document.getElementById('currentVersionText');
  263. const latestVersionText = document.getElementById('latestVersionText');
  264. const updateButton = document.getElementById('updateSoftware');
  265. const updateIcon = document.getElementById('updateIcon');
  266. const updateText = document.getElementById('updateText');
  267. if (currentVersionText) {
  268. currentVersionText.textContent = updateData.current;
  269. }
  270. if (latestVersionText) {
  271. if (updateData.error) {
  272. latestVersionText.textContent = 'Error checking updates';
  273. latestVersionText.className = 'text-red-500 text-sm font-normal leading-normal';
  274. } else {
  275. latestVersionText.textContent = updateData.latest;
  276. latestVersionText.className = 'text-slate-500 text-sm font-normal leading-normal';
  277. }
  278. }
  279. // Update button state
  280. if (updateButton && updateIcon && updateText) {
  281. if (updateData.update_available) {
  282. updateButton.disabled = false;
  283. 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';
  284. updateIcon.textContent = 'download';
  285. updateText.textContent = 'Update';
  286. } else {
  287. updateButton.disabled = true;
  288. 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';
  289. updateIcon.textContent = 'check';
  290. updateText.textContent = 'Up to date';
  291. }
  292. }
  293. // Update port selection
  294. const portSelect = document.getElementById('portSelect');
  295. if (portSelect) {
  296. // Clear existing options except the first one
  297. while (portSelect.options.length > 1) {
  298. portSelect.remove(1);
  299. }
  300. // Add new options
  301. ports.forEach(port => {
  302. const option = document.createElement('option');
  303. option.value = port;
  304. option.textContent = port;
  305. portSelect.appendChild(option);
  306. });
  307. // If there's exactly one port available, select it
  308. if (ports.length === 1) {
  309. portSelect.value = ports[0];
  310. }
  311. }
  312. // Initialize autocomplete for clear patterns
  313. const clearFromInInput = document.getElementById('customClearFromInInput');
  314. const clearFromOutInput = document.getElementById('customClearFromOutInput');
  315. if (clearFromInInput && clearFromOutInput && patterns && Array.isArray(patterns)) {
  316. // Store patterns globally for autocomplete
  317. window.availablePatterns = patterns;
  318. // Set current values if they exist
  319. if (clearPatterns && clearPatterns.custom_clear_from_in) {
  320. clearFromInInput.value = clearPatterns.custom_clear_from_in;
  321. }
  322. if (clearPatterns && clearPatterns.custom_clear_from_out) {
  323. clearFromOutInput.value = clearPatterns.custom_clear_from_out;
  324. }
  325. // Initialize autocomplete for both inputs
  326. initializeAutocomplete('customClearFromInInput', 'clearFromInSuggestions', 'clearFromInClear', patterns);
  327. initializeAutocomplete('customClearFromOutInput', 'clearFromOutSuggestions', 'clearFromOutClear', patterns);
  328. console.log('Autocomplete initialized with', patterns.length, 'patterns');
  329. }
  330. // Set clear pattern speed
  331. const clearPatternSpeedInput = document.getElementById('clearPatternSpeedInput');
  332. const effectiveClearSpeed = document.getElementById('effectiveClearSpeed');
  333. if (clearPatternSpeedInput && clearSpeedData) {
  334. // Only set value if clear_pattern_speed is not null
  335. if (clearSpeedData.clear_pattern_speed !== null && clearSpeedData.clear_pattern_speed !== undefined) {
  336. clearPatternSpeedInput.value = clearSpeedData.clear_pattern_speed;
  337. if (effectiveClearSpeed) {
  338. effectiveClearSpeed.textContent = `Current: ${clearSpeedData.clear_pattern_speed} steps/min`;
  339. }
  340. } else {
  341. // Leave empty to show placeholder for default
  342. clearPatternSpeedInput.value = '';
  343. if (effectiveClearSpeed && clearSpeedData.effective_speed) {
  344. effectiveClearSpeed.textContent = `Using default pattern speed: ${clearSpeedData.effective_speed} steps/min`;
  345. }
  346. }
  347. }
  348. // Update app name
  349. const appNameInput = document.getElementById('appNameInput');
  350. if (appNameInput && appNameData.app_name) {
  351. appNameInput.value = appNameData.app_name;
  352. }
  353. // Store Still Sands data for later initialization
  354. window.initialStillSandsData = scheduledPauseData;
  355. }).catch(error => {
  356. logMessage(`Error initializing settings page: ${error.message}`, LOG_TYPE.ERROR);
  357. });
  358. // Set up event listeners
  359. setupEventListeners();
  360. });
  361. // Setup event listeners
  362. function setupEventListeners() {
  363. // Save App Name
  364. const saveAppNameButton = document.getElementById('saveAppName');
  365. const appNameInput = document.getElementById('appNameInput');
  366. if (saveAppNameButton && appNameInput) {
  367. saveAppNameButton.addEventListener('click', async () => {
  368. const appName = appNameInput.value.trim() || 'Dune Weaver';
  369. try {
  370. const response = await fetch('/api/app-name', {
  371. method: 'POST',
  372. headers: { 'Content-Type': 'application/json' },
  373. body: JSON.stringify({ app_name: appName })
  374. });
  375. if (response.ok) {
  376. const data = await response.json();
  377. showStatusMessage('Application name updated successfully. Refresh the page to see changes.', 'success');
  378. // Update the page title and header immediately
  379. document.title = `Settings - ${data.app_name}`;
  380. const headerTitle = document.querySelector('h1.text-gray-800');
  381. if (headerTitle) {
  382. // Update just the text content, preserving the connection status dot
  383. const textNode = headerTitle.childNodes[0];
  384. if (textNode && textNode.nodeType === Node.TEXT_NODE) {
  385. textNode.textContent = data.app_name;
  386. }
  387. }
  388. } else {
  389. throw new Error('Failed to save application name');
  390. }
  391. } catch (error) {
  392. showStatusMessage(`Failed to save application name: ${error.message}`, 'error');
  393. }
  394. });
  395. // Handle Enter key in app name input
  396. appNameInput.addEventListener('keypress', (e) => {
  397. if (e.key === 'Enter') {
  398. saveAppNameButton.click();
  399. }
  400. });
  401. }
  402. // LED provider selection change handlers
  403. const ledProviderRadios = document.querySelectorAll('input[name="ledProvider"]');
  404. ledProviderRadios.forEach(radio => {
  405. radio.addEventListener('change', updateLedProviderUI);
  406. });
  407. // Save LED configuration
  408. const saveLedConfig = document.getElementById('saveLedConfig');
  409. if (saveLedConfig) {
  410. saveLedConfig.addEventListener('click', async () => {
  411. const provider = document.querySelector('input[name="ledProvider"]:checked')?.value || 'none';
  412. let requestBody = { provider };
  413. if (provider === 'wled') {
  414. const wledIp = document.getElementById('wledIpInput')?.value;
  415. if (!wledIp) {
  416. showStatusMessage('Please enter a WLED IP address', 'error');
  417. return;
  418. }
  419. requestBody.ip_address = wledIp;
  420. } else if (provider === 'dw_leds') {
  421. const numLeds = parseInt(document.getElementById('dwLedNumLeds')?.value) || 60;
  422. const gpioPin = parseInt(document.getElementById('dwLedGpioPin')?.value) || 12;
  423. const pixelOrder = document.getElementById('dwLedPixelOrder')?.value || 'GRB';
  424. requestBody.num_leds = numLeds;
  425. requestBody.gpio_pin = gpioPin;
  426. requestBody.pixel_order = pixelOrder;
  427. }
  428. try {
  429. const response = await fetch('/set_led_config', {
  430. method: 'POST',
  431. headers: { 'Content-Type': 'application/json' },
  432. body: JSON.stringify(requestBody)
  433. });
  434. if (response.ok) {
  435. const data = await response.json();
  436. if (provider === 'wled' && data.wled_ip) {
  437. localStorage.setItem('wled_ip', data.wled_ip);
  438. showStatusMessage('WLED configured successfully', 'success');
  439. } else if (provider === 'dw_leds') {
  440. // Check if there's a warning (hardware not available but settings saved)
  441. if (data.warning) {
  442. showStatusMessage(
  443. `Settings saved for testing. Hardware issue: ${data.warning}`,
  444. 'warning'
  445. );
  446. } else {
  447. showStatusMessage(
  448. `DW LEDs configured: ${data.dw_led_num_leds} LEDs on GPIO${data.dw_led_gpio_pin}`,
  449. 'success'
  450. );
  451. }
  452. } else if (provider === 'none') {
  453. localStorage.removeItem('wled_ip');
  454. showStatusMessage('LED controller disabled', 'success');
  455. }
  456. } else {
  457. // Extract error detail from response
  458. const errorData = await response.json().catch(() => ({}));
  459. const errorMessage = errorData.detail || 'Failed to save LED configuration';
  460. showStatusMessage(errorMessage, 'error');
  461. }
  462. } catch (error) {
  463. showStatusMessage(`Failed to save LED configuration: ${error.message}`, 'error');
  464. }
  465. });
  466. }
  467. // Fetch and populate available versions
  468. async function loadAvailableVersions() {
  469. try {
  470. const response = await fetch('/api/versions');
  471. const data = await response.json();
  472. if (data.success && data.versions) {
  473. const versionSelect = document.getElementById('versionSelect');
  474. if (versionSelect) {
  475. // Clear existing options except "Latest"
  476. versionSelect.innerHTML = '<option value="latest">Latest Version</option>';
  477. // Add optgroup for tags
  478. if (data.versions.tags && data.versions.tags.length > 0) {
  479. const tagsOptgroup = document.createElement('optgroup');
  480. tagsOptgroup.label = 'Tags (Releases)';
  481. data.versions.tags.forEach(tag => {
  482. const option = document.createElement('option');
  483. option.value = tag;
  484. option.textContent = tag;
  485. tagsOptgroup.appendChild(option);
  486. });
  487. versionSelect.appendChild(tagsOptgroup);
  488. }
  489. // Add optgroup for branches
  490. if (data.versions.branches && data.versions.branches.length > 0) {
  491. const branchesOptgroup = document.createElement('optgroup');
  492. branchesOptgroup.label = 'Branches';
  493. data.versions.branches.forEach(branch => {
  494. const option = document.createElement('option');
  495. option.value = branch;
  496. option.textContent = branch;
  497. branchesOptgroup.appendChild(option);
  498. });
  499. versionSelect.appendChild(branchesOptgroup);
  500. }
  501. // Enable update button
  502. const updateButton = document.getElementById('updateSoftware');
  503. if (updateButton) {
  504. updateButton.disabled = false;
  505. updateButton.classList.remove('bg-gray-400');
  506. updateButton.classList.add('bg-sky-600', 'hover:bg-sky-700');
  507. }
  508. }
  509. }
  510. } catch (error) {
  511. console.error('Error loading versions:', error);
  512. showStatusMessage('Failed to load available versions', 'error');
  513. }
  514. }
  515. // Load versions on page load
  516. loadAvailableVersions();
  517. // Update confirmation modal logic
  518. let updateWebSocket = null;
  519. function showUpdateConfirmModal() {
  520. const modal = document.getElementById('updateConfirmModal');
  521. const versionSelect = document.getElementById('versionSelect');
  522. const targetVersionDisplay = document.getElementById('targetVersionDisplay');
  523. if (modal && versionSelect && targetVersionDisplay) {
  524. const selectedVersion = versionSelect.value;
  525. targetVersionDisplay.textContent = selectedVersion;
  526. modal.classList.remove('hidden');
  527. }
  528. }
  529. function hideUpdateConfirmModal() {
  530. const modal = document.getElementById('updateConfirmModal');
  531. if (modal) {
  532. modal.classList.add('hidden');
  533. }
  534. // Clean up WebSocket if exists
  535. if (updateWebSocket) {
  536. updateWebSocket.close();
  537. updateWebSocket = null;
  538. }
  539. }
  540. function appendUpdateLog(message) {
  541. const logContainer = document.getElementById('updateProgressLog');
  542. if (logContainer) {
  543. const logLine = document.createElement('div');
  544. logLine.textContent = message;
  545. logContainer.appendChild(logLine);
  546. // Auto-scroll to bottom
  547. logContainer.parentElement.scrollTop = logContainer.parentElement.scrollHeight;
  548. }
  549. }
  550. function startUpdateProcess() {
  551. const versionSelect = document.getElementById('versionSelect');
  552. const progressContainer = document.getElementById('updateProgressContainer');
  553. const modalActions = document.getElementById('updateModalActions');
  554. const completeActions = document.getElementById('updateCompleteActions');
  555. const selectedVersion = versionSelect ? versionSelect.value : 'latest';
  556. // Show progress container and hide action buttons
  557. if (progressContainer) progressContainer.classList.remove('hidden');
  558. if (modalActions) modalActions.classList.add('hidden');
  559. // Connect to WebSocket for live logs
  560. const wsProtocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
  561. updateWebSocket = new WebSocket(`${wsProtocol}//${window.location.host}/ws/update-progress`);
  562. updateWebSocket.onopen = () => {
  563. console.log('Update WebSocket connected');
  564. appendUpdateLog('Connected to update stream...');
  565. // Trigger the update
  566. fetch('/api/update_to_version', {
  567. method: 'POST',
  568. headers: { 'Content-Type': 'application/json' },
  569. body: JSON.stringify({ version: selectedVersion })
  570. })
  571. .then(response => response.json())
  572. .then(data => {
  573. if (!data.success) {
  574. appendUpdateLog(`ERROR: ${data.message || 'Failed to start update'}`);
  575. }
  576. })
  577. .catch(error => {
  578. appendUpdateLog(`ERROR: ${error.message}`);
  579. });
  580. };
  581. updateWebSocket.onmessage = (event) => {
  582. const data = JSON.parse(event.data);
  583. if (data.type === 'log') {
  584. appendUpdateLog(data.message);
  585. // Check for completion
  586. if (data.message.includes('Update completed successfully') ||
  587. data.message.includes('Update failed')) {
  588. if (completeActions) completeActions.classList.remove('hidden');
  589. }
  590. }
  591. };
  592. updateWebSocket.onerror = (error) => {
  593. console.error('WebSocket error:', error);
  594. appendUpdateLog('ERROR: WebSocket connection error');
  595. };
  596. updateWebSocket.onclose = () => {
  597. console.log('Update WebSocket closed');
  598. };
  599. }
  600. // Update software button - show confirmation modal
  601. const updateSoftware = document.getElementById('updateSoftware');
  602. if (updateSoftware) {
  603. updateSoftware.addEventListener('click', () => {
  604. if (updateSoftware.disabled) {
  605. return;
  606. }
  607. showUpdateConfirmModal();
  608. });
  609. }
  610. // Modal action buttons
  611. const closeUpdateModal = document.getElementById('closeUpdateModal');
  612. const cancelUpdate = document.getElementById('cancelUpdate');
  613. const confirmUpdate = document.getElementById('confirmUpdate');
  614. const closeUpdateComplete = document.getElementById('closeUpdateComplete');
  615. if (closeUpdateModal) {
  616. closeUpdateModal.addEventListener('click', hideUpdateConfirmModal);
  617. }
  618. if (cancelUpdate) {
  619. cancelUpdate.addEventListener('click', hideUpdateConfirmModal);
  620. }
  621. if (confirmUpdate) {
  622. confirmUpdate.addEventListener('click', () => {
  623. startUpdateProcess();
  624. });
  625. }
  626. if (closeUpdateComplete) {
  627. closeUpdateComplete.addEventListener('click', () => {
  628. hideUpdateConfirmModal();
  629. // Optionally reload the page to show new version
  630. setTimeout(() => window.location.reload(), 1000);
  631. });
  632. }
  633. // Connect button
  634. const connectButton = document.getElementById('connectButton');
  635. if (connectButton) {
  636. connectButton.addEventListener('click', async () => {
  637. const portSelect = document.getElementById('portSelect');
  638. if (!portSelect || !portSelect.value) {
  639. logMessage('Please select a port first', LOG_TYPE.WARNING);
  640. return;
  641. }
  642. try {
  643. const response = await fetch('/connect', {
  644. method: 'POST',
  645. headers: { 'Content-Type': 'application/json' },
  646. body: JSON.stringify({ port: portSelect.value })
  647. });
  648. if (response.ok) {
  649. logMessage('Connected successfully', LOG_TYPE.SUCCESS);
  650. await updateSerialStatus(true); // Force update after connecting
  651. } else {
  652. throw new Error('Failed to connect');
  653. }
  654. } catch (error) {
  655. logMessage(`Error connecting to device: ${error.message}`, LOG_TYPE.ERROR);
  656. }
  657. });
  658. }
  659. // Disconnect button
  660. const disconnectButton = document.getElementById('disconnectButton');
  661. if (disconnectButton) {
  662. disconnectButton.addEventListener('click', async () => {
  663. try {
  664. const response = await fetch('/disconnect', {
  665. method: 'POST'
  666. });
  667. if (response.ok) {
  668. logMessage('Device disconnected successfully', LOG_TYPE.SUCCESS);
  669. await updateSerialStatus(true); // Force update after disconnecting
  670. } else {
  671. throw new Error('Failed to disconnect device');
  672. }
  673. } catch (error) {
  674. logMessage(`Error disconnecting device: ${error.message}`, LOG_TYPE.ERROR);
  675. }
  676. });
  677. }
  678. // Save custom clear patterns button
  679. const saveClearPatterns = document.getElementById('saveClearPatterns');
  680. if (saveClearPatterns) {
  681. saveClearPatterns.addEventListener('click', async () => {
  682. const clearFromInInput = document.getElementById('customClearFromInInput');
  683. const clearFromOutInput = document.getElementById('customClearFromOutInput');
  684. if (!clearFromInInput || !clearFromOutInput) {
  685. return;
  686. }
  687. // Validate that the entered patterns exist (if not empty)
  688. const inValue = clearFromInInput.value.trim();
  689. const outValue = clearFromOutInput.value.trim();
  690. if (inValue && window.availablePatterns && !window.availablePatterns.includes(inValue)) {
  691. showStatusMessage(`Pattern not found: ${inValue}`, 'error');
  692. return;
  693. }
  694. if (outValue && window.availablePatterns && !window.availablePatterns.includes(outValue)) {
  695. showStatusMessage(`Pattern not found: ${outValue}`, 'error');
  696. return;
  697. }
  698. try {
  699. const response = await fetch('/api/custom_clear_patterns', {
  700. method: 'POST',
  701. headers: { 'Content-Type': 'application/json' },
  702. body: JSON.stringify({
  703. custom_clear_from_in: inValue || null,
  704. custom_clear_from_out: outValue || null
  705. })
  706. });
  707. if (response.ok) {
  708. showStatusMessage('Clear patterns saved successfully', 'success');
  709. } else {
  710. const error = await response.json();
  711. throw new Error(error.detail || 'Failed to save clear patterns');
  712. }
  713. } catch (error) {
  714. showStatusMessage(`Failed to save clear patterns: ${error.message}`, 'error');
  715. }
  716. });
  717. }
  718. // Save clear pattern speed button
  719. const saveClearSpeed = document.getElementById('saveClearSpeed');
  720. if (saveClearSpeed) {
  721. saveClearSpeed.addEventListener('click', async () => {
  722. const clearPatternSpeedInput = document.getElementById('clearPatternSpeedInput');
  723. if (!clearPatternSpeedInput) {
  724. return;
  725. }
  726. let speed;
  727. if (clearPatternSpeedInput.value === '' || clearPatternSpeedInput.value === null) {
  728. // Empty value means use default (None)
  729. speed = null;
  730. } else {
  731. speed = parseInt(clearPatternSpeedInput.value);
  732. // Validate speed only if it's not null
  733. if (isNaN(speed) || speed < 50 || speed > 2000) {
  734. showStatusMessage('Clear pattern speed must be between 50 and 2000, or leave empty for default', 'error');
  735. return;
  736. }
  737. }
  738. try {
  739. const response = await fetch('/api/clear_pattern_speed', {
  740. method: 'POST',
  741. headers: { 'Content-Type': 'application/json' },
  742. body: JSON.stringify({ clear_pattern_speed: speed })
  743. });
  744. if (response.ok) {
  745. const data = await response.json();
  746. if (speed === null) {
  747. showStatusMessage(`Clear pattern speed set to default (${data.effective_speed} steps/min)`, 'success');
  748. } else {
  749. showStatusMessage(`Clear pattern speed set to ${speed} steps/min`, 'success');
  750. }
  751. // Update the effective speed display
  752. const effectiveClearSpeed = document.getElementById('effectiveClearSpeed');
  753. if (effectiveClearSpeed) {
  754. if (speed === null) {
  755. effectiveClearSpeed.textContent = `Using default pattern speed: ${data.effective_speed} steps/min`;
  756. } else {
  757. effectiveClearSpeed.textContent = `Current: ${speed} steps/min`;
  758. }
  759. }
  760. } else {
  761. const error = await response.json();
  762. throw new Error(error.detail || 'Failed to save clear pattern speed');
  763. }
  764. } catch (error) {
  765. showStatusMessage(`Failed to save clear pattern speed: ${error.message}`, 'error');
  766. }
  767. });
  768. }
  769. }
  770. // Button click handlers
  771. document.addEventListener('DOMContentLoaded', function() {
  772. // Home button
  773. const homeButton = document.getElementById('homeButton');
  774. if (homeButton) {
  775. homeButton.addEventListener('click', async () => {
  776. try {
  777. const response = await fetch('/send_home', {
  778. method: 'POST',
  779. headers: {
  780. 'Content-Type': 'application/json'
  781. }
  782. });
  783. const data = await response.json();
  784. if (data.success) {
  785. updateStatus('Moving to home position...');
  786. }
  787. } catch (error) {
  788. console.error('Error sending home command:', error);
  789. updateStatus('Error: Failed to move to home position');
  790. }
  791. });
  792. }
  793. // Stop button
  794. const stopButton = document.getElementById('stopButton');
  795. if (stopButton) {
  796. stopButton.addEventListener('click', async () => {
  797. try {
  798. const response = await fetch('/stop_execution', {
  799. method: 'POST',
  800. headers: {
  801. 'Content-Type': 'application/json'
  802. }
  803. });
  804. const data = await response.json();
  805. if (data.success) {
  806. updateStatus('Execution stopped');
  807. }
  808. } catch (error) {
  809. console.error('Error stopping execution:', error);
  810. updateStatus('Error: Failed to stop execution');
  811. }
  812. });
  813. }
  814. // Move to Center button
  815. const centerButton = document.getElementById('centerButton');
  816. if (centerButton) {
  817. centerButton.addEventListener('click', async () => {
  818. try {
  819. const response = await fetch('/move_to_center', {
  820. method: 'POST',
  821. headers: {
  822. 'Content-Type': 'application/json'
  823. }
  824. });
  825. const data = await response.json();
  826. if (data.success) {
  827. updateStatus('Moving to center position...');
  828. }
  829. } catch (error) {
  830. console.error('Error moving to center:', error);
  831. updateStatus('Error: Failed to move to center');
  832. }
  833. });
  834. }
  835. // Move to Perimeter button
  836. const perimeterButton = document.getElementById('perimeterButton');
  837. if (perimeterButton) {
  838. perimeterButton.addEventListener('click', async () => {
  839. try {
  840. const response = await fetch('/move_to_perimeter', {
  841. method: 'POST',
  842. headers: {
  843. 'Content-Type': 'application/json'
  844. }
  845. });
  846. const data = await response.json();
  847. if (data.success) {
  848. updateStatus('Moving to perimeter position...');
  849. }
  850. } catch (error) {
  851. console.error('Error moving to perimeter:', error);
  852. updateStatus('Error: Failed to move to perimeter');
  853. }
  854. });
  855. }
  856. });
  857. // Function to update status
  858. function updateStatus(message) {
  859. const statusElement = document.querySelector('.text-slate-800.text-base.font-medium.leading-normal');
  860. if (statusElement) {
  861. statusElement.textContent = message;
  862. // Reset status after 3 seconds if it's a temporary message
  863. if (message.includes('Moving') || message.includes('Execution')) {
  864. setTimeout(() => {
  865. statusElement.textContent = 'Status';
  866. }, 3000);
  867. }
  868. }
  869. }
  870. // Function to show status messages (using existing base.js showStatusMessage if available)
  871. function showStatusMessage(message, type) {
  872. if (typeof window.showStatusMessage === 'function') {
  873. window.showStatusMessage(message, type);
  874. } else {
  875. // Fallback to console logging
  876. console.log(`[${type}] ${message}`);
  877. }
  878. }
  879. // Function to show update instructions modal
  880. function showUpdateInstructionsModal(data) {
  881. // Create modal HTML
  882. const modal = document.createElement('div');
  883. modal.id = 'updateInstructionsModal';
  884. modal.className = 'fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4';
  885. modal.innerHTML = `
  886. <div class="bg-white dark:bg-gray-800 rounded-lg shadow-xl w-full max-w-md">
  887. <div class="p-6">
  888. <div class="text-center mb-4">
  889. <h2 class="text-xl font-semibold text-gray-800 dark:text-gray-200 mb-2">Manual Update Required</h2>
  890. <p class="text-gray-600 dark:text-gray-400 text-sm">
  891. ${data.message}
  892. </p>
  893. </div>
  894. <div class="text-gray-700 dark:text-gray-300 text-sm mb-6">
  895. <p class="mb-3">${data.instructions}</p>
  896. </div>
  897. <div class="flex gap-3 justify-center">
  898. <button id="openGitHubRelease" class="px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-lg transition-colors">
  899. View Update Instructions
  900. </button>
  901. <button id="closeUpdateModal" class="px-4 py-2 bg-gray-600 hover:bg-gray-700 text-white rounded-lg transition-colors">
  902. Close
  903. </button>
  904. </div>
  905. </div>
  906. </div>
  907. `;
  908. document.body.appendChild(modal);
  909. // Add event listeners
  910. const openGitHubButton = modal.querySelector('#openGitHubRelease');
  911. const closeButton = modal.querySelector('#closeUpdateModal');
  912. openGitHubButton.addEventListener('click', () => {
  913. window.open(data.manual_update_url, '_blank');
  914. document.body.removeChild(modal);
  915. });
  916. closeButton.addEventListener('click', () => {
  917. document.body.removeChild(modal);
  918. });
  919. // Close on outside click
  920. modal.addEventListener('click', (e) => {
  921. if (e.target === modal) {
  922. document.body.removeChild(modal);
  923. }
  924. });
  925. }
  926. // Autocomplete functionality
  927. function initializeAutocomplete(inputId, suggestionsId, clearButtonId, patterns) {
  928. const input = document.getElementById(inputId);
  929. const suggestionsDiv = document.getElementById(suggestionsId);
  930. const clearButton = document.getElementById(clearButtonId);
  931. let selectedIndex = -1;
  932. if (!input || !suggestionsDiv) return;
  933. // Function to update clear button visibility
  934. function updateClearButton() {
  935. if (clearButton) {
  936. if (input.value.trim()) {
  937. clearButton.classList.remove('hidden');
  938. } else {
  939. clearButton.classList.add('hidden');
  940. }
  941. }
  942. }
  943. // Format pattern name for display
  944. function formatPatternName(pattern) {
  945. return pattern.replace('.thr', '').replace(/_/g, ' ');
  946. }
  947. // Filter patterns based on input
  948. function filterPatterns(searchTerm) {
  949. if (!searchTerm) return patterns.slice(0, 20); // Show first 20 when empty
  950. const term = searchTerm.toLowerCase();
  951. return patterns.filter(pattern => {
  952. const name = pattern.toLowerCase();
  953. return name.includes(term);
  954. }).sort((a, b) => {
  955. // Prioritize patterns that start with the search term
  956. const aStarts = a.toLowerCase().startsWith(term);
  957. const bStarts = b.toLowerCase().startsWith(term);
  958. if (aStarts && !bStarts) return -1;
  959. if (!aStarts && bStarts) return 1;
  960. return a.localeCompare(b);
  961. }).slice(0, 20); // Limit to 20 results
  962. }
  963. // Highlight matching text
  964. function highlightMatch(text, searchTerm) {
  965. if (!searchTerm) return text;
  966. const regex = new RegExp(`(${searchTerm.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')})`, 'gi');
  967. return text.replace(regex, '<mark>$1</mark>');
  968. }
  969. // Show suggestions
  970. function showSuggestions(searchTerm) {
  971. const filtered = filterPatterns(searchTerm);
  972. if (filtered.length === 0 && searchTerm) {
  973. suggestionsDiv.innerHTML = '<div class="suggestion-item" style="cursor: default; color: #9ca3af;">No patterns found</div>';
  974. suggestionsDiv.classList.remove('hidden');
  975. return;
  976. }
  977. suggestionsDiv.innerHTML = filtered.map((pattern, index) => {
  978. const displayName = formatPatternName(pattern);
  979. const highlighted = highlightMatch(displayName, searchTerm);
  980. return `<div class="suggestion-item" data-value="${pattern}" data-index="${index}">${highlighted}</div>`;
  981. }).join('');
  982. suggestionsDiv.classList.remove('hidden');
  983. selectedIndex = -1;
  984. }
  985. // Hide suggestions
  986. function hideSuggestions() {
  987. setTimeout(() => {
  988. suggestionsDiv.classList.add('hidden');
  989. selectedIndex = -1;
  990. }, 200);
  991. }
  992. // Select suggestion
  993. function selectSuggestion(value) {
  994. input.value = value;
  995. hideSuggestions();
  996. updateClearButton();
  997. }
  998. // Handle keyboard navigation
  999. function handleKeyboard(e) {
  1000. const items = suggestionsDiv.querySelectorAll('.suggestion-item[data-value]');
  1001. if (e.key === 'ArrowDown') {
  1002. e.preventDefault();
  1003. selectedIndex = Math.min(selectedIndex + 1, items.length - 1);
  1004. updateSelection(items);
  1005. } else if (e.key === 'ArrowUp') {
  1006. e.preventDefault();
  1007. selectedIndex = Math.max(selectedIndex - 1, -1);
  1008. updateSelection(items);
  1009. } else if (e.key === 'Enter') {
  1010. e.preventDefault();
  1011. if (selectedIndex >= 0 && items[selectedIndex]) {
  1012. selectSuggestion(items[selectedIndex].dataset.value);
  1013. } else if (items.length === 1) {
  1014. selectSuggestion(items[0].dataset.value);
  1015. }
  1016. } else if (e.key === 'Escape') {
  1017. hideSuggestions();
  1018. }
  1019. }
  1020. // Update visual selection
  1021. function updateSelection(items) {
  1022. items.forEach((item, index) => {
  1023. if (index === selectedIndex) {
  1024. item.classList.add('selected');
  1025. item.scrollIntoView({ block: 'nearest' });
  1026. } else {
  1027. item.classList.remove('selected');
  1028. }
  1029. });
  1030. }
  1031. // Event listeners
  1032. input.addEventListener('input', (e) => {
  1033. const value = e.target.value.trim();
  1034. updateClearButton();
  1035. if (value.length > 0 || e.target === document.activeElement) {
  1036. showSuggestions(value);
  1037. } else {
  1038. hideSuggestions();
  1039. }
  1040. });
  1041. input.addEventListener('focus', () => {
  1042. const value = input.value.trim();
  1043. showSuggestions(value);
  1044. });
  1045. input.addEventListener('blur', hideSuggestions);
  1046. input.addEventListener('keydown', handleKeyboard);
  1047. // Click handler for suggestions
  1048. suggestionsDiv.addEventListener('click', (e) => {
  1049. const item = e.target.closest('.suggestion-item[data-value]');
  1050. if (item) {
  1051. selectSuggestion(item.dataset.value);
  1052. }
  1053. });
  1054. // Mouse hover handler
  1055. suggestionsDiv.addEventListener('mouseover', (e) => {
  1056. const item = e.target.closest('.suggestion-item[data-value]');
  1057. if (item) {
  1058. selectedIndex = parseInt(item.dataset.index);
  1059. const items = suggestionsDiv.querySelectorAll('.suggestion-item[data-value]');
  1060. updateSelection(items);
  1061. }
  1062. });
  1063. // Clear button handler
  1064. if (clearButton) {
  1065. clearButton.addEventListener('click', () => {
  1066. input.value = '';
  1067. updateClearButton();
  1068. hideSuggestions();
  1069. input.focus();
  1070. });
  1071. }
  1072. // Initialize clear button visibility
  1073. updateClearButton();
  1074. }
  1075. // auto_play Mode Functions
  1076. async function initializeauto_playMode() {
  1077. const auto_playToggle = document.getElementById('auto_playModeToggle');
  1078. const auto_playSettings = document.getElementById('auto_playSettings');
  1079. const auto_playPlaylistSelect = document.getElementById('auto_playPlaylistSelect');
  1080. const auto_playRunModeSelect = document.getElementById('auto_playRunModeSelect');
  1081. const auto_playPauseTimeInput = document.getElementById('auto_playPauseTimeInput');
  1082. const auto_playClearPatternSelect = document.getElementById('auto_playClearPatternSelect');
  1083. const auto_playShuffleToggle = document.getElementById('auto_playShuffleToggle');
  1084. // Load current auto_play settings
  1085. try {
  1086. const response = await fetch('/api/auto_play-mode');
  1087. const data = await response.json();
  1088. auto_playToggle.checked = data.enabled;
  1089. if (data.enabled) {
  1090. auto_playSettings.style.display = 'block';
  1091. }
  1092. // Set current values
  1093. auto_playRunModeSelect.value = data.run_mode || 'loop';
  1094. auto_playPauseTimeInput.value = data.pause_time || 5.0;
  1095. auto_playClearPatternSelect.value = data.clear_pattern || 'adaptive';
  1096. auto_playShuffleToggle.checked = data.shuffle || false;
  1097. // Load playlists for selection
  1098. const playlistsResponse = await fetch('/list_all_playlists');
  1099. const playlists = await playlistsResponse.json();
  1100. // Clear and populate playlist select
  1101. auto_playPlaylistSelect.innerHTML = '<option value="">Select a playlist...</option>';
  1102. playlists.forEach(playlist => {
  1103. const option = document.createElement('option');
  1104. option.value = playlist;
  1105. option.textContent = playlist;
  1106. if (playlist === data.playlist) {
  1107. option.selected = true;
  1108. }
  1109. auto_playPlaylistSelect.appendChild(option);
  1110. });
  1111. } catch (error) {
  1112. logMessage(`Error loading auto_play settings: ${error.message}`, LOG_TYPE.ERROR);
  1113. }
  1114. // Function to save settings
  1115. async function saveSettings() {
  1116. try {
  1117. const response = await fetch('/api/auto_play-mode', {
  1118. method: 'POST',
  1119. headers: { 'Content-Type': 'application/json' },
  1120. body: JSON.stringify({
  1121. enabled: auto_playToggle.checked,
  1122. playlist: auto_playPlaylistSelect.value || null,
  1123. run_mode: auto_playRunModeSelect.value,
  1124. pause_time: parseFloat(auto_playPauseTimeInput.value) || 0,
  1125. clear_pattern: auto_playClearPatternSelect.value,
  1126. shuffle: auto_playShuffleToggle.checked
  1127. })
  1128. });
  1129. if (!response.ok) {
  1130. throw new Error('Failed to save settings');
  1131. }
  1132. } catch (error) {
  1133. logMessage(`Error saving auto_play settings: ${error.message}`, LOG_TYPE.ERROR);
  1134. }
  1135. }
  1136. // Toggle auto_play settings visibility and save
  1137. auto_playToggle.addEventListener('change', async () => {
  1138. auto_playSettings.style.display = auto_playToggle.checked ? 'block' : 'none';
  1139. await saveSettings();
  1140. });
  1141. // Save when any setting changes
  1142. auto_playPlaylistSelect.addEventListener('change', saveSettings);
  1143. auto_playRunModeSelect.addEventListener('change', saveSettings);
  1144. auto_playPauseTimeInput.addEventListener('change', saveSettings);
  1145. auto_playPauseTimeInput.addEventListener('input', saveSettings); // Save as user types
  1146. auto_playClearPatternSelect.addEventListener('change', saveSettings);
  1147. auto_playShuffleToggle.addEventListener('change', saveSettings);
  1148. }
  1149. // Initialize auto_play mode when DOM is ready
  1150. document.addEventListener('DOMContentLoaded', function() {
  1151. initializeauto_playMode();
  1152. initializeStillSandsMode();
  1153. });
  1154. // Still Sands Mode Functions
  1155. async function initializeStillSandsMode() {
  1156. logMessage('Initializing Still Sands mode', LOG_TYPE.INFO);
  1157. const stillSandsToggle = document.getElementById('scheduledPauseToggle');
  1158. const stillSandsSettings = document.getElementById('scheduledPauseSettings');
  1159. const addTimeSlotButton = document.getElementById('addTimeSlotButton');
  1160. const saveStillSandsButton = document.getElementById('savePauseSettings');
  1161. const timeSlotsContainer = document.getElementById('timeSlotsContainer');
  1162. const wledControlToggle = document.getElementById('stillSandsWledControl');
  1163. // Check if elements exist
  1164. if (!stillSandsToggle || !stillSandsSettings || !addTimeSlotButton || !saveStillSandsButton || !timeSlotsContainer) {
  1165. logMessage('Still Sands elements not found, skipping initialization', LOG_TYPE.WARNING);
  1166. logMessage(`Found elements: toggle=${!!stillSandsToggle}, settings=${!!stillSandsSettings}, addBtn=${!!addTimeSlotButton}, saveBtn=${!!saveStillSandsButton}, container=${!!timeSlotsContainer}`, LOG_TYPE.WARNING);
  1167. return;
  1168. }
  1169. logMessage('All Still Sands elements found successfully', LOG_TYPE.INFO);
  1170. // Track time slots
  1171. let timeSlots = [];
  1172. let slotIdCounter = 0;
  1173. // Load current Still Sands settings from initial data
  1174. try {
  1175. // Use the data loaded during page initialization, fallback to API if not available
  1176. let data;
  1177. if (window.initialStillSandsData) {
  1178. data = window.initialStillSandsData;
  1179. // Clear the global variable after use
  1180. delete window.initialStillSandsData;
  1181. } else {
  1182. // Fallback to API call if initial data not available
  1183. const response = await fetch('/api/scheduled-pause');
  1184. data = await response.json();
  1185. }
  1186. stillSandsToggle.checked = data.enabled || false;
  1187. if (data.enabled) {
  1188. stillSandsSettings.style.display = 'block';
  1189. }
  1190. // Load WLED control setting
  1191. if (wledControlToggle) {
  1192. wledControlToggle.checked = data.control_wled || false;
  1193. }
  1194. // Load existing time slots
  1195. timeSlots = data.time_slots || [];
  1196. // Assign IDs to loaded slots BEFORE rendering
  1197. if (timeSlots.length > 0) {
  1198. slotIdCounter = 0;
  1199. timeSlots.forEach(slot => {
  1200. slot.id = ++slotIdCounter;
  1201. });
  1202. }
  1203. renderTimeSlots();
  1204. } catch (error) {
  1205. logMessage(`Error loading Still Sands settings: ${error.message}`, LOG_TYPE.ERROR);
  1206. // Initialize with empty settings if load fails
  1207. timeSlots = [];
  1208. renderTimeSlots();
  1209. }
  1210. // Function to validate time format (HH:MM)
  1211. function isValidTime(timeString) {
  1212. const timeRegex = /^([01]?[0-9]|2[0-3]):[0-5][0-9]$/;
  1213. return timeRegex.test(timeString);
  1214. }
  1215. // Function to create a new time slot element
  1216. function createTimeSlotElement(slot) {
  1217. const slotDiv = document.createElement('div');
  1218. slotDiv.className = 'time-slot-item';
  1219. slotDiv.dataset.slotId = slot.id;
  1220. slotDiv.innerHTML = `
  1221. <div class="flex items-center gap-3">
  1222. <div class="flex-1 grid grid-cols-1 md:grid-cols-2 gap-3">
  1223. <div class="flex flex-col gap-1">
  1224. <label class="text-slate-700 dark:text-slate-300 text-xs font-medium">Start Time</label>
  1225. <input
  1226. type="time"
  1227. 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"
  1228. value="${slot.start_time || ''}"
  1229. required
  1230. />
  1231. </div>
  1232. <div class="flex flex-col gap-1">
  1233. <label class="text-slate-700 dark:text-slate-300 text-xs font-medium">End Time</label>
  1234. <input
  1235. type="time"
  1236. 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"
  1237. value="${slot.end_time || ''}"
  1238. required
  1239. />
  1240. </div>
  1241. </div>
  1242. <div class="flex flex-col gap-1">
  1243. <label class="text-slate-700 dark:text-slate-300 text-xs font-medium">Days</label>
  1244. <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">
  1245. <option value="daily" ${slot.days === 'daily' ? 'selected' : ''}>Daily</option>
  1246. <option value="weekdays" ${slot.days === 'weekdays' ? 'selected' : ''}>Weekdays</option>
  1247. <option value="weekends" ${slot.days === 'weekends' ? 'selected' : ''}>Weekends</option>
  1248. <option value="custom" ${slot.days === 'custom' ? 'selected' : ''}>Custom</option>
  1249. </select>
  1250. </div>
  1251. <button
  1252. type="button"
  1253. 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"
  1254. title="Remove time slot"
  1255. >
  1256. <span class="material-icons text-base">delete</span>
  1257. </button>
  1258. </div>
  1259. <div class="custom-days-container mt-2" style="display: ${slot.days === 'custom' ? 'block' : 'none'};">
  1260. <label class="text-slate-700 dark:text-slate-300 text-xs font-medium mb-1 block">Select Days</label>
  1261. <div class="flex flex-wrap gap-2">
  1262. ${['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday'].map(day => `
  1263. <label class="flex items-center gap-1 text-xs">
  1264. <input
  1265. type="checkbox"
  1266. name="custom-days-${slot.id}"
  1267. value="${day}"
  1268. ${slot.custom_days && slot.custom_days.includes(day) ? 'checked' : ''}
  1269. class="rounded border-slate-300 text-sky-600 focus:ring-sky-500"
  1270. />
  1271. <span class="text-slate-700 dark:text-slate-300 capitalize">${day.substring(0, 3)}</span>
  1272. </label>
  1273. `).join('')}
  1274. </div>
  1275. </div>
  1276. `;
  1277. // Add event listeners for this slot
  1278. const startTimeInput = slotDiv.querySelector('.start-time');
  1279. const endTimeInput = slotDiv.querySelector('.end-time');
  1280. const daysSelect = slotDiv.querySelector('.days-select');
  1281. const customDaysContainer = slotDiv.querySelector('.custom-days-container');
  1282. const removeButton = slotDiv.querySelector('.remove-slot-btn');
  1283. // Show/hide custom days based on selection
  1284. daysSelect.addEventListener('change', () => {
  1285. customDaysContainer.style.display = daysSelect.value === 'custom' ? 'block' : 'none';
  1286. updateTimeSlot(slot.id);
  1287. });
  1288. // Update slot data when inputs change
  1289. startTimeInput.addEventListener('change', () => updateTimeSlot(slot.id));
  1290. endTimeInput.addEventListener('change', () => updateTimeSlot(slot.id));
  1291. // Handle custom day checkboxes
  1292. customDaysContainer.addEventListener('change', () => updateTimeSlot(slot.id));
  1293. // Remove slot button
  1294. removeButton.addEventListener('click', () => {
  1295. removeTimeSlot(slot.id);
  1296. });
  1297. return slotDiv;
  1298. }
  1299. // Function to render all time slots
  1300. function renderTimeSlots() {
  1301. timeSlotsContainer.innerHTML = '';
  1302. if (timeSlots.length === 0) {
  1303. timeSlotsContainer.innerHTML = `
  1304. <div class="text-center py-8 text-slate-500 dark:text-slate-400">
  1305. <span class="material-icons text-4xl mb-2 block">schedule</span>
  1306. <p>No time slots configured</p>
  1307. <p class="text-xs mt-1">Click "Add Time Slot" to create a pause schedule</p>
  1308. </div>
  1309. `;
  1310. return;
  1311. }
  1312. timeSlots.forEach(slot => {
  1313. const slotElement = createTimeSlotElement(slot);
  1314. timeSlotsContainer.appendChild(slotElement);
  1315. });
  1316. }
  1317. // Function to add a new time slot
  1318. function addTimeSlot() {
  1319. const newSlot = {
  1320. id: ++slotIdCounter,
  1321. start_time: '22:00',
  1322. end_time: '08:00',
  1323. days: 'daily',
  1324. custom_days: []
  1325. };
  1326. timeSlots.push(newSlot);
  1327. renderTimeSlots();
  1328. }
  1329. // Function to remove a time slot
  1330. function removeTimeSlot(slotId) {
  1331. timeSlots = timeSlots.filter(slot => slot.id !== slotId);
  1332. renderTimeSlots();
  1333. }
  1334. // Function to update a time slot's data
  1335. function updateTimeSlot(slotId) {
  1336. const slotElement = timeSlotsContainer.querySelector(`[data-slot-id="${slotId}"]`);
  1337. if (!slotElement) return;
  1338. const slot = timeSlots.find(s => s.id === slotId);
  1339. if (!slot) return;
  1340. // Update slot data from inputs
  1341. slot.start_time = slotElement.querySelector('.start-time').value;
  1342. slot.end_time = slotElement.querySelector('.end-time').value;
  1343. slot.days = slotElement.querySelector('.days-select').value;
  1344. // Update custom days if applicable
  1345. if (slot.days === 'custom') {
  1346. const checkedDays = Array.from(slotElement.querySelectorAll(`input[name="custom-days-${slotId}"]:checked`))
  1347. .map(cb => cb.value);
  1348. slot.custom_days = checkedDays;
  1349. } else {
  1350. slot.custom_days = [];
  1351. }
  1352. }
  1353. // Function to validate all time slots
  1354. function validateTimeSlots() {
  1355. const errors = [];
  1356. timeSlots.forEach((slot, index) => {
  1357. if (!slot.start_time || !isValidTime(slot.start_time)) {
  1358. errors.push(`Time slot ${index + 1}: Invalid start time`);
  1359. }
  1360. if (!slot.end_time || !isValidTime(slot.end_time)) {
  1361. errors.push(`Time slot ${index + 1}: Invalid end time`);
  1362. }
  1363. if (slot.days === 'custom' && (!slot.custom_days || slot.custom_days.length === 0)) {
  1364. errors.push(`Time slot ${index + 1}: Please select at least one day for custom schedule`);
  1365. }
  1366. });
  1367. return errors;
  1368. }
  1369. // Function to save settings
  1370. async function saveStillSandsSettings() {
  1371. // Update all slots from current form values
  1372. timeSlots.forEach(slot => updateTimeSlot(slot.id));
  1373. // Validate time slots
  1374. const validationErrors = validateTimeSlots();
  1375. if (validationErrors.length > 0) {
  1376. showStatusMessage(`Validation errors: ${validationErrors.join(', ')}`, 'error');
  1377. return;
  1378. }
  1379. // Update button UI to show loading state
  1380. const originalButtonHTML = saveStillSandsButton.innerHTML;
  1381. saveStillSandsButton.disabled = true;
  1382. saveStillSandsButton.innerHTML = '<span class="material-icons text-lg animate-spin">refresh</span><span class="truncate">Saving...</span>';
  1383. try {
  1384. const response = await fetch('/api/scheduled-pause', {
  1385. method: 'POST',
  1386. headers: { 'Content-Type': 'application/json' },
  1387. body: JSON.stringify({
  1388. enabled: stillSandsToggle.checked,
  1389. control_wled: wledControlToggle ? wledControlToggle.checked : false,
  1390. time_slots: timeSlots.map(slot => ({
  1391. start_time: slot.start_time,
  1392. end_time: slot.end_time,
  1393. days: slot.days,
  1394. custom_days: slot.custom_days
  1395. }))
  1396. })
  1397. });
  1398. if (!response.ok) {
  1399. const errorData = await response.json();
  1400. throw new Error(errorData.detail || 'Failed to save Still Sands settings');
  1401. }
  1402. // Show success state temporarily
  1403. saveStillSandsButton.innerHTML = '<span class="material-icons text-lg">check</span><span class="truncate">Saved!</span>';
  1404. showStatusMessage('Still Sands settings saved successfully', 'success');
  1405. // Restore button after 2 seconds
  1406. setTimeout(() => {
  1407. saveStillSandsButton.innerHTML = originalButtonHTML;
  1408. saveStillSandsButton.disabled = false;
  1409. }, 2000);
  1410. } catch (error) {
  1411. logMessage(`Error saving Still Sands settings: ${error.message}`, LOG_TYPE.ERROR);
  1412. showStatusMessage(`Failed to save settings: ${error.message}`, 'error');
  1413. // Restore button immediately on error
  1414. saveStillSandsButton.innerHTML = originalButtonHTML;
  1415. saveStillSandsButton.disabled = false;
  1416. }
  1417. }
  1418. // Note: Slot IDs are now assigned during initialization above, before first render
  1419. // Event listeners
  1420. stillSandsToggle.addEventListener('change', async () => {
  1421. logMessage(`Still Sands toggle changed: ${stillSandsToggle.checked}`, LOG_TYPE.INFO);
  1422. stillSandsSettings.style.display = stillSandsToggle.checked ? 'block' : 'none';
  1423. logMessage(`Settings display set to: ${stillSandsSettings.style.display}`, LOG_TYPE.INFO);
  1424. // Auto-save when toggle changes
  1425. try {
  1426. await saveStillSandsSettings();
  1427. const statusText = stillSandsToggle.checked ? 'enabled' : 'disabled';
  1428. showStatusMessage(`Still Sands ${statusText} successfully`, 'success');
  1429. } catch (error) {
  1430. logMessage(`Error saving Still Sands toggle: ${error.message}`, LOG_TYPE.ERROR);
  1431. showStatusMessage(`Failed to save Still Sands setting: ${error.message}`, 'error');
  1432. }
  1433. });
  1434. addTimeSlotButton.addEventListener('click', addTimeSlot);
  1435. saveStillSandsButton.addEventListener('click', saveStillSandsSettings);
  1436. // Add listener for WLED control toggle
  1437. if (wledControlToggle) {
  1438. wledControlToggle.addEventListener('change', async () => {
  1439. logMessage(`WLED control toggle changed: ${wledControlToggle.checked}`, LOG_TYPE.INFO);
  1440. // Auto-save when WLED control changes
  1441. await saveStillSandsSettings();
  1442. });
  1443. }
  1444. }