settings.js 61 KB

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