settings.js 59 KB

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