1
0

settings.js 61 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492
  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. // Update software
  468. const updateSoftware = document.getElementById('updateSoftware');
  469. if (updateSoftware) {
  470. updateSoftware.addEventListener('click', async () => {
  471. if (updateSoftware.disabled) {
  472. return;
  473. }
  474. try {
  475. const response = await fetch('/api/update', {
  476. method: 'POST'
  477. });
  478. const data = await response.json();
  479. if (data.success) {
  480. showStatusMessage('Software update started successfully', 'success');
  481. } else if (data.manual_update_url) {
  482. // Show modal with manual update instructions, but use wiki link
  483. const wikiData = {
  484. ...data,
  485. manual_update_url: 'https://github.com/tuanchris/dune-weaver/wiki/Updating-software'
  486. };
  487. showUpdateInstructionsModal(wikiData);
  488. } else {
  489. showStatusMessage(data.message || 'No updates available', 'info');
  490. }
  491. } catch (error) {
  492. logMessage(`Error updating software: ${error.message}`, LOG_TYPE.ERROR);
  493. showStatusMessage('Failed to check for updates', 'error');
  494. }
  495. });
  496. }
  497. // Connect button
  498. const connectButton = document.getElementById('connectButton');
  499. if (connectButton) {
  500. connectButton.addEventListener('click', async () => {
  501. const portSelect = document.getElementById('portSelect');
  502. if (!portSelect || !portSelect.value) {
  503. logMessage('Please select a port first', LOG_TYPE.WARNING);
  504. return;
  505. }
  506. try {
  507. const response = await fetch('/connect', {
  508. method: 'POST',
  509. headers: { 'Content-Type': 'application/json' },
  510. body: JSON.stringify({ port: portSelect.value })
  511. });
  512. if (response.ok) {
  513. logMessage('Connected successfully', LOG_TYPE.SUCCESS);
  514. await updateSerialStatus(true); // Force update after connecting
  515. } else {
  516. throw new Error('Failed to connect');
  517. }
  518. } catch (error) {
  519. logMessage(`Error connecting to device: ${error.message}`, LOG_TYPE.ERROR);
  520. }
  521. });
  522. }
  523. // Disconnect button
  524. const disconnectButton = document.getElementById('disconnectButton');
  525. if (disconnectButton) {
  526. disconnectButton.addEventListener('click', async () => {
  527. try {
  528. const response = await fetch('/disconnect', {
  529. method: 'POST'
  530. });
  531. if (response.ok) {
  532. logMessage('Device disconnected successfully', LOG_TYPE.SUCCESS);
  533. await updateSerialStatus(true); // Force update after disconnecting
  534. } else {
  535. throw new Error('Failed to disconnect device');
  536. }
  537. } catch (error) {
  538. logMessage(`Error disconnecting device: ${error.message}`, LOG_TYPE.ERROR);
  539. }
  540. });
  541. }
  542. // Save custom clear patterns button
  543. const saveClearPatterns = document.getElementById('saveClearPatterns');
  544. if (saveClearPatterns) {
  545. saveClearPatterns.addEventListener('click', async () => {
  546. const clearFromInInput = document.getElementById('customClearFromInInput');
  547. const clearFromOutInput = document.getElementById('customClearFromOutInput');
  548. if (!clearFromInInput || !clearFromOutInput) {
  549. return;
  550. }
  551. // Validate that the entered patterns exist (if not empty)
  552. const inValue = clearFromInInput.value.trim();
  553. const outValue = clearFromOutInput.value.trim();
  554. if (inValue && window.availablePatterns && !window.availablePatterns.includes(inValue)) {
  555. showStatusMessage(`Pattern not found: ${inValue}`, 'error');
  556. return;
  557. }
  558. if (outValue && window.availablePatterns && !window.availablePatterns.includes(outValue)) {
  559. showStatusMessage(`Pattern not found: ${outValue}`, 'error');
  560. return;
  561. }
  562. try {
  563. const response = await fetch('/api/custom_clear_patterns', {
  564. method: 'POST',
  565. headers: { 'Content-Type': 'application/json' },
  566. body: JSON.stringify({
  567. custom_clear_from_in: inValue || null,
  568. custom_clear_from_out: outValue || null
  569. })
  570. });
  571. if (response.ok) {
  572. showStatusMessage('Clear patterns saved successfully', 'success');
  573. } else {
  574. const error = await response.json();
  575. throw new Error(error.detail || 'Failed to save clear patterns');
  576. }
  577. } catch (error) {
  578. showStatusMessage(`Failed to save clear patterns: ${error.message}`, 'error');
  579. }
  580. });
  581. }
  582. // Save clear pattern speed button
  583. const saveClearSpeed = document.getElementById('saveClearSpeed');
  584. if (saveClearSpeed) {
  585. saveClearSpeed.addEventListener('click', async () => {
  586. const clearPatternSpeedInput = document.getElementById('clearPatternSpeedInput');
  587. if (!clearPatternSpeedInput) {
  588. return;
  589. }
  590. let speed;
  591. if (clearPatternSpeedInput.value === '' || clearPatternSpeedInput.value === null) {
  592. // Empty value means use default (None)
  593. speed = null;
  594. } else {
  595. speed = parseInt(clearPatternSpeedInput.value);
  596. // Validate speed only if it's not null
  597. if (isNaN(speed) || speed < 50 || speed > 2000) {
  598. showStatusMessage('Clear pattern speed must be between 50 and 2000, or leave empty for default', 'error');
  599. return;
  600. }
  601. }
  602. try {
  603. const response = await fetch('/api/clear_pattern_speed', {
  604. method: 'POST',
  605. headers: { 'Content-Type': 'application/json' },
  606. body: JSON.stringify({ clear_pattern_speed: speed })
  607. });
  608. if (response.ok) {
  609. const data = await response.json();
  610. if (speed === null) {
  611. showStatusMessage(`Clear pattern speed set to default (${data.effective_speed} steps/min)`, 'success');
  612. } else {
  613. showStatusMessage(`Clear pattern speed set to ${speed} steps/min`, 'success');
  614. }
  615. // Update the effective speed display
  616. const effectiveClearSpeed = document.getElementById('effectiveClearSpeed');
  617. if (effectiveClearSpeed) {
  618. if (speed === null) {
  619. effectiveClearSpeed.textContent = `Using default pattern speed: ${data.effective_speed} steps/min`;
  620. } else {
  621. effectiveClearSpeed.textContent = `Current: ${speed} steps/min`;
  622. }
  623. }
  624. } else {
  625. const error = await response.json();
  626. throw new Error(error.detail || 'Failed to save clear pattern speed');
  627. }
  628. } catch (error) {
  629. showStatusMessage(`Failed to save clear pattern speed: ${error.message}`, 'error');
  630. }
  631. });
  632. }
  633. }
  634. // Button click handlers
  635. document.addEventListener('DOMContentLoaded', function() {
  636. // Home button
  637. const homeButton = document.getElementById('homeButton');
  638. if (homeButton) {
  639. homeButton.addEventListener('click', async () => {
  640. try {
  641. const response = await fetch('/send_home', {
  642. method: 'POST',
  643. headers: {
  644. 'Content-Type': 'application/json'
  645. }
  646. });
  647. const data = await response.json();
  648. if (data.success) {
  649. updateStatus('Moving to home position...');
  650. }
  651. } catch (error) {
  652. console.error('Error sending home command:', error);
  653. updateStatus('Error: Failed to move to home position');
  654. }
  655. });
  656. }
  657. // Stop button
  658. const stopButton = document.getElementById('stopButton');
  659. if (stopButton) {
  660. stopButton.addEventListener('click', async () => {
  661. try {
  662. const response = await fetch('/stop_execution', {
  663. method: 'POST',
  664. headers: {
  665. 'Content-Type': 'application/json'
  666. }
  667. });
  668. const data = await response.json();
  669. if (data.success) {
  670. updateStatus('Execution stopped');
  671. }
  672. } catch (error) {
  673. console.error('Error stopping execution:', error);
  674. updateStatus('Error: Failed to stop execution');
  675. }
  676. });
  677. }
  678. // Move to Center button
  679. const centerButton = document.getElementById('centerButton');
  680. if (centerButton) {
  681. centerButton.addEventListener('click', async () => {
  682. try {
  683. const response = await fetch('/move_to_center', {
  684. method: 'POST',
  685. headers: {
  686. 'Content-Type': 'application/json'
  687. }
  688. });
  689. const data = await response.json();
  690. if (data.success) {
  691. updateStatus('Moving to center position...');
  692. }
  693. } catch (error) {
  694. console.error('Error moving to center:', error);
  695. updateStatus('Error: Failed to move to center');
  696. }
  697. });
  698. }
  699. // Move to Perimeter button
  700. const perimeterButton = document.getElementById('perimeterButton');
  701. if (perimeterButton) {
  702. perimeterButton.addEventListener('click', async () => {
  703. try {
  704. const response = await fetch('/move_to_perimeter', {
  705. method: 'POST',
  706. headers: {
  707. 'Content-Type': 'application/json'
  708. }
  709. });
  710. const data = await response.json();
  711. if (data.success) {
  712. updateStatus('Moving to perimeter position...');
  713. }
  714. } catch (error) {
  715. console.error('Error moving to perimeter:', error);
  716. updateStatus('Error: Failed to move to perimeter');
  717. }
  718. });
  719. }
  720. });
  721. // Function to update status
  722. function updateStatus(message) {
  723. const statusElement = document.querySelector('.text-slate-800.text-base.font-medium.leading-normal');
  724. if (statusElement) {
  725. statusElement.textContent = message;
  726. // Reset status after 3 seconds if it's a temporary message
  727. if (message.includes('Moving') || message.includes('Execution')) {
  728. setTimeout(() => {
  729. statusElement.textContent = 'Status';
  730. }, 3000);
  731. }
  732. }
  733. }
  734. // Function to show status messages (using existing base.js showStatusMessage if available)
  735. function showStatusMessage(message, type) {
  736. if (typeof window.showStatusMessage === 'function') {
  737. window.showStatusMessage(message, type);
  738. } else {
  739. // Fallback to console logging
  740. console.log(`[${type}] ${message}`);
  741. }
  742. }
  743. // Function to show update instructions modal
  744. function showUpdateInstructionsModal(data) {
  745. // Create modal HTML
  746. const modal = document.createElement('div');
  747. modal.id = 'updateInstructionsModal';
  748. modal.className = 'fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4';
  749. modal.innerHTML = `
  750. <div class="bg-white dark:bg-gray-800 rounded-lg shadow-xl w-full max-w-md">
  751. <div class="p-6">
  752. <div class="text-center mb-4">
  753. <h2 class="text-xl font-semibold text-gray-800 dark:text-gray-200 mb-2">Manual Update Required</h2>
  754. <p class="text-gray-600 dark:text-gray-400 text-sm">
  755. ${data.message}
  756. </p>
  757. </div>
  758. <div class="text-gray-700 dark:text-gray-300 text-sm mb-6">
  759. <p class="mb-3">${data.instructions}</p>
  760. </div>
  761. <div class="flex gap-3 justify-center">
  762. <button id="openGitHubRelease" class="px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-lg transition-colors">
  763. View Update Instructions
  764. </button>
  765. <button id="closeUpdateModal" class="px-4 py-2 bg-gray-600 hover:bg-gray-700 text-white rounded-lg transition-colors">
  766. Close
  767. </button>
  768. </div>
  769. </div>
  770. </div>
  771. `;
  772. document.body.appendChild(modal);
  773. // Add event listeners
  774. const openGitHubButton = modal.querySelector('#openGitHubRelease');
  775. const closeButton = modal.querySelector('#closeUpdateModal');
  776. openGitHubButton.addEventListener('click', () => {
  777. window.open(data.manual_update_url, '_blank');
  778. document.body.removeChild(modal);
  779. });
  780. closeButton.addEventListener('click', () => {
  781. document.body.removeChild(modal);
  782. });
  783. // Close on outside click
  784. modal.addEventListener('click', (e) => {
  785. if (e.target === modal) {
  786. document.body.removeChild(modal);
  787. }
  788. });
  789. }
  790. // Autocomplete functionality
  791. function initializeAutocomplete(inputId, suggestionsId, clearButtonId, patterns) {
  792. const input = document.getElementById(inputId);
  793. const suggestionsDiv = document.getElementById(suggestionsId);
  794. const clearButton = document.getElementById(clearButtonId);
  795. let selectedIndex = -1;
  796. if (!input || !suggestionsDiv) return;
  797. // Function to update clear button visibility
  798. function updateClearButton() {
  799. if (clearButton) {
  800. if (input.value.trim()) {
  801. clearButton.classList.remove('hidden');
  802. } else {
  803. clearButton.classList.add('hidden');
  804. }
  805. }
  806. }
  807. // Format pattern name for display
  808. function formatPatternName(pattern) {
  809. return pattern.replace('.thr', '').replace(/_/g, ' ');
  810. }
  811. // Filter patterns based on input
  812. function filterPatterns(searchTerm) {
  813. if (!searchTerm) return patterns.slice(0, 20); // Show first 20 when empty
  814. const term = searchTerm.toLowerCase();
  815. return patterns.filter(pattern => {
  816. const name = pattern.toLowerCase();
  817. return name.includes(term);
  818. }).sort((a, b) => {
  819. // Prioritize patterns that start with the search term
  820. const aStarts = a.toLowerCase().startsWith(term);
  821. const bStarts = b.toLowerCase().startsWith(term);
  822. if (aStarts && !bStarts) return -1;
  823. if (!aStarts && bStarts) return 1;
  824. return a.localeCompare(b);
  825. }).slice(0, 20); // Limit to 20 results
  826. }
  827. // Highlight matching text
  828. function highlightMatch(text, searchTerm) {
  829. if (!searchTerm) return text;
  830. const regex = new RegExp(`(${searchTerm.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')})`, 'gi');
  831. return text.replace(regex, '<mark>$1</mark>');
  832. }
  833. // Show suggestions
  834. function showSuggestions(searchTerm) {
  835. const filtered = filterPatterns(searchTerm);
  836. if (filtered.length === 0 && searchTerm) {
  837. suggestionsDiv.innerHTML = '<div class="suggestion-item" style="cursor: default; color: #9ca3af;">No patterns found</div>';
  838. suggestionsDiv.classList.remove('hidden');
  839. return;
  840. }
  841. suggestionsDiv.innerHTML = filtered.map((pattern, index) => {
  842. const displayName = formatPatternName(pattern);
  843. const highlighted = highlightMatch(displayName, searchTerm);
  844. return `<div class="suggestion-item" data-value="${pattern}" data-index="${index}">${highlighted}</div>`;
  845. }).join('');
  846. suggestionsDiv.classList.remove('hidden');
  847. selectedIndex = -1;
  848. }
  849. // Hide suggestions
  850. function hideSuggestions() {
  851. setTimeout(() => {
  852. suggestionsDiv.classList.add('hidden');
  853. selectedIndex = -1;
  854. }, 200);
  855. }
  856. // Select suggestion
  857. function selectSuggestion(value) {
  858. input.value = value;
  859. hideSuggestions();
  860. updateClearButton();
  861. }
  862. // Handle keyboard navigation
  863. function handleKeyboard(e) {
  864. const items = suggestionsDiv.querySelectorAll('.suggestion-item[data-value]');
  865. if (e.key === 'ArrowDown') {
  866. e.preventDefault();
  867. selectedIndex = Math.min(selectedIndex + 1, items.length - 1);
  868. updateSelection(items);
  869. } else if (e.key === 'ArrowUp') {
  870. e.preventDefault();
  871. selectedIndex = Math.max(selectedIndex - 1, -1);
  872. updateSelection(items);
  873. } else if (e.key === 'Enter') {
  874. e.preventDefault();
  875. if (selectedIndex >= 0 && items[selectedIndex]) {
  876. selectSuggestion(items[selectedIndex].dataset.value);
  877. } else if (items.length === 1) {
  878. selectSuggestion(items[0].dataset.value);
  879. }
  880. } else if (e.key === 'Escape') {
  881. hideSuggestions();
  882. }
  883. }
  884. // Update visual selection
  885. function updateSelection(items) {
  886. items.forEach((item, index) => {
  887. if (index === selectedIndex) {
  888. item.classList.add('selected');
  889. item.scrollIntoView({ block: 'nearest' });
  890. } else {
  891. item.classList.remove('selected');
  892. }
  893. });
  894. }
  895. // Event listeners
  896. input.addEventListener('input', (e) => {
  897. const value = e.target.value.trim();
  898. updateClearButton();
  899. if (value.length > 0 || e.target === document.activeElement) {
  900. showSuggestions(value);
  901. } else {
  902. hideSuggestions();
  903. }
  904. });
  905. input.addEventListener('focus', () => {
  906. const value = input.value.trim();
  907. showSuggestions(value);
  908. });
  909. input.addEventListener('blur', hideSuggestions);
  910. input.addEventListener('keydown', handleKeyboard);
  911. // Click handler for suggestions
  912. suggestionsDiv.addEventListener('click', (e) => {
  913. const item = e.target.closest('.suggestion-item[data-value]');
  914. if (item) {
  915. selectSuggestion(item.dataset.value);
  916. }
  917. });
  918. // Mouse hover handler
  919. suggestionsDiv.addEventListener('mouseover', (e) => {
  920. const item = e.target.closest('.suggestion-item[data-value]');
  921. if (item) {
  922. selectedIndex = parseInt(item.dataset.index);
  923. const items = suggestionsDiv.querySelectorAll('.suggestion-item[data-value]');
  924. updateSelection(items);
  925. }
  926. });
  927. // Clear button handler
  928. if (clearButton) {
  929. clearButton.addEventListener('click', () => {
  930. input.value = '';
  931. updateClearButton();
  932. hideSuggestions();
  933. input.focus();
  934. });
  935. }
  936. // Initialize clear button visibility
  937. updateClearButton();
  938. }
  939. // auto_play Mode Functions
  940. async function initializeauto_playMode() {
  941. const auto_playToggle = document.getElementById('auto_playModeToggle');
  942. const auto_playSettings = document.getElementById('auto_playSettings');
  943. const auto_playPlaylistSelect = document.getElementById('auto_playPlaylistSelect');
  944. const auto_playRunModeSelect = document.getElementById('auto_playRunModeSelect');
  945. const auto_playPauseTimeInput = document.getElementById('auto_playPauseTimeInput');
  946. const auto_playClearPatternSelect = document.getElementById('auto_playClearPatternSelect');
  947. const auto_playShuffleToggle = document.getElementById('auto_playShuffleToggle');
  948. // Load current auto_play settings
  949. try {
  950. const response = await fetch('/api/auto_play-mode');
  951. const data = await response.json();
  952. auto_playToggle.checked = data.enabled;
  953. if (data.enabled) {
  954. auto_playSettings.style.display = 'block';
  955. }
  956. // Set current values
  957. auto_playRunModeSelect.value = data.run_mode || 'loop';
  958. auto_playPauseTimeInput.value = data.pause_time || 5.0;
  959. auto_playClearPatternSelect.value = data.clear_pattern || 'adaptive';
  960. auto_playShuffleToggle.checked = data.shuffle || false;
  961. // Load playlists for selection
  962. const playlistsResponse = await fetch('/list_all_playlists');
  963. const playlists = await playlistsResponse.json();
  964. // Clear and populate playlist select
  965. auto_playPlaylistSelect.innerHTML = '<option value="">Select a playlist...</option>';
  966. playlists.forEach(playlist => {
  967. const option = document.createElement('option');
  968. option.value = playlist;
  969. option.textContent = playlist;
  970. if (playlist === data.playlist) {
  971. option.selected = true;
  972. }
  973. auto_playPlaylistSelect.appendChild(option);
  974. });
  975. } catch (error) {
  976. logMessage(`Error loading auto_play settings: ${error.message}`, LOG_TYPE.ERROR);
  977. }
  978. // Function to save settings
  979. async function saveSettings() {
  980. try {
  981. const response = await fetch('/api/auto_play-mode', {
  982. method: 'POST',
  983. headers: { 'Content-Type': 'application/json' },
  984. body: JSON.stringify({
  985. enabled: auto_playToggle.checked,
  986. playlist: auto_playPlaylistSelect.value || null,
  987. run_mode: auto_playRunModeSelect.value,
  988. pause_time: parseFloat(auto_playPauseTimeInput.value) || 0,
  989. clear_pattern: auto_playClearPatternSelect.value,
  990. shuffle: auto_playShuffleToggle.checked
  991. })
  992. });
  993. if (!response.ok) {
  994. throw new Error('Failed to save settings');
  995. }
  996. } catch (error) {
  997. logMessage(`Error saving auto_play settings: ${error.message}`, LOG_TYPE.ERROR);
  998. }
  999. }
  1000. // Toggle auto_play settings visibility and save
  1001. auto_playToggle.addEventListener('change', async () => {
  1002. auto_playSettings.style.display = auto_playToggle.checked ? 'block' : 'none';
  1003. await saveSettings();
  1004. });
  1005. // Save when any setting changes
  1006. auto_playPlaylistSelect.addEventListener('change', saveSettings);
  1007. auto_playRunModeSelect.addEventListener('change', saveSettings);
  1008. auto_playPauseTimeInput.addEventListener('change', saveSettings);
  1009. auto_playPauseTimeInput.addEventListener('input', saveSettings); // Save as user types
  1010. auto_playClearPatternSelect.addEventListener('change', saveSettings);
  1011. auto_playShuffleToggle.addEventListener('change', saveSettings);
  1012. }
  1013. // Initialize auto_play mode when DOM is ready
  1014. document.addEventListener('DOMContentLoaded', function() {
  1015. initializeauto_playMode();
  1016. initializeStillSandsMode();
  1017. });
  1018. // Still Sands Mode Functions
  1019. async function initializeStillSandsMode() {
  1020. logMessage('Initializing Still Sands mode', LOG_TYPE.INFO);
  1021. const stillSandsToggle = document.getElementById('scheduledPauseToggle');
  1022. const stillSandsSettings = document.getElementById('scheduledPauseSettings');
  1023. const addTimeSlotButton = document.getElementById('addTimeSlotButton');
  1024. const saveStillSandsButton = document.getElementById('savePauseSettings');
  1025. const timeSlotsContainer = document.getElementById('timeSlotsContainer');
  1026. const wledControlToggle = document.getElementById('stillSandsWledControl');
  1027. // Check if elements exist
  1028. if (!stillSandsToggle || !stillSandsSettings || !addTimeSlotButton || !saveStillSandsButton || !timeSlotsContainer) {
  1029. logMessage('Still Sands elements not found, skipping initialization', LOG_TYPE.WARNING);
  1030. logMessage(`Found elements: toggle=${!!stillSandsToggle}, settings=${!!stillSandsSettings}, addBtn=${!!addTimeSlotButton}, saveBtn=${!!saveStillSandsButton}, container=${!!timeSlotsContainer}`, LOG_TYPE.WARNING);
  1031. return;
  1032. }
  1033. logMessage('All Still Sands elements found successfully', LOG_TYPE.INFO);
  1034. // Track time slots
  1035. let timeSlots = [];
  1036. let slotIdCounter = 0;
  1037. // Load current Still Sands settings from initial data
  1038. try {
  1039. // Use the data loaded during page initialization, fallback to API if not available
  1040. let data;
  1041. if (window.initialStillSandsData) {
  1042. data = window.initialStillSandsData;
  1043. // Clear the global variable after use
  1044. delete window.initialStillSandsData;
  1045. } else {
  1046. // Fallback to API call if initial data not available
  1047. const response = await fetch('/api/scheduled-pause');
  1048. data = await response.json();
  1049. }
  1050. stillSandsToggle.checked = data.enabled || false;
  1051. if (data.enabled) {
  1052. stillSandsSettings.style.display = 'block';
  1053. }
  1054. // Load WLED control setting
  1055. if (wledControlToggle) {
  1056. wledControlToggle.checked = data.control_wled || false;
  1057. }
  1058. // Load existing time slots
  1059. timeSlots = data.time_slots || [];
  1060. // Assign IDs to loaded slots BEFORE rendering
  1061. if (timeSlots.length > 0) {
  1062. slotIdCounter = 0;
  1063. timeSlots.forEach(slot => {
  1064. slot.id = ++slotIdCounter;
  1065. });
  1066. }
  1067. renderTimeSlots();
  1068. } catch (error) {
  1069. logMessage(`Error loading Still Sands settings: ${error.message}`, LOG_TYPE.ERROR);
  1070. // Initialize with empty settings if load fails
  1071. timeSlots = [];
  1072. renderTimeSlots();
  1073. }
  1074. // Function to validate time format (HH:MM)
  1075. function isValidTime(timeString) {
  1076. const timeRegex = /^([01]?[0-9]|2[0-3]):[0-5][0-9]$/;
  1077. return timeRegex.test(timeString);
  1078. }
  1079. // Function to create a new time slot element
  1080. function createTimeSlotElement(slot) {
  1081. const slotDiv = document.createElement('div');
  1082. slotDiv.className = 'time-slot-item';
  1083. slotDiv.dataset.slotId = slot.id;
  1084. slotDiv.innerHTML = `
  1085. <div class="flex items-center gap-3">
  1086. <div class="flex-1 grid grid-cols-1 md:grid-cols-2 gap-3">
  1087. <div class="flex flex-col gap-1">
  1088. <label class="text-slate-700 dark:text-slate-300 text-xs font-medium">Start Time</label>
  1089. <input
  1090. type="time"
  1091. 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"
  1092. value="${slot.start_time || ''}"
  1093. required
  1094. />
  1095. </div>
  1096. <div class="flex flex-col gap-1">
  1097. <label class="text-slate-700 dark:text-slate-300 text-xs font-medium">End Time</label>
  1098. <input
  1099. type="time"
  1100. 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"
  1101. value="${slot.end_time || ''}"
  1102. required
  1103. />
  1104. </div>
  1105. </div>
  1106. <div class="flex flex-col gap-1">
  1107. <label class="text-slate-700 dark:text-slate-300 text-xs font-medium">Days</label>
  1108. <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">
  1109. <option value="daily" ${slot.days === 'daily' ? 'selected' : ''}>Daily</option>
  1110. <option value="weekdays" ${slot.days === 'weekdays' ? 'selected' : ''}>Weekdays</option>
  1111. <option value="weekends" ${slot.days === 'weekends' ? 'selected' : ''}>Weekends</option>
  1112. <option value="custom" ${slot.days === 'custom' ? 'selected' : ''}>Custom</option>
  1113. </select>
  1114. </div>
  1115. <button
  1116. type="button"
  1117. 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"
  1118. title="Remove time slot"
  1119. >
  1120. <span class="material-icons text-base">delete</span>
  1121. </button>
  1122. </div>
  1123. <div class="custom-days-container mt-2" style="display: ${slot.days === 'custom' ? 'block' : 'none'};">
  1124. <label class="text-slate-700 dark:text-slate-300 text-xs font-medium mb-1 block">Select Days</label>
  1125. <div class="flex flex-wrap gap-2">
  1126. ${['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday'].map(day => `
  1127. <label class="flex items-center gap-1 text-xs">
  1128. <input
  1129. type="checkbox"
  1130. name="custom-days-${slot.id}"
  1131. value="${day}"
  1132. ${slot.custom_days && slot.custom_days.includes(day) ? 'checked' : ''}
  1133. class="rounded border-slate-300 text-sky-600 focus:ring-sky-500"
  1134. />
  1135. <span class="text-slate-700 dark:text-slate-300 capitalize">${day.substring(0, 3)}</span>
  1136. </label>
  1137. `).join('')}
  1138. </div>
  1139. </div>
  1140. `;
  1141. // Add event listeners for this slot
  1142. const startTimeInput = slotDiv.querySelector('.start-time');
  1143. const endTimeInput = slotDiv.querySelector('.end-time');
  1144. const daysSelect = slotDiv.querySelector('.days-select');
  1145. const customDaysContainer = slotDiv.querySelector('.custom-days-container');
  1146. const removeButton = slotDiv.querySelector('.remove-slot-btn');
  1147. // Show/hide custom days based on selection
  1148. daysSelect.addEventListener('change', () => {
  1149. customDaysContainer.style.display = daysSelect.value === 'custom' ? 'block' : 'none';
  1150. updateTimeSlot(slot.id);
  1151. });
  1152. // Update slot data when inputs change
  1153. startTimeInput.addEventListener('change', () => updateTimeSlot(slot.id));
  1154. endTimeInput.addEventListener('change', () => updateTimeSlot(slot.id));
  1155. // Handle custom day checkboxes
  1156. customDaysContainer.addEventListener('change', () => updateTimeSlot(slot.id));
  1157. // Remove slot button
  1158. removeButton.addEventListener('click', () => {
  1159. removeTimeSlot(slot.id);
  1160. });
  1161. return slotDiv;
  1162. }
  1163. // Function to render all time slots
  1164. function renderTimeSlots() {
  1165. timeSlotsContainer.innerHTML = '';
  1166. if (timeSlots.length === 0) {
  1167. timeSlotsContainer.innerHTML = `
  1168. <div class="text-center py-8 text-slate-500 dark:text-slate-400">
  1169. <span class="material-icons text-4xl mb-2 block">schedule</span>
  1170. <p>No time slots configured</p>
  1171. <p class="text-xs mt-1">Click "Add Time Slot" to create a pause schedule</p>
  1172. </div>
  1173. `;
  1174. return;
  1175. }
  1176. timeSlots.forEach(slot => {
  1177. const slotElement = createTimeSlotElement(slot);
  1178. timeSlotsContainer.appendChild(slotElement);
  1179. });
  1180. }
  1181. // Function to add a new time slot
  1182. function addTimeSlot() {
  1183. const newSlot = {
  1184. id: ++slotIdCounter,
  1185. start_time: '22:00',
  1186. end_time: '08:00',
  1187. days: 'daily',
  1188. custom_days: []
  1189. };
  1190. timeSlots.push(newSlot);
  1191. renderTimeSlots();
  1192. }
  1193. // Function to remove a time slot
  1194. function removeTimeSlot(slotId) {
  1195. timeSlots = timeSlots.filter(slot => slot.id !== slotId);
  1196. renderTimeSlots();
  1197. }
  1198. // Function to update a time slot's data
  1199. function updateTimeSlot(slotId) {
  1200. const slotElement = timeSlotsContainer.querySelector(`[data-slot-id="${slotId}"]`);
  1201. if (!slotElement) return;
  1202. const slot = timeSlots.find(s => s.id === slotId);
  1203. if (!slot) return;
  1204. // Update slot data from inputs
  1205. slot.start_time = slotElement.querySelector('.start-time').value;
  1206. slot.end_time = slotElement.querySelector('.end-time').value;
  1207. slot.days = slotElement.querySelector('.days-select').value;
  1208. // Update custom days if applicable
  1209. if (slot.days === 'custom') {
  1210. const checkedDays = Array.from(slotElement.querySelectorAll(`input[name="custom-days-${slotId}"]:checked`))
  1211. .map(cb => cb.value);
  1212. slot.custom_days = checkedDays;
  1213. } else {
  1214. slot.custom_days = [];
  1215. }
  1216. }
  1217. // Function to validate all time slots
  1218. function validateTimeSlots() {
  1219. const errors = [];
  1220. timeSlots.forEach((slot, index) => {
  1221. if (!slot.start_time || !isValidTime(slot.start_time)) {
  1222. errors.push(`Time slot ${index + 1}: Invalid start time`);
  1223. }
  1224. if (!slot.end_time || !isValidTime(slot.end_time)) {
  1225. errors.push(`Time slot ${index + 1}: Invalid end time`);
  1226. }
  1227. if (slot.days === 'custom' && (!slot.custom_days || slot.custom_days.length === 0)) {
  1228. errors.push(`Time slot ${index + 1}: Please select at least one day for custom schedule`);
  1229. }
  1230. });
  1231. return errors;
  1232. }
  1233. // Function to save settings
  1234. async function saveStillSandsSettings() {
  1235. // Update all slots from current form values
  1236. timeSlots.forEach(slot => updateTimeSlot(slot.id));
  1237. // Validate time slots
  1238. const validationErrors = validateTimeSlots();
  1239. if (validationErrors.length > 0) {
  1240. showStatusMessage(`Validation errors: ${validationErrors.join(', ')}`, 'error');
  1241. return;
  1242. }
  1243. // Update button UI to show loading state
  1244. const originalButtonHTML = saveStillSandsButton.innerHTML;
  1245. saveStillSandsButton.disabled = true;
  1246. saveStillSandsButton.innerHTML = '<span class="material-icons text-lg animate-spin">refresh</span><span class="truncate">Saving...</span>';
  1247. try {
  1248. const response = await fetch('/api/scheduled-pause', {
  1249. method: 'POST',
  1250. headers: { 'Content-Type': 'application/json' },
  1251. body: JSON.stringify({
  1252. enabled: stillSandsToggle.checked,
  1253. control_wled: wledControlToggle ? wledControlToggle.checked : false,
  1254. time_slots: timeSlots.map(slot => ({
  1255. start_time: slot.start_time,
  1256. end_time: slot.end_time,
  1257. days: slot.days,
  1258. custom_days: slot.custom_days
  1259. }))
  1260. })
  1261. });
  1262. if (!response.ok) {
  1263. const errorData = await response.json();
  1264. throw new Error(errorData.detail || 'Failed to save Still Sands settings');
  1265. }
  1266. // Show success state temporarily
  1267. saveStillSandsButton.innerHTML = '<span class="material-icons text-lg">check</span><span class="truncate">Saved!</span>';
  1268. showStatusMessage('Still Sands settings saved successfully', 'success');
  1269. // Restore button after 2 seconds
  1270. setTimeout(() => {
  1271. saveStillSandsButton.innerHTML = originalButtonHTML;
  1272. saveStillSandsButton.disabled = false;
  1273. }, 2000);
  1274. } catch (error) {
  1275. logMessage(`Error saving Still Sands settings: ${error.message}`, LOG_TYPE.ERROR);
  1276. showStatusMessage(`Failed to save settings: ${error.message}`, 'error');
  1277. // Restore button immediately on error
  1278. saveStillSandsButton.innerHTML = originalButtonHTML;
  1279. saveStillSandsButton.disabled = false;
  1280. }
  1281. }
  1282. // Note: Slot IDs are now assigned during initialization above, before first render
  1283. // Event listeners
  1284. stillSandsToggle.addEventListener('change', async () => {
  1285. logMessage(`Still Sands toggle changed: ${stillSandsToggle.checked}`, LOG_TYPE.INFO);
  1286. stillSandsSettings.style.display = stillSandsToggle.checked ? 'block' : 'none';
  1287. logMessage(`Settings display set to: ${stillSandsSettings.style.display}`, LOG_TYPE.INFO);
  1288. // Auto-save when toggle changes
  1289. try {
  1290. await saveStillSandsSettings();
  1291. const statusText = stillSandsToggle.checked ? 'enabled' : 'disabled';
  1292. showStatusMessage(`Still Sands ${statusText} successfully`, 'success');
  1293. } catch (error) {
  1294. logMessage(`Error saving Still Sands toggle: ${error.message}`, LOG_TYPE.ERROR);
  1295. showStatusMessage(`Failed to save Still Sands setting: ${error.message}`, 'error');
  1296. }
  1297. });
  1298. addTimeSlotButton.addEventListener('click', addTimeSlot);
  1299. saveStillSandsButton.addEventListener('click', saveStillSandsSettings);
  1300. // Add listener for WLED control toggle
  1301. if (wledControlToggle) {
  1302. wledControlToggle.addEventListener('change', async () => {
  1303. logMessage(`WLED control toggle changed: ${wledControlToggle.checked}`, LOG_TYPE.INFO);
  1304. // Auto-save when WLED control changes
  1305. await saveStillSandsSettings();
  1306. });
  1307. }
  1308. }