settings.js 59 KB

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