1
0

settings.js 67 KB

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