settings.js 60 KB

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