1
0

settings.js 59 KB

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