settings.js 68 KB

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