settings.js 60 KB

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